1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/Loads.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/Analysis/VectorUtils.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 33 #include "llvm/CodeGen/CodeGenCommonISel.h" 34 #include "llvm/CodeGen/FunctionLoweringInfo.h" 35 #include "llvm/CodeGen/GCMetadata.h" 36 #include "llvm/CodeGen/MachineBasicBlock.h" 37 #include "llvm/CodeGen/MachineFrameInfo.h" 38 #include "llvm/CodeGen/MachineFunction.h" 39 #include "llvm/CodeGen/MachineInstrBuilder.h" 40 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 41 #include "llvm/CodeGen/MachineMemOperand.h" 42 #include "llvm/CodeGen/MachineModuleInfo.h" 43 #include "llvm/CodeGen/MachineOperand.h" 44 #include "llvm/CodeGen/MachineRegisterInfo.h" 45 #include "llvm/CodeGen/RuntimeLibcalls.h" 46 #include "llvm/CodeGen/SelectionDAG.h" 47 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 48 #include "llvm/CodeGen/StackMaps.h" 49 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 50 #include "llvm/CodeGen/TargetFrameLowering.h" 51 #include "llvm/CodeGen/TargetInstrInfo.h" 52 #include "llvm/CodeGen/TargetOpcodes.h" 53 #include "llvm/CodeGen/TargetRegisterInfo.h" 54 #include "llvm/CodeGen/TargetSubtargetInfo.h" 55 #include "llvm/CodeGen/WinEHFuncInfo.h" 56 #include "llvm/IR/Argument.h" 57 #include "llvm/IR/Attributes.h" 58 #include "llvm/IR/BasicBlock.h" 59 #include "llvm/IR/CFG.h" 60 #include "llvm/IR/CallingConv.h" 61 #include "llvm/IR/Constant.h" 62 #include "llvm/IR/ConstantRange.h" 63 #include "llvm/IR/Constants.h" 64 #include "llvm/IR/DataLayout.h" 65 #include "llvm/IR/DebugInfo.h" 66 #include "llvm/IR/DebugInfoMetadata.h" 67 #include "llvm/IR/DerivedTypes.h" 68 #include "llvm/IR/DiagnosticInfo.h" 69 #include "llvm/IR/EHPersonalities.h" 70 #include "llvm/IR/Function.h" 71 #include "llvm/IR/GetElementPtrTypeIterator.h" 72 #include "llvm/IR/InlineAsm.h" 73 #include "llvm/IR/InstrTypes.h" 74 #include "llvm/IR/Instructions.h" 75 #include "llvm/IR/IntrinsicInst.h" 76 #include "llvm/IR/Intrinsics.h" 77 #include "llvm/IR/IntrinsicsAArch64.h" 78 #include "llvm/IR/IntrinsicsWebAssembly.h" 79 #include "llvm/IR/LLVMContext.h" 80 #include "llvm/IR/Metadata.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/Operator.h" 83 #include "llvm/IR/PatternMatch.h" 84 #include "llvm/IR/Statepoint.h" 85 #include "llvm/IR/Type.h" 86 #include "llvm/IR/User.h" 87 #include "llvm/IR/Value.h" 88 #include "llvm/MC/MCContext.h" 89 #include "llvm/Support/AtomicOrdering.h" 90 #include "llvm/Support/Casting.h" 91 #include "llvm/Support/CommandLine.h" 92 #include "llvm/Support/Compiler.h" 93 #include "llvm/Support/Debug.h" 94 #include "llvm/Support/MathExtras.h" 95 #include "llvm/Support/raw_ostream.h" 96 #include "llvm/Target/TargetIntrinsicInfo.h" 97 #include "llvm/Target/TargetMachine.h" 98 #include "llvm/Target/TargetOptions.h" 99 #include "llvm/TargetParser/Triple.h" 100 #include "llvm/Transforms/Utils/Local.h" 101 #include <cstddef> 102 #include <iterator> 103 #include <limits> 104 #include <optional> 105 #include <tuple> 106 107 using namespace llvm; 108 using namespace PatternMatch; 109 using namespace SwitchCG; 110 111 #define DEBUG_TYPE "isel" 112 113 /// LimitFloatPrecision - Generate low-precision inline sequences for 114 /// some float libcalls (6, 8 or 12 bits). 115 static unsigned LimitFloatPrecision; 116 117 static cl::opt<bool> 118 InsertAssertAlign("insert-assert-align", cl::init(true), 119 cl::desc("Insert the experimental `assertalign` node."), 120 cl::ReallyHidden); 121 122 static cl::opt<unsigned, true> 123 LimitFPPrecision("limit-float-precision", 124 cl::desc("Generate low-precision inline sequences " 125 "for some float libcalls"), 126 cl::location(LimitFloatPrecision), cl::Hidden, 127 cl::init(0)); 128 129 static cl::opt<unsigned> SwitchPeelThreshold( 130 "switch-peel-threshold", cl::Hidden, cl::init(66), 131 cl::desc("Set the case probability threshold for peeling the case from a " 132 "switch statement. A value greater than 100 will void this " 133 "optimization")); 134 135 // Limit the width of DAG chains. This is important in general to prevent 136 // DAG-based analysis from blowing up. For example, alias analysis and 137 // load clustering may not complete in reasonable time. It is difficult to 138 // recognize and avoid this situation within each individual analysis, and 139 // future analyses are likely to have the same behavior. Limiting DAG width is 140 // the safe approach and will be especially important with global DAGs. 141 // 142 // MaxParallelChains default is arbitrarily high to avoid affecting 143 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 144 // sequence over this should have been converted to llvm.memcpy by the 145 // frontend. It is easy to induce this behavior with .ll code such as: 146 // %buffer = alloca [4096 x i8] 147 // %data = load [4096 x i8]* %argPtr 148 // store [4096 x i8] %data, [4096 x i8]* %buffer 149 static const unsigned MaxParallelChains = 64; 150 151 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 152 const SDValue *Parts, unsigned NumParts, 153 MVT PartVT, EVT ValueVT, const Value *V, 154 std::optional<CallingConv::ID> CC); 155 156 /// getCopyFromParts - Create a value that contains the specified legal parts 157 /// combined into the value they represent. If the parts combine to a type 158 /// larger than ValueVT then AssertOp can be used to specify whether the extra 159 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 160 /// (ISD::AssertSext). 161 static SDValue 162 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 163 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 164 std::optional<CallingConv::ID> CC = std::nullopt, 165 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 166 // Let the target assemble the parts if it wants to 167 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 168 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 169 PartVT, ValueVT, CC)) 170 return Val; 171 172 if (ValueVT.isVector()) 173 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 174 CC); 175 176 assert(NumParts > 0 && "No parts to assemble!"); 177 SDValue Val = Parts[0]; 178 179 if (NumParts > 1) { 180 // Assemble the value from multiple parts. 181 if (ValueVT.isInteger()) { 182 unsigned PartBits = PartVT.getSizeInBits(); 183 unsigned ValueBits = ValueVT.getSizeInBits(); 184 185 // Assemble the power of 2 part. 186 unsigned RoundParts = llvm::bit_floor(NumParts); 187 unsigned RoundBits = PartBits * RoundParts; 188 EVT RoundVT = RoundBits == ValueBits ? 189 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 190 SDValue Lo, Hi; 191 192 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 193 194 if (RoundParts > 2) { 195 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 196 PartVT, HalfVT, V); 197 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 198 RoundParts / 2, PartVT, HalfVT, V); 199 } else { 200 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 201 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 202 } 203 204 if (DAG.getDataLayout().isBigEndian()) 205 std::swap(Lo, Hi); 206 207 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 208 209 if (RoundParts < NumParts) { 210 // Assemble the trailing non-power-of-2 part. 211 unsigned OddParts = NumParts - RoundParts; 212 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 213 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 214 OddVT, V, CC); 215 216 // Combine the round and odd parts. 217 Lo = Val; 218 if (DAG.getDataLayout().isBigEndian()) 219 std::swap(Lo, Hi); 220 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 221 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 222 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 223 DAG.getConstant(Lo.getValueSizeInBits(), DL, 224 TLI.getShiftAmountTy( 225 TotalVT, DAG.getDataLayout()))); 226 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 227 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 228 } 229 } else if (PartVT.isFloatingPoint()) { 230 // FP split into multiple FP parts (for ppcf128) 231 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 232 "Unexpected split"); 233 SDValue Lo, Hi; 234 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 235 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 236 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 237 std::swap(Lo, Hi); 238 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 239 } else { 240 // FP split into integer parts (soft fp) 241 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 242 !PartVT.isVector() && "Unexpected split"); 243 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 244 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 245 } 246 } 247 248 // There is now one part, held in Val. Correct it to match ValueVT. 249 // PartEVT is the type of the register class that holds the value. 250 // ValueVT is the type of the inline asm operation. 251 EVT PartEVT = Val.getValueType(); 252 253 if (PartEVT == ValueVT) 254 return Val; 255 256 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 257 ValueVT.bitsLT(PartEVT)) { 258 // For an FP value in an integer part, we need to truncate to the right 259 // width first. 260 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 261 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 262 } 263 264 // Handle types that have the same size. 265 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 266 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 267 268 // Handle types with different sizes. 269 if (PartEVT.isInteger() && ValueVT.isInteger()) { 270 if (ValueVT.bitsLT(PartEVT)) { 271 // For a truncate, see if we have any information to 272 // indicate whether the truncated bits will always be 273 // zero or sign-extension. 274 if (AssertOp) 275 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 276 DAG.getValueType(ValueVT)); 277 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 278 } 279 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 280 } 281 282 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 283 // FP_ROUND's are always exact here. 284 if (ValueVT.bitsLT(Val.getValueType())) 285 return DAG.getNode( 286 ISD::FP_ROUND, DL, ValueVT, Val, 287 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 288 289 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 290 } 291 292 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 293 // then truncating. 294 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 295 ValueVT.bitsLT(PartEVT)) { 296 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 297 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 298 } 299 300 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 301 } 302 303 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 304 const Twine &ErrMsg) { 305 const Instruction *I = dyn_cast_or_null<Instruction>(V); 306 if (!V) 307 return Ctx.emitError(ErrMsg); 308 309 const char *AsmError = ", possible invalid constraint for vector type"; 310 if (const CallInst *CI = dyn_cast<CallInst>(I)) 311 if (CI->isInlineAsm()) 312 return Ctx.emitError(I, ErrMsg + AsmError); 313 314 return Ctx.emitError(I, ErrMsg); 315 } 316 317 /// getCopyFromPartsVector - Create a value that contains the specified legal 318 /// parts combined into the value they represent. If the parts combine to a 319 /// type larger than ValueVT then AssertOp can be used to specify whether the 320 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 321 /// ValueVT (ISD::AssertSext). 322 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 323 const SDValue *Parts, unsigned NumParts, 324 MVT PartVT, EVT ValueVT, const Value *V, 325 std::optional<CallingConv::ID> CallConv) { 326 assert(ValueVT.isVector() && "Not a vector value"); 327 assert(NumParts > 0 && "No parts to assemble!"); 328 const bool IsABIRegCopy = CallConv.has_value(); 329 330 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 331 SDValue Val = Parts[0]; 332 333 // Handle a multi-element vector. 334 if (NumParts > 1) { 335 EVT IntermediateVT; 336 MVT RegisterVT; 337 unsigned NumIntermediates; 338 unsigned NumRegs; 339 340 if (IsABIRegCopy) { 341 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 342 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 343 NumIntermediates, RegisterVT); 344 } else { 345 NumRegs = 346 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } 349 350 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 351 NumParts = NumRegs; // Silence a compiler warning. 352 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 353 assert(RegisterVT.getSizeInBits() == 354 Parts[0].getSimpleValueType().getSizeInBits() && 355 "Part type sizes don't match!"); 356 357 // Assemble the parts into intermediate operands. 358 SmallVector<SDValue, 8> Ops(NumIntermediates); 359 if (NumIntermediates == NumParts) { 360 // If the register was not expanded, truncate or copy the value, 361 // as appropriate. 362 for (unsigned i = 0; i != NumParts; ++i) 363 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 364 PartVT, IntermediateVT, V, CallConv); 365 } else if (NumParts > 0) { 366 // If the intermediate type was expanded, build the intermediate 367 // operands from the parts. 368 assert(NumParts % NumIntermediates == 0 && 369 "Must expand into a divisible number of parts!"); 370 unsigned Factor = NumParts / NumIntermediates; 371 for (unsigned i = 0; i != NumIntermediates; ++i) 372 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 373 PartVT, IntermediateVT, V, CallConv); 374 } 375 376 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 377 // intermediate operands. 378 EVT BuiltVectorTy = 379 IntermediateVT.isVector() 380 ? EVT::getVectorVT( 381 *DAG.getContext(), IntermediateVT.getScalarType(), 382 IntermediateVT.getVectorElementCount() * NumParts) 383 : EVT::getVectorVT(*DAG.getContext(), 384 IntermediateVT.getScalarType(), 385 NumIntermediates); 386 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 387 : ISD::BUILD_VECTOR, 388 DL, BuiltVectorTy, Ops); 389 } 390 391 // There is now one part, held in Val. Correct it to match ValueVT. 392 EVT PartEVT = Val.getValueType(); 393 394 if (PartEVT == ValueVT) 395 return Val; 396 397 if (PartEVT.isVector()) { 398 // Vector/Vector bitcast. 399 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 400 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 401 402 // If the parts vector has more elements than the value vector, then we 403 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 404 // Extract the elements we want. 405 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 406 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 407 ValueVT.getVectorElementCount().getKnownMinValue()) && 408 (PartEVT.getVectorElementCount().isScalable() == 409 ValueVT.getVectorElementCount().isScalable()) && 410 "Cannot narrow, it would be a lossy transformation"); 411 PartEVT = 412 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 413 ValueVT.getVectorElementCount()); 414 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 415 DAG.getVectorIdxConstant(0, DL)); 416 if (PartEVT == ValueVT) 417 return Val; 418 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 419 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 420 421 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 422 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 423 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 424 } 425 426 // Promoted vector extract 427 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 428 } 429 430 // Trivial bitcast if the types are the same size and the destination 431 // vector type is legal. 432 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 433 TLI.isTypeLegal(ValueVT)) 434 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 435 436 if (ValueVT.getVectorNumElements() != 1) { 437 // Certain ABIs require that vectors are passed as integers. For vectors 438 // are the same size, this is an obvious bitcast. 439 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 440 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 441 } else if (ValueVT.bitsLT(PartEVT)) { 442 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 443 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 444 // Drop the extra bits. 445 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 446 return DAG.getBitcast(ValueVT, Val); 447 } 448 449 diagnosePossiblyInvalidConstraint( 450 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 451 return DAG.getUNDEF(ValueVT); 452 } 453 454 // Handle cases such as i8 -> <1 x i1> 455 EVT ValueSVT = ValueVT.getVectorElementType(); 456 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 457 unsigned ValueSize = ValueSVT.getSizeInBits(); 458 if (ValueSize == PartEVT.getSizeInBits()) { 459 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 460 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 461 // It's possible a scalar floating point type gets softened to integer and 462 // then promoted to a larger integer. If PartEVT is the larger integer 463 // we need to truncate it and then bitcast to the FP type. 464 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 465 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 466 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 467 Val = DAG.getBitcast(ValueSVT, Val); 468 } else { 469 Val = ValueVT.isFloatingPoint() 470 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 471 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 472 } 473 } 474 475 return DAG.getBuildVector(ValueVT, DL, Val); 476 } 477 478 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 479 SDValue Val, SDValue *Parts, unsigned NumParts, 480 MVT PartVT, const Value *V, 481 std::optional<CallingConv::ID> CallConv); 482 483 /// getCopyToParts - Create a series of nodes that contain the specified value 484 /// split into legal parts. If the parts contain more bits than Val, then, for 485 /// integers, ExtendKind can be used to specify how to generate the extra bits. 486 static void 487 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 488 unsigned NumParts, MVT PartVT, const Value *V, 489 std::optional<CallingConv::ID> CallConv = std::nullopt, 490 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 491 // Let the target split the parts if it wants to 492 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 493 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 494 CallConv)) 495 return; 496 EVT ValueVT = Val.getValueType(); 497 498 // Handle the vector case separately. 499 if (ValueVT.isVector()) 500 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 501 CallConv); 502 503 unsigned OrigNumParts = NumParts; 504 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 505 "Copying to an illegal type!"); 506 507 if (NumParts == 0) 508 return; 509 510 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 511 EVT PartEVT = PartVT; 512 if (PartEVT == ValueVT) { 513 assert(NumParts == 1 && "No-op copy with multiple parts!"); 514 Parts[0] = Val; 515 return; 516 } 517 518 unsigned PartBits = PartVT.getSizeInBits(); 519 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 520 // If the parts cover more bits than the value has, promote the value. 521 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 522 assert(NumParts == 1 && "Do not know what to promote to!"); 523 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 524 } else { 525 if (ValueVT.isFloatingPoint()) { 526 // FP values need to be bitcast, then extended if they are being put 527 // into a larger container. 528 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 529 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 530 } 531 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 532 ValueVT.isInteger() && 533 "Unknown mismatch!"); 534 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 535 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 536 if (PartVT == MVT::x86mmx) 537 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 538 } 539 } else if (PartBits == ValueVT.getSizeInBits()) { 540 // Different types of the same size. 541 assert(NumParts == 1 && PartEVT != ValueVT); 542 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 543 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 544 // If the parts cover less bits than value has, truncate the value. 545 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 546 ValueVT.isInteger() && 547 "Unknown mismatch!"); 548 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 549 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 550 if (PartVT == MVT::x86mmx) 551 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 552 } 553 554 // The value may have changed - recompute ValueVT. 555 ValueVT = Val.getValueType(); 556 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 557 "Failed to tile the value with PartVT!"); 558 559 if (NumParts == 1) { 560 if (PartEVT != ValueVT) { 561 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 562 "scalar-to-vector conversion failed"); 563 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 564 } 565 566 Parts[0] = Val; 567 return; 568 } 569 570 // Expand the value into multiple parts. 571 if (NumParts & (NumParts - 1)) { 572 // The number of parts is not a power of 2. Split off and copy the tail. 573 assert(PartVT.isInteger() && ValueVT.isInteger() && 574 "Do not know what to expand to!"); 575 unsigned RoundParts = llvm::bit_floor(NumParts); 576 unsigned RoundBits = RoundParts * PartBits; 577 unsigned OddParts = NumParts - RoundParts; 578 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 579 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 580 581 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 582 CallConv); 583 584 if (DAG.getDataLayout().isBigEndian()) 585 // The odd parts were reversed by getCopyToParts - unreverse them. 586 std::reverse(Parts + RoundParts, Parts + NumParts); 587 588 NumParts = RoundParts; 589 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 590 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 591 } 592 593 // The number of parts is a power of 2. Repeatedly bisect the value using 594 // EXTRACT_ELEMENT. 595 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 596 EVT::getIntegerVT(*DAG.getContext(), 597 ValueVT.getSizeInBits()), 598 Val); 599 600 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 601 for (unsigned i = 0; i < NumParts; i += StepSize) { 602 unsigned ThisBits = StepSize * PartBits / 2; 603 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 604 SDValue &Part0 = Parts[i]; 605 SDValue &Part1 = Parts[i+StepSize/2]; 606 607 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 608 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 609 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 610 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 611 612 if (ThisBits == PartBits && ThisVT != PartVT) { 613 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 614 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 615 } 616 } 617 } 618 619 if (DAG.getDataLayout().isBigEndian()) 620 std::reverse(Parts, Parts + OrigNumParts); 621 } 622 623 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 624 const SDLoc &DL, EVT PartVT) { 625 if (!PartVT.isVector()) 626 return SDValue(); 627 628 EVT ValueVT = Val.getValueType(); 629 EVT PartEVT = PartVT.getVectorElementType(); 630 EVT ValueEVT = ValueVT.getVectorElementType(); 631 ElementCount PartNumElts = PartVT.getVectorElementCount(); 632 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 633 634 // We only support widening vectors with equivalent element types and 635 // fixed/scalable properties. If a target needs to widen a fixed-length type 636 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 637 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 638 PartNumElts.isScalable() != ValueNumElts.isScalable()) 639 return SDValue(); 640 641 // Have a try for bf16 because some targets share its ABI with fp16. 642 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 643 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 644 "Cannot widen to illegal type"); 645 Val = DAG.getNode(ISD::BITCAST, DL, 646 ValueVT.changeVectorElementType(MVT::f16), Val); 647 } else if (PartEVT != ValueEVT) { 648 return SDValue(); 649 } 650 651 // Widening a scalable vector to another scalable vector is done by inserting 652 // the vector into a larger undef one. 653 if (PartNumElts.isScalable()) 654 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 655 Val, DAG.getVectorIdxConstant(0, DL)); 656 657 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 658 // undef elements. 659 SmallVector<SDValue, 16> Ops; 660 DAG.ExtractVectorElements(Val, Ops); 661 SDValue EltUndef = DAG.getUNDEF(PartEVT); 662 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 663 664 // FIXME: Use CONCAT for 2x -> 4x. 665 return DAG.getBuildVector(PartVT, DL, Ops); 666 } 667 668 /// getCopyToPartsVector - Create a series of nodes that contain the specified 669 /// value split into legal parts. 670 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 671 SDValue Val, SDValue *Parts, unsigned NumParts, 672 MVT PartVT, const Value *V, 673 std::optional<CallingConv::ID> CallConv) { 674 EVT ValueVT = Val.getValueType(); 675 assert(ValueVT.isVector() && "Not a vector"); 676 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 677 const bool IsABIRegCopy = CallConv.has_value(); 678 679 if (NumParts == 1) { 680 EVT PartEVT = PartVT; 681 if (PartEVT == ValueVT) { 682 // Nothing to do. 683 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 684 // Bitconvert vector->vector case. 685 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 686 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 687 Val = Widened; 688 } else if (PartVT.isVector() && 689 PartEVT.getVectorElementType().bitsGE( 690 ValueVT.getVectorElementType()) && 691 PartEVT.getVectorElementCount() == 692 ValueVT.getVectorElementCount()) { 693 694 // Promoted vector extract 695 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 696 } else if (PartEVT.isVector() && 697 PartEVT.getVectorElementType() != 698 ValueVT.getVectorElementType() && 699 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 700 TargetLowering::TypeWidenVector) { 701 // Combination of widening and promotion. 702 EVT WidenVT = 703 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 704 PartVT.getVectorElementCount()); 705 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 706 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 707 } else { 708 // Don't extract an integer from a float vector. This can happen if the 709 // FP type gets softened to integer and then promoted. The promotion 710 // prevents it from being picked up by the earlier bitcast case. 711 if (ValueVT.getVectorElementCount().isScalar() && 712 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 713 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 714 DAG.getVectorIdxConstant(0, DL)); 715 } else { 716 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 717 assert(PartVT.getFixedSizeInBits() > ValueSize && 718 "lossy conversion of vector to scalar type"); 719 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 720 Val = DAG.getBitcast(IntermediateType, Val); 721 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 722 } 723 } 724 725 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 726 Parts[0] = Val; 727 return; 728 } 729 730 // Handle a multi-element vector. 731 EVT IntermediateVT; 732 MVT RegisterVT; 733 unsigned NumIntermediates; 734 unsigned NumRegs; 735 if (IsABIRegCopy) { 736 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 737 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 738 RegisterVT); 739 } else { 740 NumRegs = 741 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 742 NumIntermediates, RegisterVT); 743 } 744 745 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 746 NumParts = NumRegs; // Silence a compiler warning. 747 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 748 749 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 750 "Mixing scalable and fixed vectors when copying in parts"); 751 752 std::optional<ElementCount> DestEltCnt; 753 754 if (IntermediateVT.isVector()) 755 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 756 else 757 DestEltCnt = ElementCount::getFixed(NumIntermediates); 758 759 EVT BuiltVectorTy = EVT::getVectorVT( 760 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 761 762 if (ValueVT == BuiltVectorTy) { 763 // Nothing to do. 764 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 765 // Bitconvert vector->vector case. 766 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 767 } else { 768 if (BuiltVectorTy.getVectorElementType().bitsGT( 769 ValueVT.getVectorElementType())) { 770 // Integer promotion. 771 ValueVT = EVT::getVectorVT(*DAG.getContext(), 772 BuiltVectorTy.getVectorElementType(), 773 ValueVT.getVectorElementCount()); 774 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 775 } 776 777 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 778 Val = Widened; 779 } 780 } 781 782 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 783 784 // Split the vector into intermediate operands. 785 SmallVector<SDValue, 8> Ops(NumIntermediates); 786 for (unsigned i = 0; i != NumIntermediates; ++i) { 787 if (IntermediateVT.isVector()) { 788 // This does something sensible for scalable vectors - see the 789 // definition of EXTRACT_SUBVECTOR for further details. 790 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 791 Ops[i] = 792 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 793 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 794 } else { 795 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 796 DAG.getVectorIdxConstant(i, DL)); 797 } 798 } 799 800 // Split the intermediate operands into legal parts. 801 if (NumParts == NumIntermediates) { 802 // If the register was not expanded, promote or copy the value, 803 // as appropriate. 804 for (unsigned i = 0; i != NumParts; ++i) 805 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 806 } else if (NumParts > 0) { 807 // If the intermediate type was expanded, split each the value into 808 // legal parts. 809 assert(NumIntermediates != 0 && "division by zero"); 810 assert(NumParts % NumIntermediates == 0 && 811 "Must expand into a divisible number of parts!"); 812 unsigned Factor = NumParts / NumIntermediates; 813 for (unsigned i = 0; i != NumIntermediates; ++i) 814 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 815 CallConv); 816 } 817 } 818 819 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 820 EVT valuevt, std::optional<CallingConv::ID> CC) 821 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 822 RegCount(1, regs.size()), CallConv(CC) {} 823 824 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 825 const DataLayout &DL, unsigned Reg, Type *Ty, 826 std::optional<CallingConv::ID> CC) { 827 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 828 829 CallConv = CC; 830 831 for (EVT ValueVT : ValueVTs) { 832 unsigned NumRegs = 833 isABIMangled() 834 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 835 : TLI.getNumRegisters(Context, ValueVT); 836 MVT RegisterVT = 837 isABIMangled() 838 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 839 : TLI.getRegisterType(Context, ValueVT); 840 for (unsigned i = 0; i != NumRegs; ++i) 841 Regs.push_back(Reg + i); 842 RegVTs.push_back(RegisterVT); 843 RegCount.push_back(NumRegs); 844 Reg += NumRegs; 845 } 846 } 847 848 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 849 FunctionLoweringInfo &FuncInfo, 850 const SDLoc &dl, SDValue &Chain, 851 SDValue *Glue, const Value *V) const { 852 // A Value with type {} or [0 x %t] needs no registers. 853 if (ValueVTs.empty()) 854 return SDValue(); 855 856 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 857 858 // Assemble the legal parts into the final values. 859 SmallVector<SDValue, 4> Values(ValueVTs.size()); 860 SmallVector<SDValue, 8> Parts; 861 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 862 // Copy the legal parts from the registers. 863 EVT ValueVT = ValueVTs[Value]; 864 unsigned NumRegs = RegCount[Value]; 865 MVT RegisterVT = isABIMangled() 866 ? TLI.getRegisterTypeForCallingConv( 867 *DAG.getContext(), *CallConv, RegVTs[Value]) 868 : RegVTs[Value]; 869 870 Parts.resize(NumRegs); 871 for (unsigned i = 0; i != NumRegs; ++i) { 872 SDValue P; 873 if (!Glue) { 874 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 875 } else { 876 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 877 *Glue = P.getValue(2); 878 } 879 880 Chain = P.getValue(1); 881 Parts[i] = P; 882 883 // If the source register was virtual and if we know something about it, 884 // add an assert node. 885 if (!Register::isVirtualRegister(Regs[Part + i]) || 886 !RegisterVT.isInteger()) 887 continue; 888 889 const FunctionLoweringInfo::LiveOutInfo *LOI = 890 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 891 if (!LOI) 892 continue; 893 894 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 895 unsigned NumSignBits = LOI->NumSignBits; 896 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 897 898 if (NumZeroBits == RegSize) { 899 // The current value is a zero. 900 // Explicitly express that as it would be easier for 901 // optimizations to kick in. 902 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 903 continue; 904 } 905 906 // FIXME: We capture more information than the dag can represent. For 907 // now, just use the tightest assertzext/assertsext possible. 908 bool isSExt; 909 EVT FromVT(MVT::Other); 910 if (NumZeroBits) { 911 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 912 isSExt = false; 913 } else if (NumSignBits > 1) { 914 FromVT = 915 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 916 isSExt = true; 917 } else { 918 continue; 919 } 920 // Add an assertion node. 921 assert(FromVT != MVT::Other); 922 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 923 RegisterVT, P, DAG.getValueType(FromVT)); 924 } 925 926 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 927 RegisterVT, ValueVT, V, CallConv); 928 Part += NumRegs; 929 Parts.clear(); 930 } 931 932 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 933 } 934 935 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 936 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 937 const Value *V, 938 ISD::NodeType PreferredExtendType) const { 939 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 940 ISD::NodeType ExtendKind = PreferredExtendType; 941 942 // Get the list of the values's legal parts. 943 unsigned NumRegs = Regs.size(); 944 SmallVector<SDValue, 8> Parts(NumRegs); 945 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 946 unsigned NumParts = RegCount[Value]; 947 948 MVT RegisterVT = isABIMangled() 949 ? TLI.getRegisterTypeForCallingConv( 950 *DAG.getContext(), *CallConv, RegVTs[Value]) 951 : RegVTs[Value]; 952 953 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 954 ExtendKind = ISD::ZERO_EXTEND; 955 956 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 957 NumParts, RegisterVT, V, CallConv, ExtendKind); 958 Part += NumParts; 959 } 960 961 // Copy the parts into the registers. 962 SmallVector<SDValue, 8> Chains(NumRegs); 963 for (unsigned i = 0; i != NumRegs; ++i) { 964 SDValue Part; 965 if (!Glue) { 966 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 967 } else { 968 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 969 *Glue = Part.getValue(1); 970 } 971 972 Chains[i] = Part.getValue(0); 973 } 974 975 if (NumRegs == 1 || Glue) 976 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 977 // flagged to it. That is the CopyToReg nodes and the user are considered 978 // a single scheduling unit. If we create a TokenFactor and return it as 979 // chain, then the TokenFactor is both a predecessor (operand) of the 980 // user as well as a successor (the TF operands are flagged to the user). 981 // c1, f1 = CopyToReg 982 // c2, f2 = CopyToReg 983 // c3 = TokenFactor c1, c2 984 // ... 985 // = op c3, ..., f2 986 Chain = Chains[NumRegs-1]; 987 else 988 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 989 } 990 991 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 992 unsigned MatchingIdx, const SDLoc &dl, 993 SelectionDAG &DAG, 994 std::vector<SDValue> &Ops) const { 995 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 996 997 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 998 if (HasMatching) 999 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 1000 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1001 // Put the register class of the virtual registers in the flag word. That 1002 // way, later passes can recompute register class constraints for inline 1003 // assembly as well as normal instructions. 1004 // Don't do this for tied operands that can use the regclass information 1005 // from the def. 1006 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1007 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1008 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 1009 } 1010 1011 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1012 Ops.push_back(Res); 1013 1014 if (Code == InlineAsm::Kind_Clobber) { 1015 // Clobbers should always have a 1:1 mapping with registers, and may 1016 // reference registers that have illegal (e.g. vector) types. Hence, we 1017 // shouldn't try to apply any sort of splitting logic to them. 1018 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1019 "No 1:1 mapping from clobbers to regs?"); 1020 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1021 (void)SP; 1022 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1023 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1024 assert( 1025 (Regs[I] != SP || 1026 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1027 "If we clobbered the stack pointer, MFI should know about it."); 1028 } 1029 return; 1030 } 1031 1032 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1033 MVT RegisterVT = RegVTs[Value]; 1034 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1035 RegisterVT); 1036 for (unsigned i = 0; i != NumRegs; ++i) { 1037 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1038 unsigned TheReg = Regs[Reg++]; 1039 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1040 } 1041 } 1042 } 1043 1044 SmallVector<std::pair<unsigned, TypeSize>, 4> 1045 RegsForValue::getRegsAndSizes() const { 1046 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1047 unsigned I = 0; 1048 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1049 unsigned RegCount = std::get<0>(CountAndVT); 1050 MVT RegisterVT = std::get<1>(CountAndVT); 1051 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1052 for (unsigned E = I + RegCount; I != E; ++I) 1053 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1054 } 1055 return OutVec; 1056 } 1057 1058 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1059 AssumptionCache *ac, 1060 const TargetLibraryInfo *li) { 1061 AA = aa; 1062 AC = ac; 1063 GFI = gfi; 1064 LibInfo = li; 1065 Context = DAG.getContext(); 1066 LPadToCallSiteMap.clear(); 1067 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1068 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1069 *DAG.getMachineFunction().getFunction().getParent()); 1070 } 1071 1072 void SelectionDAGBuilder::clear() { 1073 NodeMap.clear(); 1074 UnusedArgNodeMap.clear(); 1075 PendingLoads.clear(); 1076 PendingExports.clear(); 1077 PendingConstrainedFP.clear(); 1078 PendingConstrainedFPStrict.clear(); 1079 CurInst = nullptr; 1080 HasTailCall = false; 1081 SDNodeOrder = LowestSDNodeOrder; 1082 StatepointLowering.clear(); 1083 } 1084 1085 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1086 DanglingDebugInfoMap.clear(); 1087 } 1088 1089 // Update DAG root to include dependencies on Pending chains. 1090 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1091 SDValue Root = DAG.getRoot(); 1092 1093 if (Pending.empty()) 1094 return Root; 1095 1096 // Add current root to PendingChains, unless we already indirectly 1097 // depend on it. 1098 if (Root.getOpcode() != ISD::EntryToken) { 1099 unsigned i = 0, e = Pending.size(); 1100 for (; i != e; ++i) { 1101 assert(Pending[i].getNode()->getNumOperands() > 1); 1102 if (Pending[i].getNode()->getOperand(0) == Root) 1103 break; // Don't add the root if we already indirectly depend on it. 1104 } 1105 1106 if (i == e) 1107 Pending.push_back(Root); 1108 } 1109 1110 if (Pending.size() == 1) 1111 Root = Pending[0]; 1112 else 1113 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1114 1115 DAG.setRoot(Root); 1116 Pending.clear(); 1117 return Root; 1118 } 1119 1120 SDValue SelectionDAGBuilder::getMemoryRoot() { 1121 return updateRoot(PendingLoads); 1122 } 1123 1124 SDValue SelectionDAGBuilder::getRoot() { 1125 // Chain up all pending constrained intrinsics together with all 1126 // pending loads, by simply appending them to PendingLoads and 1127 // then calling getMemoryRoot(). 1128 PendingLoads.reserve(PendingLoads.size() + 1129 PendingConstrainedFP.size() + 1130 PendingConstrainedFPStrict.size()); 1131 PendingLoads.append(PendingConstrainedFP.begin(), 1132 PendingConstrainedFP.end()); 1133 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1134 PendingConstrainedFPStrict.end()); 1135 PendingConstrainedFP.clear(); 1136 PendingConstrainedFPStrict.clear(); 1137 return getMemoryRoot(); 1138 } 1139 1140 SDValue SelectionDAGBuilder::getControlRoot() { 1141 // We need to emit pending fpexcept.strict constrained intrinsics, 1142 // so append them to the PendingExports list. 1143 PendingExports.append(PendingConstrainedFPStrict.begin(), 1144 PendingConstrainedFPStrict.end()); 1145 PendingConstrainedFPStrict.clear(); 1146 return updateRoot(PendingExports); 1147 } 1148 1149 void SelectionDAGBuilder::visit(const Instruction &I) { 1150 // Set up outgoing PHI node register values before emitting the terminator. 1151 if (I.isTerminator()) { 1152 HandlePHINodesInSuccessorBlocks(I.getParent()); 1153 } 1154 1155 // Add SDDbgValue nodes for any var locs here. Do so before updating 1156 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1157 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1158 // Add SDDbgValue nodes for any var locs here. Do so before updating 1159 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1160 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1161 It != End; ++It) { 1162 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1163 dropDanglingDebugInfo(Var, It->Expr); 1164 if (It->Values.isKillLocation(It->Expr)) { 1165 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1166 continue; 1167 } 1168 SmallVector<Value *> Values(It->Values.location_ops()); 1169 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1170 It->Values.hasArgList())) 1171 addDanglingDebugInfo(It, SDNodeOrder); 1172 } 1173 } 1174 1175 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1176 if (!isa<DbgInfoIntrinsic>(I)) 1177 ++SDNodeOrder; 1178 1179 CurInst = &I; 1180 1181 // Set inserted listener only if required. 1182 bool NodeInserted = false; 1183 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1184 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1185 if (PCSectionsMD) { 1186 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1187 DAG, [&](SDNode *) { NodeInserted = true; }); 1188 } 1189 1190 visit(I.getOpcode(), I); 1191 1192 if (!I.isTerminator() && !HasTailCall && 1193 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1194 CopyToExportRegsIfNeeded(&I); 1195 1196 // Handle metadata. 1197 if (PCSectionsMD) { 1198 auto It = NodeMap.find(&I); 1199 if (It != NodeMap.end()) { 1200 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1201 } else if (NodeInserted) { 1202 // This should not happen; if it does, don't let it go unnoticed so we can 1203 // fix it. Relevant visit*() function is probably missing a setValue(). 1204 errs() << "warning: loosing !pcsections metadata [" 1205 << I.getModule()->getName() << "]\n"; 1206 LLVM_DEBUG(I.dump()); 1207 assert(false); 1208 } 1209 } 1210 1211 CurInst = nullptr; 1212 } 1213 1214 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1215 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1216 } 1217 1218 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1219 // Note: this doesn't use InstVisitor, because it has to work with 1220 // ConstantExpr's in addition to instructions. 1221 switch (Opcode) { 1222 default: llvm_unreachable("Unknown instruction type encountered!"); 1223 // Build the switch statement using the Instruction.def file. 1224 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1225 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1226 #include "llvm/IR/Instruction.def" 1227 } 1228 } 1229 1230 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1231 DILocalVariable *Variable, 1232 DebugLoc DL, unsigned Order, 1233 RawLocationWrapper Values, 1234 DIExpression *Expression) { 1235 if (!Values.hasArgList()) 1236 return false; 1237 // For variadic dbg_values we will now insert an undef. 1238 // FIXME: We can potentially recover these! 1239 SmallVector<SDDbgOperand, 2> Locs; 1240 for (const Value *V : Values.location_ops()) { 1241 auto *Undef = UndefValue::get(V->getType()); 1242 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1243 } 1244 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1245 /*IsIndirect=*/false, DL, Order, 1246 /*IsVariadic=*/true); 1247 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1248 return true; 1249 } 1250 1251 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc, 1252 unsigned Order) { 1253 if (!handleDanglingVariadicDebugInfo( 1254 DAG, 1255 const_cast<DILocalVariable *>(DAG.getFunctionVarLocs() 1256 ->getVariable(VarLoc->VariableID) 1257 .getVariable()), 1258 VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) { 1259 DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back( 1260 VarLoc, Order); 1261 } 1262 } 1263 1264 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1265 unsigned Order) { 1266 // We treat variadic dbg_values differently at this stage. 1267 if (!handleDanglingVariadicDebugInfo( 1268 DAG, DI->getVariable(), DI->getDebugLoc(), Order, 1269 DI->getWrappedLocation(), DI->getExpression())) { 1270 // TODO: Dangling debug info will eventually either be resolved or produce 1271 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1272 // between the original dbg.value location and its resolved DBG_VALUE, 1273 // which we should ideally fill with an extra Undef DBG_VALUE. 1274 assert(DI->getNumVariableLocationOps() == 1 && 1275 "DbgValueInst without an ArgList should have a single location " 1276 "operand."); 1277 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order); 1278 } 1279 } 1280 1281 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1282 const DIExpression *Expr) { 1283 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1284 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs()); 1285 DIExpression *DanglingExpr = DDI.getExpression(); 1286 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1287 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI) 1288 << "\n"); 1289 return true; 1290 } 1291 return false; 1292 }; 1293 1294 for (auto &DDIMI : DanglingDebugInfoMap) { 1295 DanglingDebugInfoVector &DDIV = DDIMI.second; 1296 1297 // If debug info is to be dropped, run it through final checks to see 1298 // whether it can be salvaged. 1299 for (auto &DDI : DDIV) 1300 if (isMatchingDbgValue(DDI)) 1301 salvageUnresolvedDbgValue(DDI); 1302 1303 erase_if(DDIV, isMatchingDbgValue); 1304 } 1305 } 1306 1307 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1308 // generate the debug data structures now that we've seen its definition. 1309 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1310 SDValue Val) { 1311 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1312 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1313 return; 1314 1315 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1316 for (auto &DDI : DDIV) { 1317 DebugLoc DL = DDI.getDebugLoc(); 1318 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1319 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1320 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs()); 1321 DIExpression *Expr = DDI.getExpression(); 1322 assert(Variable->isValidLocationForIntrinsic(DL) && 1323 "Expected inlined-at fields to agree"); 1324 SDDbgValue *SDV; 1325 if (Val.getNode()) { 1326 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1327 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1328 // we couldn't resolve it directly when examining the DbgValue intrinsic 1329 // in the first place we should not be more successful here). Unless we 1330 // have some test case that prove this to be correct we should avoid 1331 // calling EmitFuncArgumentDbgValue here. 1332 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1333 FuncArgumentDbgValueKind::Value, Val)) { 1334 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI) 1335 << "\n"); 1336 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1337 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1338 // inserted after the definition of Val when emitting the instructions 1339 // after ISel. An alternative could be to teach 1340 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1341 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1342 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1343 << ValSDNodeOrder << "\n"); 1344 SDV = getDbgValue(Val, Variable, Expr, DL, 1345 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1346 DAG.AddDbgValue(SDV, false); 1347 } else 1348 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1349 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"); 1350 } else { 1351 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n"); 1352 auto Undef = UndefValue::get(V->getType()); 1353 auto SDV = 1354 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1355 DAG.AddDbgValue(SDV, false); 1356 } 1357 } 1358 DDIV.clear(); 1359 } 1360 1361 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1362 // TODO: For the variadic implementation, instead of only checking the fail 1363 // state of `handleDebugValue`, we need know specifically which values were 1364 // invalid, so that we attempt to salvage only those values when processing 1365 // a DIArgList. 1366 Value *V = DDI.getVariableLocationOp(0); 1367 Value *OrigV = V; 1368 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs()); 1369 DIExpression *Expr = DDI.getExpression(); 1370 DebugLoc DL = DDI.getDebugLoc(); 1371 unsigned SDOrder = DDI.getSDNodeOrder(); 1372 1373 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1374 // that DW_OP_stack_value is desired. 1375 bool StackValue = true; 1376 1377 // Can this Value can be encoded without any further work? 1378 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1379 return; 1380 1381 // Attempt to salvage back through as many instructions as possible. Bail if 1382 // a non-instruction is seen, such as a constant expression or global 1383 // variable. FIXME: Further work could recover those too. 1384 while (isa<Instruction>(V)) { 1385 Instruction &VAsInst = *cast<Instruction>(V); 1386 // Temporary "0", awaiting real implementation. 1387 SmallVector<uint64_t, 16> Ops; 1388 SmallVector<Value *, 4> AdditionalValues; 1389 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1390 AdditionalValues); 1391 // If we cannot salvage any further, and haven't yet found a suitable debug 1392 // expression, bail out. 1393 if (!V) 1394 break; 1395 1396 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1397 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1398 // here for variadic dbg_values, remove that condition. 1399 if (!AdditionalValues.empty()) 1400 break; 1401 1402 // New value and expr now represent this debuginfo. 1403 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1404 1405 // Some kind of simplification occurred: check whether the operand of the 1406 // salvaged debug expression can be encoded in this DAG. 1407 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1408 LLVM_DEBUG( 1409 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1410 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1411 return; 1412 } 1413 } 1414 1415 // This was the final opportunity to salvage this debug information, and it 1416 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1417 // any earlier variable location. 1418 assert(OrigV && "V shouldn't be null"); 1419 auto *Undef = UndefValue::get(OrigV->getType()); 1420 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1421 DAG.AddDbgValue(SDV, false); 1422 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI) 1423 << "\n"); 1424 } 1425 1426 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1427 DIExpression *Expr, 1428 DebugLoc DbgLoc, 1429 unsigned Order) { 1430 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1431 DIExpression *NewExpr = 1432 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1433 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1434 /*IsVariadic*/ false); 1435 } 1436 1437 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1438 DILocalVariable *Var, 1439 DIExpression *Expr, DebugLoc DbgLoc, 1440 unsigned Order, bool IsVariadic) { 1441 if (Values.empty()) 1442 return true; 1443 SmallVector<SDDbgOperand> LocationOps; 1444 SmallVector<SDNode *> Dependencies; 1445 for (const Value *V : Values) { 1446 // Constant value. 1447 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1448 isa<ConstantPointerNull>(V)) { 1449 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1450 continue; 1451 } 1452 1453 // Look through IntToPtr constants. 1454 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1455 if (CE->getOpcode() == Instruction::IntToPtr) { 1456 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1457 continue; 1458 } 1459 1460 // If the Value is a frame index, we can create a FrameIndex debug value 1461 // without relying on the DAG at all. 1462 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1463 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1464 if (SI != FuncInfo.StaticAllocaMap.end()) { 1465 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1466 continue; 1467 } 1468 } 1469 1470 // Do not use getValue() in here; we don't want to generate code at 1471 // this point if it hasn't been done yet. 1472 SDValue N = NodeMap[V]; 1473 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1474 N = UnusedArgNodeMap[V]; 1475 if (N.getNode()) { 1476 // Only emit func arg dbg value for non-variadic dbg.values for now. 1477 if (!IsVariadic && 1478 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1479 FuncArgumentDbgValueKind::Value, N)) 1480 return true; 1481 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1482 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1483 // describe stack slot locations. 1484 // 1485 // Consider "int x = 0; int *px = &x;". There are two kinds of 1486 // interesting debug values here after optimization: 1487 // 1488 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1489 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1490 // 1491 // Both describe the direct values of their associated variables. 1492 Dependencies.push_back(N.getNode()); 1493 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1494 continue; 1495 } 1496 LocationOps.emplace_back( 1497 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1498 continue; 1499 } 1500 1501 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1502 // Special rules apply for the first dbg.values of parameter variables in a 1503 // function. Identify them by the fact they reference Argument Values, that 1504 // they're parameters, and they are parameters of the current function. We 1505 // need to let them dangle until they get an SDNode. 1506 bool IsParamOfFunc = 1507 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1508 if (IsParamOfFunc) 1509 return false; 1510 1511 // The value is not used in this block yet (or it would have an SDNode). 1512 // We still want the value to appear for the user if possible -- if it has 1513 // an associated VReg, we can refer to that instead. 1514 auto VMI = FuncInfo.ValueMap.find(V); 1515 if (VMI != FuncInfo.ValueMap.end()) { 1516 unsigned Reg = VMI->second; 1517 // If this is a PHI node, it may be split up into several MI PHI nodes 1518 // (in FunctionLoweringInfo::set). 1519 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1520 V->getType(), std::nullopt); 1521 if (RFV.occupiesMultipleRegs()) { 1522 // FIXME: We could potentially support variadic dbg_values here. 1523 if (IsVariadic) 1524 return false; 1525 unsigned Offset = 0; 1526 unsigned BitsToDescribe = 0; 1527 if (auto VarSize = Var->getSizeInBits()) 1528 BitsToDescribe = *VarSize; 1529 if (auto Fragment = Expr->getFragmentInfo()) 1530 BitsToDescribe = Fragment->SizeInBits; 1531 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1532 // Bail out if all bits are described already. 1533 if (Offset >= BitsToDescribe) 1534 break; 1535 // TODO: handle scalable vectors. 1536 unsigned RegisterSize = RegAndSize.second; 1537 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1538 ? BitsToDescribe - Offset 1539 : RegisterSize; 1540 auto FragmentExpr = DIExpression::createFragmentExpression( 1541 Expr, Offset, FragmentSize); 1542 if (!FragmentExpr) 1543 continue; 1544 SDDbgValue *SDV = DAG.getVRegDbgValue( 1545 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1546 DAG.AddDbgValue(SDV, false); 1547 Offset += RegisterSize; 1548 } 1549 return true; 1550 } 1551 // We can use simple vreg locations for variadic dbg_values as well. 1552 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1553 continue; 1554 } 1555 // We failed to create a SDDbgOperand for V. 1556 return false; 1557 } 1558 1559 // We have created a SDDbgOperand for each Value in Values. 1560 // Should use Order instead of SDNodeOrder? 1561 assert(!LocationOps.empty()); 1562 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1563 /*IsIndirect=*/false, DbgLoc, 1564 SDNodeOrder, IsVariadic); 1565 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1566 return true; 1567 } 1568 1569 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1570 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1571 for (auto &Pair : DanglingDebugInfoMap) 1572 for (auto &DDI : Pair.second) 1573 salvageUnresolvedDbgValue(DDI); 1574 clearDanglingDebugInfo(); 1575 } 1576 1577 /// getCopyFromRegs - If there was virtual register allocated for the value V 1578 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1579 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1580 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1581 SDValue Result; 1582 1583 if (It != FuncInfo.ValueMap.end()) { 1584 Register InReg = It->second; 1585 1586 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1587 DAG.getDataLayout(), InReg, Ty, 1588 std::nullopt); // This is not an ABI copy. 1589 SDValue Chain = DAG.getEntryNode(); 1590 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1591 V); 1592 resolveDanglingDebugInfo(V, Result); 1593 } 1594 1595 return Result; 1596 } 1597 1598 /// getValue - Return an SDValue for the given Value. 1599 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1600 // If we already have an SDValue for this value, use it. It's important 1601 // to do this first, so that we don't create a CopyFromReg if we already 1602 // have a regular SDValue. 1603 SDValue &N = NodeMap[V]; 1604 if (N.getNode()) return N; 1605 1606 // If there's a virtual register allocated and initialized for this 1607 // value, use it. 1608 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1609 return copyFromReg; 1610 1611 // Otherwise create a new SDValue and remember it. 1612 SDValue Val = getValueImpl(V); 1613 NodeMap[V] = Val; 1614 resolveDanglingDebugInfo(V, Val); 1615 return Val; 1616 } 1617 1618 /// getNonRegisterValue - Return an SDValue for the given Value, but 1619 /// don't look in FuncInfo.ValueMap for a virtual register. 1620 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1621 // If we already have an SDValue for this value, use it. 1622 SDValue &N = NodeMap[V]; 1623 if (N.getNode()) { 1624 if (isIntOrFPConstant(N)) { 1625 // Remove the debug location from the node as the node is about to be used 1626 // in a location which may differ from the original debug location. This 1627 // is relevant to Constant and ConstantFP nodes because they can appear 1628 // as constant expressions inside PHI nodes. 1629 N->setDebugLoc(DebugLoc()); 1630 } 1631 return N; 1632 } 1633 1634 // Otherwise create a new SDValue and remember it. 1635 SDValue Val = getValueImpl(V); 1636 NodeMap[V] = Val; 1637 resolveDanglingDebugInfo(V, Val); 1638 return Val; 1639 } 1640 1641 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1642 /// Create an SDValue for the given value. 1643 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1644 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1645 1646 if (const Constant *C = dyn_cast<Constant>(V)) { 1647 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1648 1649 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1650 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1651 1652 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1653 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1654 1655 if (isa<ConstantPointerNull>(C)) { 1656 unsigned AS = V->getType()->getPointerAddressSpace(); 1657 return DAG.getConstant(0, getCurSDLoc(), 1658 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1659 } 1660 1661 if (match(C, m_VScale())) 1662 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1663 1664 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1665 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1666 1667 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1668 return DAG.getUNDEF(VT); 1669 1670 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1671 visit(CE->getOpcode(), *CE); 1672 SDValue N1 = NodeMap[V]; 1673 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1674 return N1; 1675 } 1676 1677 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1678 SmallVector<SDValue, 4> Constants; 1679 for (const Use &U : C->operands()) { 1680 SDNode *Val = getValue(U).getNode(); 1681 // If the operand is an empty aggregate, there are no values. 1682 if (!Val) continue; 1683 // Add each leaf value from the operand to the Constants list 1684 // to form a flattened list of all the values. 1685 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1686 Constants.push_back(SDValue(Val, i)); 1687 } 1688 1689 return DAG.getMergeValues(Constants, getCurSDLoc()); 1690 } 1691 1692 if (const ConstantDataSequential *CDS = 1693 dyn_cast<ConstantDataSequential>(C)) { 1694 SmallVector<SDValue, 4> Ops; 1695 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1696 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1697 // Add each leaf value from the operand to the Constants list 1698 // to form a flattened list of all the values. 1699 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1700 Ops.push_back(SDValue(Val, i)); 1701 } 1702 1703 if (isa<ArrayType>(CDS->getType())) 1704 return DAG.getMergeValues(Ops, getCurSDLoc()); 1705 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1706 } 1707 1708 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1709 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1710 "Unknown struct or array constant!"); 1711 1712 SmallVector<EVT, 4> ValueVTs; 1713 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1714 unsigned NumElts = ValueVTs.size(); 1715 if (NumElts == 0) 1716 return SDValue(); // empty struct 1717 SmallVector<SDValue, 4> Constants(NumElts); 1718 for (unsigned i = 0; i != NumElts; ++i) { 1719 EVT EltVT = ValueVTs[i]; 1720 if (isa<UndefValue>(C)) 1721 Constants[i] = DAG.getUNDEF(EltVT); 1722 else if (EltVT.isFloatingPoint()) 1723 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1724 else 1725 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1726 } 1727 1728 return DAG.getMergeValues(Constants, getCurSDLoc()); 1729 } 1730 1731 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1732 return DAG.getBlockAddress(BA, VT); 1733 1734 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1735 return getValue(Equiv->getGlobalValue()); 1736 1737 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1738 return getValue(NC->getGlobalValue()); 1739 1740 VectorType *VecTy = cast<VectorType>(V->getType()); 1741 1742 // Now that we know the number and type of the elements, get that number of 1743 // elements into the Ops array based on what kind of constant it is. 1744 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1745 SmallVector<SDValue, 16> Ops; 1746 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1747 for (unsigned i = 0; i != NumElements; ++i) 1748 Ops.push_back(getValue(CV->getOperand(i))); 1749 1750 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1751 } 1752 1753 if (isa<ConstantAggregateZero>(C)) { 1754 EVT EltVT = 1755 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1756 1757 SDValue Op; 1758 if (EltVT.isFloatingPoint()) 1759 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1760 else 1761 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1762 1763 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1764 } 1765 1766 llvm_unreachable("Unknown vector constant"); 1767 } 1768 1769 // If this is a static alloca, generate it as the frameindex instead of 1770 // computation. 1771 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1772 DenseMap<const AllocaInst*, int>::iterator SI = 1773 FuncInfo.StaticAllocaMap.find(AI); 1774 if (SI != FuncInfo.StaticAllocaMap.end()) 1775 return DAG.getFrameIndex( 1776 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1777 } 1778 1779 // If this is an instruction which fast-isel has deferred, select it now. 1780 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1781 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1782 1783 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1784 Inst->getType(), std::nullopt); 1785 SDValue Chain = DAG.getEntryNode(); 1786 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1787 } 1788 1789 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1790 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1791 1792 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1793 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1794 1795 llvm_unreachable("Can't get register for value!"); 1796 } 1797 1798 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1799 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1800 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1801 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1802 bool IsSEH = isAsynchronousEHPersonality(Pers); 1803 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1804 if (!IsSEH) 1805 CatchPadMBB->setIsEHScopeEntry(); 1806 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1807 if (IsMSVCCXX || IsCoreCLR) 1808 CatchPadMBB->setIsEHFuncletEntry(); 1809 } 1810 1811 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1812 // Update machine-CFG edge. 1813 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1814 FuncInfo.MBB->addSuccessor(TargetMBB); 1815 TargetMBB->setIsEHCatchretTarget(true); 1816 DAG.getMachineFunction().setHasEHCatchret(true); 1817 1818 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1819 bool IsSEH = isAsynchronousEHPersonality(Pers); 1820 if (IsSEH) { 1821 // If this is not a fall-through branch or optimizations are switched off, 1822 // emit the branch. 1823 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1824 TM.getOptLevel() == CodeGenOpt::None) 1825 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1826 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1827 return; 1828 } 1829 1830 // Figure out the funclet membership for the catchret's successor. 1831 // This will be used by the FuncletLayout pass to determine how to order the 1832 // BB's. 1833 // A 'catchret' returns to the outer scope's color. 1834 Value *ParentPad = I.getCatchSwitchParentPad(); 1835 const BasicBlock *SuccessorColor; 1836 if (isa<ConstantTokenNone>(ParentPad)) 1837 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1838 else 1839 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1840 assert(SuccessorColor && "No parent funclet for catchret!"); 1841 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1842 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1843 1844 // Create the terminator node. 1845 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1846 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1847 DAG.getBasicBlock(SuccessorColorMBB)); 1848 DAG.setRoot(Ret); 1849 } 1850 1851 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1852 // Don't emit any special code for the cleanuppad instruction. It just marks 1853 // the start of an EH scope/funclet. 1854 FuncInfo.MBB->setIsEHScopeEntry(); 1855 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1856 if (Pers != EHPersonality::Wasm_CXX) { 1857 FuncInfo.MBB->setIsEHFuncletEntry(); 1858 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1859 } 1860 } 1861 1862 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1863 // not match, it is OK to add only the first unwind destination catchpad to the 1864 // successors, because there will be at least one invoke instruction within the 1865 // catch scope that points to the next unwind destination, if one exists, so 1866 // CFGSort cannot mess up with BB sorting order. 1867 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1868 // call within them, and catchpads only consisting of 'catch (...)' have a 1869 // '__cxa_end_catch' call within them, both of which generate invokes in case 1870 // the next unwind destination exists, i.e., the next unwind destination is not 1871 // the caller.) 1872 // 1873 // Having at most one EH pad successor is also simpler and helps later 1874 // transformations. 1875 // 1876 // For example, 1877 // current: 1878 // invoke void @foo to ... unwind label %catch.dispatch 1879 // catch.dispatch: 1880 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1881 // catch.start: 1882 // ... 1883 // ... in this BB or some other child BB dominated by this BB there will be an 1884 // invoke that points to 'next' BB as an unwind destination 1885 // 1886 // next: ; We don't need to add this to 'current' BB's successor 1887 // ... 1888 static void findWasmUnwindDestinations( 1889 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1890 BranchProbability Prob, 1891 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1892 &UnwindDests) { 1893 while (EHPadBB) { 1894 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1895 if (isa<CleanupPadInst>(Pad)) { 1896 // Stop on cleanup pads. 1897 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1898 UnwindDests.back().first->setIsEHScopeEntry(); 1899 break; 1900 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1901 // Add the catchpad handlers to the possible destinations. We don't 1902 // continue to the unwind destination of the catchswitch for wasm. 1903 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1904 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1905 UnwindDests.back().first->setIsEHScopeEntry(); 1906 } 1907 break; 1908 } else { 1909 continue; 1910 } 1911 } 1912 } 1913 1914 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1915 /// many places it could ultimately go. In the IR, we have a single unwind 1916 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1917 /// This function skips over imaginary basic blocks that hold catchswitch 1918 /// instructions, and finds all the "real" machine 1919 /// basic block destinations. As those destinations may not be successors of 1920 /// EHPadBB, here we also calculate the edge probability to those destinations. 1921 /// The passed-in Prob is the edge probability to EHPadBB. 1922 static void findUnwindDestinations( 1923 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1924 BranchProbability Prob, 1925 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1926 &UnwindDests) { 1927 EHPersonality Personality = 1928 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1929 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1930 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1931 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1932 bool IsSEH = isAsynchronousEHPersonality(Personality); 1933 1934 if (IsWasmCXX) { 1935 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1936 assert(UnwindDests.size() <= 1 && 1937 "There should be at most one unwind destination for wasm"); 1938 return; 1939 } 1940 1941 while (EHPadBB) { 1942 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1943 BasicBlock *NewEHPadBB = nullptr; 1944 if (isa<LandingPadInst>(Pad)) { 1945 // Stop on landingpads. They are not funclets. 1946 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1947 break; 1948 } else if (isa<CleanupPadInst>(Pad)) { 1949 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1950 // personalities. 1951 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1952 UnwindDests.back().first->setIsEHScopeEntry(); 1953 UnwindDests.back().first->setIsEHFuncletEntry(); 1954 break; 1955 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1956 // Add the catchpad handlers to the possible destinations. 1957 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1958 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1959 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1960 if (IsMSVCCXX || IsCoreCLR) 1961 UnwindDests.back().first->setIsEHFuncletEntry(); 1962 if (!IsSEH) 1963 UnwindDests.back().first->setIsEHScopeEntry(); 1964 } 1965 NewEHPadBB = CatchSwitch->getUnwindDest(); 1966 } else { 1967 continue; 1968 } 1969 1970 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1971 if (BPI && NewEHPadBB) 1972 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1973 EHPadBB = NewEHPadBB; 1974 } 1975 } 1976 1977 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1978 // Update successor info. 1979 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1980 auto UnwindDest = I.getUnwindDest(); 1981 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1982 BranchProbability UnwindDestProb = 1983 (BPI && UnwindDest) 1984 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1985 : BranchProbability::getZero(); 1986 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1987 for (auto &UnwindDest : UnwindDests) { 1988 UnwindDest.first->setIsEHPad(); 1989 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1990 } 1991 FuncInfo.MBB->normalizeSuccProbs(); 1992 1993 // Create the terminator node. 1994 SDValue Ret = 1995 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1996 DAG.setRoot(Ret); 1997 } 1998 1999 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2000 report_fatal_error("visitCatchSwitch not yet implemented!"); 2001 } 2002 2003 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2004 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2005 auto &DL = DAG.getDataLayout(); 2006 SDValue Chain = getControlRoot(); 2007 SmallVector<ISD::OutputArg, 8> Outs; 2008 SmallVector<SDValue, 8> OutVals; 2009 2010 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2011 // lower 2012 // 2013 // %val = call <ty> @llvm.experimental.deoptimize() 2014 // ret <ty> %val 2015 // 2016 // differently. 2017 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2018 LowerDeoptimizingReturn(); 2019 return; 2020 } 2021 2022 if (!FuncInfo.CanLowerReturn) { 2023 unsigned DemoteReg = FuncInfo.DemoteRegister; 2024 const Function *F = I.getParent()->getParent(); 2025 2026 // Emit a store of the return value through the virtual register. 2027 // Leave Outs empty so that LowerReturn won't try to load return 2028 // registers the usual way. 2029 SmallVector<EVT, 1> PtrValueVTs; 2030 ComputeValueVTs(TLI, DL, 2031 F->getReturnType()->getPointerTo( 2032 DAG.getDataLayout().getAllocaAddrSpace()), 2033 PtrValueVTs); 2034 2035 SDValue RetPtr = 2036 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2037 SDValue RetOp = getValue(I.getOperand(0)); 2038 2039 SmallVector<EVT, 4> ValueVTs, MemVTs; 2040 SmallVector<uint64_t, 4> Offsets; 2041 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2042 &Offsets, 0); 2043 unsigned NumValues = ValueVTs.size(); 2044 2045 SmallVector<SDValue, 4> Chains(NumValues); 2046 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2047 for (unsigned i = 0; i != NumValues; ++i) { 2048 // An aggregate return value cannot wrap around the address space, so 2049 // offsets to its parts don't wrap either. 2050 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2051 TypeSize::Fixed(Offsets[i])); 2052 2053 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2054 if (MemVTs[i] != ValueVTs[i]) 2055 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2056 Chains[i] = DAG.getStore( 2057 Chain, getCurSDLoc(), Val, 2058 // FIXME: better loc info would be nice. 2059 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2060 commonAlignment(BaseAlign, Offsets[i])); 2061 } 2062 2063 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2064 MVT::Other, Chains); 2065 } else if (I.getNumOperands() != 0) { 2066 SmallVector<EVT, 4> ValueVTs; 2067 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2068 unsigned NumValues = ValueVTs.size(); 2069 if (NumValues) { 2070 SDValue RetOp = getValue(I.getOperand(0)); 2071 2072 const Function *F = I.getParent()->getParent(); 2073 2074 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2075 I.getOperand(0)->getType(), F->getCallingConv(), 2076 /*IsVarArg*/ false, DL); 2077 2078 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2079 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2080 ExtendKind = ISD::SIGN_EXTEND; 2081 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2082 ExtendKind = ISD::ZERO_EXTEND; 2083 2084 LLVMContext &Context = F->getContext(); 2085 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2086 2087 for (unsigned j = 0; j != NumValues; ++j) { 2088 EVT VT = ValueVTs[j]; 2089 2090 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2091 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2092 2093 CallingConv::ID CC = F->getCallingConv(); 2094 2095 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2096 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2097 SmallVector<SDValue, 4> Parts(NumParts); 2098 getCopyToParts(DAG, getCurSDLoc(), 2099 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2100 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2101 2102 // 'inreg' on function refers to return value 2103 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2104 if (RetInReg) 2105 Flags.setInReg(); 2106 2107 if (I.getOperand(0)->getType()->isPointerTy()) { 2108 Flags.setPointer(); 2109 Flags.setPointerAddrSpace( 2110 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2111 } 2112 2113 if (NeedsRegBlock) { 2114 Flags.setInConsecutiveRegs(); 2115 if (j == NumValues - 1) 2116 Flags.setInConsecutiveRegsLast(); 2117 } 2118 2119 // Propagate extension type if any 2120 if (ExtendKind == ISD::SIGN_EXTEND) 2121 Flags.setSExt(); 2122 else if (ExtendKind == ISD::ZERO_EXTEND) 2123 Flags.setZExt(); 2124 2125 for (unsigned i = 0; i < NumParts; ++i) { 2126 Outs.push_back(ISD::OutputArg(Flags, 2127 Parts[i].getValueType().getSimpleVT(), 2128 VT, /*isfixed=*/true, 0, 0)); 2129 OutVals.push_back(Parts[i]); 2130 } 2131 } 2132 } 2133 } 2134 2135 // Push in swifterror virtual register as the last element of Outs. This makes 2136 // sure swifterror virtual register will be returned in the swifterror 2137 // physical register. 2138 const Function *F = I.getParent()->getParent(); 2139 if (TLI.supportSwiftError() && 2140 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2141 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2142 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2143 Flags.setSwiftError(); 2144 Outs.push_back(ISD::OutputArg( 2145 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2146 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2147 // Create SDNode for the swifterror virtual register. 2148 OutVals.push_back( 2149 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2150 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2151 EVT(TLI.getPointerTy(DL)))); 2152 } 2153 2154 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2155 CallingConv::ID CallConv = 2156 DAG.getMachineFunction().getFunction().getCallingConv(); 2157 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2158 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2159 2160 // Verify that the target's LowerReturn behaved as expected. 2161 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2162 "LowerReturn didn't return a valid chain!"); 2163 2164 // Update the DAG with the new chain value resulting from return lowering. 2165 DAG.setRoot(Chain); 2166 } 2167 2168 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2169 /// created for it, emit nodes to copy the value into the virtual 2170 /// registers. 2171 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2172 // Skip empty types 2173 if (V->getType()->isEmptyTy()) 2174 return; 2175 2176 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2177 if (VMI != FuncInfo.ValueMap.end()) { 2178 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2179 "Unused value assigned virtual registers!"); 2180 CopyValueToVirtualRegister(V, VMI->second); 2181 } 2182 } 2183 2184 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2185 /// the current basic block, add it to ValueMap now so that we'll get a 2186 /// CopyTo/FromReg. 2187 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2188 // No need to export constants. 2189 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2190 2191 // Already exported? 2192 if (FuncInfo.isExportedInst(V)) return; 2193 2194 Register Reg = FuncInfo.InitializeRegForValue(V); 2195 CopyValueToVirtualRegister(V, Reg); 2196 } 2197 2198 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2199 const BasicBlock *FromBB) { 2200 // The operands of the setcc have to be in this block. We don't know 2201 // how to export them from some other block. 2202 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2203 // Can export from current BB. 2204 if (VI->getParent() == FromBB) 2205 return true; 2206 2207 // Is already exported, noop. 2208 return FuncInfo.isExportedInst(V); 2209 } 2210 2211 // If this is an argument, we can export it if the BB is the entry block or 2212 // if it is already exported. 2213 if (isa<Argument>(V)) { 2214 if (FromBB->isEntryBlock()) 2215 return true; 2216 2217 // Otherwise, can only export this if it is already exported. 2218 return FuncInfo.isExportedInst(V); 2219 } 2220 2221 // Otherwise, constants can always be exported. 2222 return true; 2223 } 2224 2225 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2226 BranchProbability 2227 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2228 const MachineBasicBlock *Dst) const { 2229 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2230 const BasicBlock *SrcBB = Src->getBasicBlock(); 2231 const BasicBlock *DstBB = Dst->getBasicBlock(); 2232 if (!BPI) { 2233 // If BPI is not available, set the default probability as 1 / N, where N is 2234 // the number of successors. 2235 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2236 return BranchProbability(1, SuccSize); 2237 } 2238 return BPI->getEdgeProbability(SrcBB, DstBB); 2239 } 2240 2241 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2242 MachineBasicBlock *Dst, 2243 BranchProbability Prob) { 2244 if (!FuncInfo.BPI) 2245 Src->addSuccessorWithoutProb(Dst); 2246 else { 2247 if (Prob.isUnknown()) 2248 Prob = getEdgeProbability(Src, Dst); 2249 Src->addSuccessor(Dst, Prob); 2250 } 2251 } 2252 2253 static bool InBlock(const Value *V, const BasicBlock *BB) { 2254 if (const Instruction *I = dyn_cast<Instruction>(V)) 2255 return I->getParent() == BB; 2256 return true; 2257 } 2258 2259 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2260 /// This function emits a branch and is used at the leaves of an OR or an 2261 /// AND operator tree. 2262 void 2263 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2264 MachineBasicBlock *TBB, 2265 MachineBasicBlock *FBB, 2266 MachineBasicBlock *CurBB, 2267 MachineBasicBlock *SwitchBB, 2268 BranchProbability TProb, 2269 BranchProbability FProb, 2270 bool InvertCond) { 2271 const BasicBlock *BB = CurBB->getBasicBlock(); 2272 2273 // If the leaf of the tree is a comparison, merge the condition into 2274 // the caseblock. 2275 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2276 // The operands of the cmp have to be in this block. We don't know 2277 // how to export them from some other block. If this is the first block 2278 // of the sequence, no exporting is needed. 2279 if (CurBB == SwitchBB || 2280 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2281 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2282 ISD::CondCode Condition; 2283 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2284 ICmpInst::Predicate Pred = 2285 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2286 Condition = getICmpCondCode(Pred); 2287 } else { 2288 const FCmpInst *FC = cast<FCmpInst>(Cond); 2289 FCmpInst::Predicate Pred = 2290 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2291 Condition = getFCmpCondCode(Pred); 2292 if (TM.Options.NoNaNsFPMath) 2293 Condition = getFCmpCodeWithoutNaN(Condition); 2294 } 2295 2296 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2297 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2298 SL->SwitchCases.push_back(CB); 2299 return; 2300 } 2301 } 2302 2303 // Create a CaseBlock record representing this branch. 2304 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2305 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2306 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2307 SL->SwitchCases.push_back(CB); 2308 } 2309 2310 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2311 MachineBasicBlock *TBB, 2312 MachineBasicBlock *FBB, 2313 MachineBasicBlock *CurBB, 2314 MachineBasicBlock *SwitchBB, 2315 Instruction::BinaryOps Opc, 2316 BranchProbability TProb, 2317 BranchProbability FProb, 2318 bool InvertCond) { 2319 // Skip over not part of the tree and remember to invert op and operands at 2320 // next level. 2321 Value *NotCond; 2322 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2323 InBlock(NotCond, CurBB->getBasicBlock())) { 2324 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2325 !InvertCond); 2326 return; 2327 } 2328 2329 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2330 const Value *BOpOp0, *BOpOp1; 2331 // Compute the effective opcode for Cond, taking into account whether it needs 2332 // to be inverted, e.g. 2333 // and (not (or A, B)), C 2334 // gets lowered as 2335 // and (and (not A, not B), C) 2336 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2337 if (BOp) { 2338 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2339 ? Instruction::And 2340 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2341 ? Instruction::Or 2342 : (Instruction::BinaryOps)0); 2343 if (InvertCond) { 2344 if (BOpc == Instruction::And) 2345 BOpc = Instruction::Or; 2346 else if (BOpc == Instruction::Or) 2347 BOpc = Instruction::And; 2348 } 2349 } 2350 2351 // If this node is not part of the or/and tree, emit it as a branch. 2352 // Note that all nodes in the tree should have same opcode. 2353 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2354 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2355 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2356 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2357 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2358 TProb, FProb, InvertCond); 2359 return; 2360 } 2361 2362 // Create TmpBB after CurBB. 2363 MachineFunction::iterator BBI(CurBB); 2364 MachineFunction &MF = DAG.getMachineFunction(); 2365 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2366 CurBB->getParent()->insert(++BBI, TmpBB); 2367 2368 if (Opc == Instruction::Or) { 2369 // Codegen X | Y as: 2370 // BB1: 2371 // jmp_if_X TBB 2372 // jmp TmpBB 2373 // TmpBB: 2374 // jmp_if_Y TBB 2375 // jmp FBB 2376 // 2377 2378 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2379 // The requirement is that 2380 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2381 // = TrueProb for original BB. 2382 // Assuming the original probabilities are A and B, one choice is to set 2383 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2384 // A/(1+B) and 2B/(1+B). This choice assumes that 2385 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2386 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2387 // TmpBB, but the math is more complicated. 2388 2389 auto NewTrueProb = TProb / 2; 2390 auto NewFalseProb = TProb / 2 + FProb; 2391 // Emit the LHS condition. 2392 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2393 NewFalseProb, InvertCond); 2394 2395 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2396 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2397 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2398 // Emit the RHS condition into TmpBB. 2399 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2400 Probs[1], InvertCond); 2401 } else { 2402 assert(Opc == Instruction::And && "Unknown merge op!"); 2403 // Codegen X & Y as: 2404 // BB1: 2405 // jmp_if_X TmpBB 2406 // jmp FBB 2407 // TmpBB: 2408 // jmp_if_Y TBB 2409 // jmp FBB 2410 // 2411 // This requires creation of TmpBB after CurBB. 2412 2413 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2414 // The requirement is that 2415 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2416 // = FalseProb for original BB. 2417 // Assuming the original probabilities are A and B, one choice is to set 2418 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2419 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2420 // TrueProb for BB1 * FalseProb for TmpBB. 2421 2422 auto NewTrueProb = TProb + FProb / 2; 2423 auto NewFalseProb = FProb / 2; 2424 // Emit the LHS condition. 2425 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2426 NewFalseProb, InvertCond); 2427 2428 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2429 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2430 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2431 // Emit the RHS condition into TmpBB. 2432 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2433 Probs[1], InvertCond); 2434 } 2435 } 2436 2437 /// If the set of cases should be emitted as a series of branches, return true. 2438 /// If we should emit this as a bunch of and/or'd together conditions, return 2439 /// false. 2440 bool 2441 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2442 if (Cases.size() != 2) return true; 2443 2444 // If this is two comparisons of the same values or'd or and'd together, they 2445 // will get folded into a single comparison, so don't emit two blocks. 2446 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2447 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2448 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2449 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2450 return false; 2451 } 2452 2453 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2454 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2455 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2456 Cases[0].CC == Cases[1].CC && 2457 isa<Constant>(Cases[0].CmpRHS) && 2458 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2459 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2460 return false; 2461 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2462 return false; 2463 } 2464 2465 return true; 2466 } 2467 2468 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2469 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2470 2471 // Update machine-CFG edges. 2472 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2473 2474 if (I.isUnconditional()) { 2475 // Update machine-CFG edges. 2476 BrMBB->addSuccessor(Succ0MBB); 2477 2478 // If this is not a fall-through branch or optimizations are switched off, 2479 // emit the branch. 2480 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2481 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2482 MVT::Other, getControlRoot(), 2483 DAG.getBasicBlock(Succ0MBB))); 2484 2485 return; 2486 } 2487 2488 // If this condition is one of the special cases we handle, do special stuff 2489 // now. 2490 const Value *CondVal = I.getCondition(); 2491 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2492 2493 // If this is a series of conditions that are or'd or and'd together, emit 2494 // this as a sequence of branches instead of setcc's with and/or operations. 2495 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2496 // unpredictable branches, and vector extracts because those jumps are likely 2497 // expensive for any target), this should improve performance. 2498 // For example, instead of something like: 2499 // cmp A, B 2500 // C = seteq 2501 // cmp D, E 2502 // F = setle 2503 // or C, F 2504 // jnz foo 2505 // Emit: 2506 // cmp A, B 2507 // je foo 2508 // cmp D, E 2509 // jle foo 2510 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2511 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2512 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2513 Value *Vec; 2514 const Value *BOp0, *BOp1; 2515 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2516 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2517 Opcode = Instruction::And; 2518 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2519 Opcode = Instruction::Or; 2520 2521 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2522 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2523 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2524 getEdgeProbability(BrMBB, Succ0MBB), 2525 getEdgeProbability(BrMBB, Succ1MBB), 2526 /*InvertCond=*/false); 2527 // If the compares in later blocks need to use values not currently 2528 // exported from this block, export them now. This block should always 2529 // be the first entry. 2530 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2531 2532 // Allow some cases to be rejected. 2533 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2534 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2535 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2536 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2537 } 2538 2539 // Emit the branch for this block. 2540 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2541 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2542 return; 2543 } 2544 2545 // Okay, we decided not to do this, remove any inserted MBB's and clear 2546 // SwitchCases. 2547 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2548 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2549 2550 SL->SwitchCases.clear(); 2551 } 2552 } 2553 2554 // Create a CaseBlock record representing this branch. 2555 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2556 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2557 2558 // Use visitSwitchCase to actually insert the fast branch sequence for this 2559 // cond branch. 2560 visitSwitchCase(CB, BrMBB); 2561 } 2562 2563 /// visitSwitchCase - Emits the necessary code to represent a single node in 2564 /// the binary search tree resulting from lowering a switch instruction. 2565 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2566 MachineBasicBlock *SwitchBB) { 2567 SDValue Cond; 2568 SDValue CondLHS = getValue(CB.CmpLHS); 2569 SDLoc dl = CB.DL; 2570 2571 if (CB.CC == ISD::SETTRUE) { 2572 // Branch or fall through to TrueBB. 2573 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2574 SwitchBB->normalizeSuccProbs(); 2575 if (CB.TrueBB != NextBlock(SwitchBB)) { 2576 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2577 DAG.getBasicBlock(CB.TrueBB))); 2578 } 2579 return; 2580 } 2581 2582 auto &TLI = DAG.getTargetLoweringInfo(); 2583 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2584 2585 // Build the setcc now. 2586 if (!CB.CmpMHS) { 2587 // Fold "(X == true)" to X and "(X == false)" to !X to 2588 // handle common cases produced by branch lowering. 2589 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2590 CB.CC == ISD::SETEQ) 2591 Cond = CondLHS; 2592 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2593 CB.CC == ISD::SETEQ) { 2594 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2595 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2596 } else { 2597 SDValue CondRHS = getValue(CB.CmpRHS); 2598 2599 // If a pointer's DAG type is larger than its memory type then the DAG 2600 // values are zero-extended. This breaks signed comparisons so truncate 2601 // back to the underlying type before doing the compare. 2602 if (CondLHS.getValueType() != MemVT) { 2603 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2604 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2605 } 2606 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2607 } 2608 } else { 2609 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2610 2611 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2612 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2613 2614 SDValue CmpOp = getValue(CB.CmpMHS); 2615 EVT VT = CmpOp.getValueType(); 2616 2617 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2618 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2619 ISD::SETLE); 2620 } else { 2621 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2622 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2623 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2624 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2625 } 2626 } 2627 2628 // Update successor info 2629 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2630 // TrueBB and FalseBB are always different unless the incoming IR is 2631 // degenerate. This only happens when running llc on weird IR. 2632 if (CB.TrueBB != CB.FalseBB) 2633 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2634 SwitchBB->normalizeSuccProbs(); 2635 2636 // If the lhs block is the next block, invert the condition so that we can 2637 // fall through to the lhs instead of the rhs block. 2638 if (CB.TrueBB == NextBlock(SwitchBB)) { 2639 std::swap(CB.TrueBB, CB.FalseBB); 2640 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2641 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2642 } 2643 2644 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2645 MVT::Other, getControlRoot(), Cond, 2646 DAG.getBasicBlock(CB.TrueBB)); 2647 2648 setValue(CurInst, BrCond); 2649 2650 // Insert the false branch. Do this even if it's a fall through branch, 2651 // this makes it easier to do DAG optimizations which require inverting 2652 // the branch condition. 2653 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2654 DAG.getBasicBlock(CB.FalseBB)); 2655 2656 DAG.setRoot(BrCond); 2657 } 2658 2659 /// visitJumpTable - Emit JumpTable node in the current MBB 2660 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2661 // Emit the code for the jump table 2662 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2663 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2664 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2665 JT.Reg, PTy); 2666 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2667 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2668 MVT::Other, Index.getValue(1), 2669 Table, Index); 2670 DAG.setRoot(BrJumpTable); 2671 } 2672 2673 /// visitJumpTableHeader - This function emits necessary code to produce index 2674 /// in the JumpTable from switch case. 2675 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2676 JumpTableHeader &JTH, 2677 MachineBasicBlock *SwitchBB) { 2678 SDLoc dl = getCurSDLoc(); 2679 2680 // Subtract the lowest switch case value from the value being switched on. 2681 SDValue SwitchOp = getValue(JTH.SValue); 2682 EVT VT = SwitchOp.getValueType(); 2683 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2684 DAG.getConstant(JTH.First, dl, VT)); 2685 2686 // The SDNode we just created, which holds the value being switched on minus 2687 // the smallest case value, needs to be copied to a virtual register so it 2688 // can be used as an index into the jump table in a subsequent basic block. 2689 // This value may be smaller or larger than the target's pointer type, and 2690 // therefore require extension or truncating. 2691 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2692 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2693 2694 unsigned JumpTableReg = 2695 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2696 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2697 JumpTableReg, SwitchOp); 2698 JT.Reg = JumpTableReg; 2699 2700 if (!JTH.FallthroughUnreachable) { 2701 // Emit the range check for the jump table, and branch to the default block 2702 // for the switch statement if the value being switched on exceeds the 2703 // largest case in the switch. 2704 SDValue CMP = DAG.getSetCC( 2705 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2706 Sub.getValueType()), 2707 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2708 2709 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2710 MVT::Other, CopyTo, CMP, 2711 DAG.getBasicBlock(JT.Default)); 2712 2713 // Avoid emitting unnecessary branches to the next block. 2714 if (JT.MBB != NextBlock(SwitchBB)) 2715 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2716 DAG.getBasicBlock(JT.MBB)); 2717 2718 DAG.setRoot(BrCond); 2719 } else { 2720 // Avoid emitting unnecessary branches to the next block. 2721 if (JT.MBB != NextBlock(SwitchBB)) 2722 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2723 DAG.getBasicBlock(JT.MBB))); 2724 else 2725 DAG.setRoot(CopyTo); 2726 } 2727 } 2728 2729 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2730 /// variable if there exists one. 2731 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2732 SDValue &Chain) { 2733 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2734 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2735 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2736 MachineFunction &MF = DAG.getMachineFunction(); 2737 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2738 MachineSDNode *Node = 2739 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2740 if (Global) { 2741 MachinePointerInfo MPInfo(Global); 2742 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2743 MachineMemOperand::MODereferenceable; 2744 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2745 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2746 DAG.setNodeMemRefs(Node, {MemRef}); 2747 } 2748 if (PtrTy != PtrMemTy) 2749 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2750 return SDValue(Node, 0); 2751 } 2752 2753 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2754 /// tail spliced into a stack protector check success bb. 2755 /// 2756 /// For a high level explanation of how this fits into the stack protector 2757 /// generation see the comment on the declaration of class 2758 /// StackProtectorDescriptor. 2759 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2760 MachineBasicBlock *ParentBB) { 2761 2762 // First create the loads to the guard/stack slot for the comparison. 2763 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2764 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2765 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2766 2767 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2768 int FI = MFI.getStackProtectorIndex(); 2769 2770 SDValue Guard; 2771 SDLoc dl = getCurSDLoc(); 2772 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2773 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2774 Align Align = 2775 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2776 2777 // Generate code to load the content of the guard slot. 2778 SDValue GuardVal = DAG.getLoad( 2779 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2780 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2781 MachineMemOperand::MOVolatile); 2782 2783 if (TLI.useStackGuardXorFP()) 2784 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2785 2786 // Retrieve guard check function, nullptr if instrumentation is inlined. 2787 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2788 // The target provides a guard check function to validate the guard value. 2789 // Generate a call to that function with the content of the guard slot as 2790 // argument. 2791 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2792 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2793 2794 TargetLowering::ArgListTy Args; 2795 TargetLowering::ArgListEntry Entry; 2796 Entry.Node = GuardVal; 2797 Entry.Ty = FnTy->getParamType(0); 2798 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2799 Entry.IsInReg = true; 2800 Args.push_back(Entry); 2801 2802 TargetLowering::CallLoweringInfo CLI(DAG); 2803 CLI.setDebugLoc(getCurSDLoc()) 2804 .setChain(DAG.getEntryNode()) 2805 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2806 getValue(GuardCheckFn), std::move(Args)); 2807 2808 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2809 DAG.setRoot(Result.second); 2810 return; 2811 } 2812 2813 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2814 // Otherwise, emit a volatile load to retrieve the stack guard value. 2815 SDValue Chain = DAG.getEntryNode(); 2816 if (TLI.useLoadStackGuardNode()) { 2817 Guard = getLoadStackGuard(DAG, dl, Chain); 2818 } else { 2819 const Value *IRGuard = TLI.getSDagStackGuard(M); 2820 SDValue GuardPtr = getValue(IRGuard); 2821 2822 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2823 MachinePointerInfo(IRGuard, 0), Align, 2824 MachineMemOperand::MOVolatile); 2825 } 2826 2827 // Perform the comparison via a getsetcc. 2828 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2829 *DAG.getContext(), 2830 Guard.getValueType()), 2831 Guard, GuardVal, ISD::SETNE); 2832 2833 // If the guard/stackslot do not equal, branch to failure MBB. 2834 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2835 MVT::Other, GuardVal.getOperand(0), 2836 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2837 // Otherwise branch to success MBB. 2838 SDValue Br = DAG.getNode(ISD::BR, dl, 2839 MVT::Other, BrCond, 2840 DAG.getBasicBlock(SPD.getSuccessMBB())); 2841 2842 DAG.setRoot(Br); 2843 } 2844 2845 /// Codegen the failure basic block for a stack protector check. 2846 /// 2847 /// A failure stack protector machine basic block consists simply of a call to 2848 /// __stack_chk_fail(). 2849 /// 2850 /// For a high level explanation of how this fits into the stack protector 2851 /// generation see the comment on the declaration of class 2852 /// StackProtectorDescriptor. 2853 void 2854 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2855 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2856 TargetLowering::MakeLibCallOptions CallOptions; 2857 CallOptions.setDiscardResult(true); 2858 SDValue Chain = 2859 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2860 std::nullopt, CallOptions, getCurSDLoc()) 2861 .second; 2862 // On PS4/PS5, the "return address" must still be within the calling 2863 // function, even if it's at the very end, so emit an explicit TRAP here. 2864 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2865 if (TM.getTargetTriple().isPS()) 2866 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2867 // WebAssembly needs an unreachable instruction after a non-returning call, 2868 // because the function return type can be different from __stack_chk_fail's 2869 // return type (void). 2870 if (TM.getTargetTriple().isWasm()) 2871 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2872 2873 DAG.setRoot(Chain); 2874 } 2875 2876 /// visitBitTestHeader - This function emits necessary code to produce value 2877 /// suitable for "bit tests" 2878 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2879 MachineBasicBlock *SwitchBB) { 2880 SDLoc dl = getCurSDLoc(); 2881 2882 // Subtract the minimum value. 2883 SDValue SwitchOp = getValue(B.SValue); 2884 EVT VT = SwitchOp.getValueType(); 2885 SDValue RangeSub = 2886 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2887 2888 // Determine the type of the test operands. 2889 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2890 bool UsePtrType = false; 2891 if (!TLI.isTypeLegal(VT)) { 2892 UsePtrType = true; 2893 } else { 2894 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2895 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2896 // Switch table case range are encoded into series of masks. 2897 // Just use pointer type, it's guaranteed to fit. 2898 UsePtrType = true; 2899 break; 2900 } 2901 } 2902 SDValue Sub = RangeSub; 2903 if (UsePtrType) { 2904 VT = TLI.getPointerTy(DAG.getDataLayout()); 2905 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2906 } 2907 2908 B.RegVT = VT.getSimpleVT(); 2909 B.Reg = FuncInfo.CreateReg(B.RegVT); 2910 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2911 2912 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2913 2914 if (!B.FallthroughUnreachable) 2915 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2916 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2917 SwitchBB->normalizeSuccProbs(); 2918 2919 SDValue Root = CopyTo; 2920 if (!B.FallthroughUnreachable) { 2921 // Conditional branch to the default block. 2922 SDValue RangeCmp = DAG.getSetCC(dl, 2923 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2924 RangeSub.getValueType()), 2925 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2926 ISD::SETUGT); 2927 2928 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2929 DAG.getBasicBlock(B.Default)); 2930 } 2931 2932 // Avoid emitting unnecessary branches to the next block. 2933 if (MBB != NextBlock(SwitchBB)) 2934 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2935 2936 DAG.setRoot(Root); 2937 } 2938 2939 /// visitBitTestCase - this function produces one "bit test" 2940 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2941 MachineBasicBlock* NextMBB, 2942 BranchProbability BranchProbToNext, 2943 unsigned Reg, 2944 BitTestCase &B, 2945 MachineBasicBlock *SwitchBB) { 2946 SDLoc dl = getCurSDLoc(); 2947 MVT VT = BB.RegVT; 2948 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2949 SDValue Cmp; 2950 unsigned PopCount = llvm::popcount(B.Mask); 2951 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2952 if (PopCount == 1) { 2953 // Testing for a single bit; just compare the shift count with what it 2954 // would need to be to shift a 1 bit in that position. 2955 Cmp = DAG.getSetCC( 2956 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2957 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 2958 ISD::SETEQ); 2959 } else if (PopCount == BB.Range) { 2960 // There is only one zero bit in the range, test for it directly. 2961 Cmp = DAG.getSetCC( 2962 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2963 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 2964 } else { 2965 // Make desired shift 2966 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2967 DAG.getConstant(1, dl, VT), ShiftOp); 2968 2969 // Emit bit tests and jumps 2970 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2971 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2972 Cmp = DAG.getSetCC( 2973 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2974 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2975 } 2976 2977 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2978 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2979 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2980 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2981 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2982 // one as they are relative probabilities (and thus work more like weights), 2983 // and hence we need to normalize them to let the sum of them become one. 2984 SwitchBB->normalizeSuccProbs(); 2985 2986 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2987 MVT::Other, getControlRoot(), 2988 Cmp, DAG.getBasicBlock(B.TargetBB)); 2989 2990 // Avoid emitting unnecessary branches to the next block. 2991 if (NextMBB != NextBlock(SwitchBB)) 2992 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2993 DAG.getBasicBlock(NextMBB)); 2994 2995 DAG.setRoot(BrAnd); 2996 } 2997 2998 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2999 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3000 3001 // Retrieve successors. Look through artificial IR level blocks like 3002 // catchswitch for successors. 3003 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 3004 const BasicBlock *EHPadBB = I.getSuccessor(1); 3005 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 3006 3007 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3008 // have to do anything here to lower funclet bundles. 3009 assert(!I.hasOperandBundlesOtherThan( 3010 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3011 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3012 LLVMContext::OB_cfguardtarget, 3013 LLVMContext::OB_clang_arc_attachedcall}) && 3014 "Cannot lower invokes with arbitrary operand bundles yet!"); 3015 3016 const Value *Callee(I.getCalledOperand()); 3017 const Function *Fn = dyn_cast<Function>(Callee); 3018 if (isa<InlineAsm>(Callee)) 3019 visitInlineAsm(I, EHPadBB); 3020 else if (Fn && Fn->isIntrinsic()) { 3021 switch (Fn->getIntrinsicID()) { 3022 default: 3023 llvm_unreachable("Cannot invoke this intrinsic"); 3024 case Intrinsic::donothing: 3025 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3026 case Intrinsic::seh_try_begin: 3027 case Intrinsic::seh_scope_begin: 3028 case Intrinsic::seh_try_end: 3029 case Intrinsic::seh_scope_end: 3030 if (EHPadMBB) 3031 // a block referenced by EH table 3032 // so dtor-funclet not removed by opts 3033 EHPadMBB->setMachineBlockAddressTaken(); 3034 break; 3035 case Intrinsic::experimental_patchpoint_void: 3036 case Intrinsic::experimental_patchpoint_i64: 3037 visitPatchpoint(I, EHPadBB); 3038 break; 3039 case Intrinsic::experimental_gc_statepoint: 3040 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3041 break; 3042 case Intrinsic::wasm_rethrow: { 3043 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3044 // special because it can be invoked, so we manually lower it to a DAG 3045 // node here. 3046 SmallVector<SDValue, 8> Ops; 3047 Ops.push_back(getRoot()); // inchain 3048 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3049 Ops.push_back( 3050 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3051 TLI.getPointerTy(DAG.getDataLayout()))); 3052 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3053 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3054 break; 3055 } 3056 } 3057 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3058 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3059 // Eventually we will support lowering the @llvm.experimental.deoptimize 3060 // intrinsic, and right now there are no plans to support other intrinsics 3061 // with deopt state. 3062 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3063 } else { 3064 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3065 } 3066 3067 // If the value of the invoke is used outside of its defining block, make it 3068 // available as a virtual register. 3069 // We already took care of the exported value for the statepoint instruction 3070 // during call to the LowerStatepoint. 3071 if (!isa<GCStatepointInst>(I)) { 3072 CopyToExportRegsIfNeeded(&I); 3073 } 3074 3075 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3076 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3077 BranchProbability EHPadBBProb = 3078 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3079 : BranchProbability::getZero(); 3080 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3081 3082 // Update successor info. 3083 addSuccessorWithProb(InvokeMBB, Return); 3084 for (auto &UnwindDest : UnwindDests) { 3085 UnwindDest.first->setIsEHPad(); 3086 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3087 } 3088 InvokeMBB->normalizeSuccProbs(); 3089 3090 // Drop into normal successor. 3091 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3092 DAG.getBasicBlock(Return))); 3093 } 3094 3095 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3096 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3097 3098 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3099 // have to do anything here to lower funclet bundles. 3100 assert(!I.hasOperandBundlesOtherThan( 3101 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3102 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3103 3104 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3105 visitInlineAsm(I); 3106 CopyToExportRegsIfNeeded(&I); 3107 3108 // Retrieve successors. 3109 SmallPtrSet<BasicBlock *, 8> Dests; 3110 Dests.insert(I.getDefaultDest()); 3111 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3112 3113 // Update successor info. 3114 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3115 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3116 BasicBlock *Dest = I.getIndirectDest(i); 3117 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3118 Target->setIsInlineAsmBrIndirectTarget(); 3119 Target->setMachineBlockAddressTaken(); 3120 Target->setLabelMustBeEmitted(); 3121 // Don't add duplicate machine successors. 3122 if (Dests.insert(Dest).second) 3123 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3124 } 3125 CallBrMBB->normalizeSuccProbs(); 3126 3127 // Drop into default successor. 3128 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3129 MVT::Other, getControlRoot(), 3130 DAG.getBasicBlock(Return))); 3131 } 3132 3133 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3134 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3135 } 3136 3137 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3138 assert(FuncInfo.MBB->isEHPad() && 3139 "Call to landingpad not in landing pad!"); 3140 3141 // If there aren't registers to copy the values into (e.g., during SjLj 3142 // exceptions), then don't bother to create these DAG nodes. 3143 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3144 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3145 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3146 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3147 return; 3148 3149 // If landingpad's return type is token type, we don't create DAG nodes 3150 // for its exception pointer and selector value. The extraction of exception 3151 // pointer or selector value from token type landingpads is not currently 3152 // supported. 3153 if (LP.getType()->isTokenTy()) 3154 return; 3155 3156 SmallVector<EVT, 2> ValueVTs; 3157 SDLoc dl = getCurSDLoc(); 3158 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3159 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3160 3161 // Get the two live-in registers as SDValues. The physregs have already been 3162 // copied into virtual registers. 3163 SDValue Ops[2]; 3164 if (FuncInfo.ExceptionPointerVirtReg) { 3165 Ops[0] = DAG.getZExtOrTrunc( 3166 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3167 FuncInfo.ExceptionPointerVirtReg, 3168 TLI.getPointerTy(DAG.getDataLayout())), 3169 dl, ValueVTs[0]); 3170 } else { 3171 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3172 } 3173 Ops[1] = DAG.getZExtOrTrunc( 3174 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3175 FuncInfo.ExceptionSelectorVirtReg, 3176 TLI.getPointerTy(DAG.getDataLayout())), 3177 dl, ValueVTs[1]); 3178 3179 // Merge into one. 3180 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3181 DAG.getVTList(ValueVTs), Ops); 3182 setValue(&LP, Res); 3183 } 3184 3185 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3186 MachineBasicBlock *Last) { 3187 // Update JTCases. 3188 for (JumpTableBlock &JTB : SL->JTCases) 3189 if (JTB.first.HeaderBB == First) 3190 JTB.first.HeaderBB = Last; 3191 3192 // Update BitTestCases. 3193 for (BitTestBlock &BTB : SL->BitTestCases) 3194 if (BTB.Parent == First) 3195 BTB.Parent = Last; 3196 } 3197 3198 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3199 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3200 3201 // Update machine-CFG edges with unique successors. 3202 SmallSet<BasicBlock*, 32> Done; 3203 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3204 BasicBlock *BB = I.getSuccessor(i); 3205 bool Inserted = Done.insert(BB).second; 3206 if (!Inserted) 3207 continue; 3208 3209 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3210 addSuccessorWithProb(IndirectBrMBB, Succ); 3211 } 3212 IndirectBrMBB->normalizeSuccProbs(); 3213 3214 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3215 MVT::Other, getControlRoot(), 3216 getValue(I.getAddress()))); 3217 } 3218 3219 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3220 if (!DAG.getTarget().Options.TrapUnreachable) 3221 return; 3222 3223 // We may be able to ignore unreachable behind a noreturn call. 3224 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3225 const BasicBlock &BB = *I.getParent(); 3226 if (&I != &BB.front()) { 3227 BasicBlock::const_iterator PredI = 3228 std::prev(BasicBlock::const_iterator(&I)); 3229 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3230 if (Call->doesNotReturn()) 3231 return; 3232 } 3233 } 3234 } 3235 3236 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3237 } 3238 3239 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3240 SDNodeFlags Flags; 3241 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3242 Flags.copyFMF(*FPOp); 3243 3244 SDValue Op = getValue(I.getOperand(0)); 3245 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3246 Op, Flags); 3247 setValue(&I, UnNodeValue); 3248 } 3249 3250 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3251 SDNodeFlags Flags; 3252 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3253 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3254 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3255 } 3256 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3257 Flags.setExact(ExactOp->isExact()); 3258 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3259 Flags.copyFMF(*FPOp); 3260 3261 SDValue Op1 = getValue(I.getOperand(0)); 3262 SDValue Op2 = getValue(I.getOperand(1)); 3263 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3264 Op1, Op2, Flags); 3265 setValue(&I, BinNodeValue); 3266 } 3267 3268 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3269 SDValue Op1 = getValue(I.getOperand(0)); 3270 SDValue Op2 = getValue(I.getOperand(1)); 3271 3272 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3273 Op1.getValueType(), DAG.getDataLayout()); 3274 3275 // Coerce the shift amount to the right type if we can. This exposes the 3276 // truncate or zext to optimization early. 3277 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3278 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3279 "Unexpected shift type"); 3280 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3281 } 3282 3283 bool nuw = false; 3284 bool nsw = false; 3285 bool exact = false; 3286 3287 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3288 3289 if (const OverflowingBinaryOperator *OFBinOp = 3290 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3291 nuw = OFBinOp->hasNoUnsignedWrap(); 3292 nsw = OFBinOp->hasNoSignedWrap(); 3293 } 3294 if (const PossiblyExactOperator *ExactOp = 3295 dyn_cast<const PossiblyExactOperator>(&I)) 3296 exact = ExactOp->isExact(); 3297 } 3298 SDNodeFlags Flags; 3299 Flags.setExact(exact); 3300 Flags.setNoSignedWrap(nsw); 3301 Flags.setNoUnsignedWrap(nuw); 3302 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3303 Flags); 3304 setValue(&I, Res); 3305 } 3306 3307 void SelectionDAGBuilder::visitSDiv(const User &I) { 3308 SDValue Op1 = getValue(I.getOperand(0)); 3309 SDValue Op2 = getValue(I.getOperand(1)); 3310 3311 SDNodeFlags Flags; 3312 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3313 cast<PossiblyExactOperator>(&I)->isExact()); 3314 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3315 Op2, Flags)); 3316 } 3317 3318 void SelectionDAGBuilder::visitICmp(const User &I) { 3319 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3320 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3321 predicate = IC->getPredicate(); 3322 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3323 predicate = ICmpInst::Predicate(IC->getPredicate()); 3324 SDValue Op1 = getValue(I.getOperand(0)); 3325 SDValue Op2 = getValue(I.getOperand(1)); 3326 ISD::CondCode Opcode = getICmpCondCode(predicate); 3327 3328 auto &TLI = DAG.getTargetLoweringInfo(); 3329 EVT MemVT = 3330 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3331 3332 // If a pointer's DAG type is larger than its memory type then the DAG values 3333 // are zero-extended. This breaks signed comparisons so truncate back to the 3334 // underlying type before doing the compare. 3335 if (Op1.getValueType() != MemVT) { 3336 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3337 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3338 } 3339 3340 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3341 I.getType()); 3342 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3343 } 3344 3345 void SelectionDAGBuilder::visitFCmp(const User &I) { 3346 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3347 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3348 predicate = FC->getPredicate(); 3349 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3350 predicate = FCmpInst::Predicate(FC->getPredicate()); 3351 SDValue Op1 = getValue(I.getOperand(0)); 3352 SDValue Op2 = getValue(I.getOperand(1)); 3353 3354 ISD::CondCode Condition = getFCmpCondCode(predicate); 3355 auto *FPMO = cast<FPMathOperator>(&I); 3356 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3357 Condition = getFCmpCodeWithoutNaN(Condition); 3358 3359 SDNodeFlags Flags; 3360 Flags.copyFMF(*FPMO); 3361 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3362 3363 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3364 I.getType()); 3365 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3366 } 3367 3368 // Check if the condition of the select has one use or two users that are both 3369 // selects with the same condition. 3370 static bool hasOnlySelectUsers(const Value *Cond) { 3371 return llvm::all_of(Cond->users(), [](const Value *V) { 3372 return isa<SelectInst>(V); 3373 }); 3374 } 3375 3376 void SelectionDAGBuilder::visitSelect(const User &I) { 3377 SmallVector<EVT, 4> ValueVTs; 3378 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3379 ValueVTs); 3380 unsigned NumValues = ValueVTs.size(); 3381 if (NumValues == 0) return; 3382 3383 SmallVector<SDValue, 4> Values(NumValues); 3384 SDValue Cond = getValue(I.getOperand(0)); 3385 SDValue LHSVal = getValue(I.getOperand(1)); 3386 SDValue RHSVal = getValue(I.getOperand(2)); 3387 SmallVector<SDValue, 1> BaseOps(1, Cond); 3388 ISD::NodeType OpCode = 3389 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3390 3391 bool IsUnaryAbs = false; 3392 bool Negate = false; 3393 3394 SDNodeFlags Flags; 3395 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3396 Flags.copyFMF(*FPOp); 3397 3398 Flags.setUnpredictable( 3399 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3400 3401 // Min/max matching is only viable if all output VTs are the same. 3402 if (all_equal(ValueVTs)) { 3403 EVT VT = ValueVTs[0]; 3404 LLVMContext &Ctx = *DAG.getContext(); 3405 auto &TLI = DAG.getTargetLoweringInfo(); 3406 3407 // We care about the legality of the operation after it has been type 3408 // legalized. 3409 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3410 VT = TLI.getTypeToTransformTo(Ctx, VT); 3411 3412 // If the vselect is legal, assume we want to leave this as a vector setcc + 3413 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3414 // min/max is legal on the scalar type. 3415 bool UseScalarMinMax = VT.isVector() && 3416 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3417 3418 // ValueTracking's select pattern matching does not account for -0.0, 3419 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3420 // -0.0 is less than +0.0. 3421 Value *LHS, *RHS; 3422 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3423 ISD::NodeType Opc = ISD::DELETED_NODE; 3424 switch (SPR.Flavor) { 3425 case SPF_UMAX: Opc = ISD::UMAX; break; 3426 case SPF_UMIN: Opc = ISD::UMIN; break; 3427 case SPF_SMAX: Opc = ISD::SMAX; break; 3428 case SPF_SMIN: Opc = ISD::SMIN; break; 3429 case SPF_FMINNUM: 3430 switch (SPR.NaNBehavior) { 3431 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3432 case SPNB_RETURNS_NAN: break; 3433 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3434 case SPNB_RETURNS_ANY: 3435 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3436 (UseScalarMinMax && 3437 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3438 Opc = ISD::FMINNUM; 3439 break; 3440 } 3441 break; 3442 case SPF_FMAXNUM: 3443 switch (SPR.NaNBehavior) { 3444 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3445 case SPNB_RETURNS_NAN: break; 3446 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3447 case SPNB_RETURNS_ANY: 3448 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3449 (UseScalarMinMax && 3450 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3451 Opc = ISD::FMAXNUM; 3452 break; 3453 } 3454 break; 3455 case SPF_NABS: 3456 Negate = true; 3457 [[fallthrough]]; 3458 case SPF_ABS: 3459 IsUnaryAbs = true; 3460 Opc = ISD::ABS; 3461 break; 3462 default: break; 3463 } 3464 3465 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3466 (TLI.isOperationLegalOrCustom(Opc, VT) || 3467 (UseScalarMinMax && 3468 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3469 // If the underlying comparison instruction is used by any other 3470 // instruction, the consumed instructions won't be destroyed, so it is 3471 // not profitable to convert to a min/max. 3472 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3473 OpCode = Opc; 3474 LHSVal = getValue(LHS); 3475 RHSVal = getValue(RHS); 3476 BaseOps.clear(); 3477 } 3478 3479 if (IsUnaryAbs) { 3480 OpCode = Opc; 3481 LHSVal = getValue(LHS); 3482 BaseOps.clear(); 3483 } 3484 } 3485 3486 if (IsUnaryAbs) { 3487 for (unsigned i = 0; i != NumValues; ++i) { 3488 SDLoc dl = getCurSDLoc(); 3489 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3490 Values[i] = 3491 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3492 if (Negate) 3493 Values[i] = DAG.getNegative(Values[i], dl, VT); 3494 } 3495 } else { 3496 for (unsigned i = 0; i != NumValues; ++i) { 3497 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3498 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3499 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3500 Values[i] = DAG.getNode( 3501 OpCode, getCurSDLoc(), 3502 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3503 } 3504 } 3505 3506 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3507 DAG.getVTList(ValueVTs), Values)); 3508 } 3509 3510 void SelectionDAGBuilder::visitTrunc(const User &I) { 3511 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3512 SDValue N = getValue(I.getOperand(0)); 3513 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3514 I.getType()); 3515 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3516 } 3517 3518 void SelectionDAGBuilder::visitZExt(const User &I) { 3519 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3520 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3521 SDValue N = getValue(I.getOperand(0)); 3522 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3523 I.getType()); 3524 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3525 } 3526 3527 void SelectionDAGBuilder::visitSExt(const User &I) { 3528 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3529 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3530 SDValue N = getValue(I.getOperand(0)); 3531 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3532 I.getType()); 3533 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3534 } 3535 3536 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3537 // FPTrunc is never a no-op cast, no need to check 3538 SDValue N = getValue(I.getOperand(0)); 3539 SDLoc dl = getCurSDLoc(); 3540 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3541 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3542 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3543 DAG.getTargetConstant( 3544 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3545 } 3546 3547 void SelectionDAGBuilder::visitFPExt(const User &I) { 3548 // FPExt is never a no-op cast, no need to check 3549 SDValue N = getValue(I.getOperand(0)); 3550 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3551 I.getType()); 3552 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3553 } 3554 3555 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3556 // FPToUI is never a no-op cast, no need to check 3557 SDValue N = getValue(I.getOperand(0)); 3558 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3559 I.getType()); 3560 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3561 } 3562 3563 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3564 // FPToSI is never a no-op cast, no need to check 3565 SDValue N = getValue(I.getOperand(0)); 3566 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3567 I.getType()); 3568 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3569 } 3570 3571 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3572 // UIToFP is never a no-op cast, no need to check 3573 SDValue N = getValue(I.getOperand(0)); 3574 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3575 I.getType()); 3576 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3577 } 3578 3579 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3580 // SIToFP is never a no-op cast, no need to check 3581 SDValue N = getValue(I.getOperand(0)); 3582 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3583 I.getType()); 3584 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3585 } 3586 3587 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3588 // What to do depends on the size of the integer and the size of the pointer. 3589 // We can either truncate, zero extend, or no-op, accordingly. 3590 SDValue N = getValue(I.getOperand(0)); 3591 auto &TLI = DAG.getTargetLoweringInfo(); 3592 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3593 I.getType()); 3594 EVT PtrMemVT = 3595 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3596 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3597 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3598 setValue(&I, N); 3599 } 3600 3601 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3602 // What to do depends on the size of the integer and the size of the pointer. 3603 // We can either truncate, zero extend, or no-op, accordingly. 3604 SDValue N = getValue(I.getOperand(0)); 3605 auto &TLI = DAG.getTargetLoweringInfo(); 3606 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3607 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3608 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3609 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3610 setValue(&I, N); 3611 } 3612 3613 void SelectionDAGBuilder::visitBitCast(const User &I) { 3614 SDValue N = getValue(I.getOperand(0)); 3615 SDLoc dl = getCurSDLoc(); 3616 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3617 I.getType()); 3618 3619 // BitCast assures us that source and destination are the same size so this is 3620 // either a BITCAST or a no-op. 3621 if (DestVT != N.getValueType()) 3622 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3623 DestVT, N)); // convert types. 3624 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3625 // might fold any kind of constant expression to an integer constant and that 3626 // is not what we are looking for. Only recognize a bitcast of a genuine 3627 // constant integer as an opaque constant. 3628 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3629 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3630 /*isOpaque*/true)); 3631 else 3632 setValue(&I, N); // noop cast. 3633 } 3634 3635 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3636 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3637 const Value *SV = I.getOperand(0); 3638 SDValue N = getValue(SV); 3639 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3640 3641 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3642 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3643 3644 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3645 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3646 3647 setValue(&I, N); 3648 } 3649 3650 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3651 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3652 SDValue InVec = getValue(I.getOperand(0)); 3653 SDValue InVal = getValue(I.getOperand(1)); 3654 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3655 TLI.getVectorIdxTy(DAG.getDataLayout())); 3656 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3657 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3658 InVec, InVal, InIdx)); 3659 } 3660 3661 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3663 SDValue InVec = getValue(I.getOperand(0)); 3664 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3665 TLI.getVectorIdxTy(DAG.getDataLayout())); 3666 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3667 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3668 InVec, InIdx)); 3669 } 3670 3671 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3672 SDValue Src1 = getValue(I.getOperand(0)); 3673 SDValue Src2 = getValue(I.getOperand(1)); 3674 ArrayRef<int> Mask; 3675 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3676 Mask = SVI->getShuffleMask(); 3677 else 3678 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3679 SDLoc DL = getCurSDLoc(); 3680 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3681 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3682 EVT SrcVT = Src1.getValueType(); 3683 3684 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3685 VT.isScalableVector()) { 3686 // Canonical splat form of first element of first input vector. 3687 SDValue FirstElt = 3688 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3689 DAG.getVectorIdxConstant(0, DL)); 3690 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3691 return; 3692 } 3693 3694 // For now, we only handle splats for scalable vectors. 3695 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3696 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3697 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3698 3699 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3700 unsigned MaskNumElts = Mask.size(); 3701 3702 if (SrcNumElts == MaskNumElts) { 3703 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3704 return; 3705 } 3706 3707 // Normalize the shuffle vector since mask and vector length don't match. 3708 if (SrcNumElts < MaskNumElts) { 3709 // Mask is longer than the source vectors. We can use concatenate vector to 3710 // make the mask and vectors lengths match. 3711 3712 if (MaskNumElts % SrcNumElts == 0) { 3713 // Mask length is a multiple of the source vector length. 3714 // Check if the shuffle is some kind of concatenation of the input 3715 // vectors. 3716 unsigned NumConcat = MaskNumElts / SrcNumElts; 3717 bool IsConcat = true; 3718 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3719 for (unsigned i = 0; i != MaskNumElts; ++i) { 3720 int Idx = Mask[i]; 3721 if (Idx < 0) 3722 continue; 3723 // Ensure the indices in each SrcVT sized piece are sequential and that 3724 // the same source is used for the whole piece. 3725 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3726 (ConcatSrcs[i / SrcNumElts] >= 0 && 3727 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3728 IsConcat = false; 3729 break; 3730 } 3731 // Remember which source this index came from. 3732 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3733 } 3734 3735 // The shuffle is concatenating multiple vectors together. Just emit 3736 // a CONCAT_VECTORS operation. 3737 if (IsConcat) { 3738 SmallVector<SDValue, 8> ConcatOps; 3739 for (auto Src : ConcatSrcs) { 3740 if (Src < 0) 3741 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3742 else if (Src == 0) 3743 ConcatOps.push_back(Src1); 3744 else 3745 ConcatOps.push_back(Src2); 3746 } 3747 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3748 return; 3749 } 3750 } 3751 3752 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3753 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3754 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3755 PaddedMaskNumElts); 3756 3757 // Pad both vectors with undefs to make them the same length as the mask. 3758 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3759 3760 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3761 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3762 MOps1[0] = Src1; 3763 MOps2[0] = Src2; 3764 3765 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3766 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3767 3768 // Readjust mask for new input vector length. 3769 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3770 for (unsigned i = 0; i != MaskNumElts; ++i) { 3771 int Idx = Mask[i]; 3772 if (Idx >= (int)SrcNumElts) 3773 Idx -= SrcNumElts - PaddedMaskNumElts; 3774 MappedOps[i] = Idx; 3775 } 3776 3777 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3778 3779 // If the concatenated vector was padded, extract a subvector with the 3780 // correct number of elements. 3781 if (MaskNumElts != PaddedMaskNumElts) 3782 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3783 DAG.getVectorIdxConstant(0, DL)); 3784 3785 setValue(&I, Result); 3786 return; 3787 } 3788 3789 if (SrcNumElts > MaskNumElts) { 3790 // Analyze the access pattern of the vector to see if we can extract 3791 // two subvectors and do the shuffle. 3792 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3793 bool CanExtract = true; 3794 for (int Idx : Mask) { 3795 unsigned Input = 0; 3796 if (Idx < 0) 3797 continue; 3798 3799 if (Idx >= (int)SrcNumElts) { 3800 Input = 1; 3801 Idx -= SrcNumElts; 3802 } 3803 3804 // If all the indices come from the same MaskNumElts sized portion of 3805 // the sources we can use extract. Also make sure the extract wouldn't 3806 // extract past the end of the source. 3807 int NewStartIdx = alignDown(Idx, MaskNumElts); 3808 if (NewStartIdx + MaskNumElts > SrcNumElts || 3809 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3810 CanExtract = false; 3811 // Make sure we always update StartIdx as we use it to track if all 3812 // elements are undef. 3813 StartIdx[Input] = NewStartIdx; 3814 } 3815 3816 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3817 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3818 return; 3819 } 3820 if (CanExtract) { 3821 // Extract appropriate subvector and generate a vector shuffle 3822 for (unsigned Input = 0; Input < 2; ++Input) { 3823 SDValue &Src = Input == 0 ? Src1 : Src2; 3824 if (StartIdx[Input] < 0) 3825 Src = DAG.getUNDEF(VT); 3826 else { 3827 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3828 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3829 } 3830 } 3831 3832 // Calculate new mask. 3833 SmallVector<int, 8> MappedOps(Mask); 3834 for (int &Idx : MappedOps) { 3835 if (Idx >= (int)SrcNumElts) 3836 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3837 else if (Idx >= 0) 3838 Idx -= StartIdx[0]; 3839 } 3840 3841 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3842 return; 3843 } 3844 } 3845 3846 // We can't use either concat vectors or extract subvectors so fall back to 3847 // replacing the shuffle with extract and build vector. 3848 // to insert and build vector. 3849 EVT EltVT = VT.getVectorElementType(); 3850 SmallVector<SDValue,8> Ops; 3851 for (int Idx : Mask) { 3852 SDValue Res; 3853 3854 if (Idx < 0) { 3855 Res = DAG.getUNDEF(EltVT); 3856 } else { 3857 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3858 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3859 3860 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3861 DAG.getVectorIdxConstant(Idx, DL)); 3862 } 3863 3864 Ops.push_back(Res); 3865 } 3866 3867 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3868 } 3869 3870 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3871 ArrayRef<unsigned> Indices = I.getIndices(); 3872 const Value *Op0 = I.getOperand(0); 3873 const Value *Op1 = I.getOperand(1); 3874 Type *AggTy = I.getType(); 3875 Type *ValTy = Op1->getType(); 3876 bool IntoUndef = isa<UndefValue>(Op0); 3877 bool FromUndef = isa<UndefValue>(Op1); 3878 3879 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3880 3881 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3882 SmallVector<EVT, 4> AggValueVTs; 3883 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3884 SmallVector<EVT, 4> ValValueVTs; 3885 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3886 3887 unsigned NumAggValues = AggValueVTs.size(); 3888 unsigned NumValValues = ValValueVTs.size(); 3889 SmallVector<SDValue, 4> Values(NumAggValues); 3890 3891 // Ignore an insertvalue that produces an empty object 3892 if (!NumAggValues) { 3893 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3894 return; 3895 } 3896 3897 SDValue Agg = getValue(Op0); 3898 unsigned i = 0; 3899 // Copy the beginning value(s) from the original aggregate. 3900 for (; i != LinearIndex; ++i) 3901 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3902 SDValue(Agg.getNode(), Agg.getResNo() + i); 3903 // Copy values from the inserted value(s). 3904 if (NumValValues) { 3905 SDValue Val = getValue(Op1); 3906 for (; i != LinearIndex + NumValValues; ++i) 3907 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3908 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3909 } 3910 // Copy remaining value(s) from the original aggregate. 3911 for (; i != NumAggValues; ++i) 3912 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3913 SDValue(Agg.getNode(), Agg.getResNo() + i); 3914 3915 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3916 DAG.getVTList(AggValueVTs), Values)); 3917 } 3918 3919 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3920 ArrayRef<unsigned> Indices = I.getIndices(); 3921 const Value *Op0 = I.getOperand(0); 3922 Type *AggTy = Op0->getType(); 3923 Type *ValTy = I.getType(); 3924 bool OutOfUndef = isa<UndefValue>(Op0); 3925 3926 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3927 3928 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3929 SmallVector<EVT, 4> ValValueVTs; 3930 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3931 3932 unsigned NumValValues = ValValueVTs.size(); 3933 3934 // Ignore a extractvalue that produces an empty object 3935 if (!NumValValues) { 3936 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3937 return; 3938 } 3939 3940 SmallVector<SDValue, 4> Values(NumValValues); 3941 3942 SDValue Agg = getValue(Op0); 3943 // Copy out the selected value(s). 3944 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3945 Values[i - LinearIndex] = 3946 OutOfUndef ? 3947 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3948 SDValue(Agg.getNode(), Agg.getResNo() + i); 3949 3950 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3951 DAG.getVTList(ValValueVTs), Values)); 3952 } 3953 3954 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3955 Value *Op0 = I.getOperand(0); 3956 // Note that the pointer operand may be a vector of pointers. Take the scalar 3957 // element which holds a pointer. 3958 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3959 SDValue N = getValue(Op0); 3960 SDLoc dl = getCurSDLoc(); 3961 auto &TLI = DAG.getTargetLoweringInfo(); 3962 3963 // Normalize Vector GEP - all scalar operands should be converted to the 3964 // splat vector. 3965 bool IsVectorGEP = I.getType()->isVectorTy(); 3966 ElementCount VectorElementCount = 3967 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3968 : ElementCount::getFixed(0); 3969 3970 if (IsVectorGEP && !N.getValueType().isVector()) { 3971 LLVMContext &Context = *DAG.getContext(); 3972 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3973 N = DAG.getSplat(VT, dl, N); 3974 } 3975 3976 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3977 GTI != E; ++GTI) { 3978 const Value *Idx = GTI.getOperand(); 3979 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3980 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3981 if (Field) { 3982 // N = N + Offset 3983 uint64_t Offset = 3984 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3985 3986 // In an inbounds GEP with an offset that is nonnegative even when 3987 // interpreted as signed, assume there is no unsigned overflow. 3988 SDNodeFlags Flags; 3989 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3990 Flags.setNoUnsignedWrap(true); 3991 3992 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3993 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3994 } 3995 } else { 3996 // IdxSize is the width of the arithmetic according to IR semantics. 3997 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3998 // (and fix up the result later). 3999 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4000 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4001 TypeSize ElementSize = 4002 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 4003 // We intentionally mask away the high bits here; ElementSize may not 4004 // fit in IdxTy. 4005 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4006 bool ElementScalable = ElementSize.isScalable(); 4007 4008 // If this is a scalar constant or a splat vector of constants, 4009 // handle it quickly. 4010 const auto *C = dyn_cast<Constant>(Idx); 4011 if (C && isa<VectorType>(C->getType())) 4012 C = C->getSplatValue(); 4013 4014 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4015 if (CI && CI->isZero()) 4016 continue; 4017 if (CI && !ElementScalable) { 4018 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4019 LLVMContext &Context = *DAG.getContext(); 4020 SDValue OffsVal; 4021 if (IsVectorGEP) 4022 OffsVal = DAG.getConstant( 4023 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4024 else 4025 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4026 4027 // In an inbounds GEP with an offset that is nonnegative even when 4028 // interpreted as signed, assume there is no unsigned overflow. 4029 SDNodeFlags Flags; 4030 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4031 Flags.setNoUnsignedWrap(true); 4032 4033 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4034 4035 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4036 continue; 4037 } 4038 4039 // N = N + Idx * ElementMul; 4040 SDValue IdxN = getValue(Idx); 4041 4042 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4043 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4044 VectorElementCount); 4045 IdxN = DAG.getSplat(VT, dl, IdxN); 4046 } 4047 4048 // If the index is smaller or larger than intptr_t, truncate or extend 4049 // it. 4050 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4051 4052 if (ElementScalable) { 4053 EVT VScaleTy = N.getValueType().getScalarType(); 4054 SDValue VScale = DAG.getNode( 4055 ISD::VSCALE, dl, VScaleTy, 4056 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4057 if (IsVectorGEP) 4058 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4059 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4060 } else { 4061 // If this is a multiply by a power of two, turn it into a shl 4062 // immediately. This is a very common case. 4063 if (ElementMul != 1) { 4064 if (ElementMul.isPowerOf2()) { 4065 unsigned Amt = ElementMul.logBase2(); 4066 IdxN = DAG.getNode(ISD::SHL, dl, 4067 N.getValueType(), IdxN, 4068 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4069 } else { 4070 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4071 IdxN.getValueType()); 4072 IdxN = DAG.getNode(ISD::MUL, dl, 4073 N.getValueType(), IdxN, Scale); 4074 } 4075 } 4076 } 4077 4078 N = DAG.getNode(ISD::ADD, dl, 4079 N.getValueType(), N, IdxN); 4080 } 4081 } 4082 4083 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4084 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4085 if (IsVectorGEP) { 4086 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4087 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4088 } 4089 4090 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4091 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4092 4093 setValue(&I, N); 4094 } 4095 4096 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4097 // If this is a fixed sized alloca in the entry block of the function, 4098 // allocate it statically on the stack. 4099 if (FuncInfo.StaticAllocaMap.count(&I)) 4100 return; // getValue will auto-populate this. 4101 4102 SDLoc dl = getCurSDLoc(); 4103 Type *Ty = I.getAllocatedType(); 4104 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4105 auto &DL = DAG.getDataLayout(); 4106 TypeSize TySize = DL.getTypeAllocSize(Ty); 4107 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4108 4109 SDValue AllocSize = getValue(I.getArraySize()); 4110 4111 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace()); 4112 if (AllocSize.getValueType() != IntPtr) 4113 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4114 4115 if (TySize.isScalable()) 4116 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4117 DAG.getVScale(dl, IntPtr, 4118 APInt(IntPtr.getScalarSizeInBits(), 4119 TySize.getKnownMinValue()))); 4120 else 4121 AllocSize = 4122 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4123 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4124 4125 // Handle alignment. If the requested alignment is less than or equal to 4126 // the stack alignment, ignore it. If the size is greater than or equal to 4127 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4128 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4129 if (*Alignment <= StackAlign) 4130 Alignment = std::nullopt; 4131 4132 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4133 // Round the size of the allocation up to the stack alignment size 4134 // by add SA-1 to the size. This doesn't overflow because we're computing 4135 // an address inside an alloca. 4136 SDNodeFlags Flags; 4137 Flags.setNoUnsignedWrap(true); 4138 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4139 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4140 4141 // Mask out the low bits for alignment purposes. 4142 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4143 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4144 4145 SDValue Ops[] = { 4146 getRoot(), AllocSize, 4147 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4148 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4149 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4150 setValue(&I, DSA); 4151 DAG.setRoot(DSA.getValue(1)); 4152 4153 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4154 } 4155 4156 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4157 if (I.isAtomic()) 4158 return visitAtomicLoad(I); 4159 4160 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4161 const Value *SV = I.getOperand(0); 4162 if (TLI.supportSwiftError()) { 4163 // Swifterror values can come from either a function parameter with 4164 // swifterror attribute or an alloca with swifterror attribute. 4165 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4166 if (Arg->hasSwiftErrorAttr()) 4167 return visitLoadFromSwiftError(I); 4168 } 4169 4170 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4171 if (Alloca->isSwiftError()) 4172 return visitLoadFromSwiftError(I); 4173 } 4174 } 4175 4176 SDValue Ptr = getValue(SV); 4177 4178 Type *Ty = I.getType(); 4179 SmallVector<EVT, 4> ValueVTs, MemVTs; 4180 SmallVector<uint64_t, 4> Offsets; 4181 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0); 4182 unsigned NumValues = ValueVTs.size(); 4183 if (NumValues == 0) 4184 return; 4185 4186 Align Alignment = I.getAlign(); 4187 AAMDNodes AAInfo = I.getAAMetadata(); 4188 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4189 bool isVolatile = I.isVolatile(); 4190 MachineMemOperand::Flags MMOFlags = 4191 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4192 4193 SDValue Root; 4194 bool ConstantMemory = false; 4195 if (isVolatile) 4196 // Serialize volatile loads with other side effects. 4197 Root = getRoot(); 4198 else if (NumValues > MaxParallelChains) 4199 Root = getMemoryRoot(); 4200 else if (AA && 4201 AA->pointsToConstantMemory(MemoryLocation( 4202 SV, 4203 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4204 AAInfo))) { 4205 // Do not serialize (non-volatile) loads of constant memory with anything. 4206 Root = DAG.getEntryNode(); 4207 ConstantMemory = true; 4208 MMOFlags |= MachineMemOperand::MOInvariant; 4209 } else { 4210 // Do not serialize non-volatile loads against each other. 4211 Root = DAG.getRoot(); 4212 } 4213 4214 SDLoc dl = getCurSDLoc(); 4215 4216 if (isVolatile) 4217 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4218 4219 // An aggregate load cannot wrap around the address space, so offsets to its 4220 // parts don't wrap either. 4221 SDNodeFlags Flags; 4222 Flags.setNoUnsignedWrap(true); 4223 4224 SmallVector<SDValue, 4> Values(NumValues); 4225 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4226 EVT PtrVT = Ptr.getValueType(); 4227 4228 unsigned ChainI = 0; 4229 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4230 // Serializing loads here may result in excessive register pressure, and 4231 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4232 // could recover a bit by hoisting nodes upward in the chain by recognizing 4233 // they are side-effect free or do not alias. The optimizer should really 4234 // avoid this case by converting large object/array copies to llvm.memcpy 4235 // (MaxParallelChains should always remain as failsafe). 4236 if (ChainI == MaxParallelChains) { 4237 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4238 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4239 ArrayRef(Chains.data(), ChainI)); 4240 Root = Chain; 4241 ChainI = 0; 4242 } 4243 SDValue A = DAG.getNode(ISD::ADD, dl, 4244 PtrVT, Ptr, 4245 DAG.getConstant(Offsets[i], dl, PtrVT), 4246 Flags); 4247 4248 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4249 MachinePointerInfo(SV, Offsets[i]), Alignment, 4250 MMOFlags, AAInfo, Ranges); 4251 Chains[ChainI] = L.getValue(1); 4252 4253 if (MemVTs[i] != ValueVTs[i]) 4254 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4255 4256 Values[i] = L; 4257 } 4258 4259 if (!ConstantMemory) { 4260 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4261 ArrayRef(Chains.data(), ChainI)); 4262 if (isVolatile) 4263 DAG.setRoot(Chain); 4264 else 4265 PendingLoads.push_back(Chain); 4266 } 4267 4268 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4269 DAG.getVTList(ValueVTs), Values)); 4270 } 4271 4272 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4273 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4274 "call visitStoreToSwiftError when backend supports swifterror"); 4275 4276 SmallVector<EVT, 4> ValueVTs; 4277 SmallVector<uint64_t, 4> Offsets; 4278 const Value *SrcV = I.getOperand(0); 4279 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4280 SrcV->getType(), ValueVTs, &Offsets, 0); 4281 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4282 "expect a single EVT for swifterror"); 4283 4284 SDValue Src = getValue(SrcV); 4285 // Create a virtual register, then update the virtual register. 4286 Register VReg = 4287 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4288 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4289 // Chain can be getRoot or getControlRoot. 4290 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4291 SDValue(Src.getNode(), Src.getResNo())); 4292 DAG.setRoot(CopyNode); 4293 } 4294 4295 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4296 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4297 "call visitLoadFromSwiftError when backend supports swifterror"); 4298 4299 assert(!I.isVolatile() && 4300 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4301 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4302 "Support volatile, non temporal, invariant for load_from_swift_error"); 4303 4304 const Value *SV = I.getOperand(0); 4305 Type *Ty = I.getType(); 4306 assert( 4307 (!AA || 4308 !AA->pointsToConstantMemory(MemoryLocation( 4309 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4310 I.getAAMetadata()))) && 4311 "load_from_swift_error should not be constant memory"); 4312 4313 SmallVector<EVT, 4> ValueVTs; 4314 SmallVector<uint64_t, 4> Offsets; 4315 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4316 ValueVTs, &Offsets, 0); 4317 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4318 "expect a single EVT for swifterror"); 4319 4320 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4321 SDValue L = DAG.getCopyFromReg( 4322 getRoot(), getCurSDLoc(), 4323 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4324 4325 setValue(&I, L); 4326 } 4327 4328 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4329 if (I.isAtomic()) 4330 return visitAtomicStore(I); 4331 4332 const Value *SrcV = I.getOperand(0); 4333 const Value *PtrV = I.getOperand(1); 4334 4335 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4336 if (TLI.supportSwiftError()) { 4337 // Swifterror values can come from either a function parameter with 4338 // swifterror attribute or an alloca with swifterror attribute. 4339 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4340 if (Arg->hasSwiftErrorAttr()) 4341 return visitStoreToSwiftError(I); 4342 } 4343 4344 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4345 if (Alloca->isSwiftError()) 4346 return visitStoreToSwiftError(I); 4347 } 4348 } 4349 4350 SmallVector<EVT, 4> ValueVTs, MemVTs; 4351 SmallVector<uint64_t, 4> Offsets; 4352 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4353 SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0); 4354 unsigned NumValues = ValueVTs.size(); 4355 if (NumValues == 0) 4356 return; 4357 4358 // Get the lowered operands. Note that we do this after 4359 // checking if NumResults is zero, because with zero results 4360 // the operands won't have values in the map. 4361 SDValue Src = getValue(SrcV); 4362 SDValue Ptr = getValue(PtrV); 4363 4364 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4365 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4366 SDLoc dl = getCurSDLoc(); 4367 Align Alignment = I.getAlign(); 4368 AAMDNodes AAInfo = I.getAAMetadata(); 4369 4370 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4371 4372 // An aggregate load cannot wrap around the address space, so offsets to its 4373 // parts don't wrap either. 4374 SDNodeFlags Flags; 4375 Flags.setNoUnsignedWrap(true); 4376 4377 unsigned ChainI = 0; 4378 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4379 // See visitLoad comments. 4380 if (ChainI == MaxParallelChains) { 4381 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4382 ArrayRef(Chains.data(), ChainI)); 4383 Root = Chain; 4384 ChainI = 0; 4385 } 4386 SDValue Add = 4387 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4388 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4389 if (MemVTs[i] != ValueVTs[i]) 4390 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4391 SDValue St = 4392 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4393 Alignment, MMOFlags, AAInfo); 4394 Chains[ChainI] = St; 4395 } 4396 4397 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4398 ArrayRef(Chains.data(), ChainI)); 4399 setValue(&I, StoreNode); 4400 DAG.setRoot(StoreNode); 4401 } 4402 4403 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4404 bool IsCompressing) { 4405 SDLoc sdl = getCurSDLoc(); 4406 4407 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4408 MaybeAlign &Alignment) { 4409 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4410 Src0 = I.getArgOperand(0); 4411 Ptr = I.getArgOperand(1); 4412 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4413 Mask = I.getArgOperand(3); 4414 }; 4415 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4416 MaybeAlign &Alignment) { 4417 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4418 Src0 = I.getArgOperand(0); 4419 Ptr = I.getArgOperand(1); 4420 Mask = I.getArgOperand(2); 4421 Alignment = std::nullopt; 4422 }; 4423 4424 Value *PtrOperand, *MaskOperand, *Src0Operand; 4425 MaybeAlign Alignment; 4426 if (IsCompressing) 4427 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4428 else 4429 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4430 4431 SDValue Ptr = getValue(PtrOperand); 4432 SDValue Src0 = getValue(Src0Operand); 4433 SDValue Mask = getValue(MaskOperand); 4434 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4435 4436 EVT VT = Src0.getValueType(); 4437 if (!Alignment) 4438 Alignment = DAG.getEVTAlign(VT); 4439 4440 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4441 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4442 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4443 SDValue StoreNode = 4444 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4445 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4446 DAG.setRoot(StoreNode); 4447 setValue(&I, StoreNode); 4448 } 4449 4450 // Get a uniform base for the Gather/Scatter intrinsic. 4451 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4452 // We try to represent it as a base pointer + vector of indices. 4453 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4454 // The first operand of the GEP may be a single pointer or a vector of pointers 4455 // Example: 4456 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4457 // or 4458 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4459 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4460 // 4461 // When the first GEP operand is a single pointer - it is the uniform base we 4462 // are looking for. If first operand of the GEP is a splat vector - we 4463 // extract the splat value and use it as a uniform base. 4464 // In all other cases the function returns 'false'. 4465 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4466 ISD::MemIndexType &IndexType, SDValue &Scale, 4467 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4468 uint64_t ElemSize) { 4469 SelectionDAG& DAG = SDB->DAG; 4470 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4471 const DataLayout &DL = DAG.getDataLayout(); 4472 4473 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4474 4475 // Handle splat constant pointer. 4476 if (auto *C = dyn_cast<Constant>(Ptr)) { 4477 C = C->getSplatValue(); 4478 if (!C) 4479 return false; 4480 4481 Base = SDB->getValue(C); 4482 4483 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4484 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4485 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4486 IndexType = ISD::SIGNED_SCALED; 4487 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4488 return true; 4489 } 4490 4491 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4492 if (!GEP || GEP->getParent() != CurBB) 4493 return false; 4494 4495 if (GEP->getNumOperands() != 2) 4496 return false; 4497 4498 const Value *BasePtr = GEP->getPointerOperand(); 4499 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4500 4501 // Make sure the base is scalar and the index is a vector. 4502 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4503 return false; 4504 4505 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4506 4507 // Target may not support the required addressing mode. 4508 if (ScaleVal != 1 && 4509 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4510 return false; 4511 4512 Base = SDB->getValue(BasePtr); 4513 Index = SDB->getValue(IndexVal); 4514 IndexType = ISD::SIGNED_SCALED; 4515 4516 Scale = 4517 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4518 return true; 4519 } 4520 4521 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4522 SDLoc sdl = getCurSDLoc(); 4523 4524 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4525 const Value *Ptr = I.getArgOperand(1); 4526 SDValue Src0 = getValue(I.getArgOperand(0)); 4527 SDValue Mask = getValue(I.getArgOperand(3)); 4528 EVT VT = Src0.getValueType(); 4529 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4530 ->getMaybeAlignValue() 4531 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4532 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4533 4534 SDValue Base; 4535 SDValue Index; 4536 ISD::MemIndexType IndexType; 4537 SDValue Scale; 4538 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4539 I.getParent(), VT.getScalarStoreSize()); 4540 4541 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4542 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4543 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4544 // TODO: Make MachineMemOperands aware of scalable 4545 // vectors. 4546 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4547 if (!UniformBase) { 4548 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4549 Index = getValue(Ptr); 4550 IndexType = ISD::SIGNED_SCALED; 4551 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4552 } 4553 4554 EVT IdxVT = Index.getValueType(); 4555 EVT EltTy = IdxVT.getVectorElementType(); 4556 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4557 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4558 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4559 } 4560 4561 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4562 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4563 Ops, MMO, IndexType, false); 4564 DAG.setRoot(Scatter); 4565 setValue(&I, Scatter); 4566 } 4567 4568 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4569 SDLoc sdl = getCurSDLoc(); 4570 4571 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4572 MaybeAlign &Alignment) { 4573 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4574 Ptr = I.getArgOperand(0); 4575 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4576 Mask = I.getArgOperand(2); 4577 Src0 = I.getArgOperand(3); 4578 }; 4579 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4580 MaybeAlign &Alignment) { 4581 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4582 Ptr = I.getArgOperand(0); 4583 Alignment = std::nullopt; 4584 Mask = I.getArgOperand(1); 4585 Src0 = I.getArgOperand(2); 4586 }; 4587 4588 Value *PtrOperand, *MaskOperand, *Src0Operand; 4589 MaybeAlign Alignment; 4590 if (IsExpanding) 4591 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4592 else 4593 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4594 4595 SDValue Ptr = getValue(PtrOperand); 4596 SDValue Src0 = getValue(Src0Operand); 4597 SDValue Mask = getValue(MaskOperand); 4598 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4599 4600 EVT VT = Src0.getValueType(); 4601 if (!Alignment) 4602 Alignment = DAG.getEVTAlign(VT); 4603 4604 AAMDNodes AAInfo = I.getAAMetadata(); 4605 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4606 4607 // Do not serialize masked loads of constant memory with anything. 4608 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4609 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4610 4611 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4612 4613 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4614 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4615 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4616 4617 SDValue Load = 4618 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4619 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4620 if (AddToChain) 4621 PendingLoads.push_back(Load.getValue(1)); 4622 setValue(&I, Load); 4623 } 4624 4625 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4626 SDLoc sdl = getCurSDLoc(); 4627 4628 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4629 const Value *Ptr = I.getArgOperand(0); 4630 SDValue Src0 = getValue(I.getArgOperand(3)); 4631 SDValue Mask = getValue(I.getArgOperand(2)); 4632 4633 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4634 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4635 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4636 ->getMaybeAlignValue() 4637 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4638 4639 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4640 4641 SDValue Root = DAG.getRoot(); 4642 SDValue Base; 4643 SDValue Index; 4644 ISD::MemIndexType IndexType; 4645 SDValue Scale; 4646 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4647 I.getParent(), VT.getScalarStoreSize()); 4648 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4649 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4650 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4651 // TODO: Make MachineMemOperands aware of scalable 4652 // vectors. 4653 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4654 4655 if (!UniformBase) { 4656 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4657 Index = getValue(Ptr); 4658 IndexType = ISD::SIGNED_SCALED; 4659 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4660 } 4661 4662 EVT IdxVT = Index.getValueType(); 4663 EVT EltTy = IdxVT.getVectorElementType(); 4664 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4665 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4666 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4667 } 4668 4669 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4670 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4671 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4672 4673 PendingLoads.push_back(Gather.getValue(1)); 4674 setValue(&I, Gather); 4675 } 4676 4677 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4678 SDLoc dl = getCurSDLoc(); 4679 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4680 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4681 SyncScope::ID SSID = I.getSyncScopeID(); 4682 4683 SDValue InChain = getRoot(); 4684 4685 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4686 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4687 4688 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4689 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4690 4691 MachineFunction &MF = DAG.getMachineFunction(); 4692 MachineMemOperand *MMO = MF.getMachineMemOperand( 4693 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4694 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4695 FailureOrdering); 4696 4697 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4698 dl, MemVT, VTs, InChain, 4699 getValue(I.getPointerOperand()), 4700 getValue(I.getCompareOperand()), 4701 getValue(I.getNewValOperand()), MMO); 4702 4703 SDValue OutChain = L.getValue(2); 4704 4705 setValue(&I, L); 4706 DAG.setRoot(OutChain); 4707 } 4708 4709 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4710 SDLoc dl = getCurSDLoc(); 4711 ISD::NodeType NT; 4712 switch (I.getOperation()) { 4713 default: llvm_unreachable("Unknown atomicrmw operation"); 4714 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4715 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4716 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4717 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4718 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4719 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4720 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4721 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4722 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4723 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4724 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4725 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4726 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4727 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4728 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4729 case AtomicRMWInst::UIncWrap: 4730 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4731 break; 4732 case AtomicRMWInst::UDecWrap: 4733 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4734 break; 4735 } 4736 AtomicOrdering Ordering = I.getOrdering(); 4737 SyncScope::ID SSID = I.getSyncScopeID(); 4738 4739 SDValue InChain = getRoot(); 4740 4741 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4742 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4743 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4744 4745 MachineFunction &MF = DAG.getMachineFunction(); 4746 MachineMemOperand *MMO = MF.getMachineMemOperand( 4747 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4748 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4749 4750 SDValue L = 4751 DAG.getAtomic(NT, dl, MemVT, InChain, 4752 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4753 MMO); 4754 4755 SDValue OutChain = L.getValue(1); 4756 4757 setValue(&I, L); 4758 DAG.setRoot(OutChain); 4759 } 4760 4761 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4762 SDLoc dl = getCurSDLoc(); 4763 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4764 SDValue Ops[3]; 4765 Ops[0] = getRoot(); 4766 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4767 TLI.getFenceOperandTy(DAG.getDataLayout())); 4768 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4769 TLI.getFenceOperandTy(DAG.getDataLayout())); 4770 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4771 setValue(&I, N); 4772 DAG.setRoot(N); 4773 } 4774 4775 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4776 SDLoc dl = getCurSDLoc(); 4777 AtomicOrdering Order = I.getOrdering(); 4778 SyncScope::ID SSID = I.getSyncScopeID(); 4779 4780 SDValue InChain = getRoot(); 4781 4782 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4783 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4784 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4785 4786 if (!TLI.supportsUnalignedAtomics() && 4787 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4788 report_fatal_error("Cannot generate unaligned atomic load"); 4789 4790 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4791 4792 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4793 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4794 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4795 4796 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4797 4798 SDValue Ptr = getValue(I.getPointerOperand()); 4799 4800 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4801 // TODO: Once this is better exercised by tests, it should be merged with 4802 // the normal path for loads to prevent future divergence. 4803 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4804 if (MemVT != VT) 4805 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4806 4807 setValue(&I, L); 4808 SDValue OutChain = L.getValue(1); 4809 if (!I.isUnordered()) 4810 DAG.setRoot(OutChain); 4811 else 4812 PendingLoads.push_back(OutChain); 4813 return; 4814 } 4815 4816 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4817 Ptr, MMO); 4818 4819 SDValue OutChain = L.getValue(1); 4820 if (MemVT != VT) 4821 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4822 4823 setValue(&I, L); 4824 DAG.setRoot(OutChain); 4825 } 4826 4827 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4828 SDLoc dl = getCurSDLoc(); 4829 4830 AtomicOrdering Ordering = I.getOrdering(); 4831 SyncScope::ID SSID = I.getSyncScopeID(); 4832 4833 SDValue InChain = getRoot(); 4834 4835 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4836 EVT MemVT = 4837 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4838 4839 if (!TLI.supportsUnalignedAtomics() && 4840 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4841 report_fatal_error("Cannot generate unaligned atomic store"); 4842 4843 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4844 4845 MachineFunction &MF = DAG.getMachineFunction(); 4846 MachineMemOperand *MMO = MF.getMachineMemOperand( 4847 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4848 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4849 4850 SDValue Val = getValue(I.getValueOperand()); 4851 if (Val.getValueType() != MemVT) 4852 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4853 SDValue Ptr = getValue(I.getPointerOperand()); 4854 4855 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4856 // TODO: Once this is better exercised by tests, it should be merged with 4857 // the normal path for stores to prevent future divergence. 4858 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4859 setValue(&I, S); 4860 DAG.setRoot(S); 4861 return; 4862 } 4863 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4864 Ptr, Val, MMO); 4865 4866 setValue(&I, OutChain); 4867 DAG.setRoot(OutChain); 4868 } 4869 4870 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4871 /// node. 4872 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4873 unsigned Intrinsic) { 4874 // Ignore the callsite's attributes. A specific call site may be marked with 4875 // readnone, but the lowering code will expect the chain based on the 4876 // definition. 4877 const Function *F = I.getCalledFunction(); 4878 bool HasChain = !F->doesNotAccessMemory(); 4879 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4880 4881 // Build the operand list. 4882 SmallVector<SDValue, 8> Ops; 4883 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4884 if (OnlyLoad) { 4885 // We don't need to serialize loads against other loads. 4886 Ops.push_back(DAG.getRoot()); 4887 } else { 4888 Ops.push_back(getRoot()); 4889 } 4890 } 4891 4892 // Info is set by getTgtMemIntrinsic 4893 TargetLowering::IntrinsicInfo Info; 4894 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4895 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4896 DAG.getMachineFunction(), 4897 Intrinsic); 4898 4899 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4900 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4901 Info.opc == ISD::INTRINSIC_W_CHAIN) 4902 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4903 TLI.getPointerTy(DAG.getDataLayout()))); 4904 4905 // Add all operands of the call to the operand list. 4906 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4907 const Value *Arg = I.getArgOperand(i); 4908 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4909 Ops.push_back(getValue(Arg)); 4910 continue; 4911 } 4912 4913 // Use TargetConstant instead of a regular constant for immarg. 4914 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4915 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4916 assert(CI->getBitWidth() <= 64 && 4917 "large intrinsic immediates not handled"); 4918 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4919 } else { 4920 Ops.push_back( 4921 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4922 } 4923 } 4924 4925 SmallVector<EVT, 4> ValueVTs; 4926 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4927 4928 if (HasChain) 4929 ValueVTs.push_back(MVT::Other); 4930 4931 SDVTList VTs = DAG.getVTList(ValueVTs); 4932 4933 // Propagate fast-math-flags from IR to node(s). 4934 SDNodeFlags Flags; 4935 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4936 Flags.copyFMF(*FPMO); 4937 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4938 4939 // Create the node. 4940 SDValue Result; 4941 // In some cases, custom collection of operands from CallInst I may be needed. 4942 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4943 if (IsTgtIntrinsic) { 4944 // This is target intrinsic that touches memory 4945 // 4946 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 4947 // didn't yield anything useful. 4948 MachinePointerInfo MPI; 4949 if (Info.ptrVal) 4950 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 4951 else if (Info.fallbackAddressSpace) 4952 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 4953 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 4954 Info.memVT, MPI, Info.align, Info.flags, 4955 Info.size, I.getAAMetadata()); 4956 } else if (!HasChain) { 4957 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4958 } else if (!I.getType()->isVoidTy()) { 4959 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4960 } else { 4961 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4962 } 4963 4964 if (HasChain) { 4965 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4966 if (OnlyLoad) 4967 PendingLoads.push_back(Chain); 4968 else 4969 DAG.setRoot(Chain); 4970 } 4971 4972 if (!I.getType()->isVoidTy()) { 4973 if (!isa<VectorType>(I.getType())) 4974 Result = lowerRangeToAssertZExt(DAG, I, Result); 4975 4976 MaybeAlign Alignment = I.getRetAlign(); 4977 4978 // Insert `assertalign` node if there's an alignment. 4979 if (InsertAssertAlign && Alignment) { 4980 Result = 4981 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4982 } 4983 4984 setValue(&I, Result); 4985 } 4986 } 4987 4988 /// GetSignificand - Get the significand and build it into a floating-point 4989 /// number with exponent of 1: 4990 /// 4991 /// Op = (Op & 0x007fffff) | 0x3f800000; 4992 /// 4993 /// where Op is the hexadecimal representation of floating point value. 4994 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4995 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4996 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4997 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4998 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4999 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5000 } 5001 5002 /// GetExponent - Get the exponent: 5003 /// 5004 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5005 /// 5006 /// where Op is the hexadecimal representation of floating point value. 5007 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5008 const TargetLowering &TLI, const SDLoc &dl) { 5009 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5010 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5011 SDValue t1 = DAG.getNode( 5012 ISD::SRL, dl, MVT::i32, t0, 5013 DAG.getConstant(23, dl, 5014 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5015 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5016 DAG.getConstant(127, dl, MVT::i32)); 5017 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5018 } 5019 5020 /// getF32Constant - Get 32-bit floating point constant. 5021 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5022 const SDLoc &dl) { 5023 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5024 MVT::f32); 5025 } 5026 5027 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5028 SelectionDAG &DAG) { 5029 // TODO: What fast-math-flags should be set on the floating-point nodes? 5030 5031 // IntegerPartOfX = ((int32_t)(t0); 5032 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5033 5034 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5035 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5036 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5037 5038 // IntegerPartOfX <<= 23; 5039 IntegerPartOfX = 5040 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5041 DAG.getConstant(23, dl, 5042 DAG.getTargetLoweringInfo().getShiftAmountTy( 5043 MVT::i32, DAG.getDataLayout()))); 5044 5045 SDValue TwoToFractionalPartOfX; 5046 if (LimitFloatPrecision <= 6) { 5047 // For floating-point precision of 6: 5048 // 5049 // TwoToFractionalPartOfX = 5050 // 0.997535578f + 5051 // (0.735607626f + 0.252464424f * x) * x; 5052 // 5053 // error 0.0144103317, which is 6 bits 5054 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5055 getF32Constant(DAG, 0x3e814304, dl)); 5056 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5057 getF32Constant(DAG, 0x3f3c50c8, dl)); 5058 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5059 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5060 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5061 } else if (LimitFloatPrecision <= 12) { 5062 // For floating-point precision of 12: 5063 // 5064 // TwoToFractionalPartOfX = 5065 // 0.999892986f + 5066 // (0.696457318f + 5067 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5068 // 5069 // error 0.000107046256, which is 13 to 14 bits 5070 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5071 getF32Constant(DAG, 0x3da235e3, dl)); 5072 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5073 getF32Constant(DAG, 0x3e65b8f3, dl)); 5074 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5075 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5076 getF32Constant(DAG, 0x3f324b07, dl)); 5077 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5078 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5079 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5080 } else { // LimitFloatPrecision <= 18 5081 // For floating-point precision of 18: 5082 // 5083 // TwoToFractionalPartOfX = 5084 // 0.999999982f + 5085 // (0.693148872f + 5086 // (0.240227044f + 5087 // (0.554906021e-1f + 5088 // (0.961591928e-2f + 5089 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5090 // error 2.47208000*10^(-7), which is better than 18 bits 5091 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5092 getF32Constant(DAG, 0x3924b03e, dl)); 5093 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5094 getF32Constant(DAG, 0x3ab24b87, dl)); 5095 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5096 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5097 getF32Constant(DAG, 0x3c1d8c17, dl)); 5098 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5099 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5100 getF32Constant(DAG, 0x3d634a1d, dl)); 5101 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5102 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5103 getF32Constant(DAG, 0x3e75fe14, dl)); 5104 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5105 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5106 getF32Constant(DAG, 0x3f317234, dl)); 5107 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5108 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5109 getF32Constant(DAG, 0x3f800000, dl)); 5110 } 5111 5112 // Add the exponent into the result in integer domain. 5113 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5114 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5115 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5116 } 5117 5118 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5119 /// limited-precision mode. 5120 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5121 const TargetLowering &TLI, SDNodeFlags Flags) { 5122 if (Op.getValueType() == MVT::f32 && 5123 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5124 5125 // Put the exponent in the right bit position for later addition to the 5126 // final result: 5127 // 5128 // t0 = Op * log2(e) 5129 5130 // TODO: What fast-math-flags should be set here? 5131 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5132 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5133 return getLimitedPrecisionExp2(t0, dl, DAG); 5134 } 5135 5136 // No special expansion. 5137 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5138 } 5139 5140 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5141 /// limited-precision mode. 5142 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5143 const TargetLowering &TLI, SDNodeFlags Flags) { 5144 // TODO: What fast-math-flags should be set on the floating-point nodes? 5145 5146 if (Op.getValueType() == MVT::f32 && 5147 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5148 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5149 5150 // Scale the exponent by log(2). 5151 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5152 SDValue LogOfExponent = 5153 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5154 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5155 5156 // Get the significand and build it into a floating-point number with 5157 // exponent of 1. 5158 SDValue X = GetSignificand(DAG, Op1, dl); 5159 5160 SDValue LogOfMantissa; 5161 if (LimitFloatPrecision <= 6) { 5162 // For floating-point precision of 6: 5163 // 5164 // LogofMantissa = 5165 // -1.1609546f + 5166 // (1.4034025f - 0.23903021f * x) * x; 5167 // 5168 // error 0.0034276066, which is better than 8 bits 5169 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5170 getF32Constant(DAG, 0xbe74c456, dl)); 5171 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5172 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5173 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5174 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5175 getF32Constant(DAG, 0x3f949a29, dl)); 5176 } else if (LimitFloatPrecision <= 12) { 5177 // For floating-point precision of 12: 5178 // 5179 // LogOfMantissa = 5180 // -1.7417939f + 5181 // (2.8212026f + 5182 // (-1.4699568f + 5183 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5184 // 5185 // error 0.000061011436, which is 14 bits 5186 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5187 getF32Constant(DAG, 0xbd67b6d6, dl)); 5188 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5189 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5190 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5191 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5192 getF32Constant(DAG, 0x3fbc278b, dl)); 5193 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5194 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5195 getF32Constant(DAG, 0x40348e95, dl)); 5196 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5197 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5198 getF32Constant(DAG, 0x3fdef31a, dl)); 5199 } else { // LimitFloatPrecision <= 18 5200 // For floating-point precision of 18: 5201 // 5202 // LogOfMantissa = 5203 // -2.1072184f + 5204 // (4.2372794f + 5205 // (-3.7029485f + 5206 // (2.2781945f + 5207 // (-0.87823314f + 5208 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5209 // 5210 // error 0.0000023660568, which is better than 18 bits 5211 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5212 getF32Constant(DAG, 0xbc91e5ac, dl)); 5213 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5214 getF32Constant(DAG, 0x3e4350aa, dl)); 5215 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5216 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5217 getF32Constant(DAG, 0x3f60d3e3, dl)); 5218 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5219 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5220 getF32Constant(DAG, 0x4011cdf0, dl)); 5221 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5222 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5223 getF32Constant(DAG, 0x406cfd1c, dl)); 5224 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5225 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5226 getF32Constant(DAG, 0x408797cb, dl)); 5227 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5228 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5229 getF32Constant(DAG, 0x4006dcab, dl)); 5230 } 5231 5232 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5233 } 5234 5235 // No special expansion. 5236 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5237 } 5238 5239 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5240 /// limited-precision mode. 5241 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5242 const TargetLowering &TLI, SDNodeFlags Flags) { 5243 // TODO: What fast-math-flags should be set on the floating-point nodes? 5244 5245 if (Op.getValueType() == MVT::f32 && 5246 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5247 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5248 5249 // Get the exponent. 5250 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5251 5252 // Get the significand and build it into a floating-point number with 5253 // exponent of 1. 5254 SDValue X = GetSignificand(DAG, Op1, dl); 5255 5256 // Different possible minimax approximations of significand in 5257 // floating-point for various degrees of accuracy over [1,2]. 5258 SDValue Log2ofMantissa; 5259 if (LimitFloatPrecision <= 6) { 5260 // For floating-point precision of 6: 5261 // 5262 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5263 // 5264 // error 0.0049451742, which is more than 7 bits 5265 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5266 getF32Constant(DAG, 0xbeb08fe0, dl)); 5267 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5268 getF32Constant(DAG, 0x40019463, dl)); 5269 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5270 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5271 getF32Constant(DAG, 0x3fd6633d, dl)); 5272 } else if (LimitFloatPrecision <= 12) { 5273 // For floating-point precision of 12: 5274 // 5275 // Log2ofMantissa = 5276 // -2.51285454f + 5277 // (4.07009056f + 5278 // (-2.12067489f + 5279 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5280 // 5281 // error 0.0000876136000, which is better than 13 bits 5282 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5283 getF32Constant(DAG, 0xbda7262e, dl)); 5284 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5285 getF32Constant(DAG, 0x3f25280b, dl)); 5286 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5287 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5288 getF32Constant(DAG, 0x4007b923, dl)); 5289 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5290 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5291 getF32Constant(DAG, 0x40823e2f, dl)); 5292 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5293 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5294 getF32Constant(DAG, 0x4020d29c, dl)); 5295 } else { // LimitFloatPrecision <= 18 5296 // For floating-point precision of 18: 5297 // 5298 // Log2ofMantissa = 5299 // -3.0400495f + 5300 // (6.1129976f + 5301 // (-5.3420409f + 5302 // (3.2865683f + 5303 // (-1.2669343f + 5304 // (0.27515199f - 5305 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5306 // 5307 // error 0.0000018516, which is better than 18 bits 5308 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5309 getF32Constant(DAG, 0xbcd2769e, dl)); 5310 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5311 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5312 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5313 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5314 getF32Constant(DAG, 0x3fa22ae7, dl)); 5315 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5316 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5317 getF32Constant(DAG, 0x40525723, dl)); 5318 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5319 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5320 getF32Constant(DAG, 0x40aaf200, dl)); 5321 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5322 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5323 getF32Constant(DAG, 0x40c39dad, dl)); 5324 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5325 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5326 getF32Constant(DAG, 0x4042902c, dl)); 5327 } 5328 5329 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5330 } 5331 5332 // No special expansion. 5333 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5334 } 5335 5336 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5337 /// limited-precision mode. 5338 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5339 const TargetLowering &TLI, SDNodeFlags Flags) { 5340 // TODO: What fast-math-flags should be set on the floating-point nodes? 5341 5342 if (Op.getValueType() == MVT::f32 && 5343 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5344 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5345 5346 // Scale the exponent by log10(2) [0.30102999f]. 5347 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5348 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5349 getF32Constant(DAG, 0x3e9a209a, dl)); 5350 5351 // Get the significand and build it into a floating-point number with 5352 // exponent of 1. 5353 SDValue X = GetSignificand(DAG, Op1, dl); 5354 5355 SDValue Log10ofMantissa; 5356 if (LimitFloatPrecision <= 6) { 5357 // For floating-point precision of 6: 5358 // 5359 // Log10ofMantissa = 5360 // -0.50419619f + 5361 // (0.60948995f - 0.10380950f * x) * x; 5362 // 5363 // error 0.0014886165, which is 6 bits 5364 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5365 getF32Constant(DAG, 0xbdd49a13, dl)); 5366 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5367 getF32Constant(DAG, 0x3f1c0789, dl)); 5368 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5369 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5370 getF32Constant(DAG, 0x3f011300, dl)); 5371 } else if (LimitFloatPrecision <= 12) { 5372 // For floating-point precision of 12: 5373 // 5374 // Log10ofMantissa = 5375 // -0.64831180f + 5376 // (0.91751397f + 5377 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5378 // 5379 // error 0.00019228036, which is better than 12 bits 5380 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5381 getF32Constant(DAG, 0x3d431f31, dl)); 5382 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5383 getF32Constant(DAG, 0x3ea21fb2, dl)); 5384 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5385 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5386 getF32Constant(DAG, 0x3f6ae232, dl)); 5387 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5388 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5389 getF32Constant(DAG, 0x3f25f7c3, dl)); 5390 } else { // LimitFloatPrecision <= 18 5391 // For floating-point precision of 18: 5392 // 5393 // Log10ofMantissa = 5394 // -0.84299375f + 5395 // (1.5327582f + 5396 // (-1.0688956f + 5397 // (0.49102474f + 5398 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5399 // 5400 // error 0.0000037995730, which is better than 18 bits 5401 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5402 getF32Constant(DAG, 0x3c5d51ce, dl)); 5403 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5404 getF32Constant(DAG, 0x3e00685a, dl)); 5405 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5406 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5407 getF32Constant(DAG, 0x3efb6798, dl)); 5408 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5409 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5410 getF32Constant(DAG, 0x3f88d192, dl)); 5411 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5412 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5413 getF32Constant(DAG, 0x3fc4316c, dl)); 5414 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5415 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5416 getF32Constant(DAG, 0x3f57ce70, dl)); 5417 } 5418 5419 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5420 } 5421 5422 // No special expansion. 5423 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5424 } 5425 5426 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5427 /// limited-precision mode. 5428 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5429 const TargetLowering &TLI, SDNodeFlags Flags) { 5430 if (Op.getValueType() == MVT::f32 && 5431 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5432 return getLimitedPrecisionExp2(Op, dl, DAG); 5433 5434 // No special expansion. 5435 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5436 } 5437 5438 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5439 /// limited-precision mode with x == 10.0f. 5440 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5441 SelectionDAG &DAG, const TargetLowering &TLI, 5442 SDNodeFlags Flags) { 5443 bool IsExp10 = false; 5444 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5445 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5446 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5447 APFloat Ten(10.0f); 5448 IsExp10 = LHSC->isExactlyValue(Ten); 5449 } 5450 } 5451 5452 // TODO: What fast-math-flags should be set on the FMUL node? 5453 if (IsExp10) { 5454 // Put the exponent in the right bit position for later addition to the 5455 // final result: 5456 // 5457 // #define LOG2OF10 3.3219281f 5458 // t0 = Op * LOG2OF10; 5459 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5460 getF32Constant(DAG, 0x40549a78, dl)); 5461 return getLimitedPrecisionExp2(t0, dl, DAG); 5462 } 5463 5464 // No special expansion. 5465 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5466 } 5467 5468 /// ExpandPowI - Expand a llvm.powi intrinsic. 5469 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5470 SelectionDAG &DAG) { 5471 // If RHS is a constant, we can expand this out to a multiplication tree if 5472 // it's beneficial on the target, otherwise we end up lowering to a call to 5473 // __powidf2 (for example). 5474 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5475 unsigned Val = RHSC->getSExtValue(); 5476 5477 // powi(x, 0) -> 1.0 5478 if (Val == 0) 5479 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5480 5481 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5482 Val, DAG.shouldOptForSize())) { 5483 // Get the exponent as a positive value. 5484 if ((int)Val < 0) 5485 Val = -Val; 5486 // We use the simple binary decomposition method to generate the multiply 5487 // sequence. There are more optimal ways to do this (for example, 5488 // powi(x,15) generates one more multiply than it should), but this has 5489 // the benefit of being both really simple and much better than a libcall. 5490 SDValue Res; // Logically starts equal to 1.0 5491 SDValue CurSquare = LHS; 5492 // TODO: Intrinsics should have fast-math-flags that propagate to these 5493 // nodes. 5494 while (Val) { 5495 if (Val & 1) { 5496 if (Res.getNode()) 5497 Res = 5498 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5499 else 5500 Res = CurSquare; // 1.0*CurSquare. 5501 } 5502 5503 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5504 CurSquare, CurSquare); 5505 Val >>= 1; 5506 } 5507 5508 // If the original was negative, invert the result, producing 1/(x*x*x). 5509 if (RHSC->getSExtValue() < 0) 5510 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5511 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5512 return Res; 5513 } 5514 } 5515 5516 // Otherwise, expand to a libcall. 5517 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5518 } 5519 5520 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5521 SDValue LHS, SDValue RHS, SDValue Scale, 5522 SelectionDAG &DAG, const TargetLowering &TLI) { 5523 EVT VT = LHS.getValueType(); 5524 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5525 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5526 LLVMContext &Ctx = *DAG.getContext(); 5527 5528 // If the type is legal but the operation isn't, this node might survive all 5529 // the way to operation legalization. If we end up there and we do not have 5530 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5531 // node. 5532 5533 // Coax the legalizer into expanding the node during type legalization instead 5534 // by bumping the size by one bit. This will force it to Promote, enabling the 5535 // early expansion and avoiding the need to expand later. 5536 5537 // We don't have to do this if Scale is 0; that can always be expanded, unless 5538 // it's a saturating signed operation. Those can experience true integer 5539 // division overflow, a case which we must avoid. 5540 5541 // FIXME: We wouldn't have to do this (or any of the early 5542 // expansion/promotion) if it was possible to expand a libcall of an 5543 // illegal type during operation legalization. But it's not, so things 5544 // get a bit hacky. 5545 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5546 if ((ScaleInt > 0 || (Saturating && Signed)) && 5547 (TLI.isTypeLegal(VT) || 5548 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5549 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5550 Opcode, VT, ScaleInt); 5551 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5552 EVT PromVT; 5553 if (VT.isScalarInteger()) 5554 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5555 else if (VT.isVector()) { 5556 PromVT = VT.getVectorElementType(); 5557 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5558 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5559 } else 5560 llvm_unreachable("Wrong VT for DIVFIX?"); 5561 if (Signed) { 5562 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5563 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5564 } else { 5565 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5566 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5567 } 5568 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5569 // For saturating operations, we need to shift up the LHS to get the 5570 // proper saturation width, and then shift down again afterwards. 5571 if (Saturating) 5572 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5573 DAG.getConstant(1, DL, ShiftTy)); 5574 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5575 if (Saturating) 5576 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5577 DAG.getConstant(1, DL, ShiftTy)); 5578 return DAG.getZExtOrTrunc(Res, DL, VT); 5579 } 5580 } 5581 5582 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5583 } 5584 5585 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5586 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5587 static void 5588 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5589 const SDValue &N) { 5590 switch (N.getOpcode()) { 5591 case ISD::CopyFromReg: { 5592 SDValue Op = N.getOperand(1); 5593 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5594 Op.getValueType().getSizeInBits()); 5595 return; 5596 } 5597 case ISD::BITCAST: 5598 case ISD::AssertZext: 5599 case ISD::AssertSext: 5600 case ISD::TRUNCATE: 5601 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5602 return; 5603 case ISD::BUILD_PAIR: 5604 case ISD::BUILD_VECTOR: 5605 case ISD::CONCAT_VECTORS: 5606 for (SDValue Op : N->op_values()) 5607 getUnderlyingArgRegs(Regs, Op); 5608 return; 5609 default: 5610 return; 5611 } 5612 } 5613 5614 /// If the DbgValueInst is a dbg_value of a function argument, create the 5615 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5616 /// instruction selection, they will be inserted to the entry BB. 5617 /// We don't currently support this for variadic dbg_values, as they shouldn't 5618 /// appear for function arguments or in the prologue. 5619 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5620 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5621 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5622 const Argument *Arg = dyn_cast<Argument>(V); 5623 if (!Arg) 5624 return false; 5625 5626 MachineFunction &MF = DAG.getMachineFunction(); 5627 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5628 5629 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5630 // we've been asked to pursue. 5631 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5632 bool Indirect) { 5633 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5634 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5635 // pointing at the VReg, which will be patched up later. 5636 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5637 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5638 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5639 /* isKill */ false, /* isDead */ false, 5640 /* isUndef */ false, /* isEarlyClobber */ false, 5641 /* SubReg */ 0, /* isDebug */ true)}); 5642 5643 auto *NewDIExpr = FragExpr; 5644 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5645 // the DIExpression. 5646 if (Indirect) 5647 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5648 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5649 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5650 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5651 } else { 5652 // Create a completely standard DBG_VALUE. 5653 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5654 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5655 } 5656 }; 5657 5658 if (Kind == FuncArgumentDbgValueKind::Value) { 5659 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5660 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5661 // the entry block. 5662 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5663 if (!IsInEntryBlock) 5664 return false; 5665 5666 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5667 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5668 // variable that also is a param. 5669 // 5670 // Although, if we are at the top of the entry block already, we can still 5671 // emit using ArgDbgValue. This might catch some situations when the 5672 // dbg.value refers to an argument that isn't used in the entry block, so 5673 // any CopyToReg node would be optimized out and the only way to express 5674 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5675 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5676 // we should only emit as ArgDbgValue if the Variable is an argument to the 5677 // current function, and the dbg.value intrinsic is found in the entry 5678 // block. 5679 bool VariableIsFunctionInputArg = Variable->isParameter() && 5680 !DL->getInlinedAt(); 5681 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5682 if (!IsInPrologue && !VariableIsFunctionInputArg) 5683 return false; 5684 5685 // Here we assume that a function argument on IR level only can be used to 5686 // describe one input parameter on source level. If we for example have 5687 // source code like this 5688 // 5689 // struct A { long x, y; }; 5690 // void foo(struct A a, long b) { 5691 // ... 5692 // b = a.x; 5693 // ... 5694 // } 5695 // 5696 // and IR like this 5697 // 5698 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5699 // entry: 5700 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5701 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5702 // call void @llvm.dbg.value(metadata i32 %b, "b", 5703 // ... 5704 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5705 // ... 5706 // 5707 // then the last dbg.value is describing a parameter "b" using a value that 5708 // is an argument. But since we already has used %a1 to describe a parameter 5709 // we should not handle that last dbg.value here (that would result in an 5710 // incorrect hoisting of the DBG_VALUE to the function entry). 5711 // Notice that we allow one dbg.value per IR level argument, to accommodate 5712 // for the situation with fragments above. 5713 if (VariableIsFunctionInputArg) { 5714 unsigned ArgNo = Arg->getArgNo(); 5715 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5716 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5717 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5718 return false; 5719 FuncInfo.DescribedArgs.set(ArgNo); 5720 } 5721 } 5722 5723 bool IsIndirect = false; 5724 std::optional<MachineOperand> Op; 5725 // Some arguments' frame index is recorded during argument lowering. 5726 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5727 if (FI != std::numeric_limits<int>::max()) 5728 Op = MachineOperand::CreateFI(FI); 5729 5730 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5731 if (!Op && N.getNode()) { 5732 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5733 Register Reg; 5734 if (ArgRegsAndSizes.size() == 1) 5735 Reg = ArgRegsAndSizes.front().first; 5736 5737 if (Reg && Reg.isVirtual()) { 5738 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5739 Register PR = RegInfo.getLiveInPhysReg(Reg); 5740 if (PR) 5741 Reg = PR; 5742 } 5743 if (Reg) { 5744 Op = MachineOperand::CreateReg(Reg, false); 5745 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5746 } 5747 } 5748 5749 if (!Op && N.getNode()) { 5750 // Check if frame index is available. 5751 SDValue LCandidate = peekThroughBitcasts(N); 5752 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5753 if (FrameIndexSDNode *FINode = 5754 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5755 Op = MachineOperand::CreateFI(FINode->getIndex()); 5756 } 5757 5758 if (!Op) { 5759 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5760 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5761 SplitRegs) { 5762 unsigned Offset = 0; 5763 for (const auto &RegAndSize : SplitRegs) { 5764 // If the expression is already a fragment, the current register 5765 // offset+size might extend beyond the fragment. In this case, only 5766 // the register bits that are inside the fragment are relevant. 5767 int RegFragmentSizeInBits = RegAndSize.second; 5768 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5769 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5770 // The register is entirely outside the expression fragment, 5771 // so is irrelevant for debug info. 5772 if (Offset >= ExprFragmentSizeInBits) 5773 break; 5774 // The register is partially outside the expression fragment, only 5775 // the low bits within the fragment are relevant for debug info. 5776 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5777 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5778 } 5779 } 5780 5781 auto FragmentExpr = DIExpression::createFragmentExpression( 5782 Expr, Offset, RegFragmentSizeInBits); 5783 Offset += RegAndSize.second; 5784 // If a valid fragment expression cannot be created, the variable's 5785 // correct value cannot be determined and so it is set as Undef. 5786 if (!FragmentExpr) { 5787 SDDbgValue *SDV = DAG.getConstantDbgValue( 5788 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5789 DAG.AddDbgValue(SDV, false); 5790 continue; 5791 } 5792 MachineInstr *NewMI = 5793 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5794 Kind != FuncArgumentDbgValueKind::Value); 5795 FuncInfo.ArgDbgValues.push_back(NewMI); 5796 } 5797 }; 5798 5799 // Check if ValueMap has reg number. 5800 DenseMap<const Value *, Register>::const_iterator 5801 VMI = FuncInfo.ValueMap.find(V); 5802 if (VMI != FuncInfo.ValueMap.end()) { 5803 const auto &TLI = DAG.getTargetLoweringInfo(); 5804 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5805 V->getType(), std::nullopt); 5806 if (RFV.occupiesMultipleRegs()) { 5807 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5808 return true; 5809 } 5810 5811 Op = MachineOperand::CreateReg(VMI->second, false); 5812 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5813 } else if (ArgRegsAndSizes.size() > 1) { 5814 // This was split due to the calling convention, and no virtual register 5815 // mapping exists for the value. 5816 splitMultiRegDbgValue(ArgRegsAndSizes); 5817 return true; 5818 } 5819 } 5820 5821 if (!Op) 5822 return false; 5823 5824 // If the expression refers to the entry value of an Argument, use the 5825 // corresponding livein physical register. As per the Verifier, this is only 5826 // allowed for swiftasync Arguments. 5827 if (Op->isReg() && Expr->isEntryValue()) { 5828 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 5829 auto OpReg = Op->getReg(); 5830 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 5831 if (OpReg == VirtReg || OpReg == PhysReg) { 5832 SDDbgValue *SDV = DAG.getVRegDbgValue( 5833 Variable, Expr, PhysReg, 5834 Kind != FuncArgumentDbgValueKind::Value /*is indirect*/, DL, 5835 SDNodeOrder); 5836 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 5837 return true; 5838 } 5839 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 5840 "couldn't find a physical register\n"); 5841 return true; 5842 } 5843 5844 assert(Variable->isValidLocationForIntrinsic(DL) && 5845 "Expected inlined-at fields to agree"); 5846 MachineInstr *NewMI = nullptr; 5847 5848 if (Op->isReg()) 5849 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5850 else 5851 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5852 Variable, Expr); 5853 5854 // Otherwise, use ArgDbgValues. 5855 FuncInfo.ArgDbgValues.push_back(NewMI); 5856 return true; 5857 } 5858 5859 /// Return the appropriate SDDbgValue based on N. 5860 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5861 DILocalVariable *Variable, 5862 DIExpression *Expr, 5863 const DebugLoc &dl, 5864 unsigned DbgSDNodeOrder) { 5865 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5866 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5867 // stack slot locations. 5868 // 5869 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5870 // debug values here after optimization: 5871 // 5872 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5873 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5874 // 5875 // Both describe the direct values of their associated variables. 5876 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5877 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5878 } 5879 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5880 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5881 } 5882 5883 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5884 switch (Intrinsic) { 5885 case Intrinsic::smul_fix: 5886 return ISD::SMULFIX; 5887 case Intrinsic::umul_fix: 5888 return ISD::UMULFIX; 5889 case Intrinsic::smul_fix_sat: 5890 return ISD::SMULFIXSAT; 5891 case Intrinsic::umul_fix_sat: 5892 return ISD::UMULFIXSAT; 5893 case Intrinsic::sdiv_fix: 5894 return ISD::SDIVFIX; 5895 case Intrinsic::udiv_fix: 5896 return ISD::UDIVFIX; 5897 case Intrinsic::sdiv_fix_sat: 5898 return ISD::SDIVFIXSAT; 5899 case Intrinsic::udiv_fix_sat: 5900 return ISD::UDIVFIXSAT; 5901 default: 5902 llvm_unreachable("Unhandled fixed point intrinsic"); 5903 } 5904 } 5905 5906 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5907 const char *FunctionName) { 5908 assert(FunctionName && "FunctionName must not be nullptr"); 5909 SDValue Callee = DAG.getExternalSymbol( 5910 FunctionName, 5911 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5912 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5913 } 5914 5915 /// Given a @llvm.call.preallocated.setup, return the corresponding 5916 /// preallocated call. 5917 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5918 assert(cast<CallBase>(PreallocatedSetup) 5919 ->getCalledFunction() 5920 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5921 "expected call_preallocated_setup Value"); 5922 for (const auto *U : PreallocatedSetup->users()) { 5923 auto *UseCall = cast<CallBase>(U); 5924 const Function *Fn = UseCall->getCalledFunction(); 5925 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5926 return UseCall; 5927 } 5928 } 5929 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5930 } 5931 5932 /// Lower the call to the specified intrinsic function. 5933 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5934 unsigned Intrinsic) { 5935 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5936 SDLoc sdl = getCurSDLoc(); 5937 DebugLoc dl = getCurDebugLoc(); 5938 SDValue Res; 5939 5940 SDNodeFlags Flags; 5941 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5942 Flags.copyFMF(*FPOp); 5943 5944 switch (Intrinsic) { 5945 default: 5946 // By default, turn this into a target intrinsic node. 5947 visitTargetIntrinsic(I, Intrinsic); 5948 return; 5949 case Intrinsic::vscale: { 5950 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5951 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5952 return; 5953 } 5954 case Intrinsic::vastart: visitVAStart(I); return; 5955 case Intrinsic::vaend: visitVAEnd(I); return; 5956 case Intrinsic::vacopy: visitVACopy(I); return; 5957 case Intrinsic::returnaddress: 5958 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5959 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5960 getValue(I.getArgOperand(0)))); 5961 return; 5962 case Intrinsic::addressofreturnaddress: 5963 setValue(&I, 5964 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5965 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5966 return; 5967 case Intrinsic::sponentry: 5968 setValue(&I, 5969 DAG.getNode(ISD::SPONENTRY, sdl, 5970 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5971 return; 5972 case Intrinsic::frameaddress: 5973 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5974 TLI.getFrameIndexTy(DAG.getDataLayout()), 5975 getValue(I.getArgOperand(0)))); 5976 return; 5977 case Intrinsic::read_volatile_register: 5978 case Intrinsic::read_register: { 5979 Value *Reg = I.getArgOperand(0); 5980 SDValue Chain = getRoot(); 5981 SDValue RegName = 5982 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5983 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5984 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5985 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5986 setValue(&I, Res); 5987 DAG.setRoot(Res.getValue(1)); 5988 return; 5989 } 5990 case Intrinsic::write_register: { 5991 Value *Reg = I.getArgOperand(0); 5992 Value *RegValue = I.getArgOperand(1); 5993 SDValue Chain = getRoot(); 5994 SDValue RegName = 5995 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5996 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5997 RegName, getValue(RegValue))); 5998 return; 5999 } 6000 case Intrinsic::memcpy: { 6001 const auto &MCI = cast<MemCpyInst>(I); 6002 SDValue Op1 = getValue(I.getArgOperand(0)); 6003 SDValue Op2 = getValue(I.getArgOperand(1)); 6004 SDValue Op3 = getValue(I.getArgOperand(2)); 6005 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6006 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6007 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6008 Align Alignment = std::min(DstAlign, SrcAlign); 6009 bool isVol = MCI.isVolatile(); 6010 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6011 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6012 // node. 6013 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6014 SDValue MC = DAG.getMemcpy( 6015 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6016 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6017 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6018 updateDAGForMaybeTailCall(MC); 6019 return; 6020 } 6021 case Intrinsic::memcpy_inline: { 6022 const auto &MCI = cast<MemCpyInlineInst>(I); 6023 SDValue Dst = getValue(I.getArgOperand(0)); 6024 SDValue Src = getValue(I.getArgOperand(1)); 6025 SDValue Size = getValue(I.getArgOperand(2)); 6026 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6027 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6028 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6029 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6030 Align Alignment = std::min(DstAlign, SrcAlign); 6031 bool isVol = MCI.isVolatile(); 6032 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6033 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6034 // node. 6035 SDValue MC = DAG.getMemcpy( 6036 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6037 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6038 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6039 updateDAGForMaybeTailCall(MC); 6040 return; 6041 } 6042 case Intrinsic::memset: { 6043 const auto &MSI = cast<MemSetInst>(I); 6044 SDValue Op1 = getValue(I.getArgOperand(0)); 6045 SDValue Op2 = getValue(I.getArgOperand(1)); 6046 SDValue Op3 = getValue(I.getArgOperand(2)); 6047 // @llvm.memset defines 0 and 1 to both mean no alignment. 6048 Align Alignment = MSI.getDestAlign().valueOrOne(); 6049 bool isVol = MSI.isVolatile(); 6050 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6051 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6052 SDValue MS = DAG.getMemset( 6053 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6054 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6055 updateDAGForMaybeTailCall(MS); 6056 return; 6057 } 6058 case Intrinsic::memset_inline: { 6059 const auto &MSII = cast<MemSetInlineInst>(I); 6060 SDValue Dst = getValue(I.getArgOperand(0)); 6061 SDValue Value = getValue(I.getArgOperand(1)); 6062 SDValue Size = getValue(I.getArgOperand(2)); 6063 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6064 // @llvm.memset defines 0 and 1 to both mean no alignment. 6065 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6066 bool isVol = MSII.isVolatile(); 6067 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6068 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6069 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6070 /* AlwaysInline */ true, isTC, 6071 MachinePointerInfo(I.getArgOperand(0)), 6072 I.getAAMetadata()); 6073 updateDAGForMaybeTailCall(MC); 6074 return; 6075 } 6076 case Intrinsic::memmove: { 6077 const auto &MMI = cast<MemMoveInst>(I); 6078 SDValue Op1 = getValue(I.getArgOperand(0)); 6079 SDValue Op2 = getValue(I.getArgOperand(1)); 6080 SDValue Op3 = getValue(I.getArgOperand(2)); 6081 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6082 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6083 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6084 Align Alignment = std::min(DstAlign, SrcAlign); 6085 bool isVol = MMI.isVolatile(); 6086 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6087 // FIXME: Support passing different dest/src alignments to the memmove DAG 6088 // node. 6089 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6090 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6091 isTC, MachinePointerInfo(I.getArgOperand(0)), 6092 MachinePointerInfo(I.getArgOperand(1)), 6093 I.getAAMetadata(), AA); 6094 updateDAGForMaybeTailCall(MM); 6095 return; 6096 } 6097 case Intrinsic::memcpy_element_unordered_atomic: { 6098 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6099 SDValue Dst = getValue(MI.getRawDest()); 6100 SDValue Src = getValue(MI.getRawSource()); 6101 SDValue Length = getValue(MI.getLength()); 6102 6103 Type *LengthTy = MI.getLength()->getType(); 6104 unsigned ElemSz = MI.getElementSizeInBytes(); 6105 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6106 SDValue MC = 6107 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6108 isTC, MachinePointerInfo(MI.getRawDest()), 6109 MachinePointerInfo(MI.getRawSource())); 6110 updateDAGForMaybeTailCall(MC); 6111 return; 6112 } 6113 case Intrinsic::memmove_element_unordered_atomic: { 6114 auto &MI = cast<AtomicMemMoveInst>(I); 6115 SDValue Dst = getValue(MI.getRawDest()); 6116 SDValue Src = getValue(MI.getRawSource()); 6117 SDValue Length = getValue(MI.getLength()); 6118 6119 Type *LengthTy = MI.getLength()->getType(); 6120 unsigned ElemSz = MI.getElementSizeInBytes(); 6121 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6122 SDValue MC = 6123 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6124 isTC, MachinePointerInfo(MI.getRawDest()), 6125 MachinePointerInfo(MI.getRawSource())); 6126 updateDAGForMaybeTailCall(MC); 6127 return; 6128 } 6129 case Intrinsic::memset_element_unordered_atomic: { 6130 auto &MI = cast<AtomicMemSetInst>(I); 6131 SDValue Dst = getValue(MI.getRawDest()); 6132 SDValue Val = getValue(MI.getValue()); 6133 SDValue Length = getValue(MI.getLength()); 6134 6135 Type *LengthTy = MI.getLength()->getType(); 6136 unsigned ElemSz = MI.getElementSizeInBytes(); 6137 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6138 SDValue MC = 6139 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6140 isTC, MachinePointerInfo(MI.getRawDest())); 6141 updateDAGForMaybeTailCall(MC); 6142 return; 6143 } 6144 case Intrinsic::call_preallocated_setup: { 6145 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6146 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6147 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6148 getRoot(), SrcValue); 6149 setValue(&I, Res); 6150 DAG.setRoot(Res); 6151 return; 6152 } 6153 case Intrinsic::call_preallocated_arg: { 6154 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6155 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6156 SDValue Ops[3]; 6157 Ops[0] = getRoot(); 6158 Ops[1] = SrcValue; 6159 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6160 MVT::i32); // arg index 6161 SDValue Res = DAG.getNode( 6162 ISD::PREALLOCATED_ARG, sdl, 6163 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6164 setValue(&I, Res); 6165 DAG.setRoot(Res.getValue(1)); 6166 return; 6167 } 6168 case Intrinsic::dbg_declare: { 6169 const auto &DI = cast<DbgDeclareInst>(I); 6170 // Debug intrinsics are handled separately in assignment tracking mode. 6171 // Some intrinsics are handled right after Argument lowering. 6172 if (AssignmentTrackingEnabled || 6173 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6174 return; 6175 // Assume dbg.declare can not currently use DIArgList, i.e. 6176 // it is non-variadic. 6177 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6178 DILocalVariable *Variable = DI.getVariable(); 6179 DIExpression *Expression = DI.getExpression(); 6180 dropDanglingDebugInfo(Variable, Expression); 6181 assert(Variable && "Missing variable"); 6182 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6183 << "\n"); 6184 // Check if address has undef value. 6185 const Value *Address = DI.getVariableLocationOp(0); 6186 if (!Address || isa<UndefValue>(Address) || 6187 (Address->use_empty() && !isa<Argument>(Address))) { 6188 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6189 << " (bad/undef/unused-arg address)\n"); 6190 return; 6191 } 6192 6193 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6194 6195 SDValue &N = NodeMap[Address]; 6196 if (!N.getNode() && isa<Argument>(Address)) 6197 // Check unused arguments map. 6198 N = UnusedArgNodeMap[Address]; 6199 SDDbgValue *SDV; 6200 if (N.getNode()) { 6201 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6202 Address = BCI->getOperand(0); 6203 // Parameters are handled specially. 6204 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6205 if (isParameter && FINode) { 6206 // Byval parameter. We have a frame index at this point. 6207 SDV = 6208 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6209 /*IsIndirect*/ true, dl, SDNodeOrder); 6210 } else if (isa<Argument>(Address)) { 6211 // Address is an argument, so try to emit its dbg value using 6212 // virtual register info from the FuncInfo.ValueMap. 6213 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6214 FuncArgumentDbgValueKind::Declare, N); 6215 return; 6216 } else { 6217 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6218 true, dl, SDNodeOrder); 6219 } 6220 DAG.AddDbgValue(SDV, isParameter); 6221 } else { 6222 // If Address is an argument then try to emit its dbg value using 6223 // virtual register info from the FuncInfo.ValueMap. 6224 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6225 FuncArgumentDbgValueKind::Declare, N)) { 6226 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6227 << " (could not emit func-arg dbg_value)\n"); 6228 } 6229 } 6230 return; 6231 } 6232 case Intrinsic::dbg_label: { 6233 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6234 DILabel *Label = DI.getLabel(); 6235 assert(Label && "Missing label"); 6236 6237 SDDbgLabel *SDV; 6238 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6239 DAG.AddDbgLabel(SDV); 6240 return; 6241 } 6242 case Intrinsic::dbg_assign: { 6243 // Debug intrinsics are handled seperately in assignment tracking mode. 6244 if (AssignmentTrackingEnabled) 6245 return; 6246 // If assignment tracking hasn't been enabled then fall through and treat 6247 // the dbg.assign as a dbg.value. 6248 [[fallthrough]]; 6249 } 6250 case Intrinsic::dbg_value: { 6251 // Debug intrinsics are handled seperately in assignment tracking mode. 6252 if (AssignmentTrackingEnabled) 6253 return; 6254 const DbgValueInst &DI = cast<DbgValueInst>(I); 6255 assert(DI.getVariable() && "Missing variable"); 6256 6257 DILocalVariable *Variable = DI.getVariable(); 6258 DIExpression *Expression = DI.getExpression(); 6259 dropDanglingDebugInfo(Variable, Expression); 6260 6261 if (DI.isKillLocation()) { 6262 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6263 return; 6264 } 6265 6266 SmallVector<Value *, 4> Values(DI.getValues()); 6267 if (Values.empty()) 6268 return; 6269 6270 bool IsVariadic = DI.hasArgList(); 6271 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6272 SDNodeOrder, IsVariadic)) 6273 addDanglingDebugInfo(&DI, SDNodeOrder); 6274 return; 6275 } 6276 6277 case Intrinsic::eh_typeid_for: { 6278 // Find the type id for the given typeinfo. 6279 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6280 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6281 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6282 setValue(&I, Res); 6283 return; 6284 } 6285 6286 case Intrinsic::eh_return_i32: 6287 case Intrinsic::eh_return_i64: 6288 DAG.getMachineFunction().setCallsEHReturn(true); 6289 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6290 MVT::Other, 6291 getControlRoot(), 6292 getValue(I.getArgOperand(0)), 6293 getValue(I.getArgOperand(1)))); 6294 return; 6295 case Intrinsic::eh_unwind_init: 6296 DAG.getMachineFunction().setCallsUnwindInit(true); 6297 return; 6298 case Intrinsic::eh_dwarf_cfa: 6299 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6300 TLI.getPointerTy(DAG.getDataLayout()), 6301 getValue(I.getArgOperand(0)))); 6302 return; 6303 case Intrinsic::eh_sjlj_callsite: { 6304 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6305 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6306 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6307 6308 MMI.setCurrentCallSite(CI->getZExtValue()); 6309 return; 6310 } 6311 case Intrinsic::eh_sjlj_functioncontext: { 6312 // Get and store the index of the function context. 6313 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6314 AllocaInst *FnCtx = 6315 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6316 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6317 MFI.setFunctionContextIndex(FI); 6318 return; 6319 } 6320 case Intrinsic::eh_sjlj_setjmp: { 6321 SDValue Ops[2]; 6322 Ops[0] = getRoot(); 6323 Ops[1] = getValue(I.getArgOperand(0)); 6324 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6325 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6326 setValue(&I, Op.getValue(0)); 6327 DAG.setRoot(Op.getValue(1)); 6328 return; 6329 } 6330 case Intrinsic::eh_sjlj_longjmp: 6331 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6332 getRoot(), getValue(I.getArgOperand(0)))); 6333 return; 6334 case Intrinsic::eh_sjlj_setup_dispatch: 6335 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6336 getRoot())); 6337 return; 6338 case Intrinsic::masked_gather: 6339 visitMaskedGather(I); 6340 return; 6341 case Intrinsic::masked_load: 6342 visitMaskedLoad(I); 6343 return; 6344 case Intrinsic::masked_scatter: 6345 visitMaskedScatter(I); 6346 return; 6347 case Intrinsic::masked_store: 6348 visitMaskedStore(I); 6349 return; 6350 case Intrinsic::masked_expandload: 6351 visitMaskedLoad(I, true /* IsExpanding */); 6352 return; 6353 case Intrinsic::masked_compressstore: 6354 visitMaskedStore(I, true /* IsCompressing */); 6355 return; 6356 case Intrinsic::powi: 6357 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6358 getValue(I.getArgOperand(1)), DAG)); 6359 return; 6360 case Intrinsic::log: 6361 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6362 return; 6363 case Intrinsic::log2: 6364 setValue(&I, 6365 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6366 return; 6367 case Intrinsic::log10: 6368 setValue(&I, 6369 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6370 return; 6371 case Intrinsic::exp: 6372 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6373 return; 6374 case Intrinsic::exp2: 6375 setValue(&I, 6376 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6377 return; 6378 case Intrinsic::pow: 6379 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6380 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6381 return; 6382 case Intrinsic::sqrt: 6383 case Intrinsic::fabs: 6384 case Intrinsic::sin: 6385 case Intrinsic::cos: 6386 case Intrinsic::floor: 6387 case Intrinsic::ceil: 6388 case Intrinsic::trunc: 6389 case Intrinsic::rint: 6390 case Intrinsic::nearbyint: 6391 case Intrinsic::round: 6392 case Intrinsic::roundeven: 6393 case Intrinsic::canonicalize: { 6394 unsigned Opcode; 6395 switch (Intrinsic) { 6396 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6397 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6398 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6399 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6400 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6401 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6402 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6403 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6404 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6405 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6406 case Intrinsic::round: Opcode = ISD::FROUND; break; 6407 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6408 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6409 } 6410 6411 setValue(&I, DAG.getNode(Opcode, sdl, 6412 getValue(I.getArgOperand(0)).getValueType(), 6413 getValue(I.getArgOperand(0)), Flags)); 6414 return; 6415 } 6416 case Intrinsic::lround: 6417 case Intrinsic::llround: 6418 case Intrinsic::lrint: 6419 case Intrinsic::llrint: { 6420 unsigned Opcode; 6421 switch (Intrinsic) { 6422 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6423 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6424 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6425 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6426 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6427 } 6428 6429 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6430 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6431 getValue(I.getArgOperand(0)))); 6432 return; 6433 } 6434 case Intrinsic::minnum: 6435 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6436 getValue(I.getArgOperand(0)).getValueType(), 6437 getValue(I.getArgOperand(0)), 6438 getValue(I.getArgOperand(1)), Flags)); 6439 return; 6440 case Intrinsic::maxnum: 6441 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6442 getValue(I.getArgOperand(0)).getValueType(), 6443 getValue(I.getArgOperand(0)), 6444 getValue(I.getArgOperand(1)), Flags)); 6445 return; 6446 case Intrinsic::minimum: 6447 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6448 getValue(I.getArgOperand(0)).getValueType(), 6449 getValue(I.getArgOperand(0)), 6450 getValue(I.getArgOperand(1)), Flags)); 6451 return; 6452 case Intrinsic::maximum: 6453 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6454 getValue(I.getArgOperand(0)).getValueType(), 6455 getValue(I.getArgOperand(0)), 6456 getValue(I.getArgOperand(1)), Flags)); 6457 return; 6458 case Intrinsic::copysign: 6459 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6460 getValue(I.getArgOperand(0)).getValueType(), 6461 getValue(I.getArgOperand(0)), 6462 getValue(I.getArgOperand(1)), Flags)); 6463 return; 6464 case Intrinsic::ldexp: 6465 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6466 getValue(I.getArgOperand(0)).getValueType(), 6467 getValue(I.getArgOperand(0)), 6468 getValue(I.getArgOperand(1)), Flags)); 6469 return; 6470 case Intrinsic::arithmetic_fence: { 6471 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6472 getValue(I.getArgOperand(0)).getValueType(), 6473 getValue(I.getArgOperand(0)), Flags)); 6474 return; 6475 } 6476 case Intrinsic::fma: 6477 setValue(&I, DAG.getNode( 6478 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6479 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6480 getValue(I.getArgOperand(2)), Flags)); 6481 return; 6482 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6483 case Intrinsic::INTRINSIC: 6484 #include "llvm/IR/ConstrainedOps.def" 6485 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6486 return; 6487 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6488 #include "llvm/IR/VPIntrinsics.def" 6489 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6490 return; 6491 case Intrinsic::fptrunc_round: { 6492 // Get the last argument, the metadata and convert it to an integer in the 6493 // call 6494 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6495 std::optional<RoundingMode> RoundMode = 6496 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6497 6498 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6499 6500 // Propagate fast-math-flags from IR to node(s). 6501 SDNodeFlags Flags; 6502 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6503 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6504 6505 SDValue Result; 6506 Result = DAG.getNode( 6507 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6508 DAG.getTargetConstant((int)*RoundMode, sdl, 6509 TLI.getPointerTy(DAG.getDataLayout()))); 6510 setValue(&I, Result); 6511 6512 return; 6513 } 6514 case Intrinsic::fmuladd: { 6515 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6516 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6517 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6518 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6519 getValue(I.getArgOperand(0)).getValueType(), 6520 getValue(I.getArgOperand(0)), 6521 getValue(I.getArgOperand(1)), 6522 getValue(I.getArgOperand(2)), Flags)); 6523 } else { 6524 // TODO: Intrinsic calls should have fast-math-flags. 6525 SDValue Mul = DAG.getNode( 6526 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6527 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6528 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6529 getValue(I.getArgOperand(0)).getValueType(), 6530 Mul, getValue(I.getArgOperand(2)), Flags); 6531 setValue(&I, Add); 6532 } 6533 return; 6534 } 6535 case Intrinsic::convert_to_fp16: 6536 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6537 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6538 getValue(I.getArgOperand(0)), 6539 DAG.getTargetConstant(0, sdl, 6540 MVT::i32)))); 6541 return; 6542 case Intrinsic::convert_from_fp16: 6543 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6544 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6545 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6546 getValue(I.getArgOperand(0))))); 6547 return; 6548 case Intrinsic::fptosi_sat: { 6549 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6550 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6551 getValue(I.getArgOperand(0)), 6552 DAG.getValueType(VT.getScalarType()))); 6553 return; 6554 } 6555 case Intrinsic::fptoui_sat: { 6556 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6557 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6558 getValue(I.getArgOperand(0)), 6559 DAG.getValueType(VT.getScalarType()))); 6560 return; 6561 } 6562 case Intrinsic::set_rounding: 6563 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6564 {getRoot(), getValue(I.getArgOperand(0))}); 6565 setValue(&I, Res); 6566 DAG.setRoot(Res.getValue(0)); 6567 return; 6568 case Intrinsic::is_fpclass: { 6569 const DataLayout DLayout = DAG.getDataLayout(); 6570 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6571 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6572 FPClassTest Test = static_cast<FPClassTest>( 6573 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6574 MachineFunction &MF = DAG.getMachineFunction(); 6575 const Function &F = MF.getFunction(); 6576 SDValue Op = getValue(I.getArgOperand(0)); 6577 SDNodeFlags Flags; 6578 Flags.setNoFPExcept( 6579 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6580 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6581 // expansion can use illegal types. Making expansion early allows 6582 // legalizing these types prior to selection. 6583 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6584 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6585 setValue(&I, Result); 6586 return; 6587 } 6588 6589 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6590 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6591 setValue(&I, V); 6592 return; 6593 } 6594 case Intrinsic::get_fpenv: { 6595 const DataLayout DLayout = DAG.getDataLayout(); 6596 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 6597 Align TempAlign = DAG.getEVTAlign(EnvVT); 6598 SDValue Chain = DAG.getRoot(); 6599 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 6600 // and temporary storage in stack. 6601 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 6602 Res = DAG.getNode( 6603 ISD::GET_FPENV, sdl, 6604 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6605 MVT::Other), 6606 Chain); 6607 } else { 6608 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6609 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6610 auto MPI = 6611 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6612 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6613 MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize, 6614 TempAlign); 6615 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6616 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 6617 } 6618 setValue(&I, Res); 6619 DAG.setRoot(Res.getValue(1)); 6620 return; 6621 } 6622 case Intrinsic::set_fpenv: { 6623 const DataLayout DLayout = DAG.getDataLayout(); 6624 SDValue Env = getValue(I.getArgOperand(0)); 6625 EVT EnvVT = Env.getValueType(); 6626 Align TempAlign = DAG.getEVTAlign(EnvVT); 6627 SDValue Chain = getRoot(); 6628 // If SET_FPENV is custom or legal, use it. Otherwise use loading 6629 // environment from memory. 6630 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 6631 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 6632 } else { 6633 // Allocate space in stack, copy environment bits into it and use this 6634 // memory in SET_FPENV_MEM. 6635 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6636 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6637 auto MPI = 6638 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6639 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 6640 MachineMemOperand::MOStore); 6641 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6642 MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize, 6643 TempAlign); 6644 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6645 } 6646 DAG.setRoot(Chain); 6647 return; 6648 } 6649 case Intrinsic::reset_fpenv: 6650 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 6651 return; 6652 case Intrinsic::pcmarker: { 6653 SDValue Tmp = getValue(I.getArgOperand(0)); 6654 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6655 return; 6656 } 6657 case Intrinsic::readcyclecounter: { 6658 SDValue Op = getRoot(); 6659 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6660 DAG.getVTList(MVT::i64, MVT::Other), Op); 6661 setValue(&I, Res); 6662 DAG.setRoot(Res.getValue(1)); 6663 return; 6664 } 6665 case Intrinsic::bitreverse: 6666 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6667 getValue(I.getArgOperand(0)).getValueType(), 6668 getValue(I.getArgOperand(0)))); 6669 return; 6670 case Intrinsic::bswap: 6671 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6672 getValue(I.getArgOperand(0)).getValueType(), 6673 getValue(I.getArgOperand(0)))); 6674 return; 6675 case Intrinsic::cttz: { 6676 SDValue Arg = getValue(I.getArgOperand(0)); 6677 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6678 EVT Ty = Arg.getValueType(); 6679 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6680 sdl, Ty, Arg)); 6681 return; 6682 } 6683 case Intrinsic::ctlz: { 6684 SDValue Arg = getValue(I.getArgOperand(0)); 6685 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6686 EVT Ty = Arg.getValueType(); 6687 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6688 sdl, Ty, Arg)); 6689 return; 6690 } 6691 case Intrinsic::ctpop: { 6692 SDValue Arg = getValue(I.getArgOperand(0)); 6693 EVT Ty = Arg.getValueType(); 6694 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6695 return; 6696 } 6697 case Intrinsic::fshl: 6698 case Intrinsic::fshr: { 6699 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6700 SDValue X = getValue(I.getArgOperand(0)); 6701 SDValue Y = getValue(I.getArgOperand(1)); 6702 SDValue Z = getValue(I.getArgOperand(2)); 6703 EVT VT = X.getValueType(); 6704 6705 if (X == Y) { 6706 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6707 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6708 } else { 6709 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6710 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6711 } 6712 return; 6713 } 6714 case Intrinsic::sadd_sat: { 6715 SDValue Op1 = getValue(I.getArgOperand(0)); 6716 SDValue Op2 = getValue(I.getArgOperand(1)); 6717 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6718 return; 6719 } 6720 case Intrinsic::uadd_sat: { 6721 SDValue Op1 = getValue(I.getArgOperand(0)); 6722 SDValue Op2 = getValue(I.getArgOperand(1)); 6723 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6724 return; 6725 } 6726 case Intrinsic::ssub_sat: { 6727 SDValue Op1 = getValue(I.getArgOperand(0)); 6728 SDValue Op2 = getValue(I.getArgOperand(1)); 6729 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6730 return; 6731 } 6732 case Intrinsic::usub_sat: { 6733 SDValue Op1 = getValue(I.getArgOperand(0)); 6734 SDValue Op2 = getValue(I.getArgOperand(1)); 6735 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6736 return; 6737 } 6738 case Intrinsic::sshl_sat: { 6739 SDValue Op1 = getValue(I.getArgOperand(0)); 6740 SDValue Op2 = getValue(I.getArgOperand(1)); 6741 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6742 return; 6743 } 6744 case Intrinsic::ushl_sat: { 6745 SDValue Op1 = getValue(I.getArgOperand(0)); 6746 SDValue Op2 = getValue(I.getArgOperand(1)); 6747 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6748 return; 6749 } 6750 case Intrinsic::smul_fix: 6751 case Intrinsic::umul_fix: 6752 case Intrinsic::smul_fix_sat: 6753 case Intrinsic::umul_fix_sat: { 6754 SDValue Op1 = getValue(I.getArgOperand(0)); 6755 SDValue Op2 = getValue(I.getArgOperand(1)); 6756 SDValue Op3 = getValue(I.getArgOperand(2)); 6757 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6758 Op1.getValueType(), Op1, Op2, Op3)); 6759 return; 6760 } 6761 case Intrinsic::sdiv_fix: 6762 case Intrinsic::udiv_fix: 6763 case Intrinsic::sdiv_fix_sat: 6764 case Intrinsic::udiv_fix_sat: { 6765 SDValue Op1 = getValue(I.getArgOperand(0)); 6766 SDValue Op2 = getValue(I.getArgOperand(1)); 6767 SDValue Op3 = getValue(I.getArgOperand(2)); 6768 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6769 Op1, Op2, Op3, DAG, TLI)); 6770 return; 6771 } 6772 case Intrinsic::smax: { 6773 SDValue Op1 = getValue(I.getArgOperand(0)); 6774 SDValue Op2 = getValue(I.getArgOperand(1)); 6775 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6776 return; 6777 } 6778 case Intrinsic::smin: { 6779 SDValue Op1 = getValue(I.getArgOperand(0)); 6780 SDValue Op2 = getValue(I.getArgOperand(1)); 6781 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6782 return; 6783 } 6784 case Intrinsic::umax: { 6785 SDValue Op1 = getValue(I.getArgOperand(0)); 6786 SDValue Op2 = getValue(I.getArgOperand(1)); 6787 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6788 return; 6789 } 6790 case Intrinsic::umin: { 6791 SDValue Op1 = getValue(I.getArgOperand(0)); 6792 SDValue Op2 = getValue(I.getArgOperand(1)); 6793 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6794 return; 6795 } 6796 case Intrinsic::abs: { 6797 // TODO: Preserve "int min is poison" arg in SDAG? 6798 SDValue Op1 = getValue(I.getArgOperand(0)); 6799 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6800 return; 6801 } 6802 case Intrinsic::stacksave: { 6803 SDValue Op = getRoot(); 6804 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6805 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6806 setValue(&I, Res); 6807 DAG.setRoot(Res.getValue(1)); 6808 return; 6809 } 6810 case Intrinsic::stackrestore: 6811 Res = getValue(I.getArgOperand(0)); 6812 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6813 return; 6814 case Intrinsic::get_dynamic_area_offset: { 6815 SDValue Op = getRoot(); 6816 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6817 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6818 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6819 // target. 6820 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6821 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6822 " intrinsic!"); 6823 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6824 Op); 6825 DAG.setRoot(Op); 6826 setValue(&I, Res); 6827 return; 6828 } 6829 case Intrinsic::stackguard: { 6830 MachineFunction &MF = DAG.getMachineFunction(); 6831 const Module &M = *MF.getFunction().getParent(); 6832 SDValue Chain = getRoot(); 6833 if (TLI.useLoadStackGuardNode()) { 6834 Res = getLoadStackGuard(DAG, sdl, Chain); 6835 } else { 6836 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6837 const Value *Global = TLI.getSDagStackGuard(M); 6838 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6839 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6840 MachinePointerInfo(Global, 0), Align, 6841 MachineMemOperand::MOVolatile); 6842 } 6843 if (TLI.useStackGuardXorFP()) 6844 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6845 DAG.setRoot(Chain); 6846 setValue(&I, Res); 6847 return; 6848 } 6849 case Intrinsic::stackprotector: { 6850 // Emit code into the DAG to store the stack guard onto the stack. 6851 MachineFunction &MF = DAG.getMachineFunction(); 6852 MachineFrameInfo &MFI = MF.getFrameInfo(); 6853 SDValue Src, Chain = getRoot(); 6854 6855 if (TLI.useLoadStackGuardNode()) 6856 Src = getLoadStackGuard(DAG, sdl, Chain); 6857 else 6858 Src = getValue(I.getArgOperand(0)); // The guard's value. 6859 6860 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6861 6862 int FI = FuncInfo.StaticAllocaMap[Slot]; 6863 MFI.setStackProtectorIndex(FI); 6864 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6865 6866 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6867 6868 // Store the stack protector onto the stack. 6869 Res = DAG.getStore( 6870 Chain, sdl, Src, FIN, 6871 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6872 MaybeAlign(), MachineMemOperand::MOVolatile); 6873 setValue(&I, Res); 6874 DAG.setRoot(Res); 6875 return; 6876 } 6877 case Intrinsic::objectsize: 6878 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6879 6880 case Intrinsic::is_constant: 6881 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6882 6883 case Intrinsic::annotation: 6884 case Intrinsic::ptr_annotation: 6885 case Intrinsic::launder_invariant_group: 6886 case Intrinsic::strip_invariant_group: 6887 // Drop the intrinsic, but forward the value 6888 setValue(&I, getValue(I.getOperand(0))); 6889 return; 6890 6891 case Intrinsic::assume: 6892 case Intrinsic::experimental_noalias_scope_decl: 6893 case Intrinsic::var_annotation: 6894 case Intrinsic::sideeffect: 6895 // Discard annotate attributes, noalias scope declarations, assumptions, and 6896 // artificial side-effects. 6897 return; 6898 6899 case Intrinsic::codeview_annotation: { 6900 // Emit a label associated with this metadata. 6901 MachineFunction &MF = DAG.getMachineFunction(); 6902 MCSymbol *Label = 6903 MF.getMMI().getContext().createTempSymbol("annotation", true); 6904 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6905 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6906 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6907 DAG.setRoot(Res); 6908 return; 6909 } 6910 6911 case Intrinsic::init_trampoline: { 6912 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6913 6914 SDValue Ops[6]; 6915 Ops[0] = getRoot(); 6916 Ops[1] = getValue(I.getArgOperand(0)); 6917 Ops[2] = getValue(I.getArgOperand(1)); 6918 Ops[3] = getValue(I.getArgOperand(2)); 6919 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6920 Ops[5] = DAG.getSrcValue(F); 6921 6922 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6923 6924 DAG.setRoot(Res); 6925 return; 6926 } 6927 case Intrinsic::adjust_trampoline: 6928 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6929 TLI.getPointerTy(DAG.getDataLayout()), 6930 getValue(I.getArgOperand(0)))); 6931 return; 6932 case Intrinsic::gcroot: { 6933 assert(DAG.getMachineFunction().getFunction().hasGC() && 6934 "only valid in functions with gc specified, enforced by Verifier"); 6935 assert(GFI && "implied by previous"); 6936 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6937 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6938 6939 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6940 GFI->addStackRoot(FI->getIndex(), TypeMap); 6941 return; 6942 } 6943 case Intrinsic::gcread: 6944 case Intrinsic::gcwrite: 6945 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6946 case Intrinsic::get_rounding: 6947 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 6948 setValue(&I, Res); 6949 DAG.setRoot(Res.getValue(1)); 6950 return; 6951 6952 case Intrinsic::expect: 6953 // Just replace __builtin_expect(exp, c) with EXP. 6954 setValue(&I, getValue(I.getArgOperand(0))); 6955 return; 6956 6957 case Intrinsic::ubsantrap: 6958 case Intrinsic::debugtrap: 6959 case Intrinsic::trap: { 6960 StringRef TrapFuncName = 6961 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6962 if (TrapFuncName.empty()) { 6963 switch (Intrinsic) { 6964 case Intrinsic::trap: 6965 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6966 break; 6967 case Intrinsic::debugtrap: 6968 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6969 break; 6970 case Intrinsic::ubsantrap: 6971 DAG.setRoot(DAG.getNode( 6972 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6973 DAG.getTargetConstant( 6974 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6975 MVT::i32))); 6976 break; 6977 default: llvm_unreachable("unknown trap intrinsic"); 6978 } 6979 return; 6980 } 6981 TargetLowering::ArgListTy Args; 6982 if (Intrinsic == Intrinsic::ubsantrap) { 6983 Args.push_back(TargetLoweringBase::ArgListEntry()); 6984 Args[0].Val = I.getArgOperand(0); 6985 Args[0].Node = getValue(Args[0].Val); 6986 Args[0].Ty = Args[0].Val->getType(); 6987 } 6988 6989 TargetLowering::CallLoweringInfo CLI(DAG); 6990 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6991 CallingConv::C, I.getType(), 6992 DAG.getExternalSymbol(TrapFuncName.data(), 6993 TLI.getPointerTy(DAG.getDataLayout())), 6994 std::move(Args)); 6995 6996 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6997 DAG.setRoot(Result.second); 6998 return; 6999 } 7000 7001 case Intrinsic::uadd_with_overflow: 7002 case Intrinsic::sadd_with_overflow: 7003 case Intrinsic::usub_with_overflow: 7004 case Intrinsic::ssub_with_overflow: 7005 case Intrinsic::umul_with_overflow: 7006 case Intrinsic::smul_with_overflow: { 7007 ISD::NodeType Op; 7008 switch (Intrinsic) { 7009 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7010 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7011 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7012 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7013 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7014 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7015 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7016 } 7017 SDValue Op1 = getValue(I.getArgOperand(0)); 7018 SDValue Op2 = getValue(I.getArgOperand(1)); 7019 7020 EVT ResultVT = Op1.getValueType(); 7021 EVT OverflowVT = MVT::i1; 7022 if (ResultVT.isVector()) 7023 OverflowVT = EVT::getVectorVT( 7024 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7025 7026 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7027 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7028 return; 7029 } 7030 case Intrinsic::prefetch: { 7031 SDValue Ops[5]; 7032 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7033 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7034 Ops[0] = DAG.getRoot(); 7035 Ops[1] = getValue(I.getArgOperand(0)); 7036 Ops[2] = getValue(I.getArgOperand(1)); 7037 Ops[3] = getValue(I.getArgOperand(2)); 7038 Ops[4] = getValue(I.getArgOperand(3)); 7039 SDValue Result = DAG.getMemIntrinsicNode( 7040 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7041 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7042 /* align */ std::nullopt, Flags); 7043 7044 // Chain the prefetch in parallell with any pending loads, to stay out of 7045 // the way of later optimizations. 7046 PendingLoads.push_back(Result); 7047 Result = getRoot(); 7048 DAG.setRoot(Result); 7049 return; 7050 } 7051 case Intrinsic::lifetime_start: 7052 case Intrinsic::lifetime_end: { 7053 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7054 // Stack coloring is not enabled in O0, discard region information. 7055 if (TM.getOptLevel() == CodeGenOpt::None) 7056 return; 7057 7058 const int64_t ObjectSize = 7059 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7060 Value *const ObjectPtr = I.getArgOperand(1); 7061 SmallVector<const Value *, 4> Allocas; 7062 getUnderlyingObjects(ObjectPtr, Allocas); 7063 7064 for (const Value *Alloca : Allocas) { 7065 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7066 7067 // Could not find an Alloca. 7068 if (!LifetimeObject) 7069 continue; 7070 7071 // First check that the Alloca is static, otherwise it won't have a 7072 // valid frame index. 7073 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7074 if (SI == FuncInfo.StaticAllocaMap.end()) 7075 return; 7076 7077 const int FrameIndex = SI->second; 7078 int64_t Offset; 7079 if (GetPointerBaseWithConstantOffset( 7080 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7081 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7082 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7083 Offset); 7084 DAG.setRoot(Res); 7085 } 7086 return; 7087 } 7088 case Intrinsic::pseudoprobe: { 7089 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7090 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7091 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7092 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7093 DAG.setRoot(Res); 7094 return; 7095 } 7096 case Intrinsic::invariant_start: 7097 // Discard region information. 7098 setValue(&I, 7099 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7100 return; 7101 case Intrinsic::invariant_end: 7102 // Discard region information. 7103 return; 7104 case Intrinsic::clear_cache: 7105 /// FunctionName may be null. 7106 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7107 lowerCallToExternalSymbol(I, FunctionName); 7108 return; 7109 case Intrinsic::donothing: 7110 case Intrinsic::seh_try_begin: 7111 case Intrinsic::seh_scope_begin: 7112 case Intrinsic::seh_try_end: 7113 case Intrinsic::seh_scope_end: 7114 // ignore 7115 return; 7116 case Intrinsic::experimental_stackmap: 7117 visitStackmap(I); 7118 return; 7119 case Intrinsic::experimental_patchpoint_void: 7120 case Intrinsic::experimental_patchpoint_i64: 7121 visitPatchpoint(I); 7122 return; 7123 case Intrinsic::experimental_gc_statepoint: 7124 LowerStatepoint(cast<GCStatepointInst>(I)); 7125 return; 7126 case Intrinsic::experimental_gc_result: 7127 visitGCResult(cast<GCResultInst>(I)); 7128 return; 7129 case Intrinsic::experimental_gc_relocate: 7130 visitGCRelocate(cast<GCRelocateInst>(I)); 7131 return; 7132 case Intrinsic::instrprof_cover: 7133 llvm_unreachable("instrprof failed to lower a cover"); 7134 case Intrinsic::instrprof_increment: 7135 llvm_unreachable("instrprof failed to lower an increment"); 7136 case Intrinsic::instrprof_timestamp: 7137 llvm_unreachable("instrprof failed to lower a timestamp"); 7138 case Intrinsic::instrprof_value_profile: 7139 llvm_unreachable("instrprof failed to lower a value profiling call"); 7140 case Intrinsic::localescape: { 7141 MachineFunction &MF = DAG.getMachineFunction(); 7142 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7143 7144 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7145 // is the same on all targets. 7146 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7147 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7148 if (isa<ConstantPointerNull>(Arg)) 7149 continue; // Skip null pointers. They represent a hole in index space. 7150 AllocaInst *Slot = cast<AllocaInst>(Arg); 7151 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7152 "can only escape static allocas"); 7153 int FI = FuncInfo.StaticAllocaMap[Slot]; 7154 MCSymbol *FrameAllocSym = 7155 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7156 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7157 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7158 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7159 .addSym(FrameAllocSym) 7160 .addFrameIndex(FI); 7161 } 7162 7163 return; 7164 } 7165 7166 case Intrinsic::localrecover: { 7167 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7168 MachineFunction &MF = DAG.getMachineFunction(); 7169 7170 // Get the symbol that defines the frame offset. 7171 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7172 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7173 unsigned IdxVal = 7174 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7175 MCSymbol *FrameAllocSym = 7176 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7177 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7178 7179 Value *FP = I.getArgOperand(1); 7180 SDValue FPVal = getValue(FP); 7181 EVT PtrVT = FPVal.getValueType(); 7182 7183 // Create a MCSymbol for the label to avoid any target lowering 7184 // that would make this PC relative. 7185 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7186 SDValue OffsetVal = 7187 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7188 7189 // Add the offset to the FP. 7190 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7191 setValue(&I, Add); 7192 7193 return; 7194 } 7195 7196 case Intrinsic::eh_exceptionpointer: 7197 case Intrinsic::eh_exceptioncode: { 7198 // Get the exception pointer vreg, copy from it, and resize it to fit. 7199 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7200 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7201 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7202 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7203 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7204 if (Intrinsic == Intrinsic::eh_exceptioncode) 7205 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7206 setValue(&I, N); 7207 return; 7208 } 7209 case Intrinsic::xray_customevent: { 7210 // Here we want to make sure that the intrinsic behaves as if it has a 7211 // specific calling convention, and only for x86_64. 7212 // FIXME: Support other platforms later. 7213 const auto &Triple = DAG.getTarget().getTargetTriple(); 7214 if (Triple.getArch() != Triple::x86_64) 7215 return; 7216 7217 SmallVector<SDValue, 8> Ops; 7218 7219 // We want to say that we always want the arguments in registers. 7220 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7221 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7222 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7223 SDValue Chain = getRoot(); 7224 Ops.push_back(LogEntryVal); 7225 Ops.push_back(StrSizeVal); 7226 Ops.push_back(Chain); 7227 7228 // We need to enforce the calling convention for the callsite, so that 7229 // argument ordering is enforced correctly, and that register allocation can 7230 // see that some registers may be assumed clobbered and have to preserve 7231 // them across calls to the intrinsic. 7232 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7233 sdl, NodeTys, Ops); 7234 SDValue patchableNode = SDValue(MN, 0); 7235 DAG.setRoot(patchableNode); 7236 setValue(&I, patchableNode); 7237 return; 7238 } 7239 case Intrinsic::xray_typedevent: { 7240 // Here we want to make sure that the intrinsic behaves as if it has a 7241 // specific calling convention, and only for x86_64. 7242 // FIXME: Support other platforms later. 7243 const auto &Triple = DAG.getTarget().getTargetTriple(); 7244 if (Triple.getArch() != Triple::x86_64) 7245 return; 7246 7247 SmallVector<SDValue, 8> Ops; 7248 7249 // We want to say that we always want the arguments in registers. 7250 // It's unclear to me how manipulating the selection DAG here forces callers 7251 // to provide arguments in registers instead of on the stack. 7252 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7253 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7254 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7255 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7256 SDValue Chain = getRoot(); 7257 Ops.push_back(LogTypeId); 7258 Ops.push_back(LogEntryVal); 7259 Ops.push_back(StrSizeVal); 7260 Ops.push_back(Chain); 7261 7262 // We need to enforce the calling convention for the callsite, so that 7263 // argument ordering is enforced correctly, and that register allocation can 7264 // see that some registers may be assumed clobbered and have to preserve 7265 // them across calls to the intrinsic. 7266 MachineSDNode *MN = DAG.getMachineNode( 7267 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7268 SDValue patchableNode = SDValue(MN, 0); 7269 DAG.setRoot(patchableNode); 7270 setValue(&I, patchableNode); 7271 return; 7272 } 7273 case Intrinsic::experimental_deoptimize: 7274 LowerDeoptimizeCall(&I); 7275 return; 7276 case Intrinsic::experimental_stepvector: 7277 visitStepVector(I); 7278 return; 7279 case Intrinsic::vector_reduce_fadd: 7280 case Intrinsic::vector_reduce_fmul: 7281 case Intrinsic::vector_reduce_add: 7282 case Intrinsic::vector_reduce_mul: 7283 case Intrinsic::vector_reduce_and: 7284 case Intrinsic::vector_reduce_or: 7285 case Intrinsic::vector_reduce_xor: 7286 case Intrinsic::vector_reduce_smax: 7287 case Intrinsic::vector_reduce_smin: 7288 case Intrinsic::vector_reduce_umax: 7289 case Intrinsic::vector_reduce_umin: 7290 case Intrinsic::vector_reduce_fmax: 7291 case Intrinsic::vector_reduce_fmin: 7292 visitVectorReduce(I, Intrinsic); 7293 return; 7294 7295 case Intrinsic::icall_branch_funnel: { 7296 SmallVector<SDValue, 16> Ops; 7297 Ops.push_back(getValue(I.getArgOperand(0))); 7298 7299 int64_t Offset; 7300 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7301 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7302 if (!Base) 7303 report_fatal_error( 7304 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7305 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7306 7307 struct BranchFunnelTarget { 7308 int64_t Offset; 7309 SDValue Target; 7310 }; 7311 SmallVector<BranchFunnelTarget, 8> Targets; 7312 7313 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7314 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7315 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7316 if (ElemBase != Base) 7317 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7318 "to the same GlobalValue"); 7319 7320 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7321 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7322 if (!GA) 7323 report_fatal_error( 7324 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7325 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7326 GA->getGlobal(), sdl, Val.getValueType(), 7327 GA->getOffset())}); 7328 } 7329 llvm::sort(Targets, 7330 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7331 return T1.Offset < T2.Offset; 7332 }); 7333 7334 for (auto &T : Targets) { 7335 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7336 Ops.push_back(T.Target); 7337 } 7338 7339 Ops.push_back(DAG.getRoot()); // Chain 7340 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7341 MVT::Other, Ops), 7342 0); 7343 DAG.setRoot(N); 7344 setValue(&I, N); 7345 HasTailCall = true; 7346 return; 7347 } 7348 7349 case Intrinsic::wasm_landingpad_index: 7350 // Information this intrinsic contained has been transferred to 7351 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7352 // delete it now. 7353 return; 7354 7355 case Intrinsic::aarch64_settag: 7356 case Intrinsic::aarch64_settag_zero: { 7357 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7358 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7359 SDValue Val = TSI.EmitTargetCodeForSetTag( 7360 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7361 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7362 ZeroMemory); 7363 DAG.setRoot(Val); 7364 setValue(&I, Val); 7365 return; 7366 } 7367 case Intrinsic::ptrmask: { 7368 SDValue Ptr = getValue(I.getOperand(0)); 7369 SDValue Const = getValue(I.getOperand(1)); 7370 7371 EVT PtrVT = Ptr.getValueType(); 7372 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7373 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7374 return; 7375 } 7376 case Intrinsic::threadlocal_address: { 7377 setValue(&I, getValue(I.getOperand(0))); 7378 return; 7379 } 7380 case Intrinsic::get_active_lane_mask: { 7381 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7382 SDValue Index = getValue(I.getOperand(0)); 7383 EVT ElementVT = Index.getValueType(); 7384 7385 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7386 visitTargetIntrinsic(I, Intrinsic); 7387 return; 7388 } 7389 7390 SDValue TripCount = getValue(I.getOperand(1)); 7391 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7392 7393 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7394 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7395 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7396 SDValue VectorInduction = DAG.getNode( 7397 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7398 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7399 VectorTripCount, ISD::CondCode::SETULT); 7400 setValue(&I, SetCC); 7401 return; 7402 } 7403 case Intrinsic::experimental_get_vector_length: { 7404 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7405 "Expected positive VF"); 7406 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7407 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7408 7409 SDValue Count = getValue(I.getOperand(0)); 7410 EVT CountVT = Count.getValueType(); 7411 7412 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7413 visitTargetIntrinsic(I, Intrinsic); 7414 return; 7415 } 7416 7417 // Expand to a umin between the trip count and the maximum elements the type 7418 // can hold. 7419 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7420 7421 // Extend the trip count to at least the result VT. 7422 if (CountVT.bitsLT(VT)) { 7423 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7424 CountVT = VT; 7425 } 7426 7427 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7428 ElementCount::get(VF, IsScalable)); 7429 7430 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7431 // Clip to the result type if needed. 7432 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7433 7434 setValue(&I, Trunc); 7435 return; 7436 } 7437 case Intrinsic::vector_insert: { 7438 SDValue Vec = getValue(I.getOperand(0)); 7439 SDValue SubVec = getValue(I.getOperand(1)); 7440 SDValue Index = getValue(I.getOperand(2)); 7441 7442 // The intrinsic's index type is i64, but the SDNode requires an index type 7443 // suitable for the target. Convert the index as required. 7444 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7445 if (Index.getValueType() != VectorIdxTy) 7446 Index = DAG.getVectorIdxConstant( 7447 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7448 7449 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7450 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7451 Index)); 7452 return; 7453 } 7454 case Intrinsic::vector_extract: { 7455 SDValue Vec = getValue(I.getOperand(0)); 7456 SDValue Index = getValue(I.getOperand(1)); 7457 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7458 7459 // The intrinsic's index type is i64, but the SDNode requires an index type 7460 // suitable for the target. Convert the index as required. 7461 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7462 if (Index.getValueType() != VectorIdxTy) 7463 Index = DAG.getVectorIdxConstant( 7464 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7465 7466 setValue(&I, 7467 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7468 return; 7469 } 7470 case Intrinsic::experimental_vector_reverse: 7471 visitVectorReverse(I); 7472 return; 7473 case Intrinsic::experimental_vector_splice: 7474 visitVectorSplice(I); 7475 return; 7476 case Intrinsic::callbr_landingpad: 7477 visitCallBrLandingPad(I); 7478 return; 7479 case Intrinsic::experimental_vector_interleave2: 7480 visitVectorInterleave(I); 7481 return; 7482 case Intrinsic::experimental_vector_deinterleave2: 7483 visitVectorDeinterleave(I); 7484 return; 7485 } 7486 } 7487 7488 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7489 const ConstrainedFPIntrinsic &FPI) { 7490 SDLoc sdl = getCurSDLoc(); 7491 7492 // We do not need to serialize constrained FP intrinsics against 7493 // each other or against (nonvolatile) loads, so they can be 7494 // chained like loads. 7495 SDValue Chain = DAG.getRoot(); 7496 SmallVector<SDValue, 4> Opers; 7497 Opers.push_back(Chain); 7498 if (FPI.isUnaryOp()) { 7499 Opers.push_back(getValue(FPI.getArgOperand(0))); 7500 } else if (FPI.isTernaryOp()) { 7501 Opers.push_back(getValue(FPI.getArgOperand(0))); 7502 Opers.push_back(getValue(FPI.getArgOperand(1))); 7503 Opers.push_back(getValue(FPI.getArgOperand(2))); 7504 } else { 7505 Opers.push_back(getValue(FPI.getArgOperand(0))); 7506 Opers.push_back(getValue(FPI.getArgOperand(1))); 7507 } 7508 7509 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7510 assert(Result.getNode()->getNumValues() == 2); 7511 7512 // Push node to the appropriate list so that future instructions can be 7513 // chained up correctly. 7514 SDValue OutChain = Result.getValue(1); 7515 switch (EB) { 7516 case fp::ExceptionBehavior::ebIgnore: 7517 // The only reason why ebIgnore nodes still need to be chained is that 7518 // they might depend on the current rounding mode, and therefore must 7519 // not be moved across instruction that may change that mode. 7520 [[fallthrough]]; 7521 case fp::ExceptionBehavior::ebMayTrap: 7522 // These must not be moved across calls or instructions that may change 7523 // floating-point exception masks. 7524 PendingConstrainedFP.push_back(OutChain); 7525 break; 7526 case fp::ExceptionBehavior::ebStrict: 7527 // These must not be moved across calls or instructions that may change 7528 // floating-point exception masks or read floating-point exception flags. 7529 // In addition, they cannot be optimized out even if unused. 7530 PendingConstrainedFPStrict.push_back(OutChain); 7531 break; 7532 } 7533 }; 7534 7535 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7536 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7537 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7538 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7539 7540 SDNodeFlags Flags; 7541 if (EB == fp::ExceptionBehavior::ebIgnore) 7542 Flags.setNoFPExcept(true); 7543 7544 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7545 Flags.copyFMF(*FPOp); 7546 7547 unsigned Opcode; 7548 switch (FPI.getIntrinsicID()) { 7549 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7550 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7551 case Intrinsic::INTRINSIC: \ 7552 Opcode = ISD::STRICT_##DAGN; \ 7553 break; 7554 #include "llvm/IR/ConstrainedOps.def" 7555 case Intrinsic::experimental_constrained_fmuladd: { 7556 Opcode = ISD::STRICT_FMA; 7557 // Break fmuladd into fmul and fadd. 7558 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7559 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7560 Opers.pop_back(); 7561 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7562 pushOutChain(Mul, EB); 7563 Opcode = ISD::STRICT_FADD; 7564 Opers.clear(); 7565 Opers.push_back(Mul.getValue(1)); 7566 Opers.push_back(Mul.getValue(0)); 7567 Opers.push_back(getValue(FPI.getArgOperand(2))); 7568 } 7569 break; 7570 } 7571 } 7572 7573 // A few strict DAG nodes carry additional operands that are not 7574 // set up by the default code above. 7575 switch (Opcode) { 7576 default: break; 7577 case ISD::STRICT_FP_ROUND: 7578 Opers.push_back( 7579 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7580 break; 7581 case ISD::STRICT_FSETCC: 7582 case ISD::STRICT_FSETCCS: { 7583 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7584 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7585 if (TM.Options.NoNaNsFPMath) 7586 Condition = getFCmpCodeWithoutNaN(Condition); 7587 Opers.push_back(DAG.getCondCode(Condition)); 7588 break; 7589 } 7590 } 7591 7592 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7593 pushOutChain(Result, EB); 7594 7595 SDValue FPResult = Result.getValue(0); 7596 setValue(&FPI, FPResult); 7597 } 7598 7599 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7600 std::optional<unsigned> ResOPC; 7601 switch (VPIntrin.getIntrinsicID()) { 7602 case Intrinsic::vp_ctlz: { 7603 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7604 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7605 break; 7606 } 7607 case Intrinsic::vp_cttz: { 7608 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7609 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7610 break; 7611 } 7612 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7613 case Intrinsic::VPID: \ 7614 ResOPC = ISD::VPSD; \ 7615 break; 7616 #include "llvm/IR/VPIntrinsics.def" 7617 } 7618 7619 if (!ResOPC) 7620 llvm_unreachable( 7621 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7622 7623 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7624 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7625 if (VPIntrin.getFastMathFlags().allowReassoc()) 7626 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7627 : ISD::VP_REDUCE_FMUL; 7628 } 7629 7630 return *ResOPC; 7631 } 7632 7633 void SelectionDAGBuilder::visitVPLoad( 7634 const VPIntrinsic &VPIntrin, EVT VT, 7635 const SmallVectorImpl<SDValue> &OpValues) { 7636 SDLoc DL = getCurSDLoc(); 7637 Value *PtrOperand = VPIntrin.getArgOperand(0); 7638 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7639 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7640 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7641 SDValue LD; 7642 // Do not serialize variable-length loads of constant memory with 7643 // anything. 7644 if (!Alignment) 7645 Alignment = DAG.getEVTAlign(VT); 7646 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7647 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7648 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7649 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7650 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7651 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7652 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7653 MMO, false /*IsExpanding */); 7654 if (AddToChain) 7655 PendingLoads.push_back(LD.getValue(1)); 7656 setValue(&VPIntrin, LD); 7657 } 7658 7659 void SelectionDAGBuilder::visitVPGather( 7660 const VPIntrinsic &VPIntrin, EVT VT, 7661 const SmallVectorImpl<SDValue> &OpValues) { 7662 SDLoc DL = getCurSDLoc(); 7663 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7664 Value *PtrOperand = VPIntrin.getArgOperand(0); 7665 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7666 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7667 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7668 SDValue LD; 7669 if (!Alignment) 7670 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7671 unsigned AS = 7672 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7673 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7674 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7675 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7676 SDValue Base, Index, Scale; 7677 ISD::MemIndexType IndexType; 7678 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7679 this, VPIntrin.getParent(), 7680 VT.getScalarStoreSize()); 7681 if (!UniformBase) { 7682 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7683 Index = getValue(PtrOperand); 7684 IndexType = ISD::SIGNED_SCALED; 7685 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7686 } 7687 EVT IdxVT = Index.getValueType(); 7688 EVT EltTy = IdxVT.getVectorElementType(); 7689 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7690 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7691 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7692 } 7693 LD = DAG.getGatherVP( 7694 DAG.getVTList(VT, MVT::Other), VT, DL, 7695 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7696 IndexType); 7697 PendingLoads.push_back(LD.getValue(1)); 7698 setValue(&VPIntrin, LD); 7699 } 7700 7701 void SelectionDAGBuilder::visitVPStore( 7702 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7703 SDLoc DL = getCurSDLoc(); 7704 Value *PtrOperand = VPIntrin.getArgOperand(1); 7705 EVT VT = OpValues[0].getValueType(); 7706 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7707 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7708 SDValue ST; 7709 if (!Alignment) 7710 Alignment = DAG.getEVTAlign(VT); 7711 SDValue Ptr = OpValues[1]; 7712 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7713 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7714 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7715 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7716 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7717 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7718 /* IsTruncating */ false, /*IsCompressing*/ false); 7719 DAG.setRoot(ST); 7720 setValue(&VPIntrin, ST); 7721 } 7722 7723 void SelectionDAGBuilder::visitVPScatter( 7724 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7725 SDLoc DL = getCurSDLoc(); 7726 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7727 Value *PtrOperand = VPIntrin.getArgOperand(1); 7728 EVT VT = OpValues[0].getValueType(); 7729 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7730 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7731 SDValue ST; 7732 if (!Alignment) 7733 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7734 unsigned AS = 7735 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7736 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7737 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7738 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7739 SDValue Base, Index, Scale; 7740 ISD::MemIndexType IndexType; 7741 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7742 this, VPIntrin.getParent(), 7743 VT.getScalarStoreSize()); 7744 if (!UniformBase) { 7745 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7746 Index = getValue(PtrOperand); 7747 IndexType = ISD::SIGNED_SCALED; 7748 Scale = 7749 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7750 } 7751 EVT IdxVT = Index.getValueType(); 7752 EVT EltTy = IdxVT.getVectorElementType(); 7753 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7754 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7755 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7756 } 7757 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7758 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7759 OpValues[2], OpValues[3]}, 7760 MMO, IndexType); 7761 DAG.setRoot(ST); 7762 setValue(&VPIntrin, ST); 7763 } 7764 7765 void SelectionDAGBuilder::visitVPStridedLoad( 7766 const VPIntrinsic &VPIntrin, EVT VT, 7767 const SmallVectorImpl<SDValue> &OpValues) { 7768 SDLoc DL = getCurSDLoc(); 7769 Value *PtrOperand = VPIntrin.getArgOperand(0); 7770 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7771 if (!Alignment) 7772 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7773 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7774 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7775 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7776 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7777 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7778 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7779 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7780 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7781 7782 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7783 OpValues[2], OpValues[3], MMO, 7784 false /*IsExpanding*/); 7785 7786 if (AddToChain) 7787 PendingLoads.push_back(LD.getValue(1)); 7788 setValue(&VPIntrin, LD); 7789 } 7790 7791 void SelectionDAGBuilder::visitVPStridedStore( 7792 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7793 SDLoc DL = getCurSDLoc(); 7794 Value *PtrOperand = VPIntrin.getArgOperand(1); 7795 EVT VT = OpValues[0].getValueType(); 7796 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7797 if (!Alignment) 7798 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7799 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7800 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7801 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7802 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7803 7804 SDValue ST = DAG.getStridedStoreVP( 7805 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7806 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7807 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7808 /*IsCompressing*/ false); 7809 7810 DAG.setRoot(ST); 7811 setValue(&VPIntrin, ST); 7812 } 7813 7814 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7815 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7816 SDLoc DL = getCurSDLoc(); 7817 7818 ISD::CondCode Condition; 7819 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7820 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7821 if (IsFP) { 7822 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7823 // flags, but calls that don't return floating-point types can't be 7824 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7825 Condition = getFCmpCondCode(CondCode); 7826 if (TM.Options.NoNaNsFPMath) 7827 Condition = getFCmpCodeWithoutNaN(Condition); 7828 } else { 7829 Condition = getICmpCondCode(CondCode); 7830 } 7831 7832 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7833 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7834 // #2 is the condition code 7835 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7836 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7837 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7838 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7839 "Unexpected target EVL type"); 7840 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7841 7842 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7843 VPIntrin.getType()); 7844 setValue(&VPIntrin, 7845 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7846 } 7847 7848 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7849 const VPIntrinsic &VPIntrin) { 7850 SDLoc DL = getCurSDLoc(); 7851 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7852 7853 auto IID = VPIntrin.getIntrinsicID(); 7854 7855 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7856 return visitVPCmp(*CmpI); 7857 7858 SmallVector<EVT, 4> ValueVTs; 7859 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7860 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7861 SDVTList VTs = DAG.getVTList(ValueVTs); 7862 7863 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7864 7865 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7866 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7867 "Unexpected target EVL type"); 7868 7869 // Request operands. 7870 SmallVector<SDValue, 7> OpValues; 7871 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7872 auto Op = getValue(VPIntrin.getArgOperand(I)); 7873 if (I == EVLParamPos) 7874 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7875 OpValues.push_back(Op); 7876 } 7877 7878 switch (Opcode) { 7879 default: { 7880 SDNodeFlags SDFlags; 7881 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7882 SDFlags.copyFMF(*FPMO); 7883 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7884 setValue(&VPIntrin, Result); 7885 break; 7886 } 7887 case ISD::VP_LOAD: 7888 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7889 break; 7890 case ISD::VP_GATHER: 7891 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7892 break; 7893 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7894 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7895 break; 7896 case ISD::VP_STORE: 7897 visitVPStore(VPIntrin, OpValues); 7898 break; 7899 case ISD::VP_SCATTER: 7900 visitVPScatter(VPIntrin, OpValues); 7901 break; 7902 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7903 visitVPStridedStore(VPIntrin, OpValues); 7904 break; 7905 case ISD::VP_FMULADD: { 7906 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7907 SDNodeFlags SDFlags; 7908 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7909 SDFlags.copyFMF(*FPMO); 7910 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7911 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7912 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7913 } else { 7914 SDValue Mul = DAG.getNode( 7915 ISD::VP_FMUL, DL, VTs, 7916 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7917 SDValue Add = 7918 DAG.getNode(ISD::VP_FADD, DL, VTs, 7919 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7920 setValue(&VPIntrin, Add); 7921 } 7922 break; 7923 } 7924 case ISD::VP_INTTOPTR: { 7925 SDValue N = OpValues[0]; 7926 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 7927 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 7928 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7929 OpValues[2]); 7930 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7931 OpValues[2]); 7932 setValue(&VPIntrin, N); 7933 break; 7934 } 7935 case ISD::VP_PTRTOINT: { 7936 SDValue N = OpValues[0]; 7937 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7938 VPIntrin.getType()); 7939 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 7940 VPIntrin.getOperand(0)->getType()); 7941 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7942 OpValues[2]); 7943 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7944 OpValues[2]); 7945 setValue(&VPIntrin, N); 7946 break; 7947 } 7948 case ISD::VP_ABS: 7949 case ISD::VP_CTLZ: 7950 case ISD::VP_CTLZ_ZERO_UNDEF: 7951 case ISD::VP_CTTZ: 7952 case ISD::VP_CTTZ_ZERO_UNDEF: { 7953 SDValue Result = 7954 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 7955 setValue(&VPIntrin, Result); 7956 break; 7957 } 7958 } 7959 } 7960 7961 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7962 const BasicBlock *EHPadBB, 7963 MCSymbol *&BeginLabel) { 7964 MachineFunction &MF = DAG.getMachineFunction(); 7965 MachineModuleInfo &MMI = MF.getMMI(); 7966 7967 // Insert a label before the invoke call to mark the try range. This can be 7968 // used to detect deletion of the invoke via the MachineModuleInfo. 7969 BeginLabel = MMI.getContext().createTempSymbol(); 7970 7971 // For SjLj, keep track of which landing pads go with which invokes 7972 // so as to maintain the ordering of pads in the LSDA. 7973 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7974 if (CallSiteIndex) { 7975 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7976 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7977 7978 // Now that the call site is handled, stop tracking it. 7979 MMI.setCurrentCallSite(0); 7980 } 7981 7982 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7983 } 7984 7985 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7986 const BasicBlock *EHPadBB, 7987 MCSymbol *BeginLabel) { 7988 assert(BeginLabel && "BeginLabel should've been set"); 7989 7990 MachineFunction &MF = DAG.getMachineFunction(); 7991 MachineModuleInfo &MMI = MF.getMMI(); 7992 7993 // Insert a label at the end of the invoke call to mark the try range. This 7994 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7995 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7996 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7997 7998 // Inform MachineModuleInfo of range. 7999 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8000 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8001 // actually use outlined funclets and their LSDA info style. 8002 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8003 assert(II && "II should've been set"); 8004 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8005 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8006 } else if (!isScopedEHPersonality(Pers)) { 8007 assert(EHPadBB); 8008 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 8009 } 8010 8011 return Chain; 8012 } 8013 8014 std::pair<SDValue, SDValue> 8015 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8016 const BasicBlock *EHPadBB) { 8017 MCSymbol *BeginLabel = nullptr; 8018 8019 if (EHPadBB) { 8020 // Both PendingLoads and PendingExports must be flushed here; 8021 // this call might not return. 8022 (void)getRoot(); 8023 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8024 CLI.setChain(getRoot()); 8025 } 8026 8027 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8028 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8029 8030 assert((CLI.IsTailCall || Result.second.getNode()) && 8031 "Non-null chain expected with non-tail call!"); 8032 assert((Result.second.getNode() || !Result.first.getNode()) && 8033 "Null value expected with tail call!"); 8034 8035 if (!Result.second.getNode()) { 8036 // As a special case, a null chain means that a tail call has been emitted 8037 // and the DAG root is already updated. 8038 HasTailCall = true; 8039 8040 // Since there's no actual continuation from this block, nothing can be 8041 // relying on us setting vregs for them. 8042 PendingExports.clear(); 8043 } else { 8044 DAG.setRoot(Result.second); 8045 } 8046 8047 if (EHPadBB) { 8048 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8049 BeginLabel)); 8050 } 8051 8052 return Result; 8053 } 8054 8055 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8056 bool isTailCall, 8057 bool isMustTailCall, 8058 const BasicBlock *EHPadBB) { 8059 auto &DL = DAG.getDataLayout(); 8060 FunctionType *FTy = CB.getFunctionType(); 8061 Type *RetTy = CB.getType(); 8062 8063 TargetLowering::ArgListTy Args; 8064 Args.reserve(CB.arg_size()); 8065 8066 const Value *SwiftErrorVal = nullptr; 8067 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8068 8069 if (isTailCall) { 8070 // Avoid emitting tail calls in functions with the disable-tail-calls 8071 // attribute. 8072 auto *Caller = CB.getParent()->getParent(); 8073 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8074 "true" && !isMustTailCall) 8075 isTailCall = false; 8076 8077 // We can't tail call inside a function with a swifterror argument. Lowering 8078 // does not support this yet. It would have to move into the swifterror 8079 // register before the call. 8080 if (TLI.supportSwiftError() && 8081 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8082 isTailCall = false; 8083 } 8084 8085 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8086 TargetLowering::ArgListEntry Entry; 8087 const Value *V = *I; 8088 8089 // Skip empty types 8090 if (V->getType()->isEmptyTy()) 8091 continue; 8092 8093 SDValue ArgNode = getValue(V); 8094 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8095 8096 Entry.setAttributes(&CB, I - CB.arg_begin()); 8097 8098 // Use swifterror virtual register as input to the call. 8099 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8100 SwiftErrorVal = V; 8101 // We find the virtual register for the actual swifterror argument. 8102 // Instead of using the Value, we use the virtual register instead. 8103 Entry.Node = 8104 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8105 EVT(TLI.getPointerTy(DL))); 8106 } 8107 8108 Args.push_back(Entry); 8109 8110 // If we have an explicit sret argument that is an Instruction, (i.e., it 8111 // might point to function-local memory), we can't meaningfully tail-call. 8112 if (Entry.IsSRet && isa<Instruction>(V)) 8113 isTailCall = false; 8114 } 8115 8116 // If call site has a cfguardtarget operand bundle, create and add an 8117 // additional ArgListEntry. 8118 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8119 TargetLowering::ArgListEntry Entry; 8120 Value *V = Bundle->Inputs[0]; 8121 SDValue ArgNode = getValue(V); 8122 Entry.Node = ArgNode; 8123 Entry.Ty = V->getType(); 8124 Entry.IsCFGuardTarget = true; 8125 Args.push_back(Entry); 8126 } 8127 8128 // Check if target-independent constraints permit a tail call here. 8129 // Target-dependent constraints are checked within TLI->LowerCallTo. 8130 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8131 isTailCall = false; 8132 8133 // Disable tail calls if there is an swifterror argument. Targets have not 8134 // been updated to support tail calls. 8135 if (TLI.supportSwiftError() && SwiftErrorVal) 8136 isTailCall = false; 8137 8138 ConstantInt *CFIType = nullptr; 8139 if (CB.isIndirectCall()) { 8140 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8141 if (!TLI.supportKCFIBundles()) 8142 report_fatal_error( 8143 "Target doesn't support calls with kcfi operand bundles."); 8144 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8145 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8146 } 8147 } 8148 8149 TargetLowering::CallLoweringInfo CLI(DAG); 8150 CLI.setDebugLoc(getCurSDLoc()) 8151 .setChain(getRoot()) 8152 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8153 .setTailCall(isTailCall) 8154 .setConvergent(CB.isConvergent()) 8155 .setIsPreallocated( 8156 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8157 .setCFIType(CFIType); 8158 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8159 8160 if (Result.first.getNode()) { 8161 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8162 setValue(&CB, Result.first); 8163 } 8164 8165 // The last element of CLI.InVals has the SDValue for swifterror return. 8166 // Here we copy it to a virtual register and update SwiftErrorMap for 8167 // book-keeping. 8168 if (SwiftErrorVal && TLI.supportSwiftError()) { 8169 // Get the last element of InVals. 8170 SDValue Src = CLI.InVals.back(); 8171 Register VReg = 8172 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8173 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8174 DAG.setRoot(CopyNode); 8175 } 8176 } 8177 8178 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8179 SelectionDAGBuilder &Builder) { 8180 // Check to see if this load can be trivially constant folded, e.g. if the 8181 // input is from a string literal. 8182 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8183 // Cast pointer to the type we really want to load. 8184 Type *LoadTy = 8185 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8186 if (LoadVT.isVector()) 8187 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8188 8189 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8190 PointerType::getUnqual(LoadTy)); 8191 8192 if (const Constant *LoadCst = 8193 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8194 LoadTy, Builder.DAG.getDataLayout())) 8195 return Builder.getValue(LoadCst); 8196 } 8197 8198 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8199 // still constant memory, the input chain can be the entry node. 8200 SDValue Root; 8201 bool ConstantMemory = false; 8202 8203 // Do not serialize (non-volatile) loads of constant memory with anything. 8204 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8205 Root = Builder.DAG.getEntryNode(); 8206 ConstantMemory = true; 8207 } else { 8208 // Do not serialize non-volatile loads against each other. 8209 Root = Builder.DAG.getRoot(); 8210 } 8211 8212 SDValue Ptr = Builder.getValue(PtrVal); 8213 SDValue LoadVal = 8214 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8215 MachinePointerInfo(PtrVal), Align(1)); 8216 8217 if (!ConstantMemory) 8218 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8219 return LoadVal; 8220 } 8221 8222 /// Record the value for an instruction that produces an integer result, 8223 /// converting the type where necessary. 8224 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8225 SDValue Value, 8226 bool IsSigned) { 8227 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8228 I.getType(), true); 8229 if (IsSigned) 8230 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 8231 else 8232 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 8233 setValue(&I, Value); 8234 } 8235 8236 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8237 /// true and lower it. Otherwise return false, and it will be lowered like a 8238 /// normal call. 8239 /// The caller already checked that \p I calls the appropriate LibFunc with a 8240 /// correct prototype. 8241 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8242 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8243 const Value *Size = I.getArgOperand(2); 8244 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8245 if (CSize && CSize->getZExtValue() == 0) { 8246 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8247 I.getType(), true); 8248 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8249 return true; 8250 } 8251 8252 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8253 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8254 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8255 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8256 if (Res.first.getNode()) { 8257 processIntegerCallValue(I, Res.first, true); 8258 PendingLoads.push_back(Res.second); 8259 return true; 8260 } 8261 8262 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8263 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8264 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8265 return false; 8266 8267 // If the target has a fast compare for the given size, it will return a 8268 // preferred load type for that size. Require that the load VT is legal and 8269 // that the target supports unaligned loads of that type. Otherwise, return 8270 // INVALID. 8271 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8272 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8273 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8274 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8275 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8276 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8277 // TODO: Check alignment of src and dest ptrs. 8278 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8279 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8280 if (!TLI.isTypeLegal(LVT) || 8281 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8282 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8283 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8284 } 8285 8286 return LVT; 8287 }; 8288 8289 // This turns into unaligned loads. We only do this if the target natively 8290 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8291 // we'll only produce a small number of byte loads. 8292 MVT LoadVT; 8293 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8294 switch (NumBitsToCompare) { 8295 default: 8296 return false; 8297 case 16: 8298 LoadVT = MVT::i16; 8299 break; 8300 case 32: 8301 LoadVT = MVT::i32; 8302 break; 8303 case 64: 8304 case 128: 8305 case 256: 8306 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8307 break; 8308 } 8309 8310 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8311 return false; 8312 8313 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8314 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8315 8316 // Bitcast to a wide integer type if the loads are vectors. 8317 if (LoadVT.isVector()) { 8318 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8319 LoadL = DAG.getBitcast(CmpVT, LoadL); 8320 LoadR = DAG.getBitcast(CmpVT, LoadR); 8321 } 8322 8323 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8324 processIntegerCallValue(I, Cmp, false); 8325 return true; 8326 } 8327 8328 /// See if we can lower a memchr call into an optimized form. If so, return 8329 /// true and lower it. Otherwise return false, and it will be lowered like a 8330 /// normal call. 8331 /// The caller already checked that \p I calls the appropriate LibFunc with a 8332 /// correct prototype. 8333 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8334 const Value *Src = I.getArgOperand(0); 8335 const Value *Char = I.getArgOperand(1); 8336 const Value *Length = I.getArgOperand(2); 8337 8338 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8339 std::pair<SDValue, SDValue> Res = 8340 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8341 getValue(Src), getValue(Char), getValue(Length), 8342 MachinePointerInfo(Src)); 8343 if (Res.first.getNode()) { 8344 setValue(&I, Res.first); 8345 PendingLoads.push_back(Res.second); 8346 return true; 8347 } 8348 8349 return false; 8350 } 8351 8352 /// See if we can lower a mempcpy call into an optimized form. If so, return 8353 /// true and lower it. Otherwise return false, and it will be lowered like a 8354 /// normal call. 8355 /// The caller already checked that \p I calls the appropriate LibFunc with a 8356 /// correct prototype. 8357 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8358 SDValue Dst = getValue(I.getArgOperand(0)); 8359 SDValue Src = getValue(I.getArgOperand(1)); 8360 SDValue Size = getValue(I.getArgOperand(2)); 8361 8362 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8363 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8364 // DAG::getMemcpy needs Alignment to be defined. 8365 Align Alignment = std::min(DstAlign, SrcAlign); 8366 8367 SDLoc sdl = getCurSDLoc(); 8368 8369 // In the mempcpy context we need to pass in a false value for isTailCall 8370 // because the return pointer needs to be adjusted by the size of 8371 // the copied memory. 8372 SDValue Root = getMemoryRoot(); 8373 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8374 /*isTailCall=*/false, 8375 MachinePointerInfo(I.getArgOperand(0)), 8376 MachinePointerInfo(I.getArgOperand(1)), 8377 I.getAAMetadata()); 8378 assert(MC.getNode() != nullptr && 8379 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8380 DAG.setRoot(MC); 8381 8382 // Check if Size needs to be truncated or extended. 8383 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8384 8385 // Adjust return pointer to point just past the last dst byte. 8386 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8387 Dst, Size); 8388 setValue(&I, DstPlusSize); 8389 return true; 8390 } 8391 8392 /// See if we can lower a strcpy call into an optimized form. If so, return 8393 /// true and lower it, otherwise return false and it will be lowered like a 8394 /// normal call. 8395 /// The caller already checked that \p I calls the appropriate LibFunc with a 8396 /// correct prototype. 8397 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8398 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8399 8400 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8401 std::pair<SDValue, SDValue> Res = 8402 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8403 getValue(Arg0), getValue(Arg1), 8404 MachinePointerInfo(Arg0), 8405 MachinePointerInfo(Arg1), isStpcpy); 8406 if (Res.first.getNode()) { 8407 setValue(&I, Res.first); 8408 DAG.setRoot(Res.second); 8409 return true; 8410 } 8411 8412 return false; 8413 } 8414 8415 /// See if we can lower a strcmp call into an optimized form. If so, return 8416 /// true and lower it, otherwise return false and it will be lowered like a 8417 /// normal call. 8418 /// The caller already checked that \p I calls the appropriate LibFunc with a 8419 /// correct prototype. 8420 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8421 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8422 8423 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8424 std::pair<SDValue, SDValue> Res = 8425 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8426 getValue(Arg0), getValue(Arg1), 8427 MachinePointerInfo(Arg0), 8428 MachinePointerInfo(Arg1)); 8429 if (Res.first.getNode()) { 8430 processIntegerCallValue(I, Res.first, true); 8431 PendingLoads.push_back(Res.second); 8432 return true; 8433 } 8434 8435 return false; 8436 } 8437 8438 /// See if we can lower a strlen call into an optimized form. If so, return 8439 /// true and lower it, otherwise return false and it will be lowered like a 8440 /// normal call. 8441 /// The caller already checked that \p I calls the appropriate LibFunc with a 8442 /// correct prototype. 8443 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8444 const Value *Arg0 = I.getArgOperand(0); 8445 8446 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8447 std::pair<SDValue, SDValue> Res = 8448 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8449 getValue(Arg0), MachinePointerInfo(Arg0)); 8450 if (Res.first.getNode()) { 8451 processIntegerCallValue(I, Res.first, false); 8452 PendingLoads.push_back(Res.second); 8453 return true; 8454 } 8455 8456 return false; 8457 } 8458 8459 /// See if we can lower a strnlen call into an optimized form. If so, return 8460 /// true and lower it, otherwise return false and it will be lowered like a 8461 /// normal call. 8462 /// The caller already checked that \p I calls the appropriate LibFunc with a 8463 /// correct prototype. 8464 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8465 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8466 8467 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8468 std::pair<SDValue, SDValue> Res = 8469 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8470 getValue(Arg0), getValue(Arg1), 8471 MachinePointerInfo(Arg0)); 8472 if (Res.first.getNode()) { 8473 processIntegerCallValue(I, Res.first, false); 8474 PendingLoads.push_back(Res.second); 8475 return true; 8476 } 8477 8478 return false; 8479 } 8480 8481 /// See if we can lower a unary floating-point operation into an SDNode with 8482 /// the specified Opcode. If so, return true and lower it, otherwise return 8483 /// false and it will be lowered like a normal call. 8484 /// The caller already checked that \p I calls the appropriate LibFunc with a 8485 /// correct prototype. 8486 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8487 unsigned Opcode) { 8488 // We already checked this call's prototype; verify it doesn't modify errno. 8489 if (!I.onlyReadsMemory()) 8490 return false; 8491 8492 SDNodeFlags Flags; 8493 Flags.copyFMF(cast<FPMathOperator>(I)); 8494 8495 SDValue Tmp = getValue(I.getArgOperand(0)); 8496 setValue(&I, 8497 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8498 return true; 8499 } 8500 8501 /// See if we can lower a binary floating-point operation into an SDNode with 8502 /// the specified Opcode. If so, return true and lower it. Otherwise return 8503 /// false, and it will be lowered like a normal call. 8504 /// The caller already checked that \p I calls the appropriate LibFunc with a 8505 /// correct prototype. 8506 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8507 unsigned Opcode) { 8508 // We already checked this call's prototype; verify it doesn't modify errno. 8509 if (!I.onlyReadsMemory()) 8510 return false; 8511 8512 SDNodeFlags Flags; 8513 Flags.copyFMF(cast<FPMathOperator>(I)); 8514 8515 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8516 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8517 EVT VT = Tmp0.getValueType(); 8518 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8519 return true; 8520 } 8521 8522 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8523 // Handle inline assembly differently. 8524 if (I.isInlineAsm()) { 8525 visitInlineAsm(I); 8526 return; 8527 } 8528 8529 diagnoseDontCall(I); 8530 8531 if (Function *F = I.getCalledFunction()) { 8532 if (F->isDeclaration()) { 8533 // Is this an LLVM intrinsic or a target-specific intrinsic? 8534 unsigned IID = F->getIntrinsicID(); 8535 if (!IID) 8536 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8537 IID = II->getIntrinsicID(F); 8538 8539 if (IID) { 8540 visitIntrinsicCall(I, IID); 8541 return; 8542 } 8543 } 8544 8545 // Check for well-known libc/libm calls. If the function is internal, it 8546 // can't be a library call. Don't do the check if marked as nobuiltin for 8547 // some reason or the call site requires strict floating point semantics. 8548 LibFunc Func; 8549 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8550 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8551 LibInfo->hasOptimizedCodeGen(Func)) { 8552 switch (Func) { 8553 default: break; 8554 case LibFunc_bcmp: 8555 if (visitMemCmpBCmpCall(I)) 8556 return; 8557 break; 8558 case LibFunc_copysign: 8559 case LibFunc_copysignf: 8560 case LibFunc_copysignl: 8561 // We already checked this call's prototype; verify it doesn't modify 8562 // errno. 8563 if (I.onlyReadsMemory()) { 8564 SDValue LHS = getValue(I.getArgOperand(0)); 8565 SDValue RHS = getValue(I.getArgOperand(1)); 8566 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8567 LHS.getValueType(), LHS, RHS)); 8568 return; 8569 } 8570 break; 8571 case LibFunc_fabs: 8572 case LibFunc_fabsf: 8573 case LibFunc_fabsl: 8574 if (visitUnaryFloatCall(I, ISD::FABS)) 8575 return; 8576 break; 8577 case LibFunc_fmin: 8578 case LibFunc_fminf: 8579 case LibFunc_fminl: 8580 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8581 return; 8582 break; 8583 case LibFunc_fmax: 8584 case LibFunc_fmaxf: 8585 case LibFunc_fmaxl: 8586 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8587 return; 8588 break; 8589 case LibFunc_sin: 8590 case LibFunc_sinf: 8591 case LibFunc_sinl: 8592 if (visitUnaryFloatCall(I, ISD::FSIN)) 8593 return; 8594 break; 8595 case LibFunc_cos: 8596 case LibFunc_cosf: 8597 case LibFunc_cosl: 8598 if (visitUnaryFloatCall(I, ISD::FCOS)) 8599 return; 8600 break; 8601 case LibFunc_sqrt: 8602 case LibFunc_sqrtf: 8603 case LibFunc_sqrtl: 8604 case LibFunc_sqrt_finite: 8605 case LibFunc_sqrtf_finite: 8606 case LibFunc_sqrtl_finite: 8607 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8608 return; 8609 break; 8610 case LibFunc_floor: 8611 case LibFunc_floorf: 8612 case LibFunc_floorl: 8613 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8614 return; 8615 break; 8616 case LibFunc_nearbyint: 8617 case LibFunc_nearbyintf: 8618 case LibFunc_nearbyintl: 8619 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8620 return; 8621 break; 8622 case LibFunc_ceil: 8623 case LibFunc_ceilf: 8624 case LibFunc_ceill: 8625 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8626 return; 8627 break; 8628 case LibFunc_rint: 8629 case LibFunc_rintf: 8630 case LibFunc_rintl: 8631 if (visitUnaryFloatCall(I, ISD::FRINT)) 8632 return; 8633 break; 8634 case LibFunc_round: 8635 case LibFunc_roundf: 8636 case LibFunc_roundl: 8637 if (visitUnaryFloatCall(I, ISD::FROUND)) 8638 return; 8639 break; 8640 case LibFunc_trunc: 8641 case LibFunc_truncf: 8642 case LibFunc_truncl: 8643 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8644 return; 8645 break; 8646 case LibFunc_log2: 8647 case LibFunc_log2f: 8648 case LibFunc_log2l: 8649 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8650 return; 8651 break; 8652 case LibFunc_exp2: 8653 case LibFunc_exp2f: 8654 case LibFunc_exp2l: 8655 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8656 return; 8657 break; 8658 case LibFunc_ldexp: 8659 case LibFunc_ldexpf: 8660 case LibFunc_ldexpl: 8661 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 8662 return; 8663 break; 8664 case LibFunc_memcmp: 8665 if (visitMemCmpBCmpCall(I)) 8666 return; 8667 break; 8668 case LibFunc_mempcpy: 8669 if (visitMemPCpyCall(I)) 8670 return; 8671 break; 8672 case LibFunc_memchr: 8673 if (visitMemChrCall(I)) 8674 return; 8675 break; 8676 case LibFunc_strcpy: 8677 if (visitStrCpyCall(I, false)) 8678 return; 8679 break; 8680 case LibFunc_stpcpy: 8681 if (visitStrCpyCall(I, true)) 8682 return; 8683 break; 8684 case LibFunc_strcmp: 8685 if (visitStrCmpCall(I)) 8686 return; 8687 break; 8688 case LibFunc_strlen: 8689 if (visitStrLenCall(I)) 8690 return; 8691 break; 8692 case LibFunc_strnlen: 8693 if (visitStrNLenCall(I)) 8694 return; 8695 break; 8696 } 8697 } 8698 } 8699 8700 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8701 // have to do anything here to lower funclet bundles. 8702 // CFGuardTarget bundles are lowered in LowerCallTo. 8703 assert(!I.hasOperandBundlesOtherThan( 8704 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8705 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8706 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8707 "Cannot lower calls with arbitrary operand bundles!"); 8708 8709 SDValue Callee = getValue(I.getCalledOperand()); 8710 8711 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8712 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8713 else 8714 // Check if we can potentially perform a tail call. More detailed checking 8715 // is be done within LowerCallTo, after more information about the call is 8716 // known. 8717 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8718 } 8719 8720 namespace { 8721 8722 /// AsmOperandInfo - This contains information for each constraint that we are 8723 /// lowering. 8724 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8725 public: 8726 /// CallOperand - If this is the result output operand or a clobber 8727 /// this is null, otherwise it is the incoming operand to the CallInst. 8728 /// This gets modified as the asm is processed. 8729 SDValue CallOperand; 8730 8731 /// AssignedRegs - If this is a register or register class operand, this 8732 /// contains the set of register corresponding to the operand. 8733 RegsForValue AssignedRegs; 8734 8735 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8736 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8737 } 8738 8739 /// Whether or not this operand accesses memory 8740 bool hasMemory(const TargetLowering &TLI) const { 8741 // Indirect operand accesses access memory. 8742 if (isIndirect) 8743 return true; 8744 8745 for (const auto &Code : Codes) 8746 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8747 return true; 8748 8749 return false; 8750 } 8751 }; 8752 8753 8754 } // end anonymous namespace 8755 8756 /// Make sure that the output operand \p OpInfo and its corresponding input 8757 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8758 /// out). 8759 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8760 SDISelAsmOperandInfo &MatchingOpInfo, 8761 SelectionDAG &DAG) { 8762 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8763 return; 8764 8765 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8766 const auto &TLI = DAG.getTargetLoweringInfo(); 8767 8768 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8769 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8770 OpInfo.ConstraintVT); 8771 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8772 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8773 MatchingOpInfo.ConstraintVT); 8774 if ((OpInfo.ConstraintVT.isInteger() != 8775 MatchingOpInfo.ConstraintVT.isInteger()) || 8776 (MatchRC.second != InputRC.second)) { 8777 // FIXME: error out in a more elegant fashion 8778 report_fatal_error("Unsupported asm: input constraint" 8779 " with a matching output constraint of" 8780 " incompatible type!"); 8781 } 8782 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8783 } 8784 8785 /// Get a direct memory input to behave well as an indirect operand. 8786 /// This may introduce stores, hence the need for a \p Chain. 8787 /// \return The (possibly updated) chain. 8788 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8789 SDISelAsmOperandInfo &OpInfo, 8790 SelectionDAG &DAG) { 8791 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8792 8793 // If we don't have an indirect input, put it in the constpool if we can, 8794 // otherwise spill it to a stack slot. 8795 // TODO: This isn't quite right. We need to handle these according to 8796 // the addressing mode that the constraint wants. Also, this may take 8797 // an additional register for the computation and we don't want that 8798 // either. 8799 8800 // If the operand is a float, integer, or vector constant, spill to a 8801 // constant pool entry to get its address. 8802 const Value *OpVal = OpInfo.CallOperandVal; 8803 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8804 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8805 OpInfo.CallOperand = DAG.getConstantPool( 8806 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8807 return Chain; 8808 } 8809 8810 // Otherwise, create a stack slot and emit a store to it before the asm. 8811 Type *Ty = OpVal->getType(); 8812 auto &DL = DAG.getDataLayout(); 8813 uint64_t TySize = DL.getTypeAllocSize(Ty); 8814 MachineFunction &MF = DAG.getMachineFunction(); 8815 int SSFI = MF.getFrameInfo().CreateStackObject( 8816 TySize, DL.getPrefTypeAlign(Ty), false); 8817 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8818 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8819 MachinePointerInfo::getFixedStack(MF, SSFI), 8820 TLI.getMemValueType(DL, Ty)); 8821 OpInfo.CallOperand = StackSlot; 8822 8823 return Chain; 8824 } 8825 8826 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8827 /// specified operand. We prefer to assign virtual registers, to allow the 8828 /// register allocator to handle the assignment process. However, if the asm 8829 /// uses features that we can't model on machineinstrs, we have SDISel do the 8830 /// allocation. This produces generally horrible, but correct, code. 8831 /// 8832 /// OpInfo describes the operand 8833 /// RefOpInfo describes the matching operand if any, the operand otherwise 8834 static std::optional<unsigned> 8835 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8836 SDISelAsmOperandInfo &OpInfo, 8837 SDISelAsmOperandInfo &RefOpInfo) { 8838 LLVMContext &Context = *DAG.getContext(); 8839 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8840 8841 MachineFunction &MF = DAG.getMachineFunction(); 8842 SmallVector<unsigned, 4> Regs; 8843 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8844 8845 // No work to do for memory/address operands. 8846 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8847 OpInfo.ConstraintType == TargetLowering::C_Address) 8848 return std::nullopt; 8849 8850 // If this is a constraint for a single physreg, or a constraint for a 8851 // register class, find it. 8852 unsigned AssignedReg; 8853 const TargetRegisterClass *RC; 8854 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8855 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8856 // RC is unset only on failure. Return immediately. 8857 if (!RC) 8858 return std::nullopt; 8859 8860 // Get the actual register value type. This is important, because the user 8861 // may have asked for (e.g.) the AX register in i32 type. We need to 8862 // remember that AX is actually i16 to get the right extension. 8863 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8864 8865 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8866 // If this is an FP operand in an integer register (or visa versa), or more 8867 // generally if the operand value disagrees with the register class we plan 8868 // to stick it in, fix the operand type. 8869 // 8870 // If this is an input value, the bitcast to the new type is done now. 8871 // Bitcast for output value is done at the end of visitInlineAsm(). 8872 if ((OpInfo.Type == InlineAsm::isOutput || 8873 OpInfo.Type == InlineAsm::isInput) && 8874 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8875 // Try to convert to the first EVT that the reg class contains. If the 8876 // types are identical size, use a bitcast to convert (e.g. two differing 8877 // vector types). Note: output bitcast is done at the end of 8878 // visitInlineAsm(). 8879 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8880 // Exclude indirect inputs while they are unsupported because the code 8881 // to perform the load is missing and thus OpInfo.CallOperand still 8882 // refers to the input address rather than the pointed-to value. 8883 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8884 OpInfo.CallOperand = 8885 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8886 OpInfo.ConstraintVT = RegVT; 8887 // If the operand is an FP value and we want it in integer registers, 8888 // use the corresponding integer type. This turns an f64 value into 8889 // i64, which can be passed with two i32 values on a 32-bit machine. 8890 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8891 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8892 if (OpInfo.Type == InlineAsm::isInput) 8893 OpInfo.CallOperand = 8894 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8895 OpInfo.ConstraintVT = VT; 8896 } 8897 } 8898 } 8899 8900 // No need to allocate a matching input constraint since the constraint it's 8901 // matching to has already been allocated. 8902 if (OpInfo.isMatchingInputConstraint()) 8903 return std::nullopt; 8904 8905 EVT ValueVT = OpInfo.ConstraintVT; 8906 if (OpInfo.ConstraintVT == MVT::Other) 8907 ValueVT = RegVT; 8908 8909 // Initialize NumRegs. 8910 unsigned NumRegs = 1; 8911 if (OpInfo.ConstraintVT != MVT::Other) 8912 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8913 8914 // If this is a constraint for a specific physical register, like {r17}, 8915 // assign it now. 8916 8917 // If this associated to a specific register, initialize iterator to correct 8918 // place. If virtual, make sure we have enough registers 8919 8920 // Initialize iterator if necessary 8921 TargetRegisterClass::iterator I = RC->begin(); 8922 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8923 8924 // Do not check for single registers. 8925 if (AssignedReg) { 8926 I = std::find(I, RC->end(), AssignedReg); 8927 if (I == RC->end()) { 8928 // RC does not contain the selected register, which indicates a 8929 // mismatch between the register and the required type/bitwidth. 8930 return {AssignedReg}; 8931 } 8932 } 8933 8934 for (; NumRegs; --NumRegs, ++I) { 8935 assert(I != RC->end() && "Ran out of registers to allocate!"); 8936 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8937 Regs.push_back(R); 8938 } 8939 8940 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8941 return std::nullopt; 8942 } 8943 8944 static unsigned 8945 findMatchingInlineAsmOperand(unsigned OperandNo, 8946 const std::vector<SDValue> &AsmNodeOperands) { 8947 // Scan until we find the definition we already emitted of this operand. 8948 unsigned CurOp = InlineAsm::Op_FirstOperand; 8949 for (; OperandNo; --OperandNo) { 8950 // Advance to the next operand. 8951 unsigned OpFlag = 8952 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8953 assert((InlineAsm::isRegDefKind(OpFlag) || 8954 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8955 InlineAsm::isMemKind(OpFlag)) && 8956 "Skipped past definitions?"); 8957 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8958 } 8959 return CurOp; 8960 } 8961 8962 namespace { 8963 8964 class ExtraFlags { 8965 unsigned Flags = 0; 8966 8967 public: 8968 explicit ExtraFlags(const CallBase &Call) { 8969 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8970 if (IA->hasSideEffects()) 8971 Flags |= InlineAsm::Extra_HasSideEffects; 8972 if (IA->isAlignStack()) 8973 Flags |= InlineAsm::Extra_IsAlignStack; 8974 if (Call.isConvergent()) 8975 Flags |= InlineAsm::Extra_IsConvergent; 8976 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8977 } 8978 8979 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8980 // Ideally, we would only check against memory constraints. However, the 8981 // meaning of an Other constraint can be target-specific and we can't easily 8982 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8983 // for Other constraints as well. 8984 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8985 OpInfo.ConstraintType == TargetLowering::C_Other) { 8986 if (OpInfo.Type == InlineAsm::isInput) 8987 Flags |= InlineAsm::Extra_MayLoad; 8988 else if (OpInfo.Type == InlineAsm::isOutput) 8989 Flags |= InlineAsm::Extra_MayStore; 8990 else if (OpInfo.Type == InlineAsm::isClobber) 8991 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8992 } 8993 } 8994 8995 unsigned get() const { return Flags; } 8996 }; 8997 8998 } // end anonymous namespace 8999 9000 static bool isFunction(SDValue Op) { 9001 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9002 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9003 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9004 9005 // In normal "call dllimport func" instruction (non-inlineasm) it force 9006 // indirect access by specifing call opcode. And usually specially print 9007 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9008 // not do in this way now. (In fact, this is similar with "Data Access" 9009 // action). So here we ignore dllimport function. 9010 if (Fn && !Fn->hasDLLImportStorageClass()) 9011 return true; 9012 } 9013 } 9014 return false; 9015 } 9016 9017 /// visitInlineAsm - Handle a call to an InlineAsm object. 9018 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9019 const BasicBlock *EHPadBB) { 9020 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9021 9022 /// ConstraintOperands - Information about all of the constraints. 9023 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9024 9025 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9026 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9027 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9028 9029 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9030 // AsmDialect, MayLoad, MayStore). 9031 bool HasSideEffect = IA->hasSideEffects(); 9032 ExtraFlags ExtraInfo(Call); 9033 9034 for (auto &T : TargetConstraints) { 9035 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9036 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9037 9038 if (OpInfo.CallOperandVal) 9039 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9040 9041 if (!HasSideEffect) 9042 HasSideEffect = OpInfo.hasMemory(TLI); 9043 9044 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9045 // FIXME: Could we compute this on OpInfo rather than T? 9046 9047 // Compute the constraint code and ConstraintType to use. 9048 TLI.ComputeConstraintToUse(T, SDValue()); 9049 9050 if (T.ConstraintType == TargetLowering::C_Immediate && 9051 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9052 // We've delayed emitting a diagnostic like the "n" constraint because 9053 // inlining could cause an integer showing up. 9054 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9055 "' expects an integer constant " 9056 "expression"); 9057 9058 ExtraInfo.update(T); 9059 } 9060 9061 // We won't need to flush pending loads if this asm doesn't touch 9062 // memory and is nonvolatile. 9063 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9064 9065 bool EmitEHLabels = isa<InvokeInst>(Call); 9066 if (EmitEHLabels) { 9067 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9068 } 9069 bool IsCallBr = isa<CallBrInst>(Call); 9070 9071 if (IsCallBr || EmitEHLabels) { 9072 // If this is a callbr or invoke we need to flush pending exports since 9073 // inlineasm_br and invoke are terminators. 9074 // We need to do this before nodes are glued to the inlineasm_br node. 9075 Chain = getControlRoot(); 9076 } 9077 9078 MCSymbol *BeginLabel = nullptr; 9079 if (EmitEHLabels) { 9080 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9081 } 9082 9083 int OpNo = -1; 9084 SmallVector<StringRef> AsmStrs; 9085 IA->collectAsmStrs(AsmStrs); 9086 9087 // Second pass over the constraints: compute which constraint option to use. 9088 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9089 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9090 OpNo++; 9091 9092 // If this is an output operand with a matching input operand, look up the 9093 // matching input. If their types mismatch, e.g. one is an integer, the 9094 // other is floating point, or their sizes are different, flag it as an 9095 // error. 9096 if (OpInfo.hasMatchingInput()) { 9097 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9098 patchMatchingInput(OpInfo, Input, DAG); 9099 } 9100 9101 // Compute the constraint code and ConstraintType to use. 9102 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9103 9104 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9105 OpInfo.Type == InlineAsm::isClobber) || 9106 OpInfo.ConstraintType == TargetLowering::C_Address) 9107 continue; 9108 9109 // In Linux PIC model, there are 4 cases about value/label addressing: 9110 // 9111 // 1: Function call or Label jmp inside the module. 9112 // 2: Data access (such as global variable, static variable) inside module. 9113 // 3: Function call or Label jmp outside the module. 9114 // 4: Data access (such as global variable) outside the module. 9115 // 9116 // Due to current llvm inline asm architecture designed to not "recognize" 9117 // the asm code, there are quite troubles for us to treat mem addressing 9118 // differently for same value/adress used in different instuctions. 9119 // For example, in pic model, call a func may in plt way or direclty 9120 // pc-related, but lea/mov a function adress may use got. 9121 // 9122 // Here we try to "recognize" function call for the case 1 and case 3 in 9123 // inline asm. And try to adjust the constraint for them. 9124 // 9125 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9126 // label, so here we don't handle jmp function label now, but we need to 9127 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9128 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9129 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9130 TM.getCodeModel() != CodeModel::Large) { 9131 OpInfo.isIndirect = false; 9132 OpInfo.ConstraintType = TargetLowering::C_Address; 9133 } 9134 9135 // If this is a memory input, and if the operand is not indirect, do what we 9136 // need to provide an address for the memory input. 9137 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9138 !OpInfo.isIndirect) { 9139 assert((OpInfo.isMultipleAlternative || 9140 (OpInfo.Type == InlineAsm::isInput)) && 9141 "Can only indirectify direct input operands!"); 9142 9143 // Memory operands really want the address of the value. 9144 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9145 9146 // There is no longer a Value* corresponding to this operand. 9147 OpInfo.CallOperandVal = nullptr; 9148 9149 // It is now an indirect operand. 9150 OpInfo.isIndirect = true; 9151 } 9152 9153 } 9154 9155 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9156 std::vector<SDValue> AsmNodeOperands; 9157 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9158 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9159 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9160 9161 // If we have a !srcloc metadata node associated with it, we want to attach 9162 // this to the ultimately generated inline asm machineinstr. To do this, we 9163 // pass in the third operand as this (potentially null) inline asm MDNode. 9164 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9165 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9166 9167 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9168 // bits as operand 3. 9169 AsmNodeOperands.push_back(DAG.getTargetConstant( 9170 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9171 9172 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9173 // this, assign virtual and physical registers for inputs and otput. 9174 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9175 // Assign Registers. 9176 SDISelAsmOperandInfo &RefOpInfo = 9177 OpInfo.isMatchingInputConstraint() 9178 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9179 : OpInfo; 9180 const auto RegError = 9181 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9182 if (RegError) { 9183 const MachineFunction &MF = DAG.getMachineFunction(); 9184 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9185 const char *RegName = TRI.getName(*RegError); 9186 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9187 "' allocated for constraint '" + 9188 Twine(OpInfo.ConstraintCode) + 9189 "' does not match required type"); 9190 return; 9191 } 9192 9193 auto DetectWriteToReservedRegister = [&]() { 9194 const MachineFunction &MF = DAG.getMachineFunction(); 9195 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9196 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9197 if (Register::isPhysicalRegister(Reg) && 9198 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9199 const char *RegName = TRI.getName(Reg); 9200 emitInlineAsmError(Call, "write to reserved register '" + 9201 Twine(RegName) + "'"); 9202 return true; 9203 } 9204 } 9205 return false; 9206 }; 9207 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9208 (OpInfo.Type == InlineAsm::isInput && 9209 !OpInfo.isMatchingInputConstraint())) && 9210 "Only address as input operand is allowed."); 9211 9212 switch (OpInfo.Type) { 9213 case InlineAsm::isOutput: 9214 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9215 unsigned ConstraintID = 9216 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9217 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9218 "Failed to convert memory constraint code to constraint id."); 9219 9220 // Add information to the INLINEASM node to know about this output. 9221 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9222 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 9223 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9224 MVT::i32)); 9225 AsmNodeOperands.push_back(OpInfo.CallOperand); 9226 } else { 9227 // Otherwise, this outputs to a register (directly for C_Register / 9228 // C_RegisterClass, and a target-defined fashion for 9229 // C_Immediate/C_Other). Find a register that we can use. 9230 if (OpInfo.AssignedRegs.Regs.empty()) { 9231 emitInlineAsmError( 9232 Call, "couldn't allocate output register for constraint '" + 9233 Twine(OpInfo.ConstraintCode) + "'"); 9234 return; 9235 } 9236 9237 if (DetectWriteToReservedRegister()) 9238 return; 9239 9240 // Add information to the INLINEASM node to know that this register is 9241 // set. 9242 OpInfo.AssignedRegs.AddInlineAsmOperands( 9243 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 9244 : InlineAsm::Kind_RegDef, 9245 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9246 } 9247 break; 9248 9249 case InlineAsm::isInput: 9250 case InlineAsm::isLabel: { 9251 SDValue InOperandVal = OpInfo.CallOperand; 9252 9253 if (OpInfo.isMatchingInputConstraint()) { 9254 // If this is required to match an output register we have already set, 9255 // just use its register. 9256 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9257 AsmNodeOperands); 9258 unsigned OpFlag = 9259 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9260 if (InlineAsm::isRegDefKind(OpFlag) || 9261 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9262 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9263 if (OpInfo.isIndirect) { 9264 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9265 emitInlineAsmError(Call, "inline asm not supported yet: " 9266 "don't know how to handle tied " 9267 "indirect register inputs"); 9268 return; 9269 } 9270 9271 SmallVector<unsigned, 4> Regs; 9272 MachineFunction &MF = DAG.getMachineFunction(); 9273 MachineRegisterInfo &MRI = MF.getRegInfo(); 9274 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9275 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9276 Register TiedReg = R->getReg(); 9277 MVT RegVT = R->getSimpleValueType(0); 9278 const TargetRegisterClass *RC = 9279 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9280 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9281 : TRI.getMinimalPhysRegClass(TiedReg); 9282 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9283 for (unsigned i = 0; i != NumRegs; ++i) 9284 Regs.push_back(MRI.createVirtualRegister(RC)); 9285 9286 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9287 9288 SDLoc dl = getCurSDLoc(); 9289 // Use the produced MatchedRegs object to 9290 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9291 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9292 true, OpInfo.getMatchedOperand(), dl, 9293 DAG, AsmNodeOperands); 9294 break; 9295 } 9296 9297 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9298 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9299 "Unexpected number of operands"); 9300 // Add information to the INLINEASM node to know about this input. 9301 // See InlineAsm.h isUseOperandTiedToDef. 9302 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9303 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9304 OpInfo.getMatchedOperand()); 9305 AsmNodeOperands.push_back(DAG.getTargetConstant( 9306 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9307 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9308 break; 9309 } 9310 9311 // Treat indirect 'X' constraint as memory. 9312 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9313 OpInfo.isIndirect) 9314 OpInfo.ConstraintType = TargetLowering::C_Memory; 9315 9316 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9317 OpInfo.ConstraintType == TargetLowering::C_Other) { 9318 std::vector<SDValue> Ops; 9319 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9320 Ops, DAG); 9321 if (Ops.empty()) { 9322 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9323 if (isa<ConstantSDNode>(InOperandVal)) { 9324 emitInlineAsmError(Call, "value out of range for constraint '" + 9325 Twine(OpInfo.ConstraintCode) + "'"); 9326 return; 9327 } 9328 9329 emitInlineAsmError(Call, 9330 "invalid operand for inline asm constraint '" + 9331 Twine(OpInfo.ConstraintCode) + "'"); 9332 return; 9333 } 9334 9335 // Add information to the INLINEASM node to know about this input. 9336 unsigned ResOpType = 9337 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9338 AsmNodeOperands.push_back(DAG.getTargetConstant( 9339 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9340 llvm::append_range(AsmNodeOperands, Ops); 9341 break; 9342 } 9343 9344 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9345 assert((OpInfo.isIndirect || 9346 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9347 "Operand must be indirect to be a mem!"); 9348 assert(InOperandVal.getValueType() == 9349 TLI.getPointerTy(DAG.getDataLayout()) && 9350 "Memory operands expect pointer values"); 9351 9352 unsigned ConstraintID = 9353 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9354 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9355 "Failed to convert memory constraint code to constraint id."); 9356 9357 // Add information to the INLINEASM node to know about this input. 9358 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9359 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9360 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9361 getCurSDLoc(), 9362 MVT::i32)); 9363 AsmNodeOperands.push_back(InOperandVal); 9364 break; 9365 } 9366 9367 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9368 assert(InOperandVal.getValueType() == 9369 TLI.getPointerTy(DAG.getDataLayout()) && 9370 "Address operands expect pointer values"); 9371 9372 unsigned ConstraintID = 9373 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9374 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9375 "Failed to convert memory constraint code to constraint id."); 9376 9377 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9378 9379 SDValue AsmOp = InOperandVal; 9380 if (isFunction(InOperandVal)) { 9381 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9382 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9383 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9384 InOperandVal.getValueType(), 9385 GA->getOffset()); 9386 } 9387 9388 // Add information to the INLINEASM node to know about this input. 9389 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9390 9391 AsmNodeOperands.push_back( 9392 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9393 9394 AsmNodeOperands.push_back(AsmOp); 9395 break; 9396 } 9397 9398 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9399 OpInfo.ConstraintType == TargetLowering::C_Register) && 9400 "Unknown constraint type!"); 9401 9402 // TODO: Support this. 9403 if (OpInfo.isIndirect) { 9404 emitInlineAsmError( 9405 Call, "Don't know how to handle indirect register inputs yet " 9406 "for constraint '" + 9407 Twine(OpInfo.ConstraintCode) + "'"); 9408 return; 9409 } 9410 9411 // Copy the input into the appropriate registers. 9412 if (OpInfo.AssignedRegs.Regs.empty()) { 9413 emitInlineAsmError(Call, 9414 "couldn't allocate input reg for constraint '" + 9415 Twine(OpInfo.ConstraintCode) + "'"); 9416 return; 9417 } 9418 9419 if (DetectWriteToReservedRegister()) 9420 return; 9421 9422 SDLoc dl = getCurSDLoc(); 9423 9424 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9425 &Call); 9426 9427 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9428 dl, DAG, AsmNodeOperands); 9429 break; 9430 } 9431 case InlineAsm::isClobber: 9432 // Add the clobbered value to the operand list, so that the register 9433 // allocator is aware that the physreg got clobbered. 9434 if (!OpInfo.AssignedRegs.Regs.empty()) 9435 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9436 false, 0, getCurSDLoc(), DAG, 9437 AsmNodeOperands); 9438 break; 9439 } 9440 } 9441 9442 // Finish up input operands. Set the input chain and add the flag last. 9443 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9444 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9445 9446 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9447 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9448 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9449 Glue = Chain.getValue(1); 9450 9451 // Do additional work to generate outputs. 9452 9453 SmallVector<EVT, 1> ResultVTs; 9454 SmallVector<SDValue, 1> ResultValues; 9455 SmallVector<SDValue, 8> OutChains; 9456 9457 llvm::Type *CallResultType = Call.getType(); 9458 ArrayRef<Type *> ResultTypes; 9459 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9460 ResultTypes = StructResult->elements(); 9461 else if (!CallResultType->isVoidTy()) 9462 ResultTypes = ArrayRef(CallResultType); 9463 9464 auto CurResultType = ResultTypes.begin(); 9465 auto handleRegAssign = [&](SDValue V) { 9466 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9467 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9468 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9469 ++CurResultType; 9470 // If the type of the inline asm call site return value is different but has 9471 // same size as the type of the asm output bitcast it. One example of this 9472 // is for vectors with different width / number of elements. This can 9473 // happen for register classes that can contain multiple different value 9474 // types. The preg or vreg allocated may not have the same VT as was 9475 // expected. 9476 // 9477 // This can also happen for a return value that disagrees with the register 9478 // class it is put in, eg. a double in a general-purpose register on a 9479 // 32-bit machine. 9480 if (ResultVT != V.getValueType() && 9481 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9482 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9483 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9484 V.getValueType().isInteger()) { 9485 // If a result value was tied to an input value, the computed result 9486 // may have a wider width than the expected result. Extract the 9487 // relevant portion. 9488 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9489 } 9490 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9491 ResultVTs.push_back(ResultVT); 9492 ResultValues.push_back(V); 9493 }; 9494 9495 // Deal with output operands. 9496 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9497 if (OpInfo.Type == InlineAsm::isOutput) { 9498 SDValue Val; 9499 // Skip trivial output operands. 9500 if (OpInfo.AssignedRegs.Regs.empty()) 9501 continue; 9502 9503 switch (OpInfo.ConstraintType) { 9504 case TargetLowering::C_Register: 9505 case TargetLowering::C_RegisterClass: 9506 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9507 Chain, &Glue, &Call); 9508 break; 9509 case TargetLowering::C_Immediate: 9510 case TargetLowering::C_Other: 9511 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9512 OpInfo, DAG); 9513 break; 9514 case TargetLowering::C_Memory: 9515 break; // Already handled. 9516 case TargetLowering::C_Address: 9517 break; // Silence warning. 9518 case TargetLowering::C_Unknown: 9519 assert(false && "Unexpected unknown constraint"); 9520 } 9521 9522 // Indirect output manifest as stores. Record output chains. 9523 if (OpInfo.isIndirect) { 9524 const Value *Ptr = OpInfo.CallOperandVal; 9525 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9526 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9527 MachinePointerInfo(Ptr)); 9528 OutChains.push_back(Store); 9529 } else { 9530 // generate CopyFromRegs to associated registers. 9531 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9532 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9533 for (const SDValue &V : Val->op_values()) 9534 handleRegAssign(V); 9535 } else 9536 handleRegAssign(Val); 9537 } 9538 } 9539 } 9540 9541 // Set results. 9542 if (!ResultValues.empty()) { 9543 assert(CurResultType == ResultTypes.end() && 9544 "Mismatch in number of ResultTypes"); 9545 assert(ResultValues.size() == ResultTypes.size() && 9546 "Mismatch in number of output operands in asm result"); 9547 9548 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9549 DAG.getVTList(ResultVTs), ResultValues); 9550 setValue(&Call, V); 9551 } 9552 9553 // Collect store chains. 9554 if (!OutChains.empty()) 9555 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9556 9557 if (EmitEHLabels) { 9558 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9559 } 9560 9561 // Only Update Root if inline assembly has a memory effect. 9562 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9563 EmitEHLabels) 9564 DAG.setRoot(Chain); 9565 } 9566 9567 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9568 const Twine &Message) { 9569 LLVMContext &Ctx = *DAG.getContext(); 9570 Ctx.emitError(&Call, Message); 9571 9572 // Make sure we leave the DAG in a valid state 9573 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9574 SmallVector<EVT, 1> ValueVTs; 9575 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9576 9577 if (ValueVTs.empty()) 9578 return; 9579 9580 SmallVector<SDValue, 1> Ops; 9581 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9582 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9583 9584 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9585 } 9586 9587 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9588 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9589 MVT::Other, getRoot(), 9590 getValue(I.getArgOperand(0)), 9591 DAG.getSrcValue(I.getArgOperand(0)))); 9592 } 9593 9594 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9595 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9596 const DataLayout &DL = DAG.getDataLayout(); 9597 SDValue V = DAG.getVAArg( 9598 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9599 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9600 DL.getABITypeAlign(I.getType()).value()); 9601 DAG.setRoot(V.getValue(1)); 9602 9603 if (I.getType()->isPointerTy()) 9604 V = DAG.getPtrExtOrTrunc( 9605 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9606 setValue(&I, V); 9607 } 9608 9609 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9610 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9611 MVT::Other, getRoot(), 9612 getValue(I.getArgOperand(0)), 9613 DAG.getSrcValue(I.getArgOperand(0)))); 9614 } 9615 9616 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9617 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9618 MVT::Other, getRoot(), 9619 getValue(I.getArgOperand(0)), 9620 getValue(I.getArgOperand(1)), 9621 DAG.getSrcValue(I.getArgOperand(0)), 9622 DAG.getSrcValue(I.getArgOperand(1)))); 9623 } 9624 9625 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9626 const Instruction &I, 9627 SDValue Op) { 9628 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9629 if (!Range) 9630 return Op; 9631 9632 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9633 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9634 return Op; 9635 9636 APInt Lo = CR.getUnsignedMin(); 9637 if (!Lo.isMinValue()) 9638 return Op; 9639 9640 APInt Hi = CR.getUnsignedMax(); 9641 unsigned Bits = std::max(Hi.getActiveBits(), 9642 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9643 9644 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9645 9646 SDLoc SL = getCurSDLoc(); 9647 9648 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9649 DAG.getValueType(SmallVT)); 9650 unsigned NumVals = Op.getNode()->getNumValues(); 9651 if (NumVals == 1) 9652 return ZExt; 9653 9654 SmallVector<SDValue, 4> Ops; 9655 9656 Ops.push_back(ZExt); 9657 for (unsigned I = 1; I != NumVals; ++I) 9658 Ops.push_back(Op.getValue(I)); 9659 9660 return DAG.getMergeValues(Ops, SL); 9661 } 9662 9663 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9664 /// the call being lowered. 9665 /// 9666 /// This is a helper for lowering intrinsics that follow a target calling 9667 /// convention or require stack pointer adjustment. Only a subset of the 9668 /// intrinsic's operands need to participate in the calling convention. 9669 void SelectionDAGBuilder::populateCallLoweringInfo( 9670 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9671 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9672 bool IsPatchPoint) { 9673 TargetLowering::ArgListTy Args; 9674 Args.reserve(NumArgs); 9675 9676 // Populate the argument list. 9677 // Attributes for args start at offset 1, after the return attribute. 9678 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9679 ArgI != ArgE; ++ArgI) { 9680 const Value *V = Call->getOperand(ArgI); 9681 9682 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9683 9684 TargetLowering::ArgListEntry Entry; 9685 Entry.Node = getValue(V); 9686 Entry.Ty = V->getType(); 9687 Entry.setAttributes(Call, ArgI); 9688 Args.push_back(Entry); 9689 } 9690 9691 CLI.setDebugLoc(getCurSDLoc()) 9692 .setChain(getRoot()) 9693 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9694 .setDiscardResult(Call->use_empty()) 9695 .setIsPatchPoint(IsPatchPoint) 9696 .setIsPreallocated( 9697 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9698 } 9699 9700 /// Add a stack map intrinsic call's live variable operands to a stackmap 9701 /// or patchpoint target node's operand list. 9702 /// 9703 /// Constants are converted to TargetConstants purely as an optimization to 9704 /// avoid constant materialization and register allocation. 9705 /// 9706 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9707 /// generate addess computation nodes, and so FinalizeISel can convert the 9708 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9709 /// address materialization and register allocation, but may also be required 9710 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9711 /// alloca in the entry block, then the runtime may assume that the alloca's 9712 /// StackMap location can be read immediately after compilation and that the 9713 /// location is valid at any point during execution (this is similar to the 9714 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9715 /// only available in a register, then the runtime would need to trap when 9716 /// execution reaches the StackMap in order to read the alloca's location. 9717 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9718 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9719 SelectionDAGBuilder &Builder) { 9720 SelectionDAG &DAG = Builder.DAG; 9721 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9722 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9723 9724 // Things on the stack are pointer-typed, meaning that they are already 9725 // legal and can be emitted directly to target nodes. 9726 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9727 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9728 } else { 9729 // Otherwise emit a target independent node to be legalised. 9730 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9731 } 9732 } 9733 } 9734 9735 /// Lower llvm.experimental.stackmap. 9736 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9737 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9738 // [live variables...]) 9739 9740 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9741 9742 SDValue Chain, InGlue, Callee; 9743 SmallVector<SDValue, 32> Ops; 9744 9745 SDLoc DL = getCurSDLoc(); 9746 Callee = getValue(CI.getCalledOperand()); 9747 9748 // The stackmap intrinsic only records the live variables (the arguments 9749 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9750 // intrinsic, this won't be lowered to a function call. This means we don't 9751 // have to worry about calling conventions and target specific lowering code. 9752 // Instead we perform the call lowering right here. 9753 // 9754 // chain, flag = CALLSEQ_START(chain, 0, 0) 9755 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9756 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9757 // 9758 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9759 InGlue = Chain.getValue(1); 9760 9761 // Add the STACKMAP operands, starting with DAG house-keeping. 9762 Ops.push_back(Chain); 9763 Ops.push_back(InGlue); 9764 9765 // Add the <id>, <numShadowBytes> operands. 9766 // 9767 // These do not require legalisation, and can be emitted directly to target 9768 // constant nodes. 9769 SDValue ID = getValue(CI.getArgOperand(0)); 9770 assert(ID.getValueType() == MVT::i64); 9771 SDValue IDConst = DAG.getTargetConstant( 9772 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9773 Ops.push_back(IDConst); 9774 9775 SDValue Shad = getValue(CI.getArgOperand(1)); 9776 assert(Shad.getValueType() == MVT::i32); 9777 SDValue ShadConst = DAG.getTargetConstant( 9778 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9779 Ops.push_back(ShadConst); 9780 9781 // Add the live variables. 9782 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9783 9784 // Create the STACKMAP node. 9785 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9786 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9787 InGlue = Chain.getValue(1); 9788 9789 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 9790 9791 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9792 9793 // Set the root to the target-lowered call chain. 9794 DAG.setRoot(Chain); 9795 9796 // Inform the Frame Information that we have a stackmap in this function. 9797 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9798 } 9799 9800 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9801 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9802 const BasicBlock *EHPadBB) { 9803 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9804 // i32 <numBytes>, 9805 // i8* <target>, 9806 // i32 <numArgs>, 9807 // [Args...], 9808 // [live variables...]) 9809 9810 CallingConv::ID CC = CB.getCallingConv(); 9811 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9812 bool HasDef = !CB.getType()->isVoidTy(); 9813 SDLoc dl = getCurSDLoc(); 9814 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9815 9816 // Handle immediate and symbolic callees. 9817 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9818 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9819 /*isTarget=*/true); 9820 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9821 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9822 SDLoc(SymbolicCallee), 9823 SymbolicCallee->getValueType(0)); 9824 9825 // Get the real number of arguments participating in the call <numArgs> 9826 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9827 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9828 9829 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9830 // Intrinsics include all meta-operands up to but not including CC. 9831 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9832 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9833 "Not enough arguments provided to the patchpoint intrinsic"); 9834 9835 // For AnyRegCC the arguments are lowered later on manually. 9836 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9837 Type *ReturnTy = 9838 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9839 9840 TargetLowering::CallLoweringInfo CLI(DAG); 9841 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9842 ReturnTy, true); 9843 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9844 9845 SDNode *CallEnd = Result.second.getNode(); 9846 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9847 CallEnd = CallEnd->getOperand(0).getNode(); 9848 9849 /// Get a call instruction from the call sequence chain. 9850 /// Tail calls are not allowed. 9851 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9852 "Expected a callseq node."); 9853 SDNode *Call = CallEnd->getOperand(0).getNode(); 9854 bool HasGlue = Call->getGluedNode(); 9855 9856 // Replace the target specific call node with the patchable intrinsic. 9857 SmallVector<SDValue, 8> Ops; 9858 9859 // Push the chain. 9860 Ops.push_back(*(Call->op_begin())); 9861 9862 // Optionally, push the glue (if any). 9863 if (HasGlue) 9864 Ops.push_back(*(Call->op_end() - 1)); 9865 9866 // Push the register mask info. 9867 if (HasGlue) 9868 Ops.push_back(*(Call->op_end() - 2)); 9869 else 9870 Ops.push_back(*(Call->op_end() - 1)); 9871 9872 // Add the <id> and <numBytes> constants. 9873 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9874 Ops.push_back(DAG.getTargetConstant( 9875 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9876 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9877 Ops.push_back(DAG.getTargetConstant( 9878 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9879 MVT::i32)); 9880 9881 // Add the callee. 9882 Ops.push_back(Callee); 9883 9884 // Adjust <numArgs> to account for any arguments that have been passed on the 9885 // stack instead. 9886 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9887 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9888 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9889 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9890 9891 // Add the calling convention 9892 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9893 9894 // Add the arguments we omitted previously. The register allocator should 9895 // place these in any free register. 9896 if (IsAnyRegCC) 9897 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9898 Ops.push_back(getValue(CB.getArgOperand(i))); 9899 9900 // Push the arguments from the call instruction. 9901 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9902 Ops.append(Call->op_begin() + 2, e); 9903 9904 // Push live variables for the stack map. 9905 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9906 9907 SDVTList NodeTys; 9908 if (IsAnyRegCC && HasDef) { 9909 // Create the return types based on the intrinsic definition 9910 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9911 SmallVector<EVT, 3> ValueVTs; 9912 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9913 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9914 9915 // There is always a chain and a glue type at the end 9916 ValueVTs.push_back(MVT::Other); 9917 ValueVTs.push_back(MVT::Glue); 9918 NodeTys = DAG.getVTList(ValueVTs); 9919 } else 9920 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9921 9922 // Replace the target specific call node with a PATCHPOINT node. 9923 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9924 9925 // Update the NodeMap. 9926 if (HasDef) { 9927 if (IsAnyRegCC) 9928 setValue(&CB, SDValue(PPV.getNode(), 0)); 9929 else 9930 setValue(&CB, Result.first); 9931 } 9932 9933 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9934 // call sequence. Furthermore the location of the chain and glue can change 9935 // when the AnyReg calling convention is used and the intrinsic returns a 9936 // value. 9937 if (IsAnyRegCC && HasDef) { 9938 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9939 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9940 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9941 } else 9942 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9943 DAG.DeleteNode(Call); 9944 9945 // Inform the Frame Information that we have a patchpoint in this function. 9946 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9947 } 9948 9949 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9950 unsigned Intrinsic) { 9951 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9952 SDValue Op1 = getValue(I.getArgOperand(0)); 9953 SDValue Op2; 9954 if (I.arg_size() > 1) 9955 Op2 = getValue(I.getArgOperand(1)); 9956 SDLoc dl = getCurSDLoc(); 9957 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9958 SDValue Res; 9959 SDNodeFlags SDFlags; 9960 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9961 SDFlags.copyFMF(*FPMO); 9962 9963 switch (Intrinsic) { 9964 case Intrinsic::vector_reduce_fadd: 9965 if (SDFlags.hasAllowReassociation()) 9966 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9967 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9968 SDFlags); 9969 else 9970 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9971 break; 9972 case Intrinsic::vector_reduce_fmul: 9973 if (SDFlags.hasAllowReassociation()) 9974 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9975 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9976 SDFlags); 9977 else 9978 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9979 break; 9980 case Intrinsic::vector_reduce_add: 9981 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9982 break; 9983 case Intrinsic::vector_reduce_mul: 9984 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9985 break; 9986 case Intrinsic::vector_reduce_and: 9987 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9988 break; 9989 case Intrinsic::vector_reduce_or: 9990 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9991 break; 9992 case Intrinsic::vector_reduce_xor: 9993 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9994 break; 9995 case Intrinsic::vector_reduce_smax: 9996 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9997 break; 9998 case Intrinsic::vector_reduce_smin: 9999 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10000 break; 10001 case Intrinsic::vector_reduce_umax: 10002 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10003 break; 10004 case Intrinsic::vector_reduce_umin: 10005 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10006 break; 10007 case Intrinsic::vector_reduce_fmax: 10008 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10009 break; 10010 case Intrinsic::vector_reduce_fmin: 10011 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10012 break; 10013 default: 10014 llvm_unreachable("Unhandled vector reduce intrinsic"); 10015 } 10016 setValue(&I, Res); 10017 } 10018 10019 /// Returns an AttributeList representing the attributes applied to the return 10020 /// value of the given call. 10021 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10022 SmallVector<Attribute::AttrKind, 2> Attrs; 10023 if (CLI.RetSExt) 10024 Attrs.push_back(Attribute::SExt); 10025 if (CLI.RetZExt) 10026 Attrs.push_back(Attribute::ZExt); 10027 if (CLI.IsInReg) 10028 Attrs.push_back(Attribute::InReg); 10029 10030 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10031 Attrs); 10032 } 10033 10034 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10035 /// implementation, which just calls LowerCall. 10036 /// FIXME: When all targets are 10037 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10038 std::pair<SDValue, SDValue> 10039 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10040 // Handle the incoming return values from the call. 10041 CLI.Ins.clear(); 10042 Type *OrigRetTy = CLI.RetTy; 10043 SmallVector<EVT, 4> RetTys; 10044 SmallVector<uint64_t, 4> Offsets; 10045 auto &DL = CLI.DAG.getDataLayout(); 10046 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0); 10047 10048 if (CLI.IsPostTypeLegalization) { 10049 // If we are lowering a libcall after legalization, split the return type. 10050 SmallVector<EVT, 4> OldRetTys; 10051 SmallVector<uint64_t, 4> OldOffsets; 10052 RetTys.swap(OldRetTys); 10053 Offsets.swap(OldOffsets); 10054 10055 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10056 EVT RetVT = OldRetTys[i]; 10057 uint64_t Offset = OldOffsets[i]; 10058 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10059 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10060 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10061 RetTys.append(NumRegs, RegisterVT); 10062 for (unsigned j = 0; j != NumRegs; ++j) 10063 Offsets.push_back(Offset + j * RegisterVTByteSZ); 10064 } 10065 } 10066 10067 SmallVector<ISD::OutputArg, 4> Outs; 10068 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10069 10070 bool CanLowerReturn = 10071 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10072 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10073 10074 SDValue DemoteStackSlot; 10075 int DemoteStackIdx = -100; 10076 if (!CanLowerReturn) { 10077 // FIXME: equivalent assert? 10078 // assert(!CS.hasInAllocaArgument() && 10079 // "sret demotion is incompatible with inalloca"); 10080 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10081 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10082 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10083 DemoteStackIdx = 10084 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10085 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10086 DL.getAllocaAddrSpace()); 10087 10088 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10089 ArgListEntry Entry; 10090 Entry.Node = DemoteStackSlot; 10091 Entry.Ty = StackSlotPtrType; 10092 Entry.IsSExt = false; 10093 Entry.IsZExt = false; 10094 Entry.IsInReg = false; 10095 Entry.IsSRet = true; 10096 Entry.IsNest = false; 10097 Entry.IsByVal = false; 10098 Entry.IsByRef = false; 10099 Entry.IsReturned = false; 10100 Entry.IsSwiftSelf = false; 10101 Entry.IsSwiftAsync = false; 10102 Entry.IsSwiftError = false; 10103 Entry.IsCFGuardTarget = false; 10104 Entry.Alignment = Alignment; 10105 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10106 CLI.NumFixedArgs += 1; 10107 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10108 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10109 10110 // sret demotion isn't compatible with tail-calls, since the sret argument 10111 // points into the callers stack frame. 10112 CLI.IsTailCall = false; 10113 } else { 10114 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10115 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10116 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10117 ISD::ArgFlagsTy Flags; 10118 if (NeedsRegBlock) { 10119 Flags.setInConsecutiveRegs(); 10120 if (I == RetTys.size() - 1) 10121 Flags.setInConsecutiveRegsLast(); 10122 } 10123 EVT VT = RetTys[I]; 10124 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10125 CLI.CallConv, VT); 10126 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10127 CLI.CallConv, VT); 10128 for (unsigned i = 0; i != NumRegs; ++i) { 10129 ISD::InputArg MyFlags; 10130 MyFlags.Flags = Flags; 10131 MyFlags.VT = RegisterVT; 10132 MyFlags.ArgVT = VT; 10133 MyFlags.Used = CLI.IsReturnValueUsed; 10134 if (CLI.RetTy->isPointerTy()) { 10135 MyFlags.Flags.setPointer(); 10136 MyFlags.Flags.setPointerAddrSpace( 10137 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10138 } 10139 if (CLI.RetSExt) 10140 MyFlags.Flags.setSExt(); 10141 if (CLI.RetZExt) 10142 MyFlags.Flags.setZExt(); 10143 if (CLI.IsInReg) 10144 MyFlags.Flags.setInReg(); 10145 CLI.Ins.push_back(MyFlags); 10146 } 10147 } 10148 } 10149 10150 // We push in swifterror return as the last element of CLI.Ins. 10151 ArgListTy &Args = CLI.getArgs(); 10152 if (supportSwiftError()) { 10153 for (const ArgListEntry &Arg : Args) { 10154 if (Arg.IsSwiftError) { 10155 ISD::InputArg MyFlags; 10156 MyFlags.VT = getPointerTy(DL); 10157 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10158 MyFlags.Flags.setSwiftError(); 10159 CLI.Ins.push_back(MyFlags); 10160 } 10161 } 10162 } 10163 10164 // Handle all of the outgoing arguments. 10165 CLI.Outs.clear(); 10166 CLI.OutVals.clear(); 10167 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10168 SmallVector<EVT, 4> ValueVTs; 10169 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10170 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10171 Type *FinalType = Args[i].Ty; 10172 if (Args[i].IsByVal) 10173 FinalType = Args[i].IndirectType; 10174 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10175 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10176 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10177 ++Value) { 10178 EVT VT = ValueVTs[Value]; 10179 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10180 SDValue Op = SDValue(Args[i].Node.getNode(), 10181 Args[i].Node.getResNo() + Value); 10182 ISD::ArgFlagsTy Flags; 10183 10184 // Certain targets (such as MIPS), may have a different ABI alignment 10185 // for a type depending on the context. Give the target a chance to 10186 // specify the alignment it wants. 10187 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10188 Flags.setOrigAlign(OriginalAlignment); 10189 10190 if (Args[i].Ty->isPointerTy()) { 10191 Flags.setPointer(); 10192 Flags.setPointerAddrSpace( 10193 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10194 } 10195 if (Args[i].IsZExt) 10196 Flags.setZExt(); 10197 if (Args[i].IsSExt) 10198 Flags.setSExt(); 10199 if (Args[i].IsInReg) { 10200 // If we are using vectorcall calling convention, a structure that is 10201 // passed InReg - is surely an HVA 10202 if (CLI.CallConv == CallingConv::X86_VectorCall && 10203 isa<StructType>(FinalType)) { 10204 // The first value of a structure is marked 10205 if (0 == Value) 10206 Flags.setHvaStart(); 10207 Flags.setHva(); 10208 } 10209 // Set InReg Flag 10210 Flags.setInReg(); 10211 } 10212 if (Args[i].IsSRet) 10213 Flags.setSRet(); 10214 if (Args[i].IsSwiftSelf) 10215 Flags.setSwiftSelf(); 10216 if (Args[i].IsSwiftAsync) 10217 Flags.setSwiftAsync(); 10218 if (Args[i].IsSwiftError) 10219 Flags.setSwiftError(); 10220 if (Args[i].IsCFGuardTarget) 10221 Flags.setCFGuardTarget(); 10222 if (Args[i].IsByVal) 10223 Flags.setByVal(); 10224 if (Args[i].IsByRef) 10225 Flags.setByRef(); 10226 if (Args[i].IsPreallocated) { 10227 Flags.setPreallocated(); 10228 // Set the byval flag for CCAssignFn callbacks that don't know about 10229 // preallocated. This way we can know how many bytes we should've 10230 // allocated and how many bytes a callee cleanup function will pop. If 10231 // we port preallocated to more targets, we'll have to add custom 10232 // preallocated handling in the various CC lowering callbacks. 10233 Flags.setByVal(); 10234 } 10235 if (Args[i].IsInAlloca) { 10236 Flags.setInAlloca(); 10237 // Set the byval flag for CCAssignFn callbacks that don't know about 10238 // inalloca. This way we can know how many bytes we should've allocated 10239 // and how many bytes a callee cleanup function will pop. If we port 10240 // inalloca to more targets, we'll have to add custom inalloca handling 10241 // in the various CC lowering callbacks. 10242 Flags.setByVal(); 10243 } 10244 Align MemAlign; 10245 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10246 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10247 Flags.setByValSize(FrameSize); 10248 10249 // info is not there but there are cases it cannot get right. 10250 if (auto MA = Args[i].Alignment) 10251 MemAlign = *MA; 10252 else 10253 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10254 } else if (auto MA = Args[i].Alignment) { 10255 MemAlign = *MA; 10256 } else { 10257 MemAlign = OriginalAlignment; 10258 } 10259 Flags.setMemAlign(MemAlign); 10260 if (Args[i].IsNest) 10261 Flags.setNest(); 10262 if (NeedsRegBlock) 10263 Flags.setInConsecutiveRegs(); 10264 10265 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10266 CLI.CallConv, VT); 10267 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10268 CLI.CallConv, VT); 10269 SmallVector<SDValue, 4> Parts(NumParts); 10270 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10271 10272 if (Args[i].IsSExt) 10273 ExtendKind = ISD::SIGN_EXTEND; 10274 else if (Args[i].IsZExt) 10275 ExtendKind = ISD::ZERO_EXTEND; 10276 10277 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10278 // for now. 10279 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10280 CanLowerReturn) { 10281 assert((CLI.RetTy == Args[i].Ty || 10282 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10283 CLI.RetTy->getPointerAddressSpace() == 10284 Args[i].Ty->getPointerAddressSpace())) && 10285 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10286 // Before passing 'returned' to the target lowering code, ensure that 10287 // either the register MVT and the actual EVT are the same size or that 10288 // the return value and argument are extended in the same way; in these 10289 // cases it's safe to pass the argument register value unchanged as the 10290 // return register value (although it's at the target's option whether 10291 // to do so) 10292 // TODO: allow code generation to take advantage of partially preserved 10293 // registers rather than clobbering the entire register when the 10294 // parameter extension method is not compatible with the return 10295 // extension method 10296 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10297 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10298 CLI.RetZExt == Args[i].IsZExt)) 10299 Flags.setReturned(); 10300 } 10301 10302 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10303 CLI.CallConv, ExtendKind); 10304 10305 for (unsigned j = 0; j != NumParts; ++j) { 10306 // if it isn't first piece, alignment must be 1 10307 // For scalable vectors the scalable part is currently handled 10308 // by individual targets, so we just use the known minimum size here. 10309 ISD::OutputArg MyFlags( 10310 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10311 i < CLI.NumFixedArgs, i, 10312 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10313 if (NumParts > 1 && j == 0) 10314 MyFlags.Flags.setSplit(); 10315 else if (j != 0) { 10316 MyFlags.Flags.setOrigAlign(Align(1)); 10317 if (j == NumParts - 1) 10318 MyFlags.Flags.setSplitEnd(); 10319 } 10320 10321 CLI.Outs.push_back(MyFlags); 10322 CLI.OutVals.push_back(Parts[j]); 10323 } 10324 10325 if (NeedsRegBlock && Value == NumValues - 1) 10326 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10327 } 10328 } 10329 10330 SmallVector<SDValue, 4> InVals; 10331 CLI.Chain = LowerCall(CLI, InVals); 10332 10333 // Update CLI.InVals to use outside of this function. 10334 CLI.InVals = InVals; 10335 10336 // Verify that the target's LowerCall behaved as expected. 10337 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10338 "LowerCall didn't return a valid chain!"); 10339 assert((!CLI.IsTailCall || InVals.empty()) && 10340 "LowerCall emitted a return value for a tail call!"); 10341 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10342 "LowerCall didn't emit the correct number of values!"); 10343 10344 // For a tail call, the return value is merely live-out and there aren't 10345 // any nodes in the DAG representing it. Return a special value to 10346 // indicate that a tail call has been emitted and no more Instructions 10347 // should be processed in the current block. 10348 if (CLI.IsTailCall) { 10349 CLI.DAG.setRoot(CLI.Chain); 10350 return std::make_pair(SDValue(), SDValue()); 10351 } 10352 10353 #ifndef NDEBUG 10354 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10355 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10356 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10357 "LowerCall emitted a value with the wrong type!"); 10358 } 10359 #endif 10360 10361 SmallVector<SDValue, 4> ReturnValues; 10362 if (!CanLowerReturn) { 10363 // The instruction result is the result of loading from the 10364 // hidden sret parameter. 10365 SmallVector<EVT, 1> PVTs; 10366 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10367 10368 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10369 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10370 EVT PtrVT = PVTs[0]; 10371 10372 unsigned NumValues = RetTys.size(); 10373 ReturnValues.resize(NumValues); 10374 SmallVector<SDValue, 4> Chains(NumValues); 10375 10376 // An aggregate return value cannot wrap around the address space, so 10377 // offsets to its parts don't wrap either. 10378 SDNodeFlags Flags; 10379 Flags.setNoUnsignedWrap(true); 10380 10381 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10382 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10383 for (unsigned i = 0; i < NumValues; ++i) { 10384 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10385 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10386 PtrVT), Flags); 10387 SDValue L = CLI.DAG.getLoad( 10388 RetTys[i], CLI.DL, CLI.Chain, Add, 10389 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10390 DemoteStackIdx, Offsets[i]), 10391 HiddenSRetAlign); 10392 ReturnValues[i] = L; 10393 Chains[i] = L.getValue(1); 10394 } 10395 10396 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10397 } else { 10398 // Collect the legal value parts into potentially illegal values 10399 // that correspond to the original function's return values. 10400 std::optional<ISD::NodeType> AssertOp; 10401 if (CLI.RetSExt) 10402 AssertOp = ISD::AssertSext; 10403 else if (CLI.RetZExt) 10404 AssertOp = ISD::AssertZext; 10405 unsigned CurReg = 0; 10406 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10407 EVT VT = RetTys[I]; 10408 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10409 CLI.CallConv, VT); 10410 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10411 CLI.CallConv, VT); 10412 10413 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10414 NumRegs, RegisterVT, VT, nullptr, 10415 CLI.CallConv, AssertOp)); 10416 CurReg += NumRegs; 10417 } 10418 10419 // For a function returning void, there is no return value. We can't create 10420 // such a node, so we just return a null return value in that case. In 10421 // that case, nothing will actually look at the value. 10422 if (ReturnValues.empty()) 10423 return std::make_pair(SDValue(), CLI.Chain); 10424 } 10425 10426 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10427 CLI.DAG.getVTList(RetTys), ReturnValues); 10428 return std::make_pair(Res, CLI.Chain); 10429 } 10430 10431 /// Places new result values for the node in Results (their number 10432 /// and types must exactly match those of the original return values of 10433 /// the node), or leaves Results empty, which indicates that the node is not 10434 /// to be custom lowered after all. 10435 void TargetLowering::LowerOperationWrapper(SDNode *N, 10436 SmallVectorImpl<SDValue> &Results, 10437 SelectionDAG &DAG) const { 10438 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10439 10440 if (!Res.getNode()) 10441 return; 10442 10443 // If the original node has one result, take the return value from 10444 // LowerOperation as is. It might not be result number 0. 10445 if (N->getNumValues() == 1) { 10446 Results.push_back(Res); 10447 return; 10448 } 10449 10450 // If the original node has multiple results, then the return node should 10451 // have the same number of results. 10452 assert((N->getNumValues() == Res->getNumValues()) && 10453 "Lowering returned the wrong number of results!"); 10454 10455 // Places new result values base on N result number. 10456 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10457 Results.push_back(Res.getValue(I)); 10458 } 10459 10460 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10461 llvm_unreachable("LowerOperation not implemented for this target!"); 10462 } 10463 10464 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10465 unsigned Reg, 10466 ISD::NodeType ExtendType) { 10467 SDValue Op = getNonRegisterValue(V); 10468 assert((Op.getOpcode() != ISD::CopyFromReg || 10469 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10470 "Copy from a reg to the same reg!"); 10471 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10472 10473 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10474 // If this is an InlineAsm we have to match the registers required, not the 10475 // notional registers required by the type. 10476 10477 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10478 std::nullopt); // This is not an ABI copy. 10479 SDValue Chain = DAG.getEntryNode(); 10480 10481 if (ExtendType == ISD::ANY_EXTEND) { 10482 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10483 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10484 ExtendType = PreferredExtendIt->second; 10485 } 10486 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10487 PendingExports.push_back(Chain); 10488 } 10489 10490 #include "llvm/CodeGen/SelectionDAGISel.h" 10491 10492 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10493 /// entry block, return true. This includes arguments used by switches, since 10494 /// the switch may expand into multiple basic blocks. 10495 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10496 // With FastISel active, we may be splitting blocks, so force creation 10497 // of virtual registers for all non-dead arguments. 10498 if (FastISel) 10499 return A->use_empty(); 10500 10501 const BasicBlock &Entry = A->getParent()->front(); 10502 for (const User *U : A->users()) 10503 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10504 return false; // Use not in entry block. 10505 10506 return true; 10507 } 10508 10509 using ArgCopyElisionMapTy = 10510 DenseMap<const Argument *, 10511 std::pair<const AllocaInst *, const StoreInst *>>; 10512 10513 /// Scan the entry block of the function in FuncInfo for arguments that look 10514 /// like copies into a local alloca. Record any copied arguments in 10515 /// ArgCopyElisionCandidates. 10516 static void 10517 findArgumentCopyElisionCandidates(const DataLayout &DL, 10518 FunctionLoweringInfo *FuncInfo, 10519 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10520 // Record the state of every static alloca used in the entry block. Argument 10521 // allocas are all used in the entry block, so we need approximately as many 10522 // entries as we have arguments. 10523 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10524 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10525 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10526 StaticAllocas.reserve(NumArgs * 2); 10527 10528 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10529 if (!V) 10530 return nullptr; 10531 V = V->stripPointerCasts(); 10532 const auto *AI = dyn_cast<AllocaInst>(V); 10533 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10534 return nullptr; 10535 auto Iter = StaticAllocas.insert({AI, Unknown}); 10536 return &Iter.first->second; 10537 }; 10538 10539 // Look for stores of arguments to static allocas. Look through bitcasts and 10540 // GEPs to handle type coercions, as long as the alloca is fully initialized 10541 // by the store. Any non-store use of an alloca escapes it and any subsequent 10542 // unanalyzed store might write it. 10543 // FIXME: Handle structs initialized with multiple stores. 10544 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10545 // Look for stores, and handle non-store uses conservatively. 10546 const auto *SI = dyn_cast<StoreInst>(&I); 10547 if (!SI) { 10548 // We will look through cast uses, so ignore them completely. 10549 if (I.isCast()) 10550 continue; 10551 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10552 // to allocas. 10553 if (I.isDebugOrPseudoInst()) 10554 continue; 10555 // This is an unknown instruction. Assume it escapes or writes to all 10556 // static alloca operands. 10557 for (const Use &U : I.operands()) { 10558 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10559 *Info = StaticAllocaInfo::Clobbered; 10560 } 10561 continue; 10562 } 10563 10564 // If the stored value is a static alloca, mark it as escaped. 10565 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10566 *Info = StaticAllocaInfo::Clobbered; 10567 10568 // Check if the destination is a static alloca. 10569 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10570 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10571 if (!Info) 10572 continue; 10573 const AllocaInst *AI = cast<AllocaInst>(Dst); 10574 10575 // Skip allocas that have been initialized or clobbered. 10576 if (*Info != StaticAllocaInfo::Unknown) 10577 continue; 10578 10579 // Check if the stored value is an argument, and that this store fully 10580 // initializes the alloca. 10581 // If the argument type has padding bits we can't directly forward a pointer 10582 // as the upper bits may contain garbage. 10583 // Don't elide copies from the same argument twice. 10584 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10585 const auto *Arg = dyn_cast<Argument>(Val); 10586 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10587 Arg->getType()->isEmptyTy() || 10588 DL.getTypeStoreSize(Arg->getType()) != 10589 DL.getTypeAllocSize(AI->getAllocatedType()) || 10590 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10591 ArgCopyElisionCandidates.count(Arg)) { 10592 *Info = StaticAllocaInfo::Clobbered; 10593 continue; 10594 } 10595 10596 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10597 << '\n'); 10598 10599 // Mark this alloca and store for argument copy elision. 10600 *Info = StaticAllocaInfo::Elidable; 10601 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10602 10603 // Stop scanning if we've seen all arguments. This will happen early in -O0 10604 // builds, which is useful, because -O0 builds have large entry blocks and 10605 // many allocas. 10606 if (ArgCopyElisionCandidates.size() == NumArgs) 10607 break; 10608 } 10609 } 10610 10611 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10612 /// ArgVal is a load from a suitable fixed stack object. 10613 static void tryToElideArgumentCopy( 10614 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10615 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10616 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10617 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10618 SDValue ArgVal, bool &ArgHasUses) { 10619 // Check if this is a load from a fixed stack object. 10620 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10621 if (!LNode) 10622 return; 10623 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10624 if (!FINode) 10625 return; 10626 10627 // Check that the fixed stack object is the right size and alignment. 10628 // Look at the alignment that the user wrote on the alloca instead of looking 10629 // at the stack object. 10630 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10631 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10632 const AllocaInst *AI = ArgCopyIter->second.first; 10633 int FixedIndex = FINode->getIndex(); 10634 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10635 int OldIndex = AllocaIndex; 10636 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10637 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10638 LLVM_DEBUG( 10639 dbgs() << " argument copy elision failed due to bad fixed stack " 10640 "object size\n"); 10641 return; 10642 } 10643 Align RequiredAlignment = AI->getAlign(); 10644 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10645 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10646 "greater than stack argument alignment (" 10647 << DebugStr(RequiredAlignment) << " vs " 10648 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10649 return; 10650 } 10651 10652 // Perform the elision. Delete the old stack object and replace its only use 10653 // in the variable info map. Mark the stack object as mutable. 10654 LLVM_DEBUG({ 10655 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10656 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10657 << '\n'; 10658 }); 10659 MFI.RemoveStackObject(OldIndex); 10660 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10661 AllocaIndex = FixedIndex; 10662 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 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 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10925 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10926 InVals[i], ArgHasUses); 10927 } 10928 10929 // If this argument is unused then remember its value. It is used to generate 10930 // debugging information. 10931 bool isSwiftErrorArg = 10932 TLI->supportSwiftError() && 10933 Arg.hasAttribute(Attribute::SwiftError); 10934 if (!ArgHasUses && !isSwiftErrorArg) { 10935 SDB->setUnusedArgValue(&Arg, InVals[i]); 10936 10937 // Also remember any frame index for use in FastISel. 10938 if (FrameIndexSDNode *FI = 10939 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10940 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10941 } 10942 10943 for (unsigned Val = 0; Val != NumValues; ++Val) { 10944 EVT VT = ValueVTs[Val]; 10945 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10946 F.getCallingConv(), VT); 10947 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10948 *CurDAG->getContext(), F.getCallingConv(), VT); 10949 10950 // Even an apparent 'unused' swifterror argument needs to be returned. So 10951 // we do generate a copy for it that can be used on return from the 10952 // function. 10953 if (ArgHasUses || isSwiftErrorArg) { 10954 std::optional<ISD::NodeType> AssertOp; 10955 if (Arg.hasAttribute(Attribute::SExt)) 10956 AssertOp = ISD::AssertSext; 10957 else if (Arg.hasAttribute(Attribute::ZExt)) 10958 AssertOp = ISD::AssertZext; 10959 10960 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10961 PartVT, VT, nullptr, 10962 F.getCallingConv(), AssertOp)); 10963 } 10964 10965 i += NumParts; 10966 } 10967 10968 // We don't need to do anything else for unused arguments. 10969 if (ArgValues.empty()) 10970 continue; 10971 10972 // Note down frame index. 10973 if (FrameIndexSDNode *FI = 10974 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10975 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10976 10977 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 10978 SDB->getCurSDLoc()); 10979 10980 SDB->setValue(&Arg, Res); 10981 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10982 // We want to associate the argument with the frame index, among 10983 // involved operands, that correspond to the lowest address. The 10984 // getCopyFromParts function, called earlier, is swapping the order of 10985 // the operands to BUILD_PAIR depending on endianness. The result of 10986 // that swapping is that the least significant bits of the argument will 10987 // be in the first operand of the BUILD_PAIR node, and the most 10988 // significant bits will be in the second operand. 10989 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10990 if (LoadSDNode *LNode = 10991 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10992 if (FrameIndexSDNode *FI = 10993 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10994 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10995 } 10996 10997 // Analyses past this point are naive and don't expect an assertion. 10998 if (Res.getOpcode() == ISD::AssertZext) 10999 Res = Res.getOperand(0); 11000 11001 // Update the SwiftErrorVRegDefMap. 11002 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11003 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11004 if (Register::isVirtualRegister(Reg)) 11005 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11006 Reg); 11007 } 11008 11009 // If this argument is live outside of the entry block, insert a copy from 11010 // wherever we got it to the vreg that other BB's will reference it as. 11011 if (Res.getOpcode() == ISD::CopyFromReg) { 11012 // If we can, though, try to skip creating an unnecessary vreg. 11013 // FIXME: This isn't very clean... it would be nice to make this more 11014 // general. 11015 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11016 if (Register::isVirtualRegister(Reg)) { 11017 FuncInfo->ValueMap[&Arg] = Reg; 11018 continue; 11019 } 11020 } 11021 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11022 FuncInfo->InitializeRegForValue(&Arg); 11023 SDB->CopyToExportRegsIfNeeded(&Arg); 11024 } 11025 } 11026 11027 if (!Chains.empty()) { 11028 Chains.push_back(NewRoot); 11029 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11030 } 11031 11032 DAG.setRoot(NewRoot); 11033 11034 assert(i == InVals.size() && "Argument register count mismatch!"); 11035 11036 // If any argument copy elisions occurred and we have debug info, update the 11037 // stale frame indices used in the dbg.declare variable info table. 11038 if (!ArgCopyElisionFrameIndexMap.empty()) { 11039 for (MachineFunction::VariableDbgInfo &VI : 11040 MF->getInStackSlotVariableDbgInfo()) { 11041 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11042 if (I != ArgCopyElisionFrameIndexMap.end()) 11043 VI.updateStackSlot(I->second); 11044 } 11045 } 11046 11047 // Finally, if the target has anything special to do, allow it to do so. 11048 emitFunctionEntryCode(); 11049 } 11050 11051 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11052 /// ensure constants are generated when needed. Remember the virtual registers 11053 /// that need to be added to the Machine PHI nodes as input. We cannot just 11054 /// directly add them, because expansion might result in multiple MBB's for one 11055 /// BB. As such, the start of the BB might correspond to a different MBB than 11056 /// the end. 11057 void 11058 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11059 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11060 11061 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11062 11063 // Check PHI nodes in successors that expect a value to be available from this 11064 // block. 11065 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11066 if (!isa<PHINode>(SuccBB->begin())) continue; 11067 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 11068 11069 // If this terminator has multiple identical successors (common for 11070 // switches), only handle each succ once. 11071 if (!SuccsHandled.insert(SuccMBB).second) 11072 continue; 11073 11074 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11075 11076 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11077 // nodes and Machine PHI nodes, but the incoming operands have not been 11078 // emitted yet. 11079 for (const PHINode &PN : SuccBB->phis()) { 11080 // Ignore dead phi's. 11081 if (PN.use_empty()) 11082 continue; 11083 11084 // Skip empty types 11085 if (PN.getType()->isEmptyTy()) 11086 continue; 11087 11088 unsigned Reg; 11089 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11090 11091 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11092 unsigned &RegOut = ConstantsOut[C]; 11093 if (RegOut == 0) { 11094 RegOut = FuncInfo.CreateRegs(C); 11095 // We need to zero/sign extend ConstantInt phi operands to match 11096 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11097 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11098 if (auto *CI = dyn_cast<ConstantInt>(C)) 11099 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11100 : ISD::ZERO_EXTEND; 11101 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11102 } 11103 Reg = RegOut; 11104 } else { 11105 DenseMap<const Value *, Register>::iterator I = 11106 FuncInfo.ValueMap.find(PHIOp); 11107 if (I != FuncInfo.ValueMap.end()) 11108 Reg = I->second; 11109 else { 11110 assert(isa<AllocaInst>(PHIOp) && 11111 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11112 "Didn't codegen value into a register!??"); 11113 Reg = FuncInfo.CreateRegs(PHIOp); 11114 CopyValueToVirtualRegister(PHIOp, Reg); 11115 } 11116 } 11117 11118 // Remember that this register needs to added to the machine PHI node as 11119 // the input for this MBB. 11120 SmallVector<EVT, 4> ValueVTs; 11121 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11122 for (EVT VT : ValueVTs) { 11123 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11124 for (unsigned i = 0; i != NumRegisters; ++i) 11125 FuncInfo.PHINodesToUpdate.push_back( 11126 std::make_pair(&*MBBI++, Reg + i)); 11127 Reg += NumRegisters; 11128 } 11129 } 11130 } 11131 11132 ConstantsOut.clear(); 11133 } 11134 11135 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11136 MachineFunction::iterator I(MBB); 11137 if (++I == FuncInfo.MF->end()) 11138 return nullptr; 11139 return &*I; 11140 } 11141 11142 /// During lowering new call nodes can be created (such as memset, etc.). 11143 /// Those will become new roots of the current DAG, but complications arise 11144 /// when they are tail calls. In such cases, the call lowering will update 11145 /// the root, but the builder still needs to know that a tail call has been 11146 /// lowered in order to avoid generating an additional return. 11147 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11148 // If the node is null, we do have a tail call. 11149 if (MaybeTC.getNode() != nullptr) 11150 DAG.setRoot(MaybeTC); 11151 else 11152 HasTailCall = true; 11153 } 11154 11155 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11156 MachineBasicBlock *SwitchMBB, 11157 MachineBasicBlock *DefaultMBB) { 11158 MachineFunction *CurMF = FuncInfo.MF; 11159 MachineBasicBlock *NextMBB = nullptr; 11160 MachineFunction::iterator BBI(W.MBB); 11161 if (++BBI != FuncInfo.MF->end()) 11162 NextMBB = &*BBI; 11163 11164 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11165 11166 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11167 11168 if (Size == 2 && W.MBB == SwitchMBB) { 11169 // If any two of the cases has the same destination, and if one value 11170 // is the same as the other, but has one bit unset that the other has set, 11171 // use bit manipulation to do two compares at once. For example: 11172 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11173 // TODO: This could be extended to merge any 2 cases in switches with 3 11174 // cases. 11175 // TODO: Handle cases where W.CaseBB != SwitchBB. 11176 CaseCluster &Small = *W.FirstCluster; 11177 CaseCluster &Big = *W.LastCluster; 11178 11179 if (Small.Low == Small.High && Big.Low == Big.High && 11180 Small.MBB == Big.MBB) { 11181 const APInt &SmallValue = Small.Low->getValue(); 11182 const APInt &BigValue = Big.Low->getValue(); 11183 11184 // Check that there is only one bit different. 11185 APInt CommonBit = BigValue ^ SmallValue; 11186 if (CommonBit.isPowerOf2()) { 11187 SDValue CondLHS = getValue(Cond); 11188 EVT VT = CondLHS.getValueType(); 11189 SDLoc DL = getCurSDLoc(); 11190 11191 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11192 DAG.getConstant(CommonBit, DL, VT)); 11193 SDValue Cond = DAG.getSetCC( 11194 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11195 ISD::SETEQ); 11196 11197 // Update successor info. 11198 // Both Small and Big will jump to Small.BB, so we sum up the 11199 // probabilities. 11200 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11201 if (BPI) 11202 addSuccessorWithProb( 11203 SwitchMBB, DefaultMBB, 11204 // The default destination is the first successor in IR. 11205 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11206 else 11207 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11208 11209 // Insert the true branch. 11210 SDValue BrCond = 11211 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11212 DAG.getBasicBlock(Small.MBB)); 11213 // Insert the false branch. 11214 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11215 DAG.getBasicBlock(DefaultMBB)); 11216 11217 DAG.setRoot(BrCond); 11218 return; 11219 } 11220 } 11221 } 11222 11223 if (TM.getOptLevel() != CodeGenOpt::None) { 11224 // Here, we order cases by probability so the most likely case will be 11225 // checked first. However, two clusters can have the same probability in 11226 // which case their relative ordering is non-deterministic. So we use Low 11227 // as a tie-breaker as clusters are guaranteed to never overlap. 11228 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11229 [](const CaseCluster &a, const CaseCluster &b) { 11230 return a.Prob != b.Prob ? 11231 a.Prob > b.Prob : 11232 a.Low->getValue().slt(b.Low->getValue()); 11233 }); 11234 11235 // Rearrange the case blocks so that the last one falls through if possible 11236 // without changing the order of probabilities. 11237 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11238 --I; 11239 if (I->Prob > W.LastCluster->Prob) 11240 break; 11241 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11242 std::swap(*I, *W.LastCluster); 11243 break; 11244 } 11245 } 11246 } 11247 11248 // Compute total probability. 11249 BranchProbability DefaultProb = W.DefaultProb; 11250 BranchProbability UnhandledProbs = DefaultProb; 11251 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11252 UnhandledProbs += I->Prob; 11253 11254 MachineBasicBlock *CurMBB = W.MBB; 11255 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11256 bool FallthroughUnreachable = false; 11257 MachineBasicBlock *Fallthrough; 11258 if (I == W.LastCluster) { 11259 // For the last cluster, fall through to the default destination. 11260 Fallthrough = DefaultMBB; 11261 FallthroughUnreachable = isa<UnreachableInst>( 11262 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11263 } else { 11264 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11265 CurMF->insert(BBI, Fallthrough); 11266 // Put Cond in a virtual register to make it available from the new blocks. 11267 ExportFromCurrentBlock(Cond); 11268 } 11269 UnhandledProbs -= I->Prob; 11270 11271 switch (I->Kind) { 11272 case CC_JumpTable: { 11273 // FIXME: Optimize away range check based on pivot comparisons. 11274 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11275 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11276 11277 // The jump block hasn't been inserted yet; insert it here. 11278 MachineBasicBlock *JumpMBB = JT->MBB; 11279 CurMF->insert(BBI, JumpMBB); 11280 11281 auto JumpProb = I->Prob; 11282 auto FallthroughProb = UnhandledProbs; 11283 11284 // If the default statement is a target of the jump table, we evenly 11285 // distribute the default probability to successors of CurMBB. Also 11286 // update the probability on the edge from JumpMBB to Fallthrough. 11287 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11288 SE = JumpMBB->succ_end(); 11289 SI != SE; ++SI) { 11290 if (*SI == DefaultMBB) { 11291 JumpProb += DefaultProb / 2; 11292 FallthroughProb -= DefaultProb / 2; 11293 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11294 JumpMBB->normalizeSuccProbs(); 11295 break; 11296 } 11297 } 11298 11299 if (FallthroughUnreachable) 11300 JTH->FallthroughUnreachable = true; 11301 11302 if (!JTH->FallthroughUnreachable) 11303 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11304 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11305 CurMBB->normalizeSuccProbs(); 11306 11307 // The jump table header will be inserted in our current block, do the 11308 // range check, and fall through to our fallthrough block. 11309 JTH->HeaderBB = CurMBB; 11310 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11311 11312 // If we're in the right place, emit the jump table header right now. 11313 if (CurMBB == SwitchMBB) { 11314 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11315 JTH->Emitted = true; 11316 } 11317 break; 11318 } 11319 case CC_BitTests: { 11320 // FIXME: Optimize away range check based on pivot comparisons. 11321 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11322 11323 // The bit test blocks haven't been inserted yet; insert them here. 11324 for (BitTestCase &BTC : BTB->Cases) 11325 CurMF->insert(BBI, BTC.ThisBB); 11326 11327 // Fill in fields of the BitTestBlock. 11328 BTB->Parent = CurMBB; 11329 BTB->Default = Fallthrough; 11330 11331 BTB->DefaultProb = UnhandledProbs; 11332 // If the cases in bit test don't form a contiguous range, we evenly 11333 // distribute the probability on the edge to Fallthrough to two 11334 // successors of CurMBB. 11335 if (!BTB->ContiguousRange) { 11336 BTB->Prob += DefaultProb / 2; 11337 BTB->DefaultProb -= DefaultProb / 2; 11338 } 11339 11340 if (FallthroughUnreachable) 11341 BTB->FallthroughUnreachable = true; 11342 11343 // If we're in the right place, emit the bit test header right now. 11344 if (CurMBB == SwitchMBB) { 11345 visitBitTestHeader(*BTB, SwitchMBB); 11346 BTB->Emitted = true; 11347 } 11348 break; 11349 } 11350 case CC_Range: { 11351 const Value *RHS, *LHS, *MHS; 11352 ISD::CondCode CC; 11353 if (I->Low == I->High) { 11354 // Check Cond == I->Low. 11355 CC = ISD::SETEQ; 11356 LHS = Cond; 11357 RHS=I->Low; 11358 MHS = nullptr; 11359 } else { 11360 // Check I->Low <= Cond <= I->High. 11361 CC = ISD::SETLE; 11362 LHS = I->Low; 11363 MHS = Cond; 11364 RHS = I->High; 11365 } 11366 11367 // If Fallthrough is unreachable, fold away the comparison. 11368 if (FallthroughUnreachable) 11369 CC = ISD::SETTRUE; 11370 11371 // The false probability is the sum of all unhandled cases. 11372 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11373 getCurSDLoc(), I->Prob, UnhandledProbs); 11374 11375 if (CurMBB == SwitchMBB) 11376 visitSwitchCase(CB, SwitchMBB); 11377 else 11378 SL->SwitchCases.push_back(CB); 11379 11380 break; 11381 } 11382 } 11383 CurMBB = Fallthrough; 11384 } 11385 } 11386 11387 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11388 CaseClusterIt First, 11389 CaseClusterIt Last) { 11390 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11391 if (X.Prob != CC.Prob) 11392 return X.Prob > CC.Prob; 11393 11394 // Ties are broken by comparing the case value. 11395 return X.Low->getValue().slt(CC.Low->getValue()); 11396 }); 11397 } 11398 11399 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11400 const SwitchWorkListItem &W, 11401 Value *Cond, 11402 MachineBasicBlock *SwitchMBB) { 11403 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11404 "Clusters not sorted?"); 11405 11406 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11407 11408 // Balance the tree based on branch probabilities to create a near-optimal (in 11409 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11410 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11411 CaseClusterIt LastLeft = W.FirstCluster; 11412 CaseClusterIt FirstRight = W.LastCluster; 11413 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11414 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11415 11416 // Move LastLeft and FirstRight towards each other from opposite directions to 11417 // find a partitioning of the clusters which balances the probability on both 11418 // sides. If LeftProb and RightProb are equal, alternate which side is 11419 // taken to ensure 0-probability nodes are distributed evenly. 11420 unsigned I = 0; 11421 while (LastLeft + 1 < FirstRight) { 11422 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11423 LeftProb += (++LastLeft)->Prob; 11424 else 11425 RightProb += (--FirstRight)->Prob; 11426 I++; 11427 } 11428 11429 while (true) { 11430 // Our binary search tree differs from a typical BST in that ours can have up 11431 // to three values in each leaf. The pivot selection above doesn't take that 11432 // into account, which means the tree might require more nodes and be less 11433 // efficient. We compensate for this here. 11434 11435 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11436 unsigned NumRight = W.LastCluster - FirstRight + 1; 11437 11438 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11439 // If one side has less than 3 clusters, and the other has more than 3, 11440 // consider taking a cluster from the other side. 11441 11442 if (NumLeft < NumRight) { 11443 // Consider moving the first cluster on the right to the left side. 11444 CaseCluster &CC = *FirstRight; 11445 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11446 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11447 if (LeftSideRank <= RightSideRank) { 11448 // Moving the cluster to the left does not demote it. 11449 ++LastLeft; 11450 ++FirstRight; 11451 continue; 11452 } 11453 } else { 11454 assert(NumRight < NumLeft); 11455 // Consider moving the last element on the left to the right side. 11456 CaseCluster &CC = *LastLeft; 11457 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11458 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11459 if (RightSideRank <= LeftSideRank) { 11460 // Moving the cluster to the right does not demot it. 11461 --LastLeft; 11462 --FirstRight; 11463 continue; 11464 } 11465 } 11466 } 11467 break; 11468 } 11469 11470 assert(LastLeft + 1 == FirstRight); 11471 assert(LastLeft >= W.FirstCluster); 11472 assert(FirstRight <= W.LastCluster); 11473 11474 // Use the first element on the right as pivot since we will make less-than 11475 // comparisons against it. 11476 CaseClusterIt PivotCluster = FirstRight; 11477 assert(PivotCluster > W.FirstCluster); 11478 assert(PivotCluster <= W.LastCluster); 11479 11480 CaseClusterIt FirstLeft = W.FirstCluster; 11481 CaseClusterIt LastRight = W.LastCluster; 11482 11483 const ConstantInt *Pivot = PivotCluster->Low; 11484 11485 // New blocks will be inserted immediately after the current one. 11486 MachineFunction::iterator BBI(W.MBB); 11487 ++BBI; 11488 11489 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11490 // we can branch to its destination directly if it's squeezed exactly in 11491 // between the known lower bound and Pivot - 1. 11492 MachineBasicBlock *LeftMBB; 11493 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11494 FirstLeft->Low == W.GE && 11495 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11496 LeftMBB = FirstLeft->MBB; 11497 } else { 11498 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11499 FuncInfo.MF->insert(BBI, LeftMBB); 11500 WorkList.push_back( 11501 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11502 // Put Cond in a virtual register to make it available from the new blocks. 11503 ExportFromCurrentBlock(Cond); 11504 } 11505 11506 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11507 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11508 // directly if RHS.High equals the current upper bound. 11509 MachineBasicBlock *RightMBB; 11510 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11511 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11512 RightMBB = FirstRight->MBB; 11513 } else { 11514 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11515 FuncInfo.MF->insert(BBI, RightMBB); 11516 WorkList.push_back( 11517 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11518 // Put Cond in a virtual register to make it available from the new blocks. 11519 ExportFromCurrentBlock(Cond); 11520 } 11521 11522 // Create the CaseBlock record that will be used to lower the branch. 11523 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11524 getCurSDLoc(), LeftProb, RightProb); 11525 11526 if (W.MBB == SwitchMBB) 11527 visitSwitchCase(CB, SwitchMBB); 11528 else 11529 SL->SwitchCases.push_back(CB); 11530 } 11531 11532 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11533 // from the swith statement. 11534 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11535 BranchProbability PeeledCaseProb) { 11536 if (PeeledCaseProb == BranchProbability::getOne()) 11537 return BranchProbability::getZero(); 11538 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11539 11540 uint32_t Numerator = CaseProb.getNumerator(); 11541 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11542 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11543 } 11544 11545 // Try to peel the top probability case if it exceeds the threshold. 11546 // Return current MachineBasicBlock for the switch statement if the peeling 11547 // does not occur. 11548 // If the peeling is performed, return the newly created MachineBasicBlock 11549 // for the peeled switch statement. Also update Clusters to remove the peeled 11550 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11551 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11552 const SwitchInst &SI, CaseClusterVector &Clusters, 11553 BranchProbability &PeeledCaseProb) { 11554 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11555 // Don't perform if there is only one cluster or optimizing for size. 11556 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11557 TM.getOptLevel() == CodeGenOpt::None || 11558 SwitchMBB->getParent()->getFunction().hasMinSize()) 11559 return SwitchMBB; 11560 11561 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11562 unsigned PeeledCaseIndex = 0; 11563 bool SwitchPeeled = false; 11564 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11565 CaseCluster &CC = Clusters[Index]; 11566 if (CC.Prob < TopCaseProb) 11567 continue; 11568 TopCaseProb = CC.Prob; 11569 PeeledCaseIndex = Index; 11570 SwitchPeeled = true; 11571 } 11572 if (!SwitchPeeled) 11573 return SwitchMBB; 11574 11575 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11576 << TopCaseProb << "\n"); 11577 11578 // Record the MBB for the peeled switch statement. 11579 MachineFunction::iterator BBI(SwitchMBB); 11580 ++BBI; 11581 MachineBasicBlock *PeeledSwitchMBB = 11582 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11583 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11584 11585 ExportFromCurrentBlock(SI.getCondition()); 11586 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11587 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11588 nullptr, nullptr, TopCaseProb.getCompl()}; 11589 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11590 11591 Clusters.erase(PeeledCaseIt); 11592 for (CaseCluster &CC : Clusters) { 11593 LLVM_DEBUG( 11594 dbgs() << "Scale the probablity for one cluster, before scaling: " 11595 << CC.Prob << "\n"); 11596 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11597 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11598 } 11599 PeeledCaseProb = TopCaseProb; 11600 return PeeledSwitchMBB; 11601 } 11602 11603 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11604 // Extract cases from the switch. 11605 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11606 CaseClusterVector Clusters; 11607 Clusters.reserve(SI.getNumCases()); 11608 for (auto I : SI.cases()) { 11609 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11610 const ConstantInt *CaseVal = I.getCaseValue(); 11611 BranchProbability Prob = 11612 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11613 : BranchProbability(1, SI.getNumCases() + 1); 11614 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11615 } 11616 11617 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11618 11619 // Cluster adjacent cases with the same destination. We do this at all 11620 // optimization levels because it's cheap to do and will make codegen faster 11621 // if there are many clusters. 11622 sortAndRangeify(Clusters); 11623 11624 // The branch probablity of the peeled case. 11625 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11626 MachineBasicBlock *PeeledSwitchMBB = 11627 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11628 11629 // If there is only the default destination, jump there directly. 11630 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11631 if (Clusters.empty()) { 11632 assert(PeeledSwitchMBB == SwitchMBB); 11633 SwitchMBB->addSuccessor(DefaultMBB); 11634 if (DefaultMBB != NextBlock(SwitchMBB)) { 11635 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11636 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11637 } 11638 return; 11639 } 11640 11641 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11642 SL->findBitTestClusters(Clusters, &SI); 11643 11644 LLVM_DEBUG({ 11645 dbgs() << "Case clusters: "; 11646 for (const CaseCluster &C : Clusters) { 11647 if (C.Kind == CC_JumpTable) 11648 dbgs() << "JT:"; 11649 if (C.Kind == CC_BitTests) 11650 dbgs() << "BT:"; 11651 11652 C.Low->getValue().print(dbgs(), true); 11653 if (C.Low != C.High) { 11654 dbgs() << '-'; 11655 C.High->getValue().print(dbgs(), true); 11656 } 11657 dbgs() << ' '; 11658 } 11659 dbgs() << '\n'; 11660 }); 11661 11662 assert(!Clusters.empty()); 11663 SwitchWorkList WorkList; 11664 CaseClusterIt First = Clusters.begin(); 11665 CaseClusterIt Last = Clusters.end() - 1; 11666 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11667 // Scale the branchprobability for DefaultMBB if the peel occurs and 11668 // DefaultMBB is not replaced. 11669 if (PeeledCaseProb != BranchProbability::getZero() && 11670 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11671 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11672 WorkList.push_back( 11673 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11674 11675 while (!WorkList.empty()) { 11676 SwitchWorkListItem W = WorkList.pop_back_val(); 11677 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11678 11679 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11680 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11681 // For optimized builds, lower large range as a balanced binary tree. 11682 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11683 continue; 11684 } 11685 11686 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11687 } 11688 } 11689 11690 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11691 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11692 auto DL = getCurSDLoc(); 11693 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11694 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11695 } 11696 11697 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11698 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11699 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11700 11701 SDLoc DL = getCurSDLoc(); 11702 SDValue V = getValue(I.getOperand(0)); 11703 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11704 11705 if (VT.isScalableVector()) { 11706 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11707 return; 11708 } 11709 11710 // Use VECTOR_SHUFFLE for the fixed-length vector 11711 // to maintain existing behavior. 11712 SmallVector<int, 8> Mask; 11713 unsigned NumElts = VT.getVectorMinNumElements(); 11714 for (unsigned i = 0; i != NumElts; ++i) 11715 Mask.push_back(NumElts - 1 - i); 11716 11717 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11718 } 11719 11720 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11721 auto DL = getCurSDLoc(); 11722 SDValue InVec = getValue(I.getOperand(0)); 11723 EVT OutVT = 11724 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11725 11726 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11727 11728 // ISD Node needs the input vectors split into two equal parts 11729 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11730 DAG.getVectorIdxConstant(0, DL)); 11731 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11732 DAG.getVectorIdxConstant(OutNumElts, DL)); 11733 11734 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11735 // legalisation and combines. 11736 if (OutVT.isFixedLengthVector()) { 11737 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11738 createStrideMask(0, 2, OutNumElts)); 11739 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11740 createStrideMask(1, 2, OutNumElts)); 11741 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11742 setValue(&I, Res); 11743 return; 11744 } 11745 11746 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 11747 DAG.getVTList(OutVT, OutVT), Lo, Hi); 11748 setValue(&I, Res); 11749 } 11750 11751 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 11752 auto DL = getCurSDLoc(); 11753 EVT InVT = getValue(I.getOperand(0)).getValueType(); 11754 SDValue InVec0 = getValue(I.getOperand(0)); 11755 SDValue InVec1 = getValue(I.getOperand(1)); 11756 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11757 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11758 11759 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11760 // legalisation and combines. 11761 if (OutVT.isFixedLengthVector()) { 11762 unsigned NumElts = InVT.getVectorMinNumElements(); 11763 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 11764 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 11765 createInterleaveMask(NumElts, 2))); 11766 return; 11767 } 11768 11769 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 11770 DAG.getVTList(InVT, InVT), InVec0, InVec1); 11771 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 11772 Res.getValue(1)); 11773 setValue(&I, Res); 11774 } 11775 11776 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11777 SmallVector<EVT, 4> ValueVTs; 11778 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11779 ValueVTs); 11780 unsigned NumValues = ValueVTs.size(); 11781 if (NumValues == 0) return; 11782 11783 SmallVector<SDValue, 4> Values(NumValues); 11784 SDValue Op = getValue(I.getOperand(0)); 11785 11786 for (unsigned i = 0; i != NumValues; ++i) 11787 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11788 SDValue(Op.getNode(), Op.getResNo() + i)); 11789 11790 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11791 DAG.getVTList(ValueVTs), Values)); 11792 } 11793 11794 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11796 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11797 11798 SDLoc DL = getCurSDLoc(); 11799 SDValue V1 = getValue(I.getOperand(0)); 11800 SDValue V2 = getValue(I.getOperand(1)); 11801 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11802 11803 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11804 if (VT.isScalableVector()) { 11805 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11806 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11807 DAG.getConstant(Imm, DL, IdxVT))); 11808 return; 11809 } 11810 11811 unsigned NumElts = VT.getVectorNumElements(); 11812 11813 uint64_t Idx = (NumElts + Imm) % NumElts; 11814 11815 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11816 SmallVector<int, 8> Mask; 11817 for (unsigned i = 0; i < NumElts; ++i) 11818 Mask.push_back(Idx + i); 11819 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11820 } 11821 11822 // Consider the following MIR after SelectionDAG, which produces output in 11823 // phyregs in the first case or virtregs in the second case. 11824 // 11825 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 11826 // %5:gr32 = COPY $ebx 11827 // %6:gr32 = COPY $edx 11828 // %1:gr32 = COPY %6:gr32 11829 // %0:gr32 = COPY %5:gr32 11830 // 11831 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 11832 // %1:gr32 = COPY %6:gr32 11833 // %0:gr32 = COPY %5:gr32 11834 // 11835 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 11836 // Given %1, we'd like to return $edx in the first case and %6 in the second. 11837 // 11838 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 11839 // to a single virtreg (such as %0). The remaining outputs monotonically 11840 // increase in virtreg number from there. If a callbr has no outputs, then it 11841 // should not have a corresponding callbr landingpad; in fact, the callbr 11842 // landingpad would not even be able to refer to such a callbr. 11843 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 11844 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 11845 // There is definitely at least one copy. 11846 assert(MI->getOpcode() == TargetOpcode::COPY && 11847 "start of copy chain MUST be COPY"); 11848 Reg = MI->getOperand(1).getReg(); 11849 MI = MRI.def_begin(Reg)->getParent(); 11850 // There may be an optional second copy. 11851 if (MI->getOpcode() == TargetOpcode::COPY) { 11852 assert(Reg.isVirtual() && "expected COPY of virtual register"); 11853 Reg = MI->getOperand(1).getReg(); 11854 assert(Reg.isPhysical() && "expected COPY of physical register"); 11855 MI = MRI.def_begin(Reg)->getParent(); 11856 } 11857 // The start of the chain must be an INLINEASM_BR. 11858 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 11859 "end of copy chain MUST be INLINEASM_BR"); 11860 return Reg; 11861 } 11862 11863 // We must do this walk rather than the simpler 11864 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 11865 // otherwise we will end up with copies of virtregs only valid along direct 11866 // edges. 11867 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 11868 SmallVector<EVT, 8> ResultVTs; 11869 SmallVector<SDValue, 8> ResultValues; 11870 const auto *CBR = 11871 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 11872 11873 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11874 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 11875 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11876 11877 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 11878 SDValue Chain = DAG.getRoot(); 11879 11880 // Re-parse the asm constraints string. 11881 TargetLowering::AsmOperandInfoVector TargetConstraints = 11882 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 11883 for (auto &T : TargetConstraints) { 11884 SDISelAsmOperandInfo OpInfo(T); 11885 if (OpInfo.Type != InlineAsm::isOutput) 11886 continue; 11887 11888 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 11889 // individual constraint. 11890 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 11891 11892 switch (OpInfo.ConstraintType) { 11893 case TargetLowering::C_Register: 11894 case TargetLowering::C_RegisterClass: { 11895 // Fill in OpInfo.AssignedRegs.Regs. 11896 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 11897 11898 // getRegistersForValue may produce 1 to many registers based on whether 11899 // the OpInfo.ConstraintVT is legal on the target or not. 11900 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 11901 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 11902 if (Register::isPhysicalRegister(OriginalDef)) 11903 FuncInfo.MBB->addLiveIn(OriginalDef); 11904 // Update the assigned registers to use the original defs. 11905 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 11906 } 11907 11908 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 11909 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 11910 ResultValues.push_back(V); 11911 ResultVTs.push_back(OpInfo.ConstraintVT); 11912 break; 11913 } 11914 case TargetLowering::C_Other: { 11915 SDValue Flag; 11916 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 11917 OpInfo, DAG); 11918 ++InitialDef; 11919 ResultValues.push_back(V); 11920 ResultVTs.push_back(OpInfo.ConstraintVT); 11921 break; 11922 } 11923 default: 11924 break; 11925 } 11926 } 11927 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11928 DAG.getVTList(ResultVTs), ResultValues); 11929 setValue(&I, V); 11930 } 11931