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/TargetTransformInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/Analysis/VectorUtils.h" 32 #include "llvm/CodeGen/Analysis.h" 33 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 34 #include "llvm/CodeGen/CodeGenCommonISel.h" 35 #include "llvm/CodeGen/FunctionLoweringInfo.h" 36 #include "llvm/CodeGen/GCMetadata.h" 37 #include "llvm/CodeGen/ISDOpcodes.h" 38 #include "llvm/CodeGen/MachineBasicBlock.h" 39 #include "llvm/CodeGen/MachineFrameInfo.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineInstrBuilder.h" 42 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 43 #include "llvm/CodeGen/MachineMemOperand.h" 44 #include "llvm/CodeGen/MachineModuleInfo.h" 45 #include "llvm/CodeGen/MachineOperand.h" 46 #include "llvm/CodeGen/MachineRegisterInfo.h" 47 #include "llvm/CodeGen/RuntimeLibcalls.h" 48 #include "llvm/CodeGen/SelectionDAG.h" 49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 50 #include "llvm/CodeGen/StackMaps.h" 51 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 52 #include "llvm/CodeGen/TargetFrameLowering.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetOpcodes.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/TargetSubtargetInfo.h" 57 #include "llvm/CodeGen/WinEHFuncInfo.h" 58 #include "llvm/IR/Argument.h" 59 #include "llvm/IR/Attributes.h" 60 #include "llvm/IR/BasicBlock.h" 61 #include "llvm/IR/CFG.h" 62 #include "llvm/IR/CallingConv.h" 63 #include "llvm/IR/Constant.h" 64 #include "llvm/IR/ConstantRange.h" 65 #include "llvm/IR/Constants.h" 66 #include "llvm/IR/DataLayout.h" 67 #include "llvm/IR/DebugInfo.h" 68 #include "llvm/IR/DebugInfoMetadata.h" 69 #include "llvm/IR/DerivedTypes.h" 70 #include "llvm/IR/DiagnosticInfo.h" 71 #include "llvm/IR/EHPersonalities.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GetElementPtrTypeIterator.h" 74 #include "llvm/IR/InlineAsm.h" 75 #include "llvm/IR/InstrTypes.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/IntrinsicsAArch64.h" 80 #include "llvm/IR/IntrinsicsAMDGPU.h" 81 #include "llvm/IR/IntrinsicsWebAssembly.h" 82 #include "llvm/IR/LLVMContext.h" 83 #include "llvm/IR/Metadata.h" 84 #include "llvm/IR/Module.h" 85 #include "llvm/IR/Operator.h" 86 #include "llvm/IR/PatternMatch.h" 87 #include "llvm/IR/Statepoint.h" 88 #include "llvm/IR/Type.h" 89 #include "llvm/IR/User.h" 90 #include "llvm/IR/Value.h" 91 #include "llvm/MC/MCContext.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/InstructionCost.h" 98 #include "llvm/Support/MathExtras.h" 99 #include "llvm/Support/raw_ostream.h" 100 #include "llvm/Target/TargetIntrinsicInfo.h" 101 #include "llvm/Target/TargetMachine.h" 102 #include "llvm/Target/TargetOptions.h" 103 #include "llvm/TargetParser/Triple.h" 104 #include "llvm/Transforms/Utils/Local.h" 105 #include <cstddef> 106 #include <iterator> 107 #include <limits> 108 #include <optional> 109 #include <tuple> 110 111 using namespace llvm; 112 using namespace PatternMatch; 113 using namespace SwitchCG; 114 115 #define DEBUG_TYPE "isel" 116 117 /// LimitFloatPrecision - Generate low-precision inline sequences for 118 /// some float libcalls (6, 8 or 12 bits). 119 static unsigned LimitFloatPrecision; 120 121 static cl::opt<bool> 122 InsertAssertAlign("insert-assert-align", cl::init(true), 123 cl::desc("Insert the experimental `assertalign` node."), 124 cl::ReallyHidden); 125 126 static cl::opt<unsigned, true> 127 LimitFPPrecision("limit-float-precision", 128 cl::desc("Generate low-precision inline sequences " 129 "for some float libcalls"), 130 cl::location(LimitFloatPrecision), cl::Hidden, 131 cl::init(0)); 132 133 static cl::opt<unsigned> SwitchPeelThreshold( 134 "switch-peel-threshold", cl::Hidden, cl::init(66), 135 cl::desc("Set the case probability threshold for peeling the case from a " 136 "switch statement. A value greater than 100 will void this " 137 "optimization")); 138 139 // Limit the width of DAG chains. This is important in general to prevent 140 // DAG-based analysis from blowing up. For example, alias analysis and 141 // load clustering may not complete in reasonable time. It is difficult to 142 // recognize and avoid this situation within each individual analysis, and 143 // future analyses are likely to have the same behavior. Limiting DAG width is 144 // the safe approach and will be especially important with global DAGs. 145 // 146 // MaxParallelChains default is arbitrarily high to avoid affecting 147 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 148 // sequence over this should have been converted to llvm.memcpy by the 149 // frontend. It is easy to induce this behavior with .ll code such as: 150 // %buffer = alloca [4096 x i8] 151 // %data = load [4096 x i8]* %argPtr 152 // store [4096 x i8] %data, [4096 x i8]* %buffer 153 static const unsigned MaxParallelChains = 64; 154 155 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 156 const SDValue *Parts, unsigned NumParts, 157 MVT PartVT, EVT ValueVT, const Value *V, 158 SDValue InChain, 159 std::optional<CallingConv::ID> CC); 160 161 /// getCopyFromParts - Create a value that contains the specified legal parts 162 /// combined into the value they represent. If the parts combine to a type 163 /// larger than ValueVT then AssertOp can be used to specify whether the extra 164 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 165 /// (ISD::AssertSext). 166 static SDValue 167 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 168 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 169 SDValue InChain, 170 std::optional<CallingConv::ID> CC = std::nullopt, 171 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 172 // Let the target assemble the parts if it wants to 173 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 174 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 175 PartVT, ValueVT, CC)) 176 return Val; 177 178 if (ValueVT.isVector()) 179 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 180 InChain, CC); 181 182 assert(NumParts > 0 && "No parts to assemble!"); 183 SDValue Val = Parts[0]; 184 185 if (NumParts > 1) { 186 // Assemble the value from multiple parts. 187 if (ValueVT.isInteger()) { 188 unsigned PartBits = PartVT.getSizeInBits(); 189 unsigned ValueBits = ValueVT.getSizeInBits(); 190 191 // Assemble the power of 2 part. 192 unsigned RoundParts = llvm::bit_floor(NumParts); 193 unsigned RoundBits = PartBits * RoundParts; 194 EVT RoundVT = RoundBits == ValueBits ? 195 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 196 SDValue Lo, Hi; 197 198 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 199 200 if (RoundParts > 2) { 201 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V, 202 InChain); 203 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2, 204 PartVT, HalfVT, V, InChain); 205 } else { 206 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 207 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 208 } 209 210 if (DAG.getDataLayout().isBigEndian()) 211 std::swap(Lo, Hi); 212 213 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 214 215 if (RoundParts < NumParts) { 216 // Assemble the trailing non-power-of-2 part. 217 unsigned OddParts = NumParts - RoundParts; 218 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 219 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 220 OddVT, V, InChain, CC); 221 222 // Combine the round and odd parts. 223 Lo = Val; 224 if (DAG.getDataLayout().isBigEndian()) 225 std::swap(Lo, Hi); 226 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 227 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 228 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 229 DAG.getConstant(Lo.getValueSizeInBits(), DL, 230 TLI.getShiftAmountTy( 231 TotalVT, DAG.getDataLayout()))); 232 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 233 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 234 } 235 } else if (PartVT.isFloatingPoint()) { 236 // FP split into multiple FP parts (for ppcf128) 237 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 238 "Unexpected split"); 239 SDValue Lo, Hi; 240 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 241 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 242 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 243 std::swap(Lo, Hi); 244 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 245 } else { 246 // FP split into integer parts (soft fp) 247 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 248 !PartVT.isVector() && "Unexpected split"); 249 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 250 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, 251 InChain, CC); 252 } 253 } 254 255 // There is now one part, held in Val. Correct it to match ValueVT. 256 // PartEVT is the type of the register class that holds the value. 257 // ValueVT is the type of the inline asm operation. 258 EVT PartEVT = Val.getValueType(); 259 260 if (PartEVT == ValueVT) 261 return Val; 262 263 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 264 ValueVT.bitsLT(PartEVT)) { 265 // For an FP value in an integer part, we need to truncate to the right 266 // width first. 267 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 268 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 269 } 270 271 // Handle types that have the same size. 272 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 273 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 274 275 // Handle types with different sizes. 276 if (PartEVT.isInteger() && ValueVT.isInteger()) { 277 if (ValueVT.bitsLT(PartEVT)) { 278 // For a truncate, see if we have any information to 279 // indicate whether the truncated bits will always be 280 // zero or sign-extension. 281 if (AssertOp) 282 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 283 DAG.getValueType(ValueVT)); 284 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 285 } 286 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 287 } 288 289 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 290 // FP_ROUND's are always exact here. 291 if (ValueVT.bitsLT(Val.getValueType())) { 292 293 SDValue NoChange = 294 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 295 296 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr( 297 llvm::Attribute::StrictFP)) { 298 return DAG.getNode(ISD::STRICT_FP_ROUND, DL, 299 DAG.getVTList(ValueVT, MVT::Other), InChain, Val, 300 NoChange); 301 } 302 303 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange); 304 } 305 306 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 307 } 308 309 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 310 // then truncating. 311 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 312 ValueVT.bitsLT(PartEVT)) { 313 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 314 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 315 } 316 317 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 318 } 319 320 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 321 const Twine &ErrMsg) { 322 const Instruction *I = dyn_cast_or_null<Instruction>(V); 323 if (!V) 324 return Ctx.emitError(ErrMsg); 325 326 const char *AsmError = ", possible invalid constraint for vector type"; 327 if (const CallInst *CI = dyn_cast<CallInst>(I)) 328 if (CI->isInlineAsm()) 329 return Ctx.emitError(I, ErrMsg + AsmError); 330 331 return Ctx.emitError(I, ErrMsg); 332 } 333 334 /// getCopyFromPartsVector - Create a value that contains the specified legal 335 /// parts combined into the value they represent. If the parts combine to a 336 /// type larger than ValueVT then AssertOp can be used to specify whether the 337 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 338 /// ValueVT (ISD::AssertSext). 339 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 340 const SDValue *Parts, unsigned NumParts, 341 MVT PartVT, EVT ValueVT, const Value *V, 342 SDValue InChain, 343 std::optional<CallingConv::ID> CallConv) { 344 assert(ValueVT.isVector() && "Not a vector value"); 345 assert(NumParts > 0 && "No parts to assemble!"); 346 const bool IsABIRegCopy = CallConv.has_value(); 347 348 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 349 SDValue Val = Parts[0]; 350 351 // Handle a multi-element vector. 352 if (NumParts > 1) { 353 EVT IntermediateVT; 354 MVT RegisterVT; 355 unsigned NumIntermediates; 356 unsigned NumRegs; 357 358 if (IsABIRegCopy) { 359 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 360 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 361 NumIntermediates, RegisterVT); 362 } else { 363 NumRegs = 364 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 365 NumIntermediates, RegisterVT); 366 } 367 368 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 369 NumParts = NumRegs; // Silence a compiler warning. 370 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 371 assert(RegisterVT.getSizeInBits() == 372 Parts[0].getSimpleValueType().getSizeInBits() && 373 "Part type sizes don't match!"); 374 375 // Assemble the parts into intermediate operands. 376 SmallVector<SDValue, 8> Ops(NumIntermediates); 377 if (NumIntermediates == NumParts) { 378 // If the register was not expanded, truncate or copy the value, 379 // as appropriate. 380 for (unsigned i = 0; i != NumParts; ++i) 381 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT, 382 V, InChain, CallConv); 383 } else if (NumParts > 0) { 384 // If the intermediate type was expanded, build the intermediate 385 // operands from the parts. 386 assert(NumParts % NumIntermediates == 0 && 387 "Must expand into a divisible number of parts!"); 388 unsigned Factor = NumParts / NumIntermediates; 389 for (unsigned i = 0; i != NumIntermediates; ++i) 390 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT, 391 IntermediateVT, V, InChain, CallConv); 392 } 393 394 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 395 // intermediate operands. 396 EVT BuiltVectorTy = 397 IntermediateVT.isVector() 398 ? EVT::getVectorVT( 399 *DAG.getContext(), IntermediateVT.getScalarType(), 400 IntermediateVT.getVectorElementCount() * NumParts) 401 : EVT::getVectorVT(*DAG.getContext(), 402 IntermediateVT.getScalarType(), 403 NumIntermediates); 404 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 405 : ISD::BUILD_VECTOR, 406 DL, BuiltVectorTy, Ops); 407 } 408 409 // There is now one part, held in Val. Correct it to match ValueVT. 410 EVT PartEVT = Val.getValueType(); 411 412 if (PartEVT == ValueVT) 413 return Val; 414 415 if (PartEVT.isVector()) { 416 // Vector/Vector bitcast. 417 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 418 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 419 420 // If the parts vector has more elements than the value vector, then we 421 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 422 // Extract the elements we want. 423 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 424 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 425 ValueVT.getVectorElementCount().getKnownMinValue()) && 426 (PartEVT.getVectorElementCount().isScalable() == 427 ValueVT.getVectorElementCount().isScalable()) && 428 "Cannot narrow, it would be a lossy transformation"); 429 PartEVT = 430 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 431 ValueVT.getVectorElementCount()); 432 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 433 DAG.getVectorIdxConstant(0, DL)); 434 if (PartEVT == ValueVT) 435 return Val; 436 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 437 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 438 439 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 440 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 441 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 442 } 443 444 // Promoted vector extract 445 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 446 } 447 448 // Trivial bitcast if the types are the same size and the destination 449 // vector type is legal. 450 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 451 TLI.isTypeLegal(ValueVT)) 452 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 453 454 if (ValueVT.getVectorNumElements() != 1) { 455 // Certain ABIs require that vectors are passed as integers. For vectors 456 // are the same size, this is an obvious bitcast. 457 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 458 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 459 } else if (ValueVT.bitsLT(PartEVT)) { 460 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 461 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 462 // Drop the extra bits. 463 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 464 return DAG.getBitcast(ValueVT, Val); 465 } 466 467 diagnosePossiblyInvalidConstraint( 468 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 469 return DAG.getUNDEF(ValueVT); 470 } 471 472 // Handle cases such as i8 -> <1 x i1> 473 EVT ValueSVT = ValueVT.getVectorElementType(); 474 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 475 unsigned ValueSize = ValueSVT.getSizeInBits(); 476 if (ValueSize == PartEVT.getSizeInBits()) { 477 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 478 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 479 // It's possible a scalar floating point type gets softened to integer and 480 // then promoted to a larger integer. If PartEVT is the larger integer 481 // we need to truncate it and then bitcast to the FP type. 482 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 483 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 484 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 485 Val = DAG.getBitcast(ValueSVT, Val); 486 } else { 487 Val = ValueVT.isFloatingPoint() 488 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 489 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 490 } 491 } 492 493 return DAG.getBuildVector(ValueVT, DL, Val); 494 } 495 496 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 497 SDValue Val, SDValue *Parts, unsigned NumParts, 498 MVT PartVT, const Value *V, 499 std::optional<CallingConv::ID> CallConv); 500 501 /// getCopyToParts - Create a series of nodes that contain the specified value 502 /// split into legal parts. If the parts contain more bits than Val, then, for 503 /// integers, ExtendKind can be used to specify how to generate the extra bits. 504 static void 505 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 506 unsigned NumParts, MVT PartVT, const Value *V, 507 std::optional<CallingConv::ID> CallConv = std::nullopt, 508 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 509 // Let the target split the parts if it wants to 510 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 511 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 512 CallConv)) 513 return; 514 EVT ValueVT = Val.getValueType(); 515 516 // Handle the vector case separately. 517 if (ValueVT.isVector()) 518 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 519 CallConv); 520 521 unsigned OrigNumParts = NumParts; 522 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 523 "Copying to an illegal type!"); 524 525 if (NumParts == 0) 526 return; 527 528 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 529 EVT PartEVT = PartVT; 530 if (PartEVT == ValueVT) { 531 assert(NumParts == 1 && "No-op copy with multiple parts!"); 532 Parts[0] = Val; 533 return; 534 } 535 536 unsigned PartBits = PartVT.getSizeInBits(); 537 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 538 // If the parts cover more bits than the value has, promote the value. 539 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 540 assert(NumParts == 1 && "Do not know what to promote to!"); 541 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 542 } else { 543 if (ValueVT.isFloatingPoint()) { 544 // FP values need to be bitcast, then extended if they are being put 545 // into a larger container. 546 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 547 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 548 } 549 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 550 ValueVT.isInteger() && 551 "Unknown mismatch!"); 552 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 553 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 554 if (PartVT == MVT::x86mmx) 555 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 556 } 557 } else if (PartBits == ValueVT.getSizeInBits()) { 558 // Different types of the same size. 559 assert(NumParts == 1 && PartEVT != ValueVT); 560 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 561 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 562 // If the parts cover less bits than value has, truncate the value. 563 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 564 ValueVT.isInteger() && 565 "Unknown mismatch!"); 566 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 567 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 568 if (PartVT == MVT::x86mmx) 569 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 570 } 571 572 // The value may have changed - recompute ValueVT. 573 ValueVT = Val.getValueType(); 574 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 575 "Failed to tile the value with PartVT!"); 576 577 if (NumParts == 1) { 578 if (PartEVT != ValueVT) { 579 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 580 "scalar-to-vector conversion failed"); 581 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 582 } 583 584 Parts[0] = Val; 585 return; 586 } 587 588 // Expand the value into multiple parts. 589 if (NumParts & (NumParts - 1)) { 590 // The number of parts is not a power of 2. Split off and copy the tail. 591 assert(PartVT.isInteger() && ValueVT.isInteger() && 592 "Do not know what to expand to!"); 593 unsigned RoundParts = llvm::bit_floor(NumParts); 594 unsigned RoundBits = RoundParts * PartBits; 595 unsigned OddParts = NumParts - RoundParts; 596 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 597 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 598 599 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 600 CallConv); 601 602 if (DAG.getDataLayout().isBigEndian()) 603 // The odd parts were reversed by getCopyToParts - unreverse them. 604 std::reverse(Parts + RoundParts, Parts + NumParts); 605 606 NumParts = RoundParts; 607 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 608 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 609 } 610 611 // The number of parts is a power of 2. Repeatedly bisect the value using 612 // EXTRACT_ELEMENT. 613 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 614 EVT::getIntegerVT(*DAG.getContext(), 615 ValueVT.getSizeInBits()), 616 Val); 617 618 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 619 for (unsigned i = 0; i < NumParts; i += StepSize) { 620 unsigned ThisBits = StepSize * PartBits / 2; 621 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 622 SDValue &Part0 = Parts[i]; 623 SDValue &Part1 = Parts[i+StepSize/2]; 624 625 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 626 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 627 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 628 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 629 630 if (ThisBits == PartBits && ThisVT != PartVT) { 631 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 632 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 633 } 634 } 635 } 636 637 if (DAG.getDataLayout().isBigEndian()) 638 std::reverse(Parts, Parts + OrigNumParts); 639 } 640 641 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 642 const SDLoc &DL, EVT PartVT) { 643 if (!PartVT.isVector()) 644 return SDValue(); 645 646 EVT ValueVT = Val.getValueType(); 647 EVT PartEVT = PartVT.getVectorElementType(); 648 EVT ValueEVT = ValueVT.getVectorElementType(); 649 ElementCount PartNumElts = PartVT.getVectorElementCount(); 650 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 651 652 // We only support widening vectors with equivalent element types and 653 // fixed/scalable properties. If a target needs to widen a fixed-length type 654 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 655 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 656 PartNumElts.isScalable() != ValueNumElts.isScalable()) 657 return SDValue(); 658 659 // Have a try for bf16 because some targets share its ABI with fp16. 660 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 661 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 662 "Cannot widen to illegal type"); 663 Val = DAG.getNode(ISD::BITCAST, DL, 664 ValueVT.changeVectorElementType(MVT::f16), Val); 665 } else if (PartEVT != ValueEVT) { 666 return SDValue(); 667 } 668 669 // Widening a scalable vector to another scalable vector is done by inserting 670 // the vector into a larger undef one. 671 if (PartNumElts.isScalable()) 672 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 673 Val, DAG.getVectorIdxConstant(0, DL)); 674 675 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 676 // undef elements. 677 SmallVector<SDValue, 16> Ops; 678 DAG.ExtractVectorElements(Val, Ops); 679 SDValue EltUndef = DAG.getUNDEF(PartEVT); 680 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 681 682 // FIXME: Use CONCAT for 2x -> 4x. 683 return DAG.getBuildVector(PartVT, DL, Ops); 684 } 685 686 /// getCopyToPartsVector - Create a series of nodes that contain the specified 687 /// value split into legal parts. 688 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 689 SDValue Val, SDValue *Parts, unsigned NumParts, 690 MVT PartVT, const Value *V, 691 std::optional<CallingConv::ID> CallConv) { 692 EVT ValueVT = Val.getValueType(); 693 assert(ValueVT.isVector() && "Not a vector"); 694 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 695 const bool IsABIRegCopy = CallConv.has_value(); 696 697 if (NumParts == 1) { 698 EVT PartEVT = PartVT; 699 if (PartEVT == ValueVT) { 700 // Nothing to do. 701 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 702 // Bitconvert vector->vector case. 703 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 704 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 705 Val = Widened; 706 } else if (PartVT.isVector() && 707 PartEVT.getVectorElementType().bitsGE( 708 ValueVT.getVectorElementType()) && 709 PartEVT.getVectorElementCount() == 710 ValueVT.getVectorElementCount()) { 711 712 // Promoted vector extract 713 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 714 } else if (PartEVT.isVector() && 715 PartEVT.getVectorElementType() != 716 ValueVT.getVectorElementType() && 717 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 718 TargetLowering::TypeWidenVector) { 719 // Combination of widening and promotion. 720 EVT WidenVT = 721 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 722 PartVT.getVectorElementCount()); 723 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 724 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 725 } else { 726 // Don't extract an integer from a float vector. This can happen if the 727 // FP type gets softened to integer and then promoted. The promotion 728 // prevents it from being picked up by the earlier bitcast case. 729 if (ValueVT.getVectorElementCount().isScalar() && 730 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 731 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 732 DAG.getVectorIdxConstant(0, DL)); 733 } else { 734 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 735 assert(PartVT.getFixedSizeInBits() > ValueSize && 736 "lossy conversion of vector to scalar type"); 737 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 738 Val = DAG.getBitcast(IntermediateType, Val); 739 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 740 } 741 } 742 743 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 744 Parts[0] = Val; 745 return; 746 } 747 748 // Handle a multi-element vector. 749 EVT IntermediateVT; 750 MVT RegisterVT; 751 unsigned NumIntermediates; 752 unsigned NumRegs; 753 if (IsABIRegCopy) { 754 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 755 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 756 RegisterVT); 757 } else { 758 NumRegs = 759 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 760 NumIntermediates, RegisterVT); 761 } 762 763 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 764 NumParts = NumRegs; // Silence a compiler warning. 765 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 766 767 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 768 "Mixing scalable and fixed vectors when copying in parts"); 769 770 std::optional<ElementCount> DestEltCnt; 771 772 if (IntermediateVT.isVector()) 773 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 774 else 775 DestEltCnt = ElementCount::getFixed(NumIntermediates); 776 777 EVT BuiltVectorTy = EVT::getVectorVT( 778 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 779 780 if (ValueVT == BuiltVectorTy) { 781 // Nothing to do. 782 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 783 // Bitconvert vector->vector case. 784 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 785 } else { 786 if (BuiltVectorTy.getVectorElementType().bitsGT( 787 ValueVT.getVectorElementType())) { 788 // Integer promotion. 789 ValueVT = EVT::getVectorVT(*DAG.getContext(), 790 BuiltVectorTy.getVectorElementType(), 791 ValueVT.getVectorElementCount()); 792 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 793 } 794 795 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 796 Val = Widened; 797 } 798 } 799 800 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 801 802 // Split the vector into intermediate operands. 803 SmallVector<SDValue, 8> Ops(NumIntermediates); 804 for (unsigned i = 0; i != NumIntermediates; ++i) { 805 if (IntermediateVT.isVector()) { 806 // This does something sensible for scalable vectors - see the 807 // definition of EXTRACT_SUBVECTOR for further details. 808 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 809 Ops[i] = 810 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 811 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 812 } else { 813 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 814 DAG.getVectorIdxConstant(i, DL)); 815 } 816 } 817 818 // Split the intermediate operands into legal parts. 819 if (NumParts == NumIntermediates) { 820 // If the register was not expanded, promote or copy the value, 821 // as appropriate. 822 for (unsigned i = 0; i != NumParts; ++i) 823 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 824 } else if (NumParts > 0) { 825 // If the intermediate type was expanded, split each the value into 826 // legal parts. 827 assert(NumIntermediates != 0 && "division by zero"); 828 assert(NumParts % NumIntermediates == 0 && 829 "Must expand into a divisible number of parts!"); 830 unsigned Factor = NumParts / NumIntermediates; 831 for (unsigned i = 0; i != NumIntermediates; ++i) 832 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 833 CallConv); 834 } 835 } 836 837 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 838 EVT valuevt, std::optional<CallingConv::ID> CC) 839 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 840 RegCount(1, regs.size()), CallConv(CC) {} 841 842 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 843 const DataLayout &DL, unsigned Reg, Type *Ty, 844 std::optional<CallingConv::ID> CC) { 845 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 846 847 CallConv = CC; 848 849 for (EVT ValueVT : ValueVTs) { 850 unsigned NumRegs = 851 isABIMangled() 852 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 853 : TLI.getNumRegisters(Context, ValueVT); 854 MVT RegisterVT = 855 isABIMangled() 856 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 857 : TLI.getRegisterType(Context, ValueVT); 858 for (unsigned i = 0; i != NumRegs; ++i) 859 Regs.push_back(Reg + i); 860 RegVTs.push_back(RegisterVT); 861 RegCount.push_back(NumRegs); 862 Reg += NumRegs; 863 } 864 } 865 866 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 867 FunctionLoweringInfo &FuncInfo, 868 const SDLoc &dl, SDValue &Chain, 869 SDValue *Glue, const Value *V) const { 870 // A Value with type {} or [0 x %t] needs no registers. 871 if (ValueVTs.empty()) 872 return SDValue(); 873 874 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 875 876 // Assemble the legal parts into the final values. 877 SmallVector<SDValue, 4> Values(ValueVTs.size()); 878 SmallVector<SDValue, 8> Parts; 879 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 880 // Copy the legal parts from the registers. 881 EVT ValueVT = ValueVTs[Value]; 882 unsigned NumRegs = RegCount[Value]; 883 MVT RegisterVT = isABIMangled() 884 ? TLI.getRegisterTypeForCallingConv( 885 *DAG.getContext(), *CallConv, RegVTs[Value]) 886 : RegVTs[Value]; 887 888 Parts.resize(NumRegs); 889 for (unsigned i = 0; i != NumRegs; ++i) { 890 SDValue P; 891 if (!Glue) { 892 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 893 } else { 894 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 895 *Glue = P.getValue(2); 896 } 897 898 Chain = P.getValue(1); 899 Parts[i] = P; 900 901 // If the source register was virtual and if we know something about it, 902 // add an assert node. 903 if (!Register::isVirtualRegister(Regs[Part + i]) || 904 !RegisterVT.isInteger()) 905 continue; 906 907 const FunctionLoweringInfo::LiveOutInfo *LOI = 908 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 909 if (!LOI) 910 continue; 911 912 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 913 unsigned NumSignBits = LOI->NumSignBits; 914 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 915 916 if (NumZeroBits == RegSize) { 917 // The current value is a zero. 918 // Explicitly express that as it would be easier for 919 // optimizations to kick in. 920 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 921 continue; 922 } 923 924 // FIXME: We capture more information than the dag can represent. For 925 // now, just use the tightest assertzext/assertsext possible. 926 bool isSExt; 927 EVT FromVT(MVT::Other); 928 if (NumZeroBits) { 929 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 930 isSExt = false; 931 } else if (NumSignBits > 1) { 932 FromVT = 933 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 934 isSExt = true; 935 } else { 936 continue; 937 } 938 // Add an assertion node. 939 assert(FromVT != MVT::Other); 940 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 941 RegisterVT, P, DAG.getValueType(FromVT)); 942 } 943 944 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 945 RegisterVT, ValueVT, V, Chain, CallConv); 946 Part += NumRegs; 947 Parts.clear(); 948 } 949 950 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 951 } 952 953 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 954 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 955 const Value *V, 956 ISD::NodeType PreferredExtendType) const { 957 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 958 ISD::NodeType ExtendKind = PreferredExtendType; 959 960 // Get the list of the values's legal parts. 961 unsigned NumRegs = Regs.size(); 962 SmallVector<SDValue, 8> Parts(NumRegs); 963 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 964 unsigned NumParts = RegCount[Value]; 965 966 MVT RegisterVT = isABIMangled() 967 ? TLI.getRegisterTypeForCallingConv( 968 *DAG.getContext(), *CallConv, RegVTs[Value]) 969 : RegVTs[Value]; 970 971 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 972 ExtendKind = ISD::ZERO_EXTEND; 973 974 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 975 NumParts, RegisterVT, V, CallConv, ExtendKind); 976 Part += NumParts; 977 } 978 979 // Copy the parts into the registers. 980 SmallVector<SDValue, 8> Chains(NumRegs); 981 for (unsigned i = 0; i != NumRegs; ++i) { 982 SDValue Part; 983 if (!Glue) { 984 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 985 } else { 986 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 987 *Glue = Part.getValue(1); 988 } 989 990 Chains[i] = Part.getValue(0); 991 } 992 993 if (NumRegs == 1 || Glue) 994 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 995 // flagged to it. That is the CopyToReg nodes and the user are considered 996 // a single scheduling unit. If we create a TokenFactor and return it as 997 // chain, then the TokenFactor is both a predecessor (operand) of the 998 // user as well as a successor (the TF operands are flagged to the user). 999 // c1, f1 = CopyToReg 1000 // c2, f2 = CopyToReg 1001 // c3 = TokenFactor c1, c2 1002 // ... 1003 // = op c3, ..., f2 1004 Chain = Chains[NumRegs-1]; 1005 else 1006 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 1007 } 1008 1009 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, 1010 unsigned MatchingIdx, const SDLoc &dl, 1011 SelectionDAG &DAG, 1012 std::vector<SDValue> &Ops) const { 1013 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1014 1015 InlineAsm::Flag Flag(Code, Regs.size()); 1016 if (HasMatching) 1017 Flag.setMatchingOp(MatchingIdx); 1018 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1019 // Put the register class of the virtual registers in the flag word. That 1020 // way, later passes can recompute register class constraints for inline 1021 // assembly as well as normal instructions. 1022 // Don't do this for tied operands that can use the regclass information 1023 // from the def. 1024 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1025 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1026 Flag.setRegClass(RC->getID()); 1027 } 1028 1029 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1030 Ops.push_back(Res); 1031 1032 if (Code == InlineAsm::Kind::Clobber) { 1033 // Clobbers should always have a 1:1 mapping with registers, and may 1034 // reference registers that have illegal (e.g. vector) types. Hence, we 1035 // shouldn't try to apply any sort of splitting logic to them. 1036 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1037 "No 1:1 mapping from clobbers to regs?"); 1038 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1039 (void)SP; 1040 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1041 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1042 assert( 1043 (Regs[I] != SP || 1044 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1045 "If we clobbered the stack pointer, MFI should know about it."); 1046 } 1047 return; 1048 } 1049 1050 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1051 MVT RegisterVT = RegVTs[Value]; 1052 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1053 RegisterVT); 1054 for (unsigned i = 0; i != NumRegs; ++i) { 1055 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1056 unsigned TheReg = Regs[Reg++]; 1057 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1058 } 1059 } 1060 } 1061 1062 SmallVector<std::pair<unsigned, TypeSize>, 4> 1063 RegsForValue::getRegsAndSizes() const { 1064 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1065 unsigned I = 0; 1066 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1067 unsigned RegCount = std::get<0>(CountAndVT); 1068 MVT RegisterVT = std::get<1>(CountAndVT); 1069 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1070 for (unsigned E = I + RegCount; I != E; ++I) 1071 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1072 } 1073 return OutVec; 1074 } 1075 1076 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1077 AssumptionCache *ac, 1078 const TargetLibraryInfo *li) { 1079 AA = aa; 1080 AC = ac; 1081 GFI = gfi; 1082 LibInfo = li; 1083 Context = DAG.getContext(); 1084 LPadToCallSiteMap.clear(); 1085 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1086 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1087 *DAG.getMachineFunction().getFunction().getParent()); 1088 } 1089 1090 void SelectionDAGBuilder::clear() { 1091 NodeMap.clear(); 1092 UnusedArgNodeMap.clear(); 1093 PendingLoads.clear(); 1094 PendingExports.clear(); 1095 PendingConstrainedFP.clear(); 1096 PendingConstrainedFPStrict.clear(); 1097 CurInst = nullptr; 1098 HasTailCall = false; 1099 SDNodeOrder = LowestSDNodeOrder; 1100 StatepointLowering.clear(); 1101 } 1102 1103 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1104 DanglingDebugInfoMap.clear(); 1105 } 1106 1107 // Update DAG root to include dependencies on Pending chains. 1108 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1109 SDValue Root = DAG.getRoot(); 1110 1111 if (Pending.empty()) 1112 return Root; 1113 1114 // Add current root to PendingChains, unless we already indirectly 1115 // depend on it. 1116 if (Root.getOpcode() != ISD::EntryToken) { 1117 unsigned i = 0, e = Pending.size(); 1118 for (; i != e; ++i) { 1119 assert(Pending[i].getNode()->getNumOperands() > 1); 1120 if (Pending[i].getNode()->getOperand(0) == Root) 1121 break; // Don't add the root if we already indirectly depend on it. 1122 } 1123 1124 if (i == e) 1125 Pending.push_back(Root); 1126 } 1127 1128 if (Pending.size() == 1) 1129 Root = Pending[0]; 1130 else 1131 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1132 1133 DAG.setRoot(Root); 1134 Pending.clear(); 1135 return Root; 1136 } 1137 1138 SDValue SelectionDAGBuilder::getMemoryRoot() { 1139 return updateRoot(PendingLoads); 1140 } 1141 1142 SDValue SelectionDAGBuilder::getRoot() { 1143 // Chain up all pending constrained intrinsics together with all 1144 // pending loads, by simply appending them to PendingLoads and 1145 // then calling getMemoryRoot(). 1146 PendingLoads.reserve(PendingLoads.size() + 1147 PendingConstrainedFP.size() + 1148 PendingConstrainedFPStrict.size()); 1149 PendingLoads.append(PendingConstrainedFP.begin(), 1150 PendingConstrainedFP.end()); 1151 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1152 PendingConstrainedFPStrict.end()); 1153 PendingConstrainedFP.clear(); 1154 PendingConstrainedFPStrict.clear(); 1155 return getMemoryRoot(); 1156 } 1157 1158 SDValue SelectionDAGBuilder::getControlRoot() { 1159 // We need to emit pending fpexcept.strict constrained intrinsics, 1160 // so append them to the PendingExports list. 1161 PendingExports.append(PendingConstrainedFPStrict.begin(), 1162 PendingConstrainedFPStrict.end()); 1163 PendingConstrainedFPStrict.clear(); 1164 return updateRoot(PendingExports); 1165 } 1166 1167 void SelectionDAGBuilder::handleDebugDeclare(Value *Address, 1168 DILocalVariable *Variable, 1169 DIExpression *Expression, 1170 DebugLoc DL) { 1171 assert(Variable && "Missing variable"); 1172 1173 // Check if address has undef value. 1174 if (!Address || isa<UndefValue>(Address) || 1175 (Address->use_empty() && !isa<Argument>(Address))) { 1176 LLVM_DEBUG( 1177 dbgs() 1178 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n"); 1179 return; 1180 } 1181 1182 bool IsParameter = Variable->isParameter() || isa<Argument>(Address); 1183 1184 SDValue &N = NodeMap[Address]; 1185 if (!N.getNode() && isa<Argument>(Address)) 1186 // Check unused arguments map. 1187 N = UnusedArgNodeMap[Address]; 1188 SDDbgValue *SDV; 1189 if (N.getNode()) { 1190 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 1191 Address = BCI->getOperand(0); 1192 // Parameters are handled specially. 1193 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 1194 if (IsParameter && FINode) { 1195 // Byval parameter. We have a frame index at this point. 1196 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 1197 /*IsIndirect*/ true, DL, SDNodeOrder); 1198 } else if (isa<Argument>(Address)) { 1199 // Address is an argument, so try to emit its dbg value using 1200 // virtual register info from the FuncInfo.ValueMap. 1201 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1202 FuncArgumentDbgValueKind::Declare, N); 1203 return; 1204 } else { 1205 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 1206 true, DL, SDNodeOrder); 1207 } 1208 DAG.AddDbgValue(SDV, IsParameter); 1209 } else { 1210 // If Address is an argument then try to emit its dbg value using 1211 // virtual register info from the FuncInfo.ValueMap. 1212 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1213 FuncArgumentDbgValueKind::Declare, N)) { 1214 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info" 1215 << " (could not emit func-arg dbg_value)\n"); 1216 } 1217 } 1218 return; 1219 } 1220 1221 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) { 1222 // Add SDDbgValue nodes for any var locs here. Do so before updating 1223 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1224 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1225 // Add SDDbgValue nodes for any var locs here. Do so before updating 1226 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1227 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1228 It != End; ++It) { 1229 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1230 dropDanglingDebugInfo(Var, It->Expr); 1231 if (It->Values.isKillLocation(It->Expr)) { 1232 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1233 continue; 1234 } 1235 SmallVector<Value *> Values(It->Values.location_ops()); 1236 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1237 It->Values.hasArgList())) { 1238 SmallVector<Value *, 4> Vals; 1239 for (Value *V : It->Values.location_ops()) 1240 Vals.push_back(V); 1241 addDanglingDebugInfo(Vals, 1242 FnVarLocs->getDILocalVariable(It->VariableID), 1243 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder); 1244 } 1245 } 1246 } 1247 1248 // We must skip DPValues if they've already been processed above as we 1249 // have just emitted the debug values resulting from assignment tracking 1250 // analysis, making any existing DPValues redundant (and probably less 1251 // correct). We still need to process DPLabels. This does sink DPLabels 1252 // to the bottom of the group of debug records. That sholdn't be important 1253 // as it does so deterministcally and ordering between DPLabels and DPValues 1254 // is immaterial (other than for MIR/IR printing). 1255 bool SkipDPValues = DAG.getFunctionVarLocs(); 1256 // Is there is any debug-info attached to this instruction, in the form of 1257 // DbgRecord non-instruction debug-info records. 1258 for (DbgRecord &DR : I.getDbgValueRange()) { 1259 if (DPLabel *DPL = dyn_cast<DPLabel>(&DR)) { 1260 assert(DPL->getLabel() && "Missing label"); 1261 SDDbgLabel *SDV = 1262 DAG.getDbgLabel(DPL->getLabel(), DPL->getDebugLoc(), SDNodeOrder); 1263 DAG.AddDbgLabel(SDV); 1264 continue; 1265 } 1266 1267 if (SkipDPValues) 1268 continue; 1269 DPValue &DPV = cast<DPValue>(DR); 1270 DILocalVariable *Variable = DPV.getVariable(); 1271 DIExpression *Expression = DPV.getExpression(); 1272 dropDanglingDebugInfo(Variable, Expression); 1273 1274 if (DPV.getType() == DPValue::LocationType::Declare) { 1275 if (FuncInfo.PreprocessedDPVDeclares.contains(&DPV)) 1276 continue; 1277 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DPV 1278 << "\n"); 1279 handleDebugDeclare(DPV.getVariableLocationOp(0), Variable, Expression, 1280 DPV.getDebugLoc()); 1281 continue; 1282 } 1283 1284 // A DPValue with no locations is a kill location. 1285 SmallVector<Value *, 4> Values(DPV.location_ops()); 1286 if (Values.empty()) { 1287 handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(), 1288 SDNodeOrder); 1289 continue; 1290 } 1291 1292 // A DPValue with an undef or absent location is also a kill location. 1293 if (llvm::any_of(Values, 1294 [](Value *V) { return !V || isa<UndefValue>(V); })) { 1295 handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(), 1296 SDNodeOrder); 1297 continue; 1298 } 1299 1300 bool IsVariadic = DPV.hasArgList(); 1301 if (!handleDebugValue(Values, Variable, Expression, DPV.getDebugLoc(), 1302 SDNodeOrder, IsVariadic)) { 1303 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 1304 DPV.getDebugLoc(), SDNodeOrder); 1305 } 1306 } 1307 } 1308 1309 void SelectionDAGBuilder::visit(const Instruction &I) { 1310 visitDbgInfo(I); 1311 1312 // Set up outgoing PHI node register values before emitting the terminator. 1313 if (I.isTerminator()) { 1314 HandlePHINodesInSuccessorBlocks(I.getParent()); 1315 } 1316 1317 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1318 if (!isa<DbgInfoIntrinsic>(I)) 1319 ++SDNodeOrder; 1320 1321 CurInst = &I; 1322 1323 // Set inserted listener only if required. 1324 bool NodeInserted = false; 1325 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1326 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1327 if (PCSectionsMD) { 1328 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1329 DAG, [&](SDNode *) { NodeInserted = true; }); 1330 } 1331 1332 visit(I.getOpcode(), I); 1333 1334 if (!I.isTerminator() && !HasTailCall && 1335 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1336 CopyToExportRegsIfNeeded(&I); 1337 1338 // Handle metadata. 1339 if (PCSectionsMD) { 1340 auto It = NodeMap.find(&I); 1341 if (It != NodeMap.end()) { 1342 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1343 } else if (NodeInserted) { 1344 // This should not happen; if it does, don't let it go unnoticed so we can 1345 // fix it. Relevant visit*() function is probably missing a setValue(). 1346 errs() << "warning: loosing !pcsections metadata [" 1347 << I.getModule()->getName() << "]\n"; 1348 LLVM_DEBUG(I.dump()); 1349 assert(false); 1350 } 1351 } 1352 1353 CurInst = nullptr; 1354 } 1355 1356 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1357 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1358 } 1359 1360 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1361 // Note: this doesn't use InstVisitor, because it has to work with 1362 // ConstantExpr's in addition to instructions. 1363 switch (Opcode) { 1364 default: llvm_unreachable("Unknown instruction type encountered!"); 1365 // Build the switch statement using the Instruction.def file. 1366 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1367 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1368 #include "llvm/IR/Instruction.def" 1369 } 1370 } 1371 1372 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1373 DILocalVariable *Variable, 1374 DebugLoc DL, unsigned Order, 1375 SmallVectorImpl<Value *> &Values, 1376 DIExpression *Expression) { 1377 // For variadic dbg_values we will now insert an undef. 1378 // FIXME: We can potentially recover these! 1379 SmallVector<SDDbgOperand, 2> Locs; 1380 for (const Value *V : Values) { 1381 auto *Undef = UndefValue::get(V->getType()); 1382 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1383 } 1384 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1385 /*IsIndirect=*/false, DL, Order, 1386 /*IsVariadic=*/true); 1387 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1388 return true; 1389 } 1390 1391 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values, 1392 DILocalVariable *Var, 1393 DIExpression *Expr, 1394 bool IsVariadic, DebugLoc DL, 1395 unsigned Order) { 1396 if (IsVariadic) { 1397 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr); 1398 return; 1399 } 1400 // TODO: Dangling debug info will eventually either be resolved or produce 1401 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1402 // between the original dbg.value location and its resolved DBG_VALUE, 1403 // which we should ideally fill with an extra Undef DBG_VALUE. 1404 assert(Values.size() == 1); 1405 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order); 1406 } 1407 1408 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1409 const DIExpression *Expr) { 1410 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1411 DIVariable *DanglingVariable = DDI.getVariable(); 1412 DIExpression *DanglingExpr = DDI.getExpression(); 1413 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1414 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " 1415 << printDDI(nullptr, DDI) << "\n"); 1416 return true; 1417 } 1418 return false; 1419 }; 1420 1421 for (auto &DDIMI : DanglingDebugInfoMap) { 1422 DanglingDebugInfoVector &DDIV = DDIMI.second; 1423 1424 // If debug info is to be dropped, run it through final checks to see 1425 // whether it can be salvaged. 1426 for (auto &DDI : DDIV) 1427 if (isMatchingDbgValue(DDI)) 1428 salvageUnresolvedDbgValue(DDIMI.first, DDI); 1429 1430 erase_if(DDIV, isMatchingDbgValue); 1431 } 1432 } 1433 1434 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1435 // generate the debug data structures now that we've seen its definition. 1436 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1437 SDValue Val) { 1438 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1439 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1440 return; 1441 1442 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1443 for (auto &DDI : DDIV) { 1444 DebugLoc DL = DDI.getDebugLoc(); 1445 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1446 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1447 DILocalVariable *Variable = DDI.getVariable(); 1448 DIExpression *Expr = DDI.getExpression(); 1449 assert(Variable->isValidLocationForIntrinsic(DL) && 1450 "Expected inlined-at fields to agree"); 1451 SDDbgValue *SDV; 1452 if (Val.getNode()) { 1453 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1454 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1455 // we couldn't resolve it directly when examining the DbgValue intrinsic 1456 // in the first place we should not be more successful here). Unless we 1457 // have some test case that prove this to be correct we should avoid 1458 // calling EmitFuncArgumentDbgValue here. 1459 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1460 FuncArgumentDbgValueKind::Value, Val)) { 1461 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " 1462 << printDDI(V, DDI) << "\n"); 1463 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1464 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1465 // inserted after the definition of Val when emitting the instructions 1466 // after ISel. An alternative could be to teach 1467 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1468 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1469 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1470 << ValSDNodeOrder << "\n"); 1471 SDV = getDbgValue(Val, Variable, Expr, DL, 1472 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1473 DAG.AddDbgValue(SDV, false); 1474 } else 1475 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1476 << printDDI(V, DDI) 1477 << " in EmitFuncArgumentDbgValue\n"); 1478 } else { 1479 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI) 1480 << "\n"); 1481 auto Undef = UndefValue::get(V->getType()); 1482 auto SDV = 1483 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1484 DAG.AddDbgValue(SDV, false); 1485 } 1486 } 1487 DDIV.clear(); 1488 } 1489 1490 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V, 1491 DanglingDebugInfo &DDI) { 1492 // TODO: For the variadic implementation, instead of only checking the fail 1493 // state of `handleDebugValue`, we need know specifically which values were 1494 // invalid, so that we attempt to salvage only those values when processing 1495 // a DIArgList. 1496 const Value *OrigV = V; 1497 DILocalVariable *Var = DDI.getVariable(); 1498 DIExpression *Expr = DDI.getExpression(); 1499 DebugLoc DL = DDI.getDebugLoc(); 1500 unsigned SDOrder = DDI.getSDNodeOrder(); 1501 1502 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1503 // that DW_OP_stack_value is desired. 1504 bool StackValue = true; 1505 1506 // Can this Value can be encoded without any further work? 1507 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1508 return; 1509 1510 // Attempt to salvage back through as many instructions as possible. Bail if 1511 // a non-instruction is seen, such as a constant expression or global 1512 // variable. FIXME: Further work could recover those too. 1513 while (isa<Instruction>(V)) { 1514 const Instruction &VAsInst = *cast<const Instruction>(V); 1515 // Temporary "0", awaiting real implementation. 1516 SmallVector<uint64_t, 16> Ops; 1517 SmallVector<Value *, 4> AdditionalValues; 1518 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst), 1519 Expr->getNumLocationOperands(), Ops, 1520 AdditionalValues); 1521 // If we cannot salvage any further, and haven't yet found a suitable debug 1522 // expression, bail out. 1523 if (!V) 1524 break; 1525 1526 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1527 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1528 // here for variadic dbg_values, remove that condition. 1529 if (!AdditionalValues.empty()) 1530 break; 1531 1532 // New value and expr now represent this debuginfo. 1533 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1534 1535 // Some kind of simplification occurred: check whether the operand of the 1536 // salvaged debug expression can be encoded in this DAG. 1537 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1538 LLVM_DEBUG( 1539 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1540 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1541 return; 1542 } 1543 } 1544 1545 // This was the final opportunity to salvage this debug information, and it 1546 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1547 // any earlier variable location. 1548 assert(OrigV && "V shouldn't be null"); 1549 auto *Undef = UndefValue::get(OrigV->getType()); 1550 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1551 DAG.AddDbgValue(SDV, false); 1552 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " 1553 << printDDI(OrigV, DDI) << "\n"); 1554 } 1555 1556 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1557 DIExpression *Expr, 1558 DebugLoc DbgLoc, 1559 unsigned Order) { 1560 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1561 DIExpression *NewExpr = 1562 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1563 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1564 /*IsVariadic*/ false); 1565 } 1566 1567 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1568 DILocalVariable *Var, 1569 DIExpression *Expr, DebugLoc DbgLoc, 1570 unsigned Order, bool IsVariadic) { 1571 if (Values.empty()) 1572 return true; 1573 1574 // Filter EntryValue locations out early. 1575 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc)) 1576 return true; 1577 1578 SmallVector<SDDbgOperand> LocationOps; 1579 SmallVector<SDNode *> Dependencies; 1580 for (const Value *V : Values) { 1581 // Constant value. 1582 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1583 isa<ConstantPointerNull>(V)) { 1584 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1585 continue; 1586 } 1587 1588 // Look through IntToPtr constants. 1589 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1590 if (CE->getOpcode() == Instruction::IntToPtr) { 1591 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1592 continue; 1593 } 1594 1595 // If the Value is a frame index, we can create a FrameIndex debug value 1596 // without relying on the DAG at all. 1597 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1598 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1599 if (SI != FuncInfo.StaticAllocaMap.end()) { 1600 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1601 continue; 1602 } 1603 } 1604 1605 // Do not use getValue() in here; we don't want to generate code at 1606 // this point if it hasn't been done yet. 1607 SDValue N = NodeMap[V]; 1608 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1609 N = UnusedArgNodeMap[V]; 1610 if (N.getNode()) { 1611 // Only emit func arg dbg value for non-variadic dbg.values for now. 1612 if (!IsVariadic && 1613 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1614 FuncArgumentDbgValueKind::Value, N)) 1615 return true; 1616 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1617 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1618 // describe stack slot locations. 1619 // 1620 // Consider "int x = 0; int *px = &x;". There are two kinds of 1621 // interesting debug values here after optimization: 1622 // 1623 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1624 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1625 // 1626 // Both describe the direct values of their associated variables. 1627 Dependencies.push_back(N.getNode()); 1628 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1629 continue; 1630 } 1631 LocationOps.emplace_back( 1632 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1633 continue; 1634 } 1635 1636 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1637 // Special rules apply for the first dbg.values of parameter variables in a 1638 // function. Identify them by the fact they reference Argument Values, that 1639 // they're parameters, and they are parameters of the current function. We 1640 // need to let them dangle until they get an SDNode. 1641 bool IsParamOfFunc = 1642 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1643 if (IsParamOfFunc) 1644 return false; 1645 1646 // The value is not used in this block yet (or it would have an SDNode). 1647 // We still want the value to appear for the user if possible -- if it has 1648 // an associated VReg, we can refer to that instead. 1649 auto VMI = FuncInfo.ValueMap.find(V); 1650 if (VMI != FuncInfo.ValueMap.end()) { 1651 unsigned Reg = VMI->second; 1652 // If this is a PHI node, it may be split up into several MI PHI nodes 1653 // (in FunctionLoweringInfo::set). 1654 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1655 V->getType(), std::nullopt); 1656 if (RFV.occupiesMultipleRegs()) { 1657 // FIXME: We could potentially support variadic dbg_values here. 1658 if (IsVariadic) 1659 return false; 1660 unsigned Offset = 0; 1661 unsigned BitsToDescribe = 0; 1662 if (auto VarSize = Var->getSizeInBits()) 1663 BitsToDescribe = *VarSize; 1664 if (auto Fragment = Expr->getFragmentInfo()) 1665 BitsToDescribe = Fragment->SizeInBits; 1666 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1667 // Bail out if all bits are described already. 1668 if (Offset >= BitsToDescribe) 1669 break; 1670 // TODO: handle scalable vectors. 1671 unsigned RegisterSize = RegAndSize.second; 1672 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1673 ? BitsToDescribe - Offset 1674 : RegisterSize; 1675 auto FragmentExpr = DIExpression::createFragmentExpression( 1676 Expr, Offset, FragmentSize); 1677 if (!FragmentExpr) 1678 continue; 1679 SDDbgValue *SDV = DAG.getVRegDbgValue( 1680 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1681 DAG.AddDbgValue(SDV, false); 1682 Offset += RegisterSize; 1683 } 1684 return true; 1685 } 1686 // We can use simple vreg locations for variadic dbg_values as well. 1687 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1688 continue; 1689 } 1690 // We failed to create a SDDbgOperand for V. 1691 return false; 1692 } 1693 1694 // We have created a SDDbgOperand for each Value in Values. 1695 // Should use Order instead of SDNodeOrder? 1696 assert(!LocationOps.empty()); 1697 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1698 /*IsIndirect=*/false, DbgLoc, 1699 SDNodeOrder, IsVariadic); 1700 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1701 return true; 1702 } 1703 1704 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1705 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1706 for (auto &Pair : DanglingDebugInfoMap) 1707 for (auto &DDI : Pair.second) 1708 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI); 1709 clearDanglingDebugInfo(); 1710 } 1711 1712 /// getCopyFromRegs - If there was virtual register allocated for the value V 1713 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1714 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1715 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1716 SDValue Result; 1717 1718 if (It != FuncInfo.ValueMap.end()) { 1719 Register InReg = It->second; 1720 1721 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1722 DAG.getDataLayout(), InReg, Ty, 1723 std::nullopt); // This is not an ABI copy. 1724 SDValue Chain = DAG.getEntryNode(); 1725 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1726 V); 1727 resolveDanglingDebugInfo(V, Result); 1728 } 1729 1730 return Result; 1731 } 1732 1733 /// getValue - Return an SDValue for the given Value. 1734 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1735 // If we already have an SDValue for this value, use it. It's important 1736 // to do this first, so that we don't create a CopyFromReg if we already 1737 // have a regular SDValue. 1738 SDValue &N = NodeMap[V]; 1739 if (N.getNode()) return N; 1740 1741 // If there's a virtual register allocated and initialized for this 1742 // value, use it. 1743 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1744 return copyFromReg; 1745 1746 // Otherwise create a new SDValue and remember it. 1747 SDValue Val = getValueImpl(V); 1748 NodeMap[V] = Val; 1749 resolveDanglingDebugInfo(V, Val); 1750 return Val; 1751 } 1752 1753 /// getNonRegisterValue - Return an SDValue for the given Value, but 1754 /// don't look in FuncInfo.ValueMap for a virtual register. 1755 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1756 // If we already have an SDValue for this value, use it. 1757 SDValue &N = NodeMap[V]; 1758 if (N.getNode()) { 1759 if (isIntOrFPConstant(N)) { 1760 // Remove the debug location from the node as the node is about to be used 1761 // in a location which may differ from the original debug location. This 1762 // is relevant to Constant and ConstantFP nodes because they can appear 1763 // as constant expressions inside PHI nodes. 1764 N->setDebugLoc(DebugLoc()); 1765 } 1766 return N; 1767 } 1768 1769 // Otherwise create a new SDValue and remember it. 1770 SDValue Val = getValueImpl(V); 1771 NodeMap[V] = Val; 1772 resolveDanglingDebugInfo(V, Val); 1773 return Val; 1774 } 1775 1776 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1777 /// Create an SDValue for the given value. 1778 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1779 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1780 1781 if (const Constant *C = dyn_cast<Constant>(V)) { 1782 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1783 1784 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1785 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1786 1787 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1788 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1789 1790 if (isa<ConstantPointerNull>(C)) { 1791 unsigned AS = V->getType()->getPointerAddressSpace(); 1792 return DAG.getConstant(0, getCurSDLoc(), 1793 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1794 } 1795 1796 if (match(C, m_VScale())) 1797 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1798 1799 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1800 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1801 1802 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1803 return DAG.getUNDEF(VT); 1804 1805 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1806 visit(CE->getOpcode(), *CE); 1807 SDValue N1 = NodeMap[V]; 1808 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1809 return N1; 1810 } 1811 1812 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1813 SmallVector<SDValue, 4> Constants; 1814 for (const Use &U : C->operands()) { 1815 SDNode *Val = getValue(U).getNode(); 1816 // If the operand is an empty aggregate, there are no values. 1817 if (!Val) continue; 1818 // Add each leaf value from the operand to the Constants list 1819 // to form a flattened list of all the values. 1820 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1821 Constants.push_back(SDValue(Val, i)); 1822 } 1823 1824 return DAG.getMergeValues(Constants, getCurSDLoc()); 1825 } 1826 1827 if (const ConstantDataSequential *CDS = 1828 dyn_cast<ConstantDataSequential>(C)) { 1829 SmallVector<SDValue, 4> Ops; 1830 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1831 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1832 // Add each leaf value from the operand to the Constants list 1833 // to form a flattened list of all the values. 1834 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1835 Ops.push_back(SDValue(Val, i)); 1836 } 1837 1838 if (isa<ArrayType>(CDS->getType())) 1839 return DAG.getMergeValues(Ops, getCurSDLoc()); 1840 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1841 } 1842 1843 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1844 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1845 "Unknown struct or array constant!"); 1846 1847 SmallVector<EVT, 4> ValueVTs; 1848 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1849 unsigned NumElts = ValueVTs.size(); 1850 if (NumElts == 0) 1851 return SDValue(); // empty struct 1852 SmallVector<SDValue, 4> Constants(NumElts); 1853 for (unsigned i = 0; i != NumElts; ++i) { 1854 EVT EltVT = ValueVTs[i]; 1855 if (isa<UndefValue>(C)) 1856 Constants[i] = DAG.getUNDEF(EltVT); 1857 else if (EltVT.isFloatingPoint()) 1858 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1859 else 1860 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1861 } 1862 1863 return DAG.getMergeValues(Constants, getCurSDLoc()); 1864 } 1865 1866 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1867 return DAG.getBlockAddress(BA, VT); 1868 1869 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1870 return getValue(Equiv->getGlobalValue()); 1871 1872 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1873 return getValue(NC->getGlobalValue()); 1874 1875 if (VT == MVT::aarch64svcount) { 1876 assert(C->isNullValue() && "Can only zero this target type!"); 1877 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, 1878 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1)); 1879 } 1880 1881 VectorType *VecTy = cast<VectorType>(V->getType()); 1882 1883 // Now that we know the number and type of the elements, get that number of 1884 // elements into the Ops array based on what kind of constant it is. 1885 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1886 SmallVector<SDValue, 16> Ops; 1887 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1888 for (unsigned i = 0; i != NumElements; ++i) 1889 Ops.push_back(getValue(CV->getOperand(i))); 1890 1891 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1892 } 1893 1894 if (isa<ConstantAggregateZero>(C)) { 1895 EVT EltVT = 1896 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1897 1898 SDValue Op; 1899 if (EltVT.isFloatingPoint()) 1900 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1901 else 1902 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1903 1904 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1905 } 1906 1907 llvm_unreachable("Unknown vector constant"); 1908 } 1909 1910 // If this is a static alloca, generate it as the frameindex instead of 1911 // computation. 1912 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1913 DenseMap<const AllocaInst*, int>::iterator SI = 1914 FuncInfo.StaticAllocaMap.find(AI); 1915 if (SI != FuncInfo.StaticAllocaMap.end()) 1916 return DAG.getFrameIndex( 1917 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1918 } 1919 1920 // If this is an instruction which fast-isel has deferred, select it now. 1921 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1922 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1923 1924 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1925 Inst->getType(), std::nullopt); 1926 SDValue Chain = DAG.getEntryNode(); 1927 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1928 } 1929 1930 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1931 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1932 1933 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1934 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1935 1936 llvm_unreachable("Can't get register for value!"); 1937 } 1938 1939 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1940 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1941 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1942 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1943 bool IsSEH = isAsynchronousEHPersonality(Pers); 1944 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1945 if (!IsSEH) 1946 CatchPadMBB->setIsEHScopeEntry(); 1947 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1948 if (IsMSVCCXX || IsCoreCLR) 1949 CatchPadMBB->setIsEHFuncletEntry(); 1950 } 1951 1952 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1953 // Update machine-CFG edge. 1954 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1955 FuncInfo.MBB->addSuccessor(TargetMBB); 1956 TargetMBB->setIsEHCatchretTarget(true); 1957 DAG.getMachineFunction().setHasEHCatchret(true); 1958 1959 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1960 bool IsSEH = isAsynchronousEHPersonality(Pers); 1961 if (IsSEH) { 1962 // If this is not a fall-through branch or optimizations are switched off, 1963 // emit the branch. 1964 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1965 TM.getOptLevel() == CodeGenOptLevel::None) 1966 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1967 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1968 return; 1969 } 1970 1971 // Figure out the funclet membership for the catchret's successor. 1972 // This will be used by the FuncletLayout pass to determine how to order the 1973 // BB's. 1974 // A 'catchret' returns to the outer scope's color. 1975 Value *ParentPad = I.getCatchSwitchParentPad(); 1976 const BasicBlock *SuccessorColor; 1977 if (isa<ConstantTokenNone>(ParentPad)) 1978 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1979 else 1980 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1981 assert(SuccessorColor && "No parent funclet for catchret!"); 1982 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1983 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1984 1985 // Create the terminator node. 1986 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1987 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1988 DAG.getBasicBlock(SuccessorColorMBB)); 1989 DAG.setRoot(Ret); 1990 } 1991 1992 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1993 // Don't emit any special code for the cleanuppad instruction. It just marks 1994 // the start of an EH scope/funclet. 1995 FuncInfo.MBB->setIsEHScopeEntry(); 1996 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1997 if (Pers != EHPersonality::Wasm_CXX) { 1998 FuncInfo.MBB->setIsEHFuncletEntry(); 1999 FuncInfo.MBB->setIsCleanupFuncletEntry(); 2000 } 2001 } 2002 2003 // In wasm EH, even though a catchpad may not catch an exception if a tag does 2004 // not match, it is OK to add only the first unwind destination catchpad to the 2005 // successors, because there will be at least one invoke instruction within the 2006 // catch scope that points to the next unwind destination, if one exists, so 2007 // CFGSort cannot mess up with BB sorting order. 2008 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 2009 // call within them, and catchpads only consisting of 'catch (...)' have a 2010 // '__cxa_end_catch' call within them, both of which generate invokes in case 2011 // the next unwind destination exists, i.e., the next unwind destination is not 2012 // the caller.) 2013 // 2014 // Having at most one EH pad successor is also simpler and helps later 2015 // transformations. 2016 // 2017 // For example, 2018 // current: 2019 // invoke void @foo to ... unwind label %catch.dispatch 2020 // catch.dispatch: 2021 // %0 = catchswitch within ... [label %catch.start] unwind label %next 2022 // catch.start: 2023 // ... 2024 // ... in this BB or some other child BB dominated by this BB there will be an 2025 // invoke that points to 'next' BB as an unwind destination 2026 // 2027 // next: ; We don't need to add this to 'current' BB's successor 2028 // ... 2029 static void findWasmUnwindDestinations( 2030 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2031 BranchProbability Prob, 2032 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2033 &UnwindDests) { 2034 while (EHPadBB) { 2035 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2036 if (isa<CleanupPadInst>(Pad)) { 2037 // Stop on cleanup pads. 2038 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2039 UnwindDests.back().first->setIsEHScopeEntry(); 2040 break; 2041 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2042 // Add the catchpad handlers to the possible destinations. We don't 2043 // continue to the unwind destination of the catchswitch for wasm. 2044 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2045 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2046 UnwindDests.back().first->setIsEHScopeEntry(); 2047 } 2048 break; 2049 } else { 2050 continue; 2051 } 2052 } 2053 } 2054 2055 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 2056 /// many places it could ultimately go. In the IR, we have a single unwind 2057 /// destination, but in the machine CFG, we enumerate all the possible blocks. 2058 /// This function skips over imaginary basic blocks that hold catchswitch 2059 /// instructions, and finds all the "real" machine 2060 /// basic block destinations. As those destinations may not be successors of 2061 /// EHPadBB, here we also calculate the edge probability to those destinations. 2062 /// The passed-in Prob is the edge probability to EHPadBB. 2063 static void findUnwindDestinations( 2064 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2065 BranchProbability Prob, 2066 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2067 &UnwindDests) { 2068 EHPersonality Personality = 2069 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2070 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 2071 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 2072 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 2073 bool IsSEH = isAsynchronousEHPersonality(Personality); 2074 2075 if (IsWasmCXX) { 2076 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 2077 assert(UnwindDests.size() <= 1 && 2078 "There should be at most one unwind destination for wasm"); 2079 return; 2080 } 2081 2082 while (EHPadBB) { 2083 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2084 BasicBlock *NewEHPadBB = nullptr; 2085 if (isa<LandingPadInst>(Pad)) { 2086 // Stop on landingpads. They are not funclets. 2087 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2088 break; 2089 } else if (isa<CleanupPadInst>(Pad)) { 2090 // Stop on cleanup pads. Cleanups are always funclet entries for all known 2091 // personalities. 2092 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2093 UnwindDests.back().first->setIsEHScopeEntry(); 2094 UnwindDests.back().first->setIsEHFuncletEntry(); 2095 break; 2096 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2097 // Add the catchpad handlers to the possible destinations. 2098 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2099 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2100 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 2101 if (IsMSVCCXX || IsCoreCLR) 2102 UnwindDests.back().first->setIsEHFuncletEntry(); 2103 if (!IsSEH) 2104 UnwindDests.back().first->setIsEHScopeEntry(); 2105 } 2106 NewEHPadBB = CatchSwitch->getUnwindDest(); 2107 } else { 2108 continue; 2109 } 2110 2111 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2112 if (BPI && NewEHPadBB) 2113 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 2114 EHPadBB = NewEHPadBB; 2115 } 2116 } 2117 2118 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 2119 // Update successor info. 2120 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2121 auto UnwindDest = I.getUnwindDest(); 2122 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2123 BranchProbability UnwindDestProb = 2124 (BPI && UnwindDest) 2125 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 2126 : BranchProbability::getZero(); 2127 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 2128 for (auto &UnwindDest : UnwindDests) { 2129 UnwindDest.first->setIsEHPad(); 2130 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 2131 } 2132 FuncInfo.MBB->normalizeSuccProbs(); 2133 2134 // Create the terminator node. 2135 SDValue Ret = 2136 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 2137 DAG.setRoot(Ret); 2138 } 2139 2140 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2141 report_fatal_error("visitCatchSwitch not yet implemented!"); 2142 } 2143 2144 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2145 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2146 auto &DL = DAG.getDataLayout(); 2147 SDValue Chain = getControlRoot(); 2148 SmallVector<ISD::OutputArg, 8> Outs; 2149 SmallVector<SDValue, 8> OutVals; 2150 2151 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2152 // lower 2153 // 2154 // %val = call <ty> @llvm.experimental.deoptimize() 2155 // ret <ty> %val 2156 // 2157 // differently. 2158 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2159 LowerDeoptimizingReturn(); 2160 return; 2161 } 2162 2163 if (!FuncInfo.CanLowerReturn) { 2164 unsigned DemoteReg = FuncInfo.DemoteRegister; 2165 const Function *F = I.getParent()->getParent(); 2166 2167 // Emit a store of the return value through the virtual register. 2168 // Leave Outs empty so that LowerReturn won't try to load return 2169 // registers the usual way. 2170 SmallVector<EVT, 1> PtrValueVTs; 2171 ComputeValueVTs(TLI, DL, 2172 PointerType::get(F->getContext(), 2173 DAG.getDataLayout().getAllocaAddrSpace()), 2174 PtrValueVTs); 2175 2176 SDValue RetPtr = 2177 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2178 SDValue RetOp = getValue(I.getOperand(0)); 2179 2180 SmallVector<EVT, 4> ValueVTs, MemVTs; 2181 SmallVector<uint64_t, 4> Offsets; 2182 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2183 &Offsets, 0); 2184 unsigned NumValues = ValueVTs.size(); 2185 2186 SmallVector<SDValue, 4> Chains(NumValues); 2187 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2188 for (unsigned i = 0; i != NumValues; ++i) { 2189 // An aggregate return value cannot wrap around the address space, so 2190 // offsets to its parts don't wrap either. 2191 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2192 TypeSize::getFixed(Offsets[i])); 2193 2194 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2195 if (MemVTs[i] != ValueVTs[i]) 2196 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2197 Chains[i] = DAG.getStore( 2198 Chain, getCurSDLoc(), Val, 2199 // FIXME: better loc info would be nice. 2200 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2201 commonAlignment(BaseAlign, Offsets[i])); 2202 } 2203 2204 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2205 MVT::Other, Chains); 2206 } else if (I.getNumOperands() != 0) { 2207 SmallVector<EVT, 4> ValueVTs; 2208 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2209 unsigned NumValues = ValueVTs.size(); 2210 if (NumValues) { 2211 SDValue RetOp = getValue(I.getOperand(0)); 2212 2213 const Function *F = I.getParent()->getParent(); 2214 2215 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2216 I.getOperand(0)->getType(), F->getCallingConv(), 2217 /*IsVarArg*/ false, DL); 2218 2219 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2220 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2221 ExtendKind = ISD::SIGN_EXTEND; 2222 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2223 ExtendKind = ISD::ZERO_EXTEND; 2224 2225 LLVMContext &Context = F->getContext(); 2226 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2227 2228 for (unsigned j = 0; j != NumValues; ++j) { 2229 EVT VT = ValueVTs[j]; 2230 2231 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2232 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2233 2234 CallingConv::ID CC = F->getCallingConv(); 2235 2236 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2237 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2238 SmallVector<SDValue, 4> Parts(NumParts); 2239 getCopyToParts(DAG, getCurSDLoc(), 2240 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2241 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2242 2243 // 'inreg' on function refers to return value 2244 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2245 if (RetInReg) 2246 Flags.setInReg(); 2247 2248 if (I.getOperand(0)->getType()->isPointerTy()) { 2249 Flags.setPointer(); 2250 Flags.setPointerAddrSpace( 2251 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2252 } 2253 2254 if (NeedsRegBlock) { 2255 Flags.setInConsecutiveRegs(); 2256 if (j == NumValues - 1) 2257 Flags.setInConsecutiveRegsLast(); 2258 } 2259 2260 // Propagate extension type if any 2261 if (ExtendKind == ISD::SIGN_EXTEND) 2262 Flags.setSExt(); 2263 else if (ExtendKind == ISD::ZERO_EXTEND) 2264 Flags.setZExt(); 2265 2266 for (unsigned i = 0; i < NumParts; ++i) { 2267 Outs.push_back(ISD::OutputArg(Flags, 2268 Parts[i].getValueType().getSimpleVT(), 2269 VT, /*isfixed=*/true, 0, 0)); 2270 OutVals.push_back(Parts[i]); 2271 } 2272 } 2273 } 2274 } 2275 2276 // Push in swifterror virtual register as the last element of Outs. This makes 2277 // sure swifterror virtual register will be returned in the swifterror 2278 // physical register. 2279 const Function *F = I.getParent()->getParent(); 2280 if (TLI.supportSwiftError() && 2281 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2282 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2283 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2284 Flags.setSwiftError(); 2285 Outs.push_back(ISD::OutputArg( 2286 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2287 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2288 // Create SDNode for the swifterror virtual register. 2289 OutVals.push_back( 2290 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2291 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2292 EVT(TLI.getPointerTy(DL)))); 2293 } 2294 2295 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2296 CallingConv::ID CallConv = 2297 DAG.getMachineFunction().getFunction().getCallingConv(); 2298 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2299 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2300 2301 // Verify that the target's LowerReturn behaved as expected. 2302 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2303 "LowerReturn didn't return a valid chain!"); 2304 2305 // Update the DAG with the new chain value resulting from return lowering. 2306 DAG.setRoot(Chain); 2307 } 2308 2309 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2310 /// created for it, emit nodes to copy the value into the virtual 2311 /// registers. 2312 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2313 // Skip empty types 2314 if (V->getType()->isEmptyTy()) 2315 return; 2316 2317 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2318 if (VMI != FuncInfo.ValueMap.end()) { 2319 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2320 "Unused value assigned virtual registers!"); 2321 CopyValueToVirtualRegister(V, VMI->second); 2322 } 2323 } 2324 2325 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2326 /// the current basic block, add it to ValueMap now so that we'll get a 2327 /// CopyTo/FromReg. 2328 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2329 // No need to export constants. 2330 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2331 2332 // Already exported? 2333 if (FuncInfo.isExportedInst(V)) return; 2334 2335 Register Reg = FuncInfo.InitializeRegForValue(V); 2336 CopyValueToVirtualRegister(V, Reg); 2337 } 2338 2339 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2340 const BasicBlock *FromBB) { 2341 // The operands of the setcc have to be in this block. We don't know 2342 // how to export them from some other block. 2343 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2344 // Can export from current BB. 2345 if (VI->getParent() == FromBB) 2346 return true; 2347 2348 // Is already exported, noop. 2349 return FuncInfo.isExportedInst(V); 2350 } 2351 2352 // If this is an argument, we can export it if the BB is the entry block or 2353 // if it is already exported. 2354 if (isa<Argument>(V)) { 2355 if (FromBB->isEntryBlock()) 2356 return true; 2357 2358 // Otherwise, can only export this if it is already exported. 2359 return FuncInfo.isExportedInst(V); 2360 } 2361 2362 // Otherwise, constants can always be exported. 2363 return true; 2364 } 2365 2366 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2367 BranchProbability 2368 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2369 const MachineBasicBlock *Dst) const { 2370 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2371 const BasicBlock *SrcBB = Src->getBasicBlock(); 2372 const BasicBlock *DstBB = Dst->getBasicBlock(); 2373 if (!BPI) { 2374 // If BPI is not available, set the default probability as 1 / N, where N is 2375 // the number of successors. 2376 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2377 return BranchProbability(1, SuccSize); 2378 } 2379 return BPI->getEdgeProbability(SrcBB, DstBB); 2380 } 2381 2382 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2383 MachineBasicBlock *Dst, 2384 BranchProbability Prob) { 2385 if (!FuncInfo.BPI) 2386 Src->addSuccessorWithoutProb(Dst); 2387 else { 2388 if (Prob.isUnknown()) 2389 Prob = getEdgeProbability(Src, Dst); 2390 Src->addSuccessor(Dst, Prob); 2391 } 2392 } 2393 2394 static bool InBlock(const Value *V, const BasicBlock *BB) { 2395 if (const Instruction *I = dyn_cast<Instruction>(V)) 2396 return I->getParent() == BB; 2397 return true; 2398 } 2399 2400 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2401 /// This function emits a branch and is used at the leaves of an OR or an 2402 /// AND operator tree. 2403 void 2404 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2405 MachineBasicBlock *TBB, 2406 MachineBasicBlock *FBB, 2407 MachineBasicBlock *CurBB, 2408 MachineBasicBlock *SwitchBB, 2409 BranchProbability TProb, 2410 BranchProbability FProb, 2411 bool InvertCond) { 2412 const BasicBlock *BB = CurBB->getBasicBlock(); 2413 2414 // If the leaf of the tree is a comparison, merge the condition into 2415 // the caseblock. 2416 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2417 // The operands of the cmp have to be in this block. We don't know 2418 // how to export them from some other block. If this is the first block 2419 // of the sequence, no exporting is needed. 2420 if (CurBB == SwitchBB || 2421 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2422 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2423 ISD::CondCode Condition; 2424 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2425 ICmpInst::Predicate Pred = 2426 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2427 Condition = getICmpCondCode(Pred); 2428 } else { 2429 const FCmpInst *FC = cast<FCmpInst>(Cond); 2430 FCmpInst::Predicate Pred = 2431 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2432 Condition = getFCmpCondCode(Pred); 2433 if (TM.Options.NoNaNsFPMath) 2434 Condition = getFCmpCodeWithoutNaN(Condition); 2435 } 2436 2437 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2438 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2439 SL->SwitchCases.push_back(CB); 2440 return; 2441 } 2442 } 2443 2444 // Create a CaseBlock record representing this branch. 2445 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2446 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2447 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2448 SL->SwitchCases.push_back(CB); 2449 } 2450 2451 // Collect dependencies on V recursively. This is used for the cost analysis in 2452 // `shouldKeepJumpConditionsTogether`. 2453 static bool collectInstructionDeps( 2454 SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V, 2455 SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr, 2456 unsigned Depth = 0) { 2457 // Return false if we have an incomplete count. 2458 if (Depth >= SelectionDAG::MaxRecursionDepth) 2459 return false; 2460 2461 auto *I = dyn_cast<Instruction>(V); 2462 if (I == nullptr) 2463 return true; 2464 2465 if (Necessary != nullptr) { 2466 // This instruction is necessary for the other side of the condition so 2467 // don't count it. 2468 if (Necessary->contains(I)) 2469 return true; 2470 } 2471 2472 // Already added this dep. 2473 if (!Deps->try_emplace(I, false).second) 2474 return true; 2475 2476 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx) 2477 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary, 2478 Depth + 1)) 2479 return false; 2480 return true; 2481 } 2482 2483 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether( 2484 const FunctionLoweringInfo &FuncInfo, const BranchInst &I, 2485 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, 2486 TargetLoweringBase::CondMergingParams Params) const { 2487 if (I.getNumSuccessors() != 2) 2488 return false; 2489 2490 if (!I.isConditional()) 2491 return false; 2492 2493 if (Params.BaseCost < 0) 2494 return false; 2495 2496 // Baseline cost. 2497 InstructionCost CostThresh = Params.BaseCost; 2498 2499 BranchProbabilityInfo *BPI = nullptr; 2500 if (Params.LikelyBias || Params.UnlikelyBias) 2501 BPI = FuncInfo.BPI; 2502 if (BPI != nullptr) { 2503 // See if we are either likely to get an early out or compute both lhs/rhs 2504 // of the condition. 2505 BasicBlock *IfFalse = I.getSuccessor(0); 2506 BasicBlock *IfTrue = I.getSuccessor(1); 2507 2508 std::optional<bool> Likely; 2509 if (BPI->isEdgeHot(I.getParent(), IfTrue)) 2510 Likely = true; 2511 else if (BPI->isEdgeHot(I.getParent(), IfFalse)) 2512 Likely = false; 2513 2514 if (Likely) { 2515 if (Opc == (*Likely ? Instruction::And : Instruction::Or)) 2516 // Its likely we will have to compute both lhs and rhs of condition 2517 CostThresh += Params.LikelyBias; 2518 else { 2519 if (Params.UnlikelyBias < 0) 2520 return false; 2521 // Its likely we will get an early out. 2522 CostThresh -= Params.UnlikelyBias; 2523 } 2524 } 2525 } 2526 2527 if (CostThresh <= 0) 2528 return false; 2529 2530 // Collect "all" instructions that lhs condition is dependent on. 2531 // Use map for stable iteration (to avoid non-determanism of iteration of 2532 // SmallPtrSet). The `bool` value is just a dummy. 2533 SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps; 2534 collectInstructionDeps(&LhsDeps, Lhs); 2535 // Collect "all" instructions that rhs condition is dependent on AND are 2536 // dependencies of lhs. This gives us an estimate on which instructions we 2537 // stand to save by splitting the condition. 2538 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps)) 2539 return false; 2540 // Add the compare instruction itself unless its a dependency on the LHS. 2541 if (const auto *RhsI = dyn_cast<Instruction>(Rhs)) 2542 if (!LhsDeps.contains(RhsI)) 2543 RhsDeps.try_emplace(RhsI, false); 2544 2545 const auto &TLI = DAG.getTargetLoweringInfo(); 2546 const auto &TTI = 2547 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 2548 2549 InstructionCost CostOfIncluding = 0; 2550 // See if this instruction will need to computed independently of whether RHS 2551 // is. 2552 Value *BrCond = I.getCondition(); 2553 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) { 2554 for (const auto *U : Ins->users()) { 2555 // If user is independent of RHS calculation we don't need to count it. 2556 if (auto *UIns = dyn_cast<Instruction>(U)) 2557 if (UIns != BrCond && !RhsDeps.contains(UIns)) 2558 return false; 2559 } 2560 return true; 2561 }; 2562 2563 // Prune instructions from RHS Deps that are dependencies of unrelated 2564 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly 2565 // arbitrary and just meant to cap the how much time we spend in the pruning 2566 // loop. Its highly unlikely to come into affect. 2567 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth; 2568 // Stop after a certain point. No incorrectness from including too many 2569 // instructions. 2570 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) { 2571 const Instruction *ToDrop = nullptr; 2572 for (const auto &InsPair : RhsDeps) { 2573 if (!ShouldCountInsn(InsPair.first)) { 2574 ToDrop = InsPair.first; 2575 break; 2576 } 2577 } 2578 if (ToDrop == nullptr) 2579 break; 2580 RhsDeps.erase(ToDrop); 2581 } 2582 2583 for (const auto &InsPair : RhsDeps) { 2584 // Finally accumulate latency that we can only attribute to computing the 2585 // RHS condition. Use latency because we are essentially trying to calculate 2586 // the cost of the dependency chain. 2587 // Possible TODO: We could try to estimate ILP and make this more precise. 2588 CostOfIncluding += 2589 TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency); 2590 2591 if (CostOfIncluding > CostThresh) 2592 return false; 2593 } 2594 return true; 2595 } 2596 2597 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2598 MachineBasicBlock *TBB, 2599 MachineBasicBlock *FBB, 2600 MachineBasicBlock *CurBB, 2601 MachineBasicBlock *SwitchBB, 2602 Instruction::BinaryOps Opc, 2603 BranchProbability TProb, 2604 BranchProbability FProb, 2605 bool InvertCond) { 2606 // Skip over not part of the tree and remember to invert op and operands at 2607 // next level. 2608 Value *NotCond; 2609 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2610 InBlock(NotCond, CurBB->getBasicBlock())) { 2611 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2612 !InvertCond); 2613 return; 2614 } 2615 2616 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2617 const Value *BOpOp0, *BOpOp1; 2618 // Compute the effective opcode for Cond, taking into account whether it needs 2619 // to be inverted, e.g. 2620 // and (not (or A, B)), C 2621 // gets lowered as 2622 // and (and (not A, not B), C) 2623 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2624 if (BOp) { 2625 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2626 ? Instruction::And 2627 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2628 ? Instruction::Or 2629 : (Instruction::BinaryOps)0); 2630 if (InvertCond) { 2631 if (BOpc == Instruction::And) 2632 BOpc = Instruction::Or; 2633 else if (BOpc == Instruction::Or) 2634 BOpc = Instruction::And; 2635 } 2636 } 2637 2638 // If this node is not part of the or/and tree, emit it as a branch. 2639 // Note that all nodes in the tree should have same opcode. 2640 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2641 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2642 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2643 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2644 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2645 TProb, FProb, InvertCond); 2646 return; 2647 } 2648 2649 // Create TmpBB after CurBB. 2650 MachineFunction::iterator BBI(CurBB); 2651 MachineFunction &MF = DAG.getMachineFunction(); 2652 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2653 CurBB->getParent()->insert(++BBI, TmpBB); 2654 2655 if (Opc == Instruction::Or) { 2656 // Codegen X | Y as: 2657 // BB1: 2658 // jmp_if_X TBB 2659 // jmp TmpBB 2660 // TmpBB: 2661 // jmp_if_Y TBB 2662 // jmp FBB 2663 // 2664 2665 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2666 // The requirement is that 2667 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2668 // = TrueProb for original BB. 2669 // Assuming the original probabilities are A and B, one choice is to set 2670 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2671 // A/(1+B) and 2B/(1+B). This choice assumes that 2672 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2673 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2674 // TmpBB, but the math is more complicated. 2675 2676 auto NewTrueProb = TProb / 2; 2677 auto NewFalseProb = TProb / 2 + FProb; 2678 // Emit the LHS condition. 2679 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2680 NewFalseProb, InvertCond); 2681 2682 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2683 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2684 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2685 // Emit the RHS condition into TmpBB. 2686 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2687 Probs[1], InvertCond); 2688 } else { 2689 assert(Opc == Instruction::And && "Unknown merge op!"); 2690 // Codegen X & Y as: 2691 // BB1: 2692 // jmp_if_X TmpBB 2693 // jmp FBB 2694 // TmpBB: 2695 // jmp_if_Y TBB 2696 // jmp FBB 2697 // 2698 // This requires creation of TmpBB after CurBB. 2699 2700 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2701 // The requirement is that 2702 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2703 // = FalseProb for original BB. 2704 // Assuming the original probabilities are A and B, one choice is to set 2705 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2706 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2707 // TrueProb for BB1 * FalseProb for TmpBB. 2708 2709 auto NewTrueProb = TProb + FProb / 2; 2710 auto NewFalseProb = FProb / 2; 2711 // Emit the LHS condition. 2712 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2713 NewFalseProb, InvertCond); 2714 2715 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2716 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2717 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2718 // Emit the RHS condition into TmpBB. 2719 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2720 Probs[1], InvertCond); 2721 } 2722 } 2723 2724 /// If the set of cases should be emitted as a series of branches, return true. 2725 /// If we should emit this as a bunch of and/or'd together conditions, return 2726 /// false. 2727 bool 2728 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2729 if (Cases.size() != 2) return true; 2730 2731 // If this is two comparisons of the same values or'd or and'd together, they 2732 // will get folded into a single comparison, so don't emit two blocks. 2733 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2734 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2735 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2736 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2737 return false; 2738 } 2739 2740 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2741 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2742 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2743 Cases[0].CC == Cases[1].CC && 2744 isa<Constant>(Cases[0].CmpRHS) && 2745 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2746 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2747 return false; 2748 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2749 return false; 2750 } 2751 2752 return true; 2753 } 2754 2755 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2756 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2757 2758 // Update machine-CFG edges. 2759 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2760 2761 if (I.isUnconditional()) { 2762 // Update machine-CFG edges. 2763 BrMBB->addSuccessor(Succ0MBB); 2764 2765 // If this is not a fall-through branch or optimizations are switched off, 2766 // emit the branch. 2767 if (Succ0MBB != NextBlock(BrMBB) || 2768 TM.getOptLevel() == CodeGenOptLevel::None) { 2769 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2770 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2771 setValue(&I, Br); 2772 DAG.setRoot(Br); 2773 } 2774 2775 return; 2776 } 2777 2778 // If this condition is one of the special cases we handle, do special stuff 2779 // now. 2780 const Value *CondVal = I.getCondition(); 2781 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2782 2783 // If this is a series of conditions that are or'd or and'd together, emit 2784 // this as a sequence of branches instead of setcc's with and/or operations. 2785 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2786 // unpredictable branches, and vector extracts because those jumps are likely 2787 // expensive for any target), this should improve performance. 2788 // For example, instead of something like: 2789 // cmp A, B 2790 // C = seteq 2791 // cmp D, E 2792 // F = setle 2793 // or C, F 2794 // jnz foo 2795 // Emit: 2796 // cmp A, B 2797 // je foo 2798 // cmp D, E 2799 // jle foo 2800 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2801 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2802 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2803 Value *Vec; 2804 const Value *BOp0, *BOp1; 2805 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2806 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2807 Opcode = Instruction::And; 2808 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2809 Opcode = Instruction::Or; 2810 2811 if (Opcode && 2812 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2813 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) && 2814 !shouldKeepJumpConditionsTogether( 2815 FuncInfo, I, Opcode, BOp0, BOp1, 2816 DAG.getTargetLoweringInfo().getJumpConditionMergingParams( 2817 Opcode, BOp0, BOp1))) { 2818 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2819 getEdgeProbability(BrMBB, Succ0MBB), 2820 getEdgeProbability(BrMBB, Succ1MBB), 2821 /*InvertCond=*/false); 2822 // If the compares in later blocks need to use values not currently 2823 // exported from this block, export them now. This block should always 2824 // be the first entry. 2825 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2826 2827 // Allow some cases to be rejected. 2828 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2829 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2830 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2831 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2832 } 2833 2834 // Emit the branch for this block. 2835 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2836 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2837 return; 2838 } 2839 2840 // Okay, we decided not to do this, remove any inserted MBB's and clear 2841 // SwitchCases. 2842 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2843 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2844 2845 SL->SwitchCases.clear(); 2846 } 2847 } 2848 2849 // Create a CaseBlock record representing this branch. 2850 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2851 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2852 2853 // Use visitSwitchCase to actually insert the fast branch sequence for this 2854 // cond branch. 2855 visitSwitchCase(CB, BrMBB); 2856 } 2857 2858 /// visitSwitchCase - Emits the necessary code to represent a single node in 2859 /// the binary search tree resulting from lowering a switch instruction. 2860 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2861 MachineBasicBlock *SwitchBB) { 2862 SDValue Cond; 2863 SDValue CondLHS = getValue(CB.CmpLHS); 2864 SDLoc dl = CB.DL; 2865 2866 if (CB.CC == ISD::SETTRUE) { 2867 // Branch or fall through to TrueBB. 2868 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2869 SwitchBB->normalizeSuccProbs(); 2870 if (CB.TrueBB != NextBlock(SwitchBB)) { 2871 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2872 DAG.getBasicBlock(CB.TrueBB))); 2873 } 2874 return; 2875 } 2876 2877 auto &TLI = DAG.getTargetLoweringInfo(); 2878 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2879 2880 // Build the setcc now. 2881 if (!CB.CmpMHS) { 2882 // Fold "(X == true)" to X and "(X == false)" to !X to 2883 // handle common cases produced by branch lowering. 2884 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2885 CB.CC == ISD::SETEQ) 2886 Cond = CondLHS; 2887 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2888 CB.CC == ISD::SETEQ) { 2889 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2890 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2891 } else { 2892 SDValue CondRHS = getValue(CB.CmpRHS); 2893 2894 // If a pointer's DAG type is larger than its memory type then the DAG 2895 // values are zero-extended. This breaks signed comparisons so truncate 2896 // back to the underlying type before doing the compare. 2897 if (CondLHS.getValueType() != MemVT) { 2898 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2899 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2900 } 2901 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2902 } 2903 } else { 2904 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2905 2906 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2907 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2908 2909 SDValue CmpOp = getValue(CB.CmpMHS); 2910 EVT VT = CmpOp.getValueType(); 2911 2912 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2913 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2914 ISD::SETLE); 2915 } else { 2916 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2917 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2918 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2919 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2920 } 2921 } 2922 2923 // Update successor info 2924 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2925 // TrueBB and FalseBB are always different unless the incoming IR is 2926 // degenerate. This only happens when running llc on weird IR. 2927 if (CB.TrueBB != CB.FalseBB) 2928 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2929 SwitchBB->normalizeSuccProbs(); 2930 2931 // If the lhs block is the next block, invert the condition so that we can 2932 // fall through to the lhs instead of the rhs block. 2933 if (CB.TrueBB == NextBlock(SwitchBB)) { 2934 std::swap(CB.TrueBB, CB.FalseBB); 2935 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2936 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2937 } 2938 2939 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2940 MVT::Other, getControlRoot(), Cond, 2941 DAG.getBasicBlock(CB.TrueBB)); 2942 2943 setValue(CurInst, BrCond); 2944 2945 // Insert the false branch. Do this even if it's a fall through branch, 2946 // this makes it easier to do DAG optimizations which require inverting 2947 // the branch condition. 2948 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2949 DAG.getBasicBlock(CB.FalseBB)); 2950 2951 DAG.setRoot(BrCond); 2952 } 2953 2954 /// visitJumpTable - Emit JumpTable node in the current MBB 2955 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2956 // Emit the code for the jump table 2957 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2958 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2959 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2960 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy); 2961 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2962 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other, 2963 Index.getValue(1), Table, Index); 2964 DAG.setRoot(BrJumpTable); 2965 } 2966 2967 /// visitJumpTableHeader - This function emits necessary code to produce index 2968 /// in the JumpTable from switch case. 2969 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2970 JumpTableHeader &JTH, 2971 MachineBasicBlock *SwitchBB) { 2972 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2973 const SDLoc &dl = *JT.SL; 2974 2975 // Subtract the lowest switch case value from the value being switched on. 2976 SDValue SwitchOp = getValue(JTH.SValue); 2977 EVT VT = SwitchOp.getValueType(); 2978 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2979 DAG.getConstant(JTH.First, dl, VT)); 2980 2981 // The SDNode we just created, which holds the value being switched on minus 2982 // the smallest case value, needs to be copied to a virtual register so it 2983 // can be used as an index into the jump table in a subsequent basic block. 2984 // This value may be smaller or larger than the target's pointer type, and 2985 // therefore require extension or truncating. 2986 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2987 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2988 2989 unsigned JumpTableReg = 2990 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2991 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2992 JumpTableReg, SwitchOp); 2993 JT.Reg = JumpTableReg; 2994 2995 if (!JTH.FallthroughUnreachable) { 2996 // Emit the range check for the jump table, and branch to the default block 2997 // for the switch statement if the value being switched on exceeds the 2998 // largest case in the switch. 2999 SDValue CMP = DAG.getSetCC( 3000 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3001 Sub.getValueType()), 3002 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 3003 3004 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3005 MVT::Other, CopyTo, CMP, 3006 DAG.getBasicBlock(JT.Default)); 3007 3008 // Avoid emitting unnecessary branches to the next block. 3009 if (JT.MBB != NextBlock(SwitchBB)) 3010 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 3011 DAG.getBasicBlock(JT.MBB)); 3012 3013 DAG.setRoot(BrCond); 3014 } else { 3015 // Avoid emitting unnecessary branches to the next block. 3016 if (JT.MBB != NextBlock(SwitchBB)) 3017 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 3018 DAG.getBasicBlock(JT.MBB))); 3019 else 3020 DAG.setRoot(CopyTo); 3021 } 3022 } 3023 3024 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 3025 /// variable if there exists one. 3026 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 3027 SDValue &Chain) { 3028 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3029 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3030 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3031 MachineFunction &MF = DAG.getMachineFunction(); 3032 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 3033 MachineSDNode *Node = 3034 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 3035 if (Global) { 3036 MachinePointerInfo MPInfo(Global); 3037 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 3038 MachineMemOperand::MODereferenceable; 3039 MachineMemOperand *MemRef = MF.getMachineMemOperand( 3040 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 3041 DAG.setNodeMemRefs(Node, {MemRef}); 3042 } 3043 if (PtrTy != PtrMemTy) 3044 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 3045 return SDValue(Node, 0); 3046 } 3047 3048 /// Codegen a new tail for a stack protector check ParentMBB which has had its 3049 /// tail spliced into a stack protector check success bb. 3050 /// 3051 /// For a high level explanation of how this fits into the stack protector 3052 /// generation see the comment on the declaration of class 3053 /// StackProtectorDescriptor. 3054 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 3055 MachineBasicBlock *ParentBB) { 3056 3057 // First create the loads to the guard/stack slot for the comparison. 3058 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3059 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3060 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3061 3062 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 3063 int FI = MFI.getStackProtectorIndex(); 3064 3065 SDValue Guard; 3066 SDLoc dl = getCurSDLoc(); 3067 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 3068 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 3069 Align Align = 3070 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 3071 3072 // Generate code to load the content of the guard slot. 3073 SDValue GuardVal = DAG.getLoad( 3074 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 3075 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 3076 MachineMemOperand::MOVolatile); 3077 3078 if (TLI.useStackGuardXorFP()) 3079 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 3080 3081 // Retrieve guard check function, nullptr if instrumentation is inlined. 3082 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 3083 // The target provides a guard check function to validate the guard value. 3084 // Generate a call to that function with the content of the guard slot as 3085 // argument. 3086 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 3087 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 3088 3089 TargetLowering::ArgListTy Args; 3090 TargetLowering::ArgListEntry Entry; 3091 Entry.Node = GuardVal; 3092 Entry.Ty = FnTy->getParamType(0); 3093 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 3094 Entry.IsInReg = true; 3095 Args.push_back(Entry); 3096 3097 TargetLowering::CallLoweringInfo CLI(DAG); 3098 CLI.setDebugLoc(getCurSDLoc()) 3099 .setChain(DAG.getEntryNode()) 3100 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 3101 getValue(GuardCheckFn), std::move(Args)); 3102 3103 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 3104 DAG.setRoot(Result.second); 3105 return; 3106 } 3107 3108 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 3109 // Otherwise, emit a volatile load to retrieve the stack guard value. 3110 SDValue Chain = DAG.getEntryNode(); 3111 if (TLI.useLoadStackGuardNode()) { 3112 Guard = getLoadStackGuard(DAG, dl, Chain); 3113 } else { 3114 const Value *IRGuard = TLI.getSDagStackGuard(M); 3115 SDValue GuardPtr = getValue(IRGuard); 3116 3117 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 3118 MachinePointerInfo(IRGuard, 0), Align, 3119 MachineMemOperand::MOVolatile); 3120 } 3121 3122 // Perform the comparison via a getsetcc. 3123 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 3124 *DAG.getContext(), 3125 Guard.getValueType()), 3126 Guard, GuardVal, ISD::SETNE); 3127 3128 // If the guard/stackslot do not equal, branch to failure MBB. 3129 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3130 MVT::Other, GuardVal.getOperand(0), 3131 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 3132 // Otherwise branch to success MBB. 3133 SDValue Br = DAG.getNode(ISD::BR, dl, 3134 MVT::Other, BrCond, 3135 DAG.getBasicBlock(SPD.getSuccessMBB())); 3136 3137 DAG.setRoot(Br); 3138 } 3139 3140 /// Codegen the failure basic block for a stack protector check. 3141 /// 3142 /// A failure stack protector machine basic block consists simply of a call to 3143 /// __stack_chk_fail(). 3144 /// 3145 /// For a high level explanation of how this fits into the stack protector 3146 /// generation see the comment on the declaration of class 3147 /// StackProtectorDescriptor. 3148 void 3149 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 3150 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3151 TargetLowering::MakeLibCallOptions CallOptions; 3152 CallOptions.setDiscardResult(true); 3153 SDValue Chain = 3154 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 3155 std::nullopt, CallOptions, getCurSDLoc()) 3156 .second; 3157 // On PS4/PS5, the "return address" must still be within the calling 3158 // function, even if it's at the very end, so emit an explicit TRAP here. 3159 // Passing 'true' for doesNotReturn above won't generate the trap for us. 3160 if (TM.getTargetTriple().isPS()) 3161 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3162 // WebAssembly needs an unreachable instruction after a non-returning call, 3163 // because the function return type can be different from __stack_chk_fail's 3164 // return type (void). 3165 if (TM.getTargetTriple().isWasm()) 3166 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3167 3168 DAG.setRoot(Chain); 3169 } 3170 3171 /// visitBitTestHeader - This function emits necessary code to produce value 3172 /// suitable for "bit tests" 3173 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 3174 MachineBasicBlock *SwitchBB) { 3175 SDLoc dl = getCurSDLoc(); 3176 3177 // Subtract the minimum value. 3178 SDValue SwitchOp = getValue(B.SValue); 3179 EVT VT = SwitchOp.getValueType(); 3180 SDValue RangeSub = 3181 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 3182 3183 // Determine the type of the test operands. 3184 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3185 bool UsePtrType = false; 3186 if (!TLI.isTypeLegal(VT)) { 3187 UsePtrType = true; 3188 } else { 3189 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 3190 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 3191 // Switch table case range are encoded into series of masks. 3192 // Just use pointer type, it's guaranteed to fit. 3193 UsePtrType = true; 3194 break; 3195 } 3196 } 3197 SDValue Sub = RangeSub; 3198 if (UsePtrType) { 3199 VT = TLI.getPointerTy(DAG.getDataLayout()); 3200 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 3201 } 3202 3203 B.RegVT = VT.getSimpleVT(); 3204 B.Reg = FuncInfo.CreateReg(B.RegVT); 3205 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 3206 3207 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 3208 3209 if (!B.FallthroughUnreachable) 3210 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 3211 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 3212 SwitchBB->normalizeSuccProbs(); 3213 3214 SDValue Root = CopyTo; 3215 if (!B.FallthroughUnreachable) { 3216 // Conditional branch to the default block. 3217 SDValue RangeCmp = DAG.getSetCC(dl, 3218 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3219 RangeSub.getValueType()), 3220 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 3221 ISD::SETUGT); 3222 3223 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 3224 DAG.getBasicBlock(B.Default)); 3225 } 3226 3227 // Avoid emitting unnecessary branches to the next block. 3228 if (MBB != NextBlock(SwitchBB)) 3229 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 3230 3231 DAG.setRoot(Root); 3232 } 3233 3234 /// visitBitTestCase - this function produces one "bit test" 3235 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 3236 MachineBasicBlock* NextMBB, 3237 BranchProbability BranchProbToNext, 3238 unsigned Reg, 3239 BitTestCase &B, 3240 MachineBasicBlock *SwitchBB) { 3241 SDLoc dl = getCurSDLoc(); 3242 MVT VT = BB.RegVT; 3243 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 3244 SDValue Cmp; 3245 unsigned PopCount = llvm::popcount(B.Mask); 3246 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3247 if (PopCount == 1) { 3248 // Testing for a single bit; just compare the shift count with what it 3249 // would need to be to shift a 1 bit in that position. 3250 Cmp = DAG.getSetCC( 3251 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3252 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 3253 ISD::SETEQ); 3254 } else if (PopCount == BB.Range) { 3255 // There is only one zero bit in the range, test for it directly. 3256 Cmp = DAG.getSetCC( 3257 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3258 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 3259 } else { 3260 // Make desired shift 3261 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 3262 DAG.getConstant(1, dl, VT), ShiftOp); 3263 3264 // Emit bit tests and jumps 3265 SDValue AndOp = DAG.getNode(ISD::AND, dl, 3266 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 3267 Cmp = DAG.getSetCC( 3268 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3269 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 3270 } 3271 3272 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 3273 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 3274 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 3275 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 3276 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 3277 // one as they are relative probabilities (and thus work more like weights), 3278 // and hence we need to normalize them to let the sum of them become one. 3279 SwitchBB->normalizeSuccProbs(); 3280 3281 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 3282 MVT::Other, getControlRoot(), 3283 Cmp, DAG.getBasicBlock(B.TargetBB)); 3284 3285 // Avoid emitting unnecessary branches to the next block. 3286 if (NextMBB != NextBlock(SwitchBB)) 3287 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 3288 DAG.getBasicBlock(NextMBB)); 3289 3290 DAG.setRoot(BrAnd); 3291 } 3292 3293 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3294 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3295 3296 // Retrieve successors. Look through artificial IR level blocks like 3297 // catchswitch for successors. 3298 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 3299 const BasicBlock *EHPadBB = I.getSuccessor(1); 3300 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 3301 3302 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3303 // have to do anything here to lower funclet bundles. 3304 assert(!I.hasOperandBundlesOtherThan( 3305 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3306 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3307 LLVMContext::OB_cfguardtarget, 3308 LLVMContext::OB_clang_arc_attachedcall}) && 3309 "Cannot lower invokes with arbitrary operand bundles yet!"); 3310 3311 const Value *Callee(I.getCalledOperand()); 3312 const Function *Fn = dyn_cast<Function>(Callee); 3313 if (isa<InlineAsm>(Callee)) 3314 visitInlineAsm(I, EHPadBB); 3315 else if (Fn && Fn->isIntrinsic()) { 3316 switch (Fn->getIntrinsicID()) { 3317 default: 3318 llvm_unreachable("Cannot invoke this intrinsic"); 3319 case Intrinsic::donothing: 3320 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3321 case Intrinsic::seh_try_begin: 3322 case Intrinsic::seh_scope_begin: 3323 case Intrinsic::seh_try_end: 3324 case Intrinsic::seh_scope_end: 3325 if (EHPadMBB) 3326 // a block referenced by EH table 3327 // so dtor-funclet not removed by opts 3328 EHPadMBB->setMachineBlockAddressTaken(); 3329 break; 3330 case Intrinsic::experimental_patchpoint_void: 3331 case Intrinsic::experimental_patchpoint_i64: 3332 visitPatchpoint(I, EHPadBB); 3333 break; 3334 case Intrinsic::experimental_gc_statepoint: 3335 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3336 break; 3337 case Intrinsic::wasm_rethrow: { 3338 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3339 // special because it can be invoked, so we manually lower it to a DAG 3340 // node here. 3341 SmallVector<SDValue, 8> Ops; 3342 Ops.push_back(getRoot()); // inchain 3343 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3344 Ops.push_back( 3345 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3346 TLI.getPointerTy(DAG.getDataLayout()))); 3347 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3348 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3349 break; 3350 } 3351 } 3352 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3353 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3354 // Eventually we will support lowering the @llvm.experimental.deoptimize 3355 // intrinsic, and right now there are no plans to support other intrinsics 3356 // with deopt state. 3357 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3358 } else { 3359 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3360 } 3361 3362 // If the value of the invoke is used outside of its defining block, make it 3363 // available as a virtual register. 3364 // We already took care of the exported value for the statepoint instruction 3365 // during call to the LowerStatepoint. 3366 if (!isa<GCStatepointInst>(I)) { 3367 CopyToExportRegsIfNeeded(&I); 3368 } 3369 3370 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3371 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3372 BranchProbability EHPadBBProb = 3373 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3374 : BranchProbability::getZero(); 3375 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3376 3377 // Update successor info. 3378 addSuccessorWithProb(InvokeMBB, Return); 3379 for (auto &UnwindDest : UnwindDests) { 3380 UnwindDest.first->setIsEHPad(); 3381 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3382 } 3383 InvokeMBB->normalizeSuccProbs(); 3384 3385 // Drop into normal successor. 3386 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3387 DAG.getBasicBlock(Return))); 3388 } 3389 3390 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3391 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3392 3393 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3394 // have to do anything here to lower funclet bundles. 3395 assert(!I.hasOperandBundlesOtherThan( 3396 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3397 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3398 3399 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3400 visitInlineAsm(I); 3401 CopyToExportRegsIfNeeded(&I); 3402 3403 // Retrieve successors. 3404 SmallPtrSet<BasicBlock *, 8> Dests; 3405 Dests.insert(I.getDefaultDest()); 3406 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3407 3408 // Update successor info. 3409 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3410 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3411 BasicBlock *Dest = I.getIndirectDest(i); 3412 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3413 Target->setIsInlineAsmBrIndirectTarget(); 3414 Target->setMachineBlockAddressTaken(); 3415 Target->setLabelMustBeEmitted(); 3416 // Don't add duplicate machine successors. 3417 if (Dests.insert(Dest).second) 3418 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3419 } 3420 CallBrMBB->normalizeSuccProbs(); 3421 3422 // Drop into default successor. 3423 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3424 MVT::Other, getControlRoot(), 3425 DAG.getBasicBlock(Return))); 3426 } 3427 3428 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3429 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3430 } 3431 3432 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3433 assert(FuncInfo.MBB->isEHPad() && 3434 "Call to landingpad not in landing pad!"); 3435 3436 // If there aren't registers to copy the values into (e.g., during SjLj 3437 // exceptions), then don't bother to create these DAG nodes. 3438 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3439 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3440 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3441 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3442 return; 3443 3444 // If landingpad's return type is token type, we don't create DAG nodes 3445 // for its exception pointer and selector value. The extraction of exception 3446 // pointer or selector value from token type landingpads is not currently 3447 // supported. 3448 if (LP.getType()->isTokenTy()) 3449 return; 3450 3451 SmallVector<EVT, 2> ValueVTs; 3452 SDLoc dl = getCurSDLoc(); 3453 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3454 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3455 3456 // Get the two live-in registers as SDValues. The physregs have already been 3457 // copied into virtual registers. 3458 SDValue Ops[2]; 3459 if (FuncInfo.ExceptionPointerVirtReg) { 3460 Ops[0] = DAG.getZExtOrTrunc( 3461 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3462 FuncInfo.ExceptionPointerVirtReg, 3463 TLI.getPointerTy(DAG.getDataLayout())), 3464 dl, ValueVTs[0]); 3465 } else { 3466 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3467 } 3468 Ops[1] = DAG.getZExtOrTrunc( 3469 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3470 FuncInfo.ExceptionSelectorVirtReg, 3471 TLI.getPointerTy(DAG.getDataLayout())), 3472 dl, ValueVTs[1]); 3473 3474 // Merge into one. 3475 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3476 DAG.getVTList(ValueVTs), Ops); 3477 setValue(&LP, Res); 3478 } 3479 3480 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3481 MachineBasicBlock *Last) { 3482 // Update JTCases. 3483 for (JumpTableBlock &JTB : SL->JTCases) 3484 if (JTB.first.HeaderBB == First) 3485 JTB.first.HeaderBB = Last; 3486 3487 // Update BitTestCases. 3488 for (BitTestBlock &BTB : SL->BitTestCases) 3489 if (BTB.Parent == First) 3490 BTB.Parent = Last; 3491 } 3492 3493 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3494 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3495 3496 // Update machine-CFG edges with unique successors. 3497 SmallSet<BasicBlock*, 32> Done; 3498 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3499 BasicBlock *BB = I.getSuccessor(i); 3500 bool Inserted = Done.insert(BB).second; 3501 if (!Inserted) 3502 continue; 3503 3504 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3505 addSuccessorWithProb(IndirectBrMBB, Succ); 3506 } 3507 IndirectBrMBB->normalizeSuccProbs(); 3508 3509 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3510 MVT::Other, getControlRoot(), 3511 getValue(I.getAddress()))); 3512 } 3513 3514 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3515 if (!DAG.getTarget().Options.TrapUnreachable) 3516 return; 3517 3518 // We may be able to ignore unreachable behind a noreturn call. 3519 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3520 if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) { 3521 if (Call->doesNotReturn()) 3522 return; 3523 } 3524 } 3525 3526 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3527 } 3528 3529 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3530 SDNodeFlags Flags; 3531 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3532 Flags.copyFMF(*FPOp); 3533 3534 SDValue Op = getValue(I.getOperand(0)); 3535 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3536 Op, Flags); 3537 setValue(&I, UnNodeValue); 3538 } 3539 3540 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3541 SDNodeFlags Flags; 3542 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3543 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3544 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3545 } 3546 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3547 Flags.setExact(ExactOp->isExact()); 3548 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I)) 3549 Flags.setDisjoint(DisjointOp->isDisjoint()); 3550 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3551 Flags.copyFMF(*FPOp); 3552 3553 SDValue Op1 = getValue(I.getOperand(0)); 3554 SDValue Op2 = getValue(I.getOperand(1)); 3555 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3556 Op1, Op2, Flags); 3557 setValue(&I, BinNodeValue); 3558 } 3559 3560 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3561 SDValue Op1 = getValue(I.getOperand(0)); 3562 SDValue Op2 = getValue(I.getOperand(1)); 3563 3564 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3565 Op1.getValueType(), DAG.getDataLayout()); 3566 3567 // Coerce the shift amount to the right type if we can. This exposes the 3568 // truncate or zext to optimization early. 3569 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3570 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3571 "Unexpected shift type"); 3572 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3573 } 3574 3575 bool nuw = false; 3576 bool nsw = false; 3577 bool exact = false; 3578 3579 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3580 3581 if (const OverflowingBinaryOperator *OFBinOp = 3582 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3583 nuw = OFBinOp->hasNoUnsignedWrap(); 3584 nsw = OFBinOp->hasNoSignedWrap(); 3585 } 3586 if (const PossiblyExactOperator *ExactOp = 3587 dyn_cast<const PossiblyExactOperator>(&I)) 3588 exact = ExactOp->isExact(); 3589 } 3590 SDNodeFlags Flags; 3591 Flags.setExact(exact); 3592 Flags.setNoSignedWrap(nsw); 3593 Flags.setNoUnsignedWrap(nuw); 3594 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3595 Flags); 3596 setValue(&I, Res); 3597 } 3598 3599 void SelectionDAGBuilder::visitSDiv(const User &I) { 3600 SDValue Op1 = getValue(I.getOperand(0)); 3601 SDValue Op2 = getValue(I.getOperand(1)); 3602 3603 SDNodeFlags Flags; 3604 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3605 cast<PossiblyExactOperator>(&I)->isExact()); 3606 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3607 Op2, Flags)); 3608 } 3609 3610 void SelectionDAGBuilder::visitICmp(const User &I) { 3611 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3612 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3613 predicate = IC->getPredicate(); 3614 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3615 predicate = ICmpInst::Predicate(IC->getPredicate()); 3616 SDValue Op1 = getValue(I.getOperand(0)); 3617 SDValue Op2 = getValue(I.getOperand(1)); 3618 ISD::CondCode Opcode = getICmpCondCode(predicate); 3619 3620 auto &TLI = DAG.getTargetLoweringInfo(); 3621 EVT MemVT = 3622 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3623 3624 // If a pointer's DAG type is larger than its memory type then the DAG values 3625 // are zero-extended. This breaks signed comparisons so truncate back to the 3626 // underlying type before doing the compare. 3627 if (Op1.getValueType() != MemVT) { 3628 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3629 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3630 } 3631 3632 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3633 I.getType()); 3634 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3635 } 3636 3637 void SelectionDAGBuilder::visitFCmp(const User &I) { 3638 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3639 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3640 predicate = FC->getPredicate(); 3641 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3642 predicate = FCmpInst::Predicate(FC->getPredicate()); 3643 SDValue Op1 = getValue(I.getOperand(0)); 3644 SDValue Op2 = getValue(I.getOperand(1)); 3645 3646 ISD::CondCode Condition = getFCmpCondCode(predicate); 3647 auto *FPMO = cast<FPMathOperator>(&I); 3648 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3649 Condition = getFCmpCodeWithoutNaN(Condition); 3650 3651 SDNodeFlags Flags; 3652 Flags.copyFMF(*FPMO); 3653 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3654 3655 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3656 I.getType()); 3657 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3658 } 3659 3660 // Check if the condition of the select has one use or two users that are both 3661 // selects with the same condition. 3662 static bool hasOnlySelectUsers(const Value *Cond) { 3663 return llvm::all_of(Cond->users(), [](const Value *V) { 3664 return isa<SelectInst>(V); 3665 }); 3666 } 3667 3668 void SelectionDAGBuilder::visitSelect(const User &I) { 3669 SmallVector<EVT, 4> ValueVTs; 3670 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3671 ValueVTs); 3672 unsigned NumValues = ValueVTs.size(); 3673 if (NumValues == 0) return; 3674 3675 SmallVector<SDValue, 4> Values(NumValues); 3676 SDValue Cond = getValue(I.getOperand(0)); 3677 SDValue LHSVal = getValue(I.getOperand(1)); 3678 SDValue RHSVal = getValue(I.getOperand(2)); 3679 SmallVector<SDValue, 1> BaseOps(1, Cond); 3680 ISD::NodeType OpCode = 3681 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3682 3683 bool IsUnaryAbs = false; 3684 bool Negate = false; 3685 3686 SDNodeFlags Flags; 3687 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3688 Flags.copyFMF(*FPOp); 3689 3690 Flags.setUnpredictable( 3691 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3692 3693 // Min/max matching is only viable if all output VTs are the same. 3694 if (all_equal(ValueVTs)) { 3695 EVT VT = ValueVTs[0]; 3696 LLVMContext &Ctx = *DAG.getContext(); 3697 auto &TLI = DAG.getTargetLoweringInfo(); 3698 3699 // We care about the legality of the operation after it has been type 3700 // legalized. 3701 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3702 VT = TLI.getTypeToTransformTo(Ctx, VT); 3703 3704 // If the vselect is legal, assume we want to leave this as a vector setcc + 3705 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3706 // min/max is legal on the scalar type. 3707 bool UseScalarMinMax = VT.isVector() && 3708 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3709 3710 // ValueTracking's select pattern matching does not account for -0.0, 3711 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3712 // -0.0 is less than +0.0. 3713 Value *LHS, *RHS; 3714 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3715 ISD::NodeType Opc = ISD::DELETED_NODE; 3716 switch (SPR.Flavor) { 3717 case SPF_UMAX: Opc = ISD::UMAX; break; 3718 case SPF_UMIN: Opc = ISD::UMIN; break; 3719 case SPF_SMAX: Opc = ISD::SMAX; break; 3720 case SPF_SMIN: Opc = ISD::SMIN; break; 3721 case SPF_FMINNUM: 3722 switch (SPR.NaNBehavior) { 3723 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3724 case SPNB_RETURNS_NAN: break; 3725 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3726 case SPNB_RETURNS_ANY: 3727 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3728 (UseScalarMinMax && 3729 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3730 Opc = ISD::FMINNUM; 3731 break; 3732 } 3733 break; 3734 case SPF_FMAXNUM: 3735 switch (SPR.NaNBehavior) { 3736 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3737 case SPNB_RETURNS_NAN: break; 3738 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3739 case SPNB_RETURNS_ANY: 3740 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3741 (UseScalarMinMax && 3742 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3743 Opc = ISD::FMAXNUM; 3744 break; 3745 } 3746 break; 3747 case SPF_NABS: 3748 Negate = true; 3749 [[fallthrough]]; 3750 case SPF_ABS: 3751 IsUnaryAbs = true; 3752 Opc = ISD::ABS; 3753 break; 3754 default: break; 3755 } 3756 3757 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3758 (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) || 3759 (UseScalarMinMax && 3760 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3761 // If the underlying comparison instruction is used by any other 3762 // instruction, the consumed instructions won't be destroyed, so it is 3763 // not profitable to convert to a min/max. 3764 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3765 OpCode = Opc; 3766 LHSVal = getValue(LHS); 3767 RHSVal = getValue(RHS); 3768 BaseOps.clear(); 3769 } 3770 3771 if (IsUnaryAbs) { 3772 OpCode = Opc; 3773 LHSVal = getValue(LHS); 3774 BaseOps.clear(); 3775 } 3776 } 3777 3778 if (IsUnaryAbs) { 3779 for (unsigned i = 0; i != NumValues; ++i) { 3780 SDLoc dl = getCurSDLoc(); 3781 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3782 Values[i] = 3783 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3784 if (Negate) 3785 Values[i] = DAG.getNegative(Values[i], dl, VT); 3786 } 3787 } else { 3788 for (unsigned i = 0; i != NumValues; ++i) { 3789 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3790 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3791 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3792 Values[i] = DAG.getNode( 3793 OpCode, getCurSDLoc(), 3794 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3795 } 3796 } 3797 3798 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3799 DAG.getVTList(ValueVTs), Values)); 3800 } 3801 3802 void SelectionDAGBuilder::visitTrunc(const User &I) { 3803 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3804 SDValue N = getValue(I.getOperand(0)); 3805 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3806 I.getType()); 3807 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3808 } 3809 3810 void SelectionDAGBuilder::visitZExt(const User &I) { 3811 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3812 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3813 SDValue N = getValue(I.getOperand(0)); 3814 auto &TLI = DAG.getTargetLoweringInfo(); 3815 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3816 3817 SDNodeFlags Flags; 3818 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3819 Flags.setNonNeg(PNI->hasNonNeg()); 3820 3821 // Eagerly use nonneg information to canonicalize towards sign_extend if 3822 // that is the target's preference. 3823 // TODO: Let the target do this later. 3824 if (Flags.hasNonNeg() && 3825 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3826 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3827 return; 3828 } 3829 3830 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3831 } 3832 3833 void SelectionDAGBuilder::visitSExt(const User &I) { 3834 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3835 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3836 SDValue N = getValue(I.getOperand(0)); 3837 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3838 I.getType()); 3839 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3840 } 3841 3842 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3843 // FPTrunc is never a no-op cast, no need to check 3844 SDValue N = getValue(I.getOperand(0)); 3845 SDLoc dl = getCurSDLoc(); 3846 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3847 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3848 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3849 DAG.getTargetConstant( 3850 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3851 } 3852 3853 void SelectionDAGBuilder::visitFPExt(const User &I) { 3854 // FPExt is never a no-op cast, no need to check 3855 SDValue N = getValue(I.getOperand(0)); 3856 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3857 I.getType()); 3858 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3859 } 3860 3861 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3862 // FPToUI is never a no-op cast, no need to check 3863 SDValue N = getValue(I.getOperand(0)); 3864 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3865 I.getType()); 3866 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3867 } 3868 3869 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3870 // FPToSI is never a no-op cast, no need to check 3871 SDValue N = getValue(I.getOperand(0)); 3872 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3873 I.getType()); 3874 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3875 } 3876 3877 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3878 // UIToFP is never a no-op cast, no need to check 3879 SDValue N = getValue(I.getOperand(0)); 3880 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3881 I.getType()); 3882 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3883 } 3884 3885 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3886 // SIToFP is never a no-op cast, no need to check 3887 SDValue N = getValue(I.getOperand(0)); 3888 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3889 I.getType()); 3890 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3891 } 3892 3893 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3894 // What to do depends on the size of the integer and the size of the pointer. 3895 // We can either truncate, zero extend, or no-op, accordingly. 3896 SDValue N = getValue(I.getOperand(0)); 3897 auto &TLI = DAG.getTargetLoweringInfo(); 3898 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3899 I.getType()); 3900 EVT PtrMemVT = 3901 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3902 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3903 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3904 setValue(&I, N); 3905 } 3906 3907 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3908 // What to do depends on the size of the integer and the size of the pointer. 3909 // We can either truncate, zero extend, or no-op, accordingly. 3910 SDValue N = getValue(I.getOperand(0)); 3911 auto &TLI = DAG.getTargetLoweringInfo(); 3912 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3913 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3914 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3915 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3916 setValue(&I, N); 3917 } 3918 3919 void SelectionDAGBuilder::visitBitCast(const User &I) { 3920 SDValue N = getValue(I.getOperand(0)); 3921 SDLoc dl = getCurSDLoc(); 3922 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3923 I.getType()); 3924 3925 // BitCast assures us that source and destination are the same size so this is 3926 // either a BITCAST or a no-op. 3927 if (DestVT != N.getValueType()) 3928 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3929 DestVT, N)); // convert types. 3930 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3931 // might fold any kind of constant expression to an integer constant and that 3932 // is not what we are looking for. Only recognize a bitcast of a genuine 3933 // constant integer as an opaque constant. 3934 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3935 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3936 /*isOpaque*/true)); 3937 else 3938 setValue(&I, N); // noop cast. 3939 } 3940 3941 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3942 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3943 const Value *SV = I.getOperand(0); 3944 SDValue N = getValue(SV); 3945 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3946 3947 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3948 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3949 3950 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3951 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3952 3953 setValue(&I, N); 3954 } 3955 3956 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3957 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3958 SDValue InVec = getValue(I.getOperand(0)); 3959 SDValue InVal = getValue(I.getOperand(1)); 3960 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3961 TLI.getVectorIdxTy(DAG.getDataLayout())); 3962 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3963 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3964 InVec, InVal, InIdx)); 3965 } 3966 3967 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3968 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3969 SDValue InVec = getValue(I.getOperand(0)); 3970 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3971 TLI.getVectorIdxTy(DAG.getDataLayout())); 3972 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3973 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3974 InVec, InIdx)); 3975 } 3976 3977 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3978 SDValue Src1 = getValue(I.getOperand(0)); 3979 SDValue Src2 = getValue(I.getOperand(1)); 3980 ArrayRef<int> Mask; 3981 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3982 Mask = SVI->getShuffleMask(); 3983 else 3984 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3985 SDLoc DL = getCurSDLoc(); 3986 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3987 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3988 EVT SrcVT = Src1.getValueType(); 3989 3990 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3991 VT.isScalableVector()) { 3992 // Canonical splat form of first element of first input vector. 3993 SDValue FirstElt = 3994 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3995 DAG.getVectorIdxConstant(0, DL)); 3996 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3997 return; 3998 } 3999 4000 // For now, we only handle splats for scalable vectors. 4001 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 4002 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 4003 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 4004 4005 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 4006 unsigned MaskNumElts = Mask.size(); 4007 4008 if (SrcNumElts == MaskNumElts) { 4009 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 4010 return; 4011 } 4012 4013 // Normalize the shuffle vector since mask and vector length don't match. 4014 if (SrcNumElts < MaskNumElts) { 4015 // Mask is longer than the source vectors. We can use concatenate vector to 4016 // make the mask and vectors lengths match. 4017 4018 if (MaskNumElts % SrcNumElts == 0) { 4019 // Mask length is a multiple of the source vector length. 4020 // Check if the shuffle is some kind of concatenation of the input 4021 // vectors. 4022 unsigned NumConcat = MaskNumElts / SrcNumElts; 4023 bool IsConcat = true; 4024 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 4025 for (unsigned i = 0; i != MaskNumElts; ++i) { 4026 int Idx = Mask[i]; 4027 if (Idx < 0) 4028 continue; 4029 // Ensure the indices in each SrcVT sized piece are sequential and that 4030 // the same source is used for the whole piece. 4031 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 4032 (ConcatSrcs[i / SrcNumElts] >= 0 && 4033 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 4034 IsConcat = false; 4035 break; 4036 } 4037 // Remember which source this index came from. 4038 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 4039 } 4040 4041 // The shuffle is concatenating multiple vectors together. Just emit 4042 // a CONCAT_VECTORS operation. 4043 if (IsConcat) { 4044 SmallVector<SDValue, 8> ConcatOps; 4045 for (auto Src : ConcatSrcs) { 4046 if (Src < 0) 4047 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 4048 else if (Src == 0) 4049 ConcatOps.push_back(Src1); 4050 else 4051 ConcatOps.push_back(Src2); 4052 } 4053 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 4054 return; 4055 } 4056 } 4057 4058 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 4059 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 4060 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 4061 PaddedMaskNumElts); 4062 4063 // Pad both vectors with undefs to make them the same length as the mask. 4064 SDValue UndefVal = DAG.getUNDEF(SrcVT); 4065 4066 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 4067 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 4068 MOps1[0] = Src1; 4069 MOps2[0] = Src2; 4070 4071 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 4072 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 4073 4074 // Readjust mask for new input vector length. 4075 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 4076 for (unsigned i = 0; i != MaskNumElts; ++i) { 4077 int Idx = Mask[i]; 4078 if (Idx >= (int)SrcNumElts) 4079 Idx -= SrcNumElts - PaddedMaskNumElts; 4080 MappedOps[i] = Idx; 4081 } 4082 4083 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 4084 4085 // If the concatenated vector was padded, extract a subvector with the 4086 // correct number of elements. 4087 if (MaskNumElts != PaddedMaskNumElts) 4088 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 4089 DAG.getVectorIdxConstant(0, DL)); 4090 4091 setValue(&I, Result); 4092 return; 4093 } 4094 4095 if (SrcNumElts > MaskNumElts) { 4096 // Analyze the access pattern of the vector to see if we can extract 4097 // two subvectors and do the shuffle. 4098 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 4099 bool CanExtract = true; 4100 for (int Idx : Mask) { 4101 unsigned Input = 0; 4102 if (Idx < 0) 4103 continue; 4104 4105 if (Idx >= (int)SrcNumElts) { 4106 Input = 1; 4107 Idx -= SrcNumElts; 4108 } 4109 4110 // If all the indices come from the same MaskNumElts sized portion of 4111 // the sources we can use extract. Also make sure the extract wouldn't 4112 // extract past the end of the source. 4113 int NewStartIdx = alignDown(Idx, MaskNumElts); 4114 if (NewStartIdx + MaskNumElts > SrcNumElts || 4115 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 4116 CanExtract = false; 4117 // Make sure we always update StartIdx as we use it to track if all 4118 // elements are undef. 4119 StartIdx[Input] = NewStartIdx; 4120 } 4121 4122 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 4123 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 4124 return; 4125 } 4126 if (CanExtract) { 4127 // Extract appropriate subvector and generate a vector shuffle 4128 for (unsigned Input = 0; Input < 2; ++Input) { 4129 SDValue &Src = Input == 0 ? Src1 : Src2; 4130 if (StartIdx[Input] < 0) 4131 Src = DAG.getUNDEF(VT); 4132 else { 4133 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 4134 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 4135 } 4136 } 4137 4138 // Calculate new mask. 4139 SmallVector<int, 8> MappedOps(Mask); 4140 for (int &Idx : MappedOps) { 4141 if (Idx >= (int)SrcNumElts) 4142 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 4143 else if (Idx >= 0) 4144 Idx -= StartIdx[0]; 4145 } 4146 4147 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 4148 return; 4149 } 4150 } 4151 4152 // We can't use either concat vectors or extract subvectors so fall back to 4153 // replacing the shuffle with extract and build vector. 4154 // to insert and build vector. 4155 EVT EltVT = VT.getVectorElementType(); 4156 SmallVector<SDValue,8> Ops; 4157 for (int Idx : Mask) { 4158 SDValue Res; 4159 4160 if (Idx < 0) { 4161 Res = DAG.getUNDEF(EltVT); 4162 } else { 4163 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 4164 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 4165 4166 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 4167 DAG.getVectorIdxConstant(Idx, DL)); 4168 } 4169 4170 Ops.push_back(Res); 4171 } 4172 4173 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 4174 } 4175 4176 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 4177 ArrayRef<unsigned> Indices = I.getIndices(); 4178 const Value *Op0 = I.getOperand(0); 4179 const Value *Op1 = I.getOperand(1); 4180 Type *AggTy = I.getType(); 4181 Type *ValTy = Op1->getType(); 4182 bool IntoUndef = isa<UndefValue>(Op0); 4183 bool FromUndef = isa<UndefValue>(Op1); 4184 4185 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4186 4187 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4188 SmallVector<EVT, 4> AggValueVTs; 4189 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 4190 SmallVector<EVT, 4> ValValueVTs; 4191 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4192 4193 unsigned NumAggValues = AggValueVTs.size(); 4194 unsigned NumValValues = ValValueVTs.size(); 4195 SmallVector<SDValue, 4> Values(NumAggValues); 4196 4197 // Ignore an insertvalue that produces an empty object 4198 if (!NumAggValues) { 4199 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4200 return; 4201 } 4202 4203 SDValue Agg = getValue(Op0); 4204 unsigned i = 0; 4205 // Copy the beginning value(s) from the original aggregate. 4206 for (; i != LinearIndex; ++i) 4207 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4208 SDValue(Agg.getNode(), Agg.getResNo() + i); 4209 // Copy values from the inserted value(s). 4210 if (NumValValues) { 4211 SDValue Val = getValue(Op1); 4212 for (; i != LinearIndex + NumValValues; ++i) 4213 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4214 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 4215 } 4216 // Copy remaining value(s) from the original aggregate. 4217 for (; i != NumAggValues; ++i) 4218 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4219 SDValue(Agg.getNode(), Agg.getResNo() + i); 4220 4221 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4222 DAG.getVTList(AggValueVTs), Values)); 4223 } 4224 4225 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 4226 ArrayRef<unsigned> Indices = I.getIndices(); 4227 const Value *Op0 = I.getOperand(0); 4228 Type *AggTy = Op0->getType(); 4229 Type *ValTy = I.getType(); 4230 bool OutOfUndef = isa<UndefValue>(Op0); 4231 4232 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4233 4234 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4235 SmallVector<EVT, 4> ValValueVTs; 4236 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4237 4238 unsigned NumValValues = ValValueVTs.size(); 4239 4240 // Ignore a extractvalue that produces an empty object 4241 if (!NumValValues) { 4242 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4243 return; 4244 } 4245 4246 SmallVector<SDValue, 4> Values(NumValValues); 4247 4248 SDValue Agg = getValue(Op0); 4249 // Copy out the selected value(s). 4250 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 4251 Values[i - LinearIndex] = 4252 OutOfUndef ? 4253 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 4254 SDValue(Agg.getNode(), Agg.getResNo() + i); 4255 4256 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4257 DAG.getVTList(ValValueVTs), Values)); 4258 } 4259 4260 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 4261 Value *Op0 = I.getOperand(0); 4262 // Note that the pointer operand may be a vector of pointers. Take the scalar 4263 // element which holds a pointer. 4264 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 4265 SDValue N = getValue(Op0); 4266 SDLoc dl = getCurSDLoc(); 4267 auto &TLI = DAG.getTargetLoweringInfo(); 4268 4269 // Normalize Vector GEP - all scalar operands should be converted to the 4270 // splat vector. 4271 bool IsVectorGEP = I.getType()->isVectorTy(); 4272 ElementCount VectorElementCount = 4273 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 4274 : ElementCount::getFixed(0); 4275 4276 if (IsVectorGEP && !N.getValueType().isVector()) { 4277 LLVMContext &Context = *DAG.getContext(); 4278 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 4279 N = DAG.getSplat(VT, dl, N); 4280 } 4281 4282 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 4283 GTI != E; ++GTI) { 4284 const Value *Idx = GTI.getOperand(); 4285 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4286 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4287 if (Field) { 4288 // N = N + Offset 4289 uint64_t Offset = 4290 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4291 4292 // In an inbounds GEP with an offset that is nonnegative even when 4293 // interpreted as signed, assume there is no unsigned overflow. 4294 SDNodeFlags Flags; 4295 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 4296 Flags.setNoUnsignedWrap(true); 4297 4298 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4299 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4300 } 4301 } else { 4302 // IdxSize is the width of the arithmetic according to IR semantics. 4303 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4304 // (and fix up the result later). 4305 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4306 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4307 TypeSize ElementSize = 4308 GTI.getSequentialElementStride(DAG.getDataLayout()); 4309 // We intentionally mask away the high bits here; ElementSize may not 4310 // fit in IdxTy. 4311 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4312 bool ElementScalable = ElementSize.isScalable(); 4313 4314 // If this is a scalar constant or a splat vector of constants, 4315 // handle it quickly. 4316 const auto *C = dyn_cast<Constant>(Idx); 4317 if (C && isa<VectorType>(C->getType())) 4318 C = C->getSplatValue(); 4319 4320 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4321 if (CI && CI->isZero()) 4322 continue; 4323 if (CI && !ElementScalable) { 4324 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4325 LLVMContext &Context = *DAG.getContext(); 4326 SDValue OffsVal; 4327 if (IsVectorGEP) 4328 OffsVal = DAG.getConstant( 4329 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4330 else 4331 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4332 4333 // In an inbounds GEP with an offset that is nonnegative even when 4334 // interpreted as signed, assume there is no unsigned overflow. 4335 SDNodeFlags Flags; 4336 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4337 Flags.setNoUnsignedWrap(true); 4338 4339 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4340 4341 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4342 continue; 4343 } 4344 4345 // N = N + Idx * ElementMul; 4346 SDValue IdxN = getValue(Idx); 4347 4348 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4349 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4350 VectorElementCount); 4351 IdxN = DAG.getSplat(VT, dl, IdxN); 4352 } 4353 4354 // If the index is smaller or larger than intptr_t, truncate or extend 4355 // it. 4356 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4357 4358 if (ElementScalable) { 4359 EVT VScaleTy = N.getValueType().getScalarType(); 4360 SDValue VScale = DAG.getNode( 4361 ISD::VSCALE, dl, VScaleTy, 4362 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4363 if (IsVectorGEP) 4364 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4365 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4366 } else { 4367 // If this is a multiply by a power of two, turn it into a shl 4368 // immediately. This is a very common case. 4369 if (ElementMul != 1) { 4370 if (ElementMul.isPowerOf2()) { 4371 unsigned Amt = ElementMul.logBase2(); 4372 IdxN = DAG.getNode(ISD::SHL, dl, 4373 N.getValueType(), IdxN, 4374 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4375 } else { 4376 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4377 IdxN.getValueType()); 4378 IdxN = DAG.getNode(ISD::MUL, dl, 4379 N.getValueType(), IdxN, Scale); 4380 } 4381 } 4382 } 4383 4384 N = DAG.getNode(ISD::ADD, dl, 4385 N.getValueType(), N, IdxN); 4386 } 4387 } 4388 4389 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4390 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4391 if (IsVectorGEP) { 4392 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4393 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4394 } 4395 4396 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4397 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4398 4399 setValue(&I, N); 4400 } 4401 4402 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4403 // If this is a fixed sized alloca in the entry block of the function, 4404 // allocate it statically on the stack. 4405 if (FuncInfo.StaticAllocaMap.count(&I)) 4406 return; // getValue will auto-populate this. 4407 4408 SDLoc dl = getCurSDLoc(); 4409 Type *Ty = I.getAllocatedType(); 4410 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4411 auto &DL = DAG.getDataLayout(); 4412 TypeSize TySize = DL.getTypeAllocSize(Ty); 4413 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4414 4415 SDValue AllocSize = getValue(I.getArraySize()); 4416 4417 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace()); 4418 if (AllocSize.getValueType() != IntPtr) 4419 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4420 4421 if (TySize.isScalable()) 4422 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4423 DAG.getVScale(dl, IntPtr, 4424 APInt(IntPtr.getScalarSizeInBits(), 4425 TySize.getKnownMinValue()))); 4426 else { 4427 SDValue TySizeValue = 4428 DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64)); 4429 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4430 DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr)); 4431 } 4432 4433 // Handle alignment. If the requested alignment is less than or equal to 4434 // the stack alignment, ignore it. If the size is greater than or equal to 4435 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4436 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4437 if (*Alignment <= StackAlign) 4438 Alignment = std::nullopt; 4439 4440 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4441 // Round the size of the allocation up to the stack alignment size 4442 // by add SA-1 to the size. This doesn't overflow because we're computing 4443 // an address inside an alloca. 4444 SDNodeFlags Flags; 4445 Flags.setNoUnsignedWrap(true); 4446 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4447 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4448 4449 // Mask out the low bits for alignment purposes. 4450 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4451 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4452 4453 SDValue Ops[] = { 4454 getRoot(), AllocSize, 4455 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4456 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4457 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4458 setValue(&I, DSA); 4459 DAG.setRoot(DSA.getValue(1)); 4460 4461 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4462 } 4463 4464 static const MDNode *getRangeMetadata(const Instruction &I) { 4465 // If !noundef is not present, then !range violation results in a poison 4466 // value rather than immediate undefined behavior. In theory, transferring 4467 // these annotations to SDAG is fine, but in practice there are key SDAG 4468 // transforms that are known not to be poison-safe, such as folding logical 4469 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4470 // also present. 4471 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4472 return nullptr; 4473 return I.getMetadata(LLVMContext::MD_range); 4474 } 4475 4476 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4477 if (I.isAtomic()) 4478 return visitAtomicLoad(I); 4479 4480 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4481 const Value *SV = I.getOperand(0); 4482 if (TLI.supportSwiftError()) { 4483 // Swifterror values can come from either a function parameter with 4484 // swifterror attribute or an alloca with swifterror attribute. 4485 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4486 if (Arg->hasSwiftErrorAttr()) 4487 return visitLoadFromSwiftError(I); 4488 } 4489 4490 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4491 if (Alloca->isSwiftError()) 4492 return visitLoadFromSwiftError(I); 4493 } 4494 } 4495 4496 SDValue Ptr = getValue(SV); 4497 4498 Type *Ty = I.getType(); 4499 SmallVector<EVT, 4> ValueVTs, MemVTs; 4500 SmallVector<TypeSize, 4> Offsets; 4501 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4502 unsigned NumValues = ValueVTs.size(); 4503 if (NumValues == 0) 4504 return; 4505 4506 Align Alignment = I.getAlign(); 4507 AAMDNodes AAInfo = I.getAAMetadata(); 4508 const MDNode *Ranges = getRangeMetadata(I); 4509 bool isVolatile = I.isVolatile(); 4510 MachineMemOperand::Flags MMOFlags = 4511 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4512 4513 SDValue Root; 4514 bool ConstantMemory = false; 4515 if (isVolatile) 4516 // Serialize volatile loads with other side effects. 4517 Root = getRoot(); 4518 else if (NumValues > MaxParallelChains) 4519 Root = getMemoryRoot(); 4520 else if (AA && 4521 AA->pointsToConstantMemory(MemoryLocation( 4522 SV, 4523 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4524 AAInfo))) { 4525 // Do not serialize (non-volatile) loads of constant memory with anything. 4526 Root = DAG.getEntryNode(); 4527 ConstantMemory = true; 4528 MMOFlags |= MachineMemOperand::MOInvariant; 4529 } else { 4530 // Do not serialize non-volatile loads against each other. 4531 Root = DAG.getRoot(); 4532 } 4533 4534 SDLoc dl = getCurSDLoc(); 4535 4536 if (isVolatile) 4537 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4538 4539 SmallVector<SDValue, 4> Values(NumValues); 4540 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4541 4542 unsigned ChainI = 0; 4543 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4544 // Serializing loads here may result in excessive register pressure, and 4545 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4546 // could recover a bit by hoisting nodes upward in the chain by recognizing 4547 // they are side-effect free or do not alias. The optimizer should really 4548 // avoid this case by converting large object/array copies to llvm.memcpy 4549 // (MaxParallelChains should always remain as failsafe). 4550 if (ChainI == MaxParallelChains) { 4551 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4552 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4553 ArrayRef(Chains.data(), ChainI)); 4554 Root = Chain; 4555 ChainI = 0; 4556 } 4557 4558 // TODO: MachinePointerInfo only supports a fixed length offset. 4559 MachinePointerInfo PtrInfo = 4560 !Offsets[i].isScalable() || Offsets[i].isZero() 4561 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4562 : MachinePointerInfo(); 4563 4564 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4565 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4566 MMOFlags, AAInfo, Ranges); 4567 Chains[ChainI] = L.getValue(1); 4568 4569 if (MemVTs[i] != ValueVTs[i]) 4570 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4571 4572 Values[i] = L; 4573 } 4574 4575 if (!ConstantMemory) { 4576 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4577 ArrayRef(Chains.data(), ChainI)); 4578 if (isVolatile) 4579 DAG.setRoot(Chain); 4580 else 4581 PendingLoads.push_back(Chain); 4582 } 4583 4584 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4585 DAG.getVTList(ValueVTs), Values)); 4586 } 4587 4588 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4589 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4590 "call visitStoreToSwiftError when backend supports swifterror"); 4591 4592 SmallVector<EVT, 4> ValueVTs; 4593 SmallVector<uint64_t, 4> Offsets; 4594 const Value *SrcV = I.getOperand(0); 4595 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4596 SrcV->getType(), ValueVTs, &Offsets, 0); 4597 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4598 "expect a single EVT for swifterror"); 4599 4600 SDValue Src = getValue(SrcV); 4601 // Create a virtual register, then update the virtual register. 4602 Register VReg = 4603 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4604 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4605 // Chain can be getRoot or getControlRoot. 4606 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4607 SDValue(Src.getNode(), Src.getResNo())); 4608 DAG.setRoot(CopyNode); 4609 } 4610 4611 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4612 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4613 "call visitLoadFromSwiftError when backend supports swifterror"); 4614 4615 assert(!I.isVolatile() && 4616 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4617 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4618 "Support volatile, non temporal, invariant for load_from_swift_error"); 4619 4620 const Value *SV = I.getOperand(0); 4621 Type *Ty = I.getType(); 4622 assert( 4623 (!AA || 4624 !AA->pointsToConstantMemory(MemoryLocation( 4625 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4626 I.getAAMetadata()))) && 4627 "load_from_swift_error should not be constant memory"); 4628 4629 SmallVector<EVT, 4> ValueVTs; 4630 SmallVector<uint64_t, 4> Offsets; 4631 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4632 ValueVTs, &Offsets, 0); 4633 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4634 "expect a single EVT for swifterror"); 4635 4636 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4637 SDValue L = DAG.getCopyFromReg( 4638 getRoot(), getCurSDLoc(), 4639 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4640 4641 setValue(&I, L); 4642 } 4643 4644 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4645 if (I.isAtomic()) 4646 return visitAtomicStore(I); 4647 4648 const Value *SrcV = I.getOperand(0); 4649 const Value *PtrV = I.getOperand(1); 4650 4651 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4652 if (TLI.supportSwiftError()) { 4653 // Swifterror values can come from either a function parameter with 4654 // swifterror attribute or an alloca with swifterror attribute. 4655 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4656 if (Arg->hasSwiftErrorAttr()) 4657 return visitStoreToSwiftError(I); 4658 } 4659 4660 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4661 if (Alloca->isSwiftError()) 4662 return visitStoreToSwiftError(I); 4663 } 4664 } 4665 4666 SmallVector<EVT, 4> ValueVTs, MemVTs; 4667 SmallVector<TypeSize, 4> Offsets; 4668 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4669 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4670 unsigned NumValues = ValueVTs.size(); 4671 if (NumValues == 0) 4672 return; 4673 4674 // Get the lowered operands. Note that we do this after 4675 // checking if NumResults is zero, because with zero results 4676 // the operands won't have values in the map. 4677 SDValue Src = getValue(SrcV); 4678 SDValue Ptr = getValue(PtrV); 4679 4680 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4681 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4682 SDLoc dl = getCurSDLoc(); 4683 Align Alignment = I.getAlign(); 4684 AAMDNodes AAInfo = I.getAAMetadata(); 4685 4686 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4687 4688 unsigned ChainI = 0; 4689 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4690 // See visitLoad comments. 4691 if (ChainI == MaxParallelChains) { 4692 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4693 ArrayRef(Chains.data(), ChainI)); 4694 Root = Chain; 4695 ChainI = 0; 4696 } 4697 4698 // TODO: MachinePointerInfo only supports a fixed length offset. 4699 MachinePointerInfo PtrInfo = 4700 !Offsets[i].isScalable() || Offsets[i].isZero() 4701 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4702 : MachinePointerInfo(); 4703 4704 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4705 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4706 if (MemVTs[i] != ValueVTs[i]) 4707 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4708 SDValue St = 4709 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4710 Chains[ChainI] = St; 4711 } 4712 4713 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4714 ArrayRef(Chains.data(), ChainI)); 4715 setValue(&I, StoreNode); 4716 DAG.setRoot(StoreNode); 4717 } 4718 4719 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4720 bool IsCompressing) { 4721 SDLoc sdl = getCurSDLoc(); 4722 4723 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4724 MaybeAlign &Alignment) { 4725 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4726 Src0 = I.getArgOperand(0); 4727 Ptr = I.getArgOperand(1); 4728 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4729 Mask = I.getArgOperand(3); 4730 }; 4731 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4732 MaybeAlign &Alignment) { 4733 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4734 Src0 = I.getArgOperand(0); 4735 Ptr = I.getArgOperand(1); 4736 Mask = I.getArgOperand(2); 4737 Alignment = std::nullopt; 4738 }; 4739 4740 Value *PtrOperand, *MaskOperand, *Src0Operand; 4741 MaybeAlign Alignment; 4742 if (IsCompressing) 4743 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4744 else 4745 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4746 4747 SDValue Ptr = getValue(PtrOperand); 4748 SDValue Src0 = getValue(Src0Operand); 4749 SDValue Mask = getValue(MaskOperand); 4750 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4751 4752 EVT VT = Src0.getValueType(); 4753 if (!Alignment) 4754 Alignment = DAG.getEVTAlign(VT); 4755 4756 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4757 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4758 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4759 SDValue StoreNode = 4760 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4761 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4762 DAG.setRoot(StoreNode); 4763 setValue(&I, StoreNode); 4764 } 4765 4766 // Get a uniform base for the Gather/Scatter intrinsic. 4767 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4768 // We try to represent it as a base pointer + vector of indices. 4769 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4770 // The first operand of the GEP may be a single pointer or a vector of pointers 4771 // Example: 4772 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4773 // or 4774 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4775 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4776 // 4777 // When the first GEP operand is a single pointer - it is the uniform base we 4778 // are looking for. If first operand of the GEP is a splat vector - we 4779 // extract the splat value and use it as a uniform base. 4780 // In all other cases the function returns 'false'. 4781 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4782 ISD::MemIndexType &IndexType, SDValue &Scale, 4783 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4784 uint64_t ElemSize) { 4785 SelectionDAG& DAG = SDB->DAG; 4786 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4787 const DataLayout &DL = DAG.getDataLayout(); 4788 4789 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4790 4791 // Handle splat constant pointer. 4792 if (auto *C = dyn_cast<Constant>(Ptr)) { 4793 C = C->getSplatValue(); 4794 if (!C) 4795 return false; 4796 4797 Base = SDB->getValue(C); 4798 4799 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4800 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4801 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4802 IndexType = ISD::SIGNED_SCALED; 4803 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4804 return true; 4805 } 4806 4807 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4808 if (!GEP || GEP->getParent() != CurBB) 4809 return false; 4810 4811 if (GEP->getNumOperands() != 2) 4812 return false; 4813 4814 const Value *BasePtr = GEP->getPointerOperand(); 4815 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4816 4817 // Make sure the base is scalar and the index is a vector. 4818 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4819 return false; 4820 4821 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4822 if (ScaleVal.isScalable()) 4823 return false; 4824 4825 // Target may not support the required addressing mode. 4826 if (ScaleVal != 1 && 4827 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4828 return false; 4829 4830 Base = SDB->getValue(BasePtr); 4831 Index = SDB->getValue(IndexVal); 4832 IndexType = ISD::SIGNED_SCALED; 4833 4834 Scale = 4835 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4836 return true; 4837 } 4838 4839 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4840 SDLoc sdl = getCurSDLoc(); 4841 4842 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4843 const Value *Ptr = I.getArgOperand(1); 4844 SDValue Src0 = getValue(I.getArgOperand(0)); 4845 SDValue Mask = getValue(I.getArgOperand(3)); 4846 EVT VT = Src0.getValueType(); 4847 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4848 ->getMaybeAlignValue() 4849 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4850 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4851 4852 SDValue Base; 4853 SDValue Index; 4854 ISD::MemIndexType IndexType; 4855 SDValue Scale; 4856 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4857 I.getParent(), VT.getScalarStoreSize()); 4858 4859 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4860 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4861 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4862 // TODO: Make MachineMemOperands aware of scalable 4863 // vectors. 4864 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4865 if (!UniformBase) { 4866 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4867 Index = getValue(Ptr); 4868 IndexType = ISD::SIGNED_SCALED; 4869 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4870 } 4871 4872 EVT IdxVT = Index.getValueType(); 4873 EVT EltTy = IdxVT.getVectorElementType(); 4874 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4875 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4876 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4877 } 4878 4879 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4880 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4881 Ops, MMO, IndexType, false); 4882 DAG.setRoot(Scatter); 4883 setValue(&I, Scatter); 4884 } 4885 4886 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4887 SDLoc sdl = getCurSDLoc(); 4888 4889 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4890 MaybeAlign &Alignment) { 4891 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4892 Ptr = I.getArgOperand(0); 4893 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4894 Mask = I.getArgOperand(2); 4895 Src0 = I.getArgOperand(3); 4896 }; 4897 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4898 MaybeAlign &Alignment) { 4899 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4900 Ptr = I.getArgOperand(0); 4901 Alignment = std::nullopt; 4902 Mask = I.getArgOperand(1); 4903 Src0 = I.getArgOperand(2); 4904 }; 4905 4906 Value *PtrOperand, *MaskOperand, *Src0Operand; 4907 MaybeAlign Alignment; 4908 if (IsExpanding) 4909 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4910 else 4911 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4912 4913 SDValue Ptr = getValue(PtrOperand); 4914 SDValue Src0 = getValue(Src0Operand); 4915 SDValue Mask = getValue(MaskOperand); 4916 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4917 4918 EVT VT = Src0.getValueType(); 4919 if (!Alignment) 4920 Alignment = DAG.getEVTAlign(VT); 4921 4922 AAMDNodes AAInfo = I.getAAMetadata(); 4923 const MDNode *Ranges = getRangeMetadata(I); 4924 4925 // Do not serialize masked loads of constant memory with anything. 4926 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4927 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4928 4929 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4930 4931 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4932 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4933 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4934 4935 SDValue Load = 4936 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4937 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4938 if (AddToChain) 4939 PendingLoads.push_back(Load.getValue(1)); 4940 setValue(&I, Load); 4941 } 4942 4943 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4944 SDLoc sdl = getCurSDLoc(); 4945 4946 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4947 const Value *Ptr = I.getArgOperand(0); 4948 SDValue Src0 = getValue(I.getArgOperand(3)); 4949 SDValue Mask = getValue(I.getArgOperand(2)); 4950 4951 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4952 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4953 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4954 ->getMaybeAlignValue() 4955 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4956 4957 const MDNode *Ranges = getRangeMetadata(I); 4958 4959 SDValue Root = DAG.getRoot(); 4960 SDValue Base; 4961 SDValue Index; 4962 ISD::MemIndexType IndexType; 4963 SDValue Scale; 4964 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4965 I.getParent(), VT.getScalarStoreSize()); 4966 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4967 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4968 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4969 // TODO: Make MachineMemOperands aware of scalable 4970 // vectors. 4971 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4972 4973 if (!UniformBase) { 4974 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4975 Index = getValue(Ptr); 4976 IndexType = ISD::SIGNED_SCALED; 4977 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4978 } 4979 4980 EVT IdxVT = Index.getValueType(); 4981 EVT EltTy = IdxVT.getVectorElementType(); 4982 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4983 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4984 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4985 } 4986 4987 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4988 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4989 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4990 4991 PendingLoads.push_back(Gather.getValue(1)); 4992 setValue(&I, Gather); 4993 } 4994 4995 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4996 SDLoc dl = getCurSDLoc(); 4997 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4998 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4999 SyncScope::ID SSID = I.getSyncScopeID(); 5000 5001 SDValue InChain = getRoot(); 5002 5003 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 5004 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 5005 5006 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5007 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5008 5009 MachineFunction &MF = DAG.getMachineFunction(); 5010 MachineMemOperand *MMO = MF.getMachineMemOperand( 5011 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 5012 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 5013 FailureOrdering); 5014 5015 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 5016 dl, MemVT, VTs, InChain, 5017 getValue(I.getPointerOperand()), 5018 getValue(I.getCompareOperand()), 5019 getValue(I.getNewValOperand()), MMO); 5020 5021 SDValue OutChain = L.getValue(2); 5022 5023 setValue(&I, L); 5024 DAG.setRoot(OutChain); 5025 } 5026 5027 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 5028 SDLoc dl = getCurSDLoc(); 5029 ISD::NodeType NT; 5030 switch (I.getOperation()) { 5031 default: llvm_unreachable("Unknown atomicrmw operation"); 5032 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 5033 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 5034 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 5035 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 5036 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 5037 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 5038 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 5039 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 5040 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 5041 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 5042 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 5043 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 5044 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 5045 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 5046 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 5047 case AtomicRMWInst::UIncWrap: 5048 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 5049 break; 5050 case AtomicRMWInst::UDecWrap: 5051 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 5052 break; 5053 } 5054 AtomicOrdering Ordering = I.getOrdering(); 5055 SyncScope::ID SSID = I.getSyncScopeID(); 5056 5057 SDValue InChain = getRoot(); 5058 5059 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 5060 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5061 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5062 5063 MachineFunction &MF = DAG.getMachineFunction(); 5064 MachineMemOperand *MMO = MF.getMachineMemOperand( 5065 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 5066 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 5067 5068 SDValue L = 5069 DAG.getAtomic(NT, dl, MemVT, InChain, 5070 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 5071 MMO); 5072 5073 SDValue OutChain = L.getValue(1); 5074 5075 setValue(&I, L); 5076 DAG.setRoot(OutChain); 5077 } 5078 5079 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 5080 SDLoc dl = getCurSDLoc(); 5081 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5082 SDValue Ops[3]; 5083 Ops[0] = getRoot(); 5084 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 5085 TLI.getFenceOperandTy(DAG.getDataLayout())); 5086 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 5087 TLI.getFenceOperandTy(DAG.getDataLayout())); 5088 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 5089 setValue(&I, N); 5090 DAG.setRoot(N); 5091 } 5092 5093 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 5094 SDLoc dl = getCurSDLoc(); 5095 AtomicOrdering Order = I.getOrdering(); 5096 SyncScope::ID SSID = I.getSyncScopeID(); 5097 5098 SDValue InChain = getRoot(); 5099 5100 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5101 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5102 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 5103 5104 if (!TLI.supportsUnalignedAtomics() && 5105 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5106 report_fatal_error("Cannot generate unaligned atomic load"); 5107 5108 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 5109 5110 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5111 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 5112 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 5113 5114 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 5115 5116 SDValue Ptr = getValue(I.getPointerOperand()); 5117 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 5118 Ptr, MMO); 5119 5120 SDValue OutChain = L.getValue(1); 5121 if (MemVT != VT) 5122 L = DAG.getPtrExtOrTrunc(L, dl, VT); 5123 5124 setValue(&I, L); 5125 DAG.setRoot(OutChain); 5126 } 5127 5128 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 5129 SDLoc dl = getCurSDLoc(); 5130 5131 AtomicOrdering Ordering = I.getOrdering(); 5132 SyncScope::ID SSID = I.getSyncScopeID(); 5133 5134 SDValue InChain = getRoot(); 5135 5136 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5137 EVT MemVT = 5138 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 5139 5140 if (!TLI.supportsUnalignedAtomics() && 5141 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5142 report_fatal_error("Cannot generate unaligned atomic store"); 5143 5144 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 5145 5146 MachineFunction &MF = DAG.getMachineFunction(); 5147 MachineMemOperand *MMO = MF.getMachineMemOperand( 5148 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 5149 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 5150 5151 SDValue Val = getValue(I.getValueOperand()); 5152 if (Val.getValueType() != MemVT) 5153 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 5154 SDValue Ptr = getValue(I.getPointerOperand()); 5155 5156 SDValue OutChain = 5157 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 5158 5159 setValue(&I, OutChain); 5160 DAG.setRoot(OutChain); 5161 } 5162 5163 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 5164 /// node. 5165 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 5166 unsigned Intrinsic) { 5167 // Ignore the callsite's attributes. A specific call site may be marked with 5168 // readnone, but the lowering code will expect the chain based on the 5169 // definition. 5170 const Function *F = I.getCalledFunction(); 5171 bool HasChain = !F->doesNotAccessMemory(); 5172 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 5173 5174 // Build the operand list. 5175 SmallVector<SDValue, 8> Ops; 5176 if (HasChain) { // If this intrinsic has side-effects, chainify it. 5177 if (OnlyLoad) { 5178 // We don't need to serialize loads against other loads. 5179 Ops.push_back(DAG.getRoot()); 5180 } else { 5181 Ops.push_back(getRoot()); 5182 } 5183 } 5184 5185 // Info is set by getTgtMemIntrinsic 5186 TargetLowering::IntrinsicInfo Info; 5187 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5188 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 5189 DAG.getMachineFunction(), 5190 Intrinsic); 5191 5192 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 5193 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 5194 Info.opc == ISD::INTRINSIC_W_CHAIN) 5195 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 5196 TLI.getPointerTy(DAG.getDataLayout()))); 5197 5198 // Add all operands of the call to the operand list. 5199 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 5200 const Value *Arg = I.getArgOperand(i); 5201 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 5202 Ops.push_back(getValue(Arg)); 5203 continue; 5204 } 5205 5206 // Use TargetConstant instead of a regular constant for immarg. 5207 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 5208 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 5209 assert(CI->getBitWidth() <= 64 && 5210 "large intrinsic immediates not handled"); 5211 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 5212 } else { 5213 Ops.push_back( 5214 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 5215 } 5216 } 5217 5218 SmallVector<EVT, 4> ValueVTs; 5219 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 5220 5221 if (HasChain) 5222 ValueVTs.push_back(MVT::Other); 5223 5224 SDVTList VTs = DAG.getVTList(ValueVTs); 5225 5226 // Propagate fast-math-flags from IR to node(s). 5227 SDNodeFlags Flags; 5228 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 5229 Flags.copyFMF(*FPMO); 5230 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 5231 5232 // Create the node. 5233 SDValue Result; 5234 // In some cases, custom collection of operands from CallInst I may be needed. 5235 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 5236 if (IsTgtIntrinsic) { 5237 // This is target intrinsic that touches memory 5238 // 5239 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 5240 // didn't yield anything useful. 5241 MachinePointerInfo MPI; 5242 if (Info.ptrVal) 5243 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 5244 else if (Info.fallbackAddressSpace) 5245 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 5246 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 5247 Info.memVT, MPI, Info.align, Info.flags, 5248 Info.size, I.getAAMetadata()); 5249 } else if (!HasChain) { 5250 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 5251 } else if (!I.getType()->isVoidTy()) { 5252 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 5253 } else { 5254 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 5255 } 5256 5257 if (HasChain) { 5258 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 5259 if (OnlyLoad) 5260 PendingLoads.push_back(Chain); 5261 else 5262 DAG.setRoot(Chain); 5263 } 5264 5265 if (!I.getType()->isVoidTy()) { 5266 if (!isa<VectorType>(I.getType())) 5267 Result = lowerRangeToAssertZExt(DAG, I, Result); 5268 5269 MaybeAlign Alignment = I.getRetAlign(); 5270 5271 // Insert `assertalign` node if there's an alignment. 5272 if (InsertAssertAlign && Alignment) { 5273 Result = 5274 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5275 } 5276 5277 setValue(&I, Result); 5278 } 5279 } 5280 5281 /// GetSignificand - Get the significand and build it into a floating-point 5282 /// number with exponent of 1: 5283 /// 5284 /// Op = (Op & 0x007fffff) | 0x3f800000; 5285 /// 5286 /// where Op is the hexadecimal representation of floating point value. 5287 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5288 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5289 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5290 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5291 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5292 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5293 } 5294 5295 /// GetExponent - Get the exponent: 5296 /// 5297 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5298 /// 5299 /// where Op is the hexadecimal representation of floating point value. 5300 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5301 const TargetLowering &TLI, const SDLoc &dl) { 5302 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5303 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5304 SDValue t1 = DAG.getNode( 5305 ISD::SRL, dl, MVT::i32, t0, 5306 DAG.getConstant(23, dl, 5307 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5308 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5309 DAG.getConstant(127, dl, MVT::i32)); 5310 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5311 } 5312 5313 /// getF32Constant - Get 32-bit floating point constant. 5314 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5315 const SDLoc &dl) { 5316 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5317 MVT::f32); 5318 } 5319 5320 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5321 SelectionDAG &DAG) { 5322 // TODO: What fast-math-flags should be set on the floating-point nodes? 5323 5324 // IntegerPartOfX = ((int32_t)(t0); 5325 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5326 5327 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5328 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5329 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5330 5331 // IntegerPartOfX <<= 23; 5332 IntegerPartOfX = 5333 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5334 DAG.getConstant(23, dl, 5335 DAG.getTargetLoweringInfo().getShiftAmountTy( 5336 MVT::i32, DAG.getDataLayout()))); 5337 5338 SDValue TwoToFractionalPartOfX; 5339 if (LimitFloatPrecision <= 6) { 5340 // For floating-point precision of 6: 5341 // 5342 // TwoToFractionalPartOfX = 5343 // 0.997535578f + 5344 // (0.735607626f + 0.252464424f * x) * x; 5345 // 5346 // error 0.0144103317, which is 6 bits 5347 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5348 getF32Constant(DAG, 0x3e814304, dl)); 5349 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5350 getF32Constant(DAG, 0x3f3c50c8, dl)); 5351 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5352 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5353 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5354 } else if (LimitFloatPrecision <= 12) { 5355 // For floating-point precision of 12: 5356 // 5357 // TwoToFractionalPartOfX = 5358 // 0.999892986f + 5359 // (0.696457318f + 5360 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5361 // 5362 // error 0.000107046256, which is 13 to 14 bits 5363 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5364 getF32Constant(DAG, 0x3da235e3, dl)); 5365 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5366 getF32Constant(DAG, 0x3e65b8f3, dl)); 5367 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5368 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5369 getF32Constant(DAG, 0x3f324b07, dl)); 5370 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5371 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5372 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5373 } else { // LimitFloatPrecision <= 18 5374 // For floating-point precision of 18: 5375 // 5376 // TwoToFractionalPartOfX = 5377 // 0.999999982f + 5378 // (0.693148872f + 5379 // (0.240227044f + 5380 // (0.554906021e-1f + 5381 // (0.961591928e-2f + 5382 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5383 // error 2.47208000*10^(-7), which is better than 18 bits 5384 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5385 getF32Constant(DAG, 0x3924b03e, dl)); 5386 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5387 getF32Constant(DAG, 0x3ab24b87, dl)); 5388 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5389 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5390 getF32Constant(DAG, 0x3c1d8c17, dl)); 5391 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5392 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5393 getF32Constant(DAG, 0x3d634a1d, dl)); 5394 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5395 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5396 getF32Constant(DAG, 0x3e75fe14, dl)); 5397 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5398 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5399 getF32Constant(DAG, 0x3f317234, dl)); 5400 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5401 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5402 getF32Constant(DAG, 0x3f800000, dl)); 5403 } 5404 5405 // Add the exponent into the result in integer domain. 5406 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5407 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5408 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5409 } 5410 5411 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5412 /// limited-precision mode. 5413 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5414 const TargetLowering &TLI, SDNodeFlags Flags) { 5415 if (Op.getValueType() == MVT::f32 && 5416 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5417 5418 // Put the exponent in the right bit position for later addition to the 5419 // final result: 5420 // 5421 // t0 = Op * log2(e) 5422 5423 // TODO: What fast-math-flags should be set here? 5424 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5425 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5426 return getLimitedPrecisionExp2(t0, dl, DAG); 5427 } 5428 5429 // No special expansion. 5430 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5431 } 5432 5433 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5434 /// limited-precision mode. 5435 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5436 const TargetLowering &TLI, SDNodeFlags Flags) { 5437 // TODO: What fast-math-flags should be set on the floating-point nodes? 5438 5439 if (Op.getValueType() == MVT::f32 && 5440 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5441 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5442 5443 // Scale the exponent by log(2). 5444 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5445 SDValue LogOfExponent = 5446 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5447 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5448 5449 // Get the significand and build it into a floating-point number with 5450 // exponent of 1. 5451 SDValue X = GetSignificand(DAG, Op1, dl); 5452 5453 SDValue LogOfMantissa; 5454 if (LimitFloatPrecision <= 6) { 5455 // For floating-point precision of 6: 5456 // 5457 // LogofMantissa = 5458 // -1.1609546f + 5459 // (1.4034025f - 0.23903021f * x) * x; 5460 // 5461 // error 0.0034276066, which is better than 8 bits 5462 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5463 getF32Constant(DAG, 0xbe74c456, dl)); 5464 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5465 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5466 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5467 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5468 getF32Constant(DAG, 0x3f949a29, dl)); 5469 } else if (LimitFloatPrecision <= 12) { 5470 // For floating-point precision of 12: 5471 // 5472 // LogOfMantissa = 5473 // -1.7417939f + 5474 // (2.8212026f + 5475 // (-1.4699568f + 5476 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5477 // 5478 // error 0.000061011436, which is 14 bits 5479 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5480 getF32Constant(DAG, 0xbd67b6d6, dl)); 5481 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5482 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5483 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5484 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5485 getF32Constant(DAG, 0x3fbc278b, dl)); 5486 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5487 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5488 getF32Constant(DAG, 0x40348e95, dl)); 5489 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5490 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5491 getF32Constant(DAG, 0x3fdef31a, dl)); 5492 } else { // LimitFloatPrecision <= 18 5493 // For floating-point precision of 18: 5494 // 5495 // LogOfMantissa = 5496 // -2.1072184f + 5497 // (4.2372794f + 5498 // (-3.7029485f + 5499 // (2.2781945f + 5500 // (-0.87823314f + 5501 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5502 // 5503 // error 0.0000023660568, which is better than 18 bits 5504 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5505 getF32Constant(DAG, 0xbc91e5ac, dl)); 5506 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5507 getF32Constant(DAG, 0x3e4350aa, dl)); 5508 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5509 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5510 getF32Constant(DAG, 0x3f60d3e3, dl)); 5511 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5512 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5513 getF32Constant(DAG, 0x4011cdf0, dl)); 5514 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5515 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5516 getF32Constant(DAG, 0x406cfd1c, dl)); 5517 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5518 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5519 getF32Constant(DAG, 0x408797cb, dl)); 5520 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5521 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5522 getF32Constant(DAG, 0x4006dcab, dl)); 5523 } 5524 5525 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5526 } 5527 5528 // No special expansion. 5529 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5530 } 5531 5532 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5533 /// limited-precision mode. 5534 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5535 const TargetLowering &TLI, SDNodeFlags Flags) { 5536 // TODO: What fast-math-flags should be set on the floating-point nodes? 5537 5538 if (Op.getValueType() == MVT::f32 && 5539 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5540 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5541 5542 // Get the exponent. 5543 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5544 5545 // Get the significand and build it into a floating-point number with 5546 // exponent of 1. 5547 SDValue X = GetSignificand(DAG, Op1, dl); 5548 5549 // Different possible minimax approximations of significand in 5550 // floating-point for various degrees of accuracy over [1,2]. 5551 SDValue Log2ofMantissa; 5552 if (LimitFloatPrecision <= 6) { 5553 // For floating-point precision of 6: 5554 // 5555 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5556 // 5557 // error 0.0049451742, which is more than 7 bits 5558 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5559 getF32Constant(DAG, 0xbeb08fe0, dl)); 5560 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5561 getF32Constant(DAG, 0x40019463, dl)); 5562 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5563 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5564 getF32Constant(DAG, 0x3fd6633d, dl)); 5565 } else if (LimitFloatPrecision <= 12) { 5566 // For floating-point precision of 12: 5567 // 5568 // Log2ofMantissa = 5569 // -2.51285454f + 5570 // (4.07009056f + 5571 // (-2.12067489f + 5572 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5573 // 5574 // error 0.0000876136000, which is better than 13 bits 5575 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5576 getF32Constant(DAG, 0xbda7262e, dl)); 5577 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5578 getF32Constant(DAG, 0x3f25280b, dl)); 5579 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5580 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5581 getF32Constant(DAG, 0x4007b923, dl)); 5582 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5583 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5584 getF32Constant(DAG, 0x40823e2f, dl)); 5585 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5586 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5587 getF32Constant(DAG, 0x4020d29c, dl)); 5588 } else { // LimitFloatPrecision <= 18 5589 // For floating-point precision of 18: 5590 // 5591 // Log2ofMantissa = 5592 // -3.0400495f + 5593 // (6.1129976f + 5594 // (-5.3420409f + 5595 // (3.2865683f + 5596 // (-1.2669343f + 5597 // (0.27515199f - 5598 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5599 // 5600 // error 0.0000018516, which is better than 18 bits 5601 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5602 getF32Constant(DAG, 0xbcd2769e, dl)); 5603 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5604 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5605 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5606 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5607 getF32Constant(DAG, 0x3fa22ae7, dl)); 5608 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5609 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5610 getF32Constant(DAG, 0x40525723, dl)); 5611 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5612 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5613 getF32Constant(DAG, 0x40aaf200, dl)); 5614 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5615 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5616 getF32Constant(DAG, 0x40c39dad, dl)); 5617 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5618 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5619 getF32Constant(DAG, 0x4042902c, dl)); 5620 } 5621 5622 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5623 } 5624 5625 // No special expansion. 5626 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5627 } 5628 5629 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5630 /// limited-precision mode. 5631 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5632 const TargetLowering &TLI, SDNodeFlags Flags) { 5633 // TODO: What fast-math-flags should be set on the floating-point nodes? 5634 5635 if (Op.getValueType() == MVT::f32 && 5636 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5637 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5638 5639 // Scale the exponent by log10(2) [0.30102999f]. 5640 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5641 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5642 getF32Constant(DAG, 0x3e9a209a, dl)); 5643 5644 // Get the significand and build it into a floating-point number with 5645 // exponent of 1. 5646 SDValue X = GetSignificand(DAG, Op1, dl); 5647 5648 SDValue Log10ofMantissa; 5649 if (LimitFloatPrecision <= 6) { 5650 // For floating-point precision of 6: 5651 // 5652 // Log10ofMantissa = 5653 // -0.50419619f + 5654 // (0.60948995f - 0.10380950f * x) * x; 5655 // 5656 // error 0.0014886165, which is 6 bits 5657 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5658 getF32Constant(DAG, 0xbdd49a13, dl)); 5659 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5660 getF32Constant(DAG, 0x3f1c0789, dl)); 5661 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5662 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5663 getF32Constant(DAG, 0x3f011300, dl)); 5664 } else if (LimitFloatPrecision <= 12) { 5665 // For floating-point precision of 12: 5666 // 5667 // Log10ofMantissa = 5668 // -0.64831180f + 5669 // (0.91751397f + 5670 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5671 // 5672 // error 0.00019228036, which is better than 12 bits 5673 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5674 getF32Constant(DAG, 0x3d431f31, dl)); 5675 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5676 getF32Constant(DAG, 0x3ea21fb2, dl)); 5677 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5678 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5679 getF32Constant(DAG, 0x3f6ae232, dl)); 5680 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5681 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5682 getF32Constant(DAG, 0x3f25f7c3, dl)); 5683 } else { // LimitFloatPrecision <= 18 5684 // For floating-point precision of 18: 5685 // 5686 // Log10ofMantissa = 5687 // -0.84299375f + 5688 // (1.5327582f + 5689 // (-1.0688956f + 5690 // (0.49102474f + 5691 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5692 // 5693 // error 0.0000037995730, which is better than 18 bits 5694 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5695 getF32Constant(DAG, 0x3c5d51ce, dl)); 5696 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5697 getF32Constant(DAG, 0x3e00685a, dl)); 5698 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5699 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5700 getF32Constant(DAG, 0x3efb6798, dl)); 5701 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5702 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5703 getF32Constant(DAG, 0x3f88d192, dl)); 5704 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5705 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5706 getF32Constant(DAG, 0x3fc4316c, dl)); 5707 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5708 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5709 getF32Constant(DAG, 0x3f57ce70, dl)); 5710 } 5711 5712 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5713 } 5714 5715 // No special expansion. 5716 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5717 } 5718 5719 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5720 /// limited-precision mode. 5721 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5722 const TargetLowering &TLI, SDNodeFlags Flags) { 5723 if (Op.getValueType() == MVT::f32 && 5724 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5725 return getLimitedPrecisionExp2(Op, dl, DAG); 5726 5727 // No special expansion. 5728 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5729 } 5730 5731 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5732 /// limited-precision mode with x == 10.0f. 5733 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5734 SelectionDAG &DAG, const TargetLowering &TLI, 5735 SDNodeFlags Flags) { 5736 bool IsExp10 = false; 5737 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5738 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5739 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5740 APFloat Ten(10.0f); 5741 IsExp10 = LHSC->isExactlyValue(Ten); 5742 } 5743 } 5744 5745 // TODO: What fast-math-flags should be set on the FMUL node? 5746 if (IsExp10) { 5747 // Put the exponent in the right bit position for later addition to the 5748 // final result: 5749 // 5750 // #define LOG2OF10 3.3219281f 5751 // t0 = Op * LOG2OF10; 5752 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5753 getF32Constant(DAG, 0x40549a78, dl)); 5754 return getLimitedPrecisionExp2(t0, dl, DAG); 5755 } 5756 5757 // No special expansion. 5758 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5759 } 5760 5761 /// ExpandPowI - Expand a llvm.powi intrinsic. 5762 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5763 SelectionDAG &DAG) { 5764 // If RHS is a constant, we can expand this out to a multiplication tree if 5765 // it's beneficial on the target, otherwise we end up lowering to a call to 5766 // __powidf2 (for example). 5767 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5768 unsigned Val = RHSC->getSExtValue(); 5769 5770 // powi(x, 0) -> 1.0 5771 if (Val == 0) 5772 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5773 5774 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5775 Val, DAG.shouldOptForSize())) { 5776 // Get the exponent as a positive value. 5777 if ((int)Val < 0) 5778 Val = -Val; 5779 // We use the simple binary decomposition method to generate the multiply 5780 // sequence. There are more optimal ways to do this (for example, 5781 // powi(x,15) generates one more multiply than it should), but this has 5782 // the benefit of being both really simple and much better than a libcall. 5783 SDValue Res; // Logically starts equal to 1.0 5784 SDValue CurSquare = LHS; 5785 // TODO: Intrinsics should have fast-math-flags that propagate to these 5786 // nodes. 5787 while (Val) { 5788 if (Val & 1) { 5789 if (Res.getNode()) 5790 Res = 5791 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5792 else 5793 Res = CurSquare; // 1.0*CurSquare. 5794 } 5795 5796 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5797 CurSquare, CurSquare); 5798 Val >>= 1; 5799 } 5800 5801 // If the original was negative, invert the result, producing 1/(x*x*x). 5802 if (RHSC->getSExtValue() < 0) 5803 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5804 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5805 return Res; 5806 } 5807 } 5808 5809 // Otherwise, expand to a libcall. 5810 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5811 } 5812 5813 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5814 SDValue LHS, SDValue RHS, SDValue Scale, 5815 SelectionDAG &DAG, const TargetLowering &TLI) { 5816 EVT VT = LHS.getValueType(); 5817 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5818 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5819 LLVMContext &Ctx = *DAG.getContext(); 5820 5821 // If the type is legal but the operation isn't, this node might survive all 5822 // the way to operation legalization. If we end up there and we do not have 5823 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5824 // node. 5825 5826 // Coax the legalizer into expanding the node during type legalization instead 5827 // by bumping the size by one bit. This will force it to Promote, enabling the 5828 // early expansion and avoiding the need to expand later. 5829 5830 // We don't have to do this if Scale is 0; that can always be expanded, unless 5831 // it's a saturating signed operation. Those can experience true integer 5832 // division overflow, a case which we must avoid. 5833 5834 // FIXME: We wouldn't have to do this (or any of the early 5835 // expansion/promotion) if it was possible to expand a libcall of an 5836 // illegal type during operation legalization. But it's not, so things 5837 // get a bit hacky. 5838 unsigned ScaleInt = Scale->getAsZExtVal(); 5839 if ((ScaleInt > 0 || (Saturating && Signed)) && 5840 (TLI.isTypeLegal(VT) || 5841 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5842 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5843 Opcode, VT, ScaleInt); 5844 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5845 EVT PromVT; 5846 if (VT.isScalarInteger()) 5847 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5848 else if (VT.isVector()) { 5849 PromVT = VT.getVectorElementType(); 5850 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5851 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5852 } else 5853 llvm_unreachable("Wrong VT for DIVFIX?"); 5854 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5855 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5856 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5857 // For saturating operations, we need to shift up the LHS to get the 5858 // proper saturation width, and then shift down again afterwards. 5859 if (Saturating) 5860 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5861 DAG.getConstant(1, DL, ShiftTy)); 5862 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5863 if (Saturating) 5864 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5865 DAG.getConstant(1, DL, ShiftTy)); 5866 return DAG.getZExtOrTrunc(Res, DL, VT); 5867 } 5868 } 5869 5870 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5871 } 5872 5873 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5874 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5875 static void 5876 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5877 const SDValue &N) { 5878 switch (N.getOpcode()) { 5879 case ISD::CopyFromReg: { 5880 SDValue Op = N.getOperand(1); 5881 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5882 Op.getValueType().getSizeInBits()); 5883 return; 5884 } 5885 case ISD::BITCAST: 5886 case ISD::AssertZext: 5887 case ISD::AssertSext: 5888 case ISD::TRUNCATE: 5889 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5890 return; 5891 case ISD::BUILD_PAIR: 5892 case ISD::BUILD_VECTOR: 5893 case ISD::CONCAT_VECTORS: 5894 for (SDValue Op : N->op_values()) 5895 getUnderlyingArgRegs(Regs, Op); 5896 return; 5897 default: 5898 return; 5899 } 5900 } 5901 5902 /// If the DbgValueInst is a dbg_value of a function argument, create the 5903 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5904 /// instruction selection, they will be inserted to the entry BB. 5905 /// We don't currently support this for variadic dbg_values, as they shouldn't 5906 /// appear for function arguments or in the prologue. 5907 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5908 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5909 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5910 const Argument *Arg = dyn_cast<Argument>(V); 5911 if (!Arg) 5912 return false; 5913 5914 MachineFunction &MF = DAG.getMachineFunction(); 5915 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5916 5917 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5918 // we've been asked to pursue. 5919 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5920 bool Indirect) { 5921 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5922 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5923 // pointing at the VReg, which will be patched up later. 5924 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5925 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5926 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5927 /* isKill */ false, /* isDead */ false, 5928 /* isUndef */ false, /* isEarlyClobber */ false, 5929 /* SubReg */ 0, /* isDebug */ true)}); 5930 5931 auto *NewDIExpr = FragExpr; 5932 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5933 // the DIExpression. 5934 if (Indirect) 5935 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5936 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5937 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5938 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5939 } else { 5940 // Create a completely standard DBG_VALUE. 5941 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5942 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5943 } 5944 }; 5945 5946 if (Kind == FuncArgumentDbgValueKind::Value) { 5947 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5948 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5949 // the entry block. 5950 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5951 if (!IsInEntryBlock) 5952 return false; 5953 5954 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5955 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5956 // variable that also is a param. 5957 // 5958 // Although, if we are at the top of the entry block already, we can still 5959 // emit using ArgDbgValue. This might catch some situations when the 5960 // dbg.value refers to an argument that isn't used in the entry block, so 5961 // any CopyToReg node would be optimized out and the only way to express 5962 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5963 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5964 // we should only emit as ArgDbgValue if the Variable is an argument to the 5965 // current function, and the dbg.value intrinsic is found in the entry 5966 // block. 5967 bool VariableIsFunctionInputArg = Variable->isParameter() && 5968 !DL->getInlinedAt(); 5969 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5970 if (!IsInPrologue && !VariableIsFunctionInputArg) 5971 return false; 5972 5973 // Here we assume that a function argument on IR level only can be used to 5974 // describe one input parameter on source level. If we for example have 5975 // source code like this 5976 // 5977 // struct A { long x, y; }; 5978 // void foo(struct A a, long b) { 5979 // ... 5980 // b = a.x; 5981 // ... 5982 // } 5983 // 5984 // and IR like this 5985 // 5986 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5987 // entry: 5988 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5989 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5990 // call void @llvm.dbg.value(metadata i32 %b, "b", 5991 // ... 5992 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5993 // ... 5994 // 5995 // then the last dbg.value is describing a parameter "b" using a value that 5996 // is an argument. But since we already has used %a1 to describe a parameter 5997 // we should not handle that last dbg.value here (that would result in an 5998 // incorrect hoisting of the DBG_VALUE to the function entry). 5999 // Notice that we allow one dbg.value per IR level argument, to accommodate 6000 // for the situation with fragments above. 6001 if (VariableIsFunctionInputArg) { 6002 unsigned ArgNo = Arg->getArgNo(); 6003 if (ArgNo >= FuncInfo.DescribedArgs.size()) 6004 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 6005 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 6006 return false; 6007 FuncInfo.DescribedArgs.set(ArgNo); 6008 } 6009 } 6010 6011 bool IsIndirect = false; 6012 std::optional<MachineOperand> Op; 6013 // Some arguments' frame index is recorded during argument lowering. 6014 int FI = FuncInfo.getArgumentFrameIndex(Arg); 6015 if (FI != std::numeric_limits<int>::max()) 6016 Op = MachineOperand::CreateFI(FI); 6017 6018 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 6019 if (!Op && N.getNode()) { 6020 getUnderlyingArgRegs(ArgRegsAndSizes, N); 6021 Register Reg; 6022 if (ArgRegsAndSizes.size() == 1) 6023 Reg = ArgRegsAndSizes.front().first; 6024 6025 if (Reg && Reg.isVirtual()) { 6026 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6027 Register PR = RegInfo.getLiveInPhysReg(Reg); 6028 if (PR) 6029 Reg = PR; 6030 } 6031 if (Reg) { 6032 Op = MachineOperand::CreateReg(Reg, false); 6033 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6034 } 6035 } 6036 6037 if (!Op && N.getNode()) { 6038 // Check if frame index is available. 6039 SDValue LCandidate = peekThroughBitcasts(N); 6040 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 6041 if (FrameIndexSDNode *FINode = 6042 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 6043 Op = MachineOperand::CreateFI(FINode->getIndex()); 6044 } 6045 6046 if (!Op) { 6047 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 6048 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 6049 SplitRegs) { 6050 unsigned Offset = 0; 6051 for (const auto &RegAndSize : SplitRegs) { 6052 // If the expression is already a fragment, the current register 6053 // offset+size might extend beyond the fragment. In this case, only 6054 // the register bits that are inside the fragment are relevant. 6055 int RegFragmentSizeInBits = RegAndSize.second; 6056 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 6057 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 6058 // The register is entirely outside the expression fragment, 6059 // so is irrelevant for debug info. 6060 if (Offset >= ExprFragmentSizeInBits) 6061 break; 6062 // The register is partially outside the expression fragment, only 6063 // the low bits within the fragment are relevant for debug info. 6064 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 6065 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 6066 } 6067 } 6068 6069 auto FragmentExpr = DIExpression::createFragmentExpression( 6070 Expr, Offset, RegFragmentSizeInBits); 6071 Offset += RegAndSize.second; 6072 // If a valid fragment expression cannot be created, the variable's 6073 // correct value cannot be determined and so it is set as Undef. 6074 if (!FragmentExpr) { 6075 SDDbgValue *SDV = DAG.getConstantDbgValue( 6076 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 6077 DAG.AddDbgValue(SDV, false); 6078 continue; 6079 } 6080 MachineInstr *NewMI = 6081 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 6082 Kind != FuncArgumentDbgValueKind::Value); 6083 FuncInfo.ArgDbgValues.push_back(NewMI); 6084 } 6085 }; 6086 6087 // Check if ValueMap has reg number. 6088 DenseMap<const Value *, Register>::const_iterator 6089 VMI = FuncInfo.ValueMap.find(V); 6090 if (VMI != FuncInfo.ValueMap.end()) { 6091 const auto &TLI = DAG.getTargetLoweringInfo(); 6092 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 6093 V->getType(), std::nullopt); 6094 if (RFV.occupiesMultipleRegs()) { 6095 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 6096 return true; 6097 } 6098 6099 Op = MachineOperand::CreateReg(VMI->second, false); 6100 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6101 } else if (ArgRegsAndSizes.size() > 1) { 6102 // This was split due to the calling convention, and no virtual register 6103 // mapping exists for the value. 6104 splitMultiRegDbgValue(ArgRegsAndSizes); 6105 return true; 6106 } 6107 } 6108 6109 if (!Op) 6110 return false; 6111 6112 assert(Variable->isValidLocationForIntrinsic(DL) && 6113 "Expected inlined-at fields to agree"); 6114 MachineInstr *NewMI = nullptr; 6115 6116 if (Op->isReg()) 6117 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 6118 else 6119 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 6120 Variable, Expr); 6121 6122 // Otherwise, use ArgDbgValues. 6123 FuncInfo.ArgDbgValues.push_back(NewMI); 6124 return true; 6125 } 6126 6127 /// Return the appropriate SDDbgValue based on N. 6128 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 6129 DILocalVariable *Variable, 6130 DIExpression *Expr, 6131 const DebugLoc &dl, 6132 unsigned DbgSDNodeOrder) { 6133 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 6134 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 6135 // stack slot locations. 6136 // 6137 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 6138 // debug values here after optimization: 6139 // 6140 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 6141 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 6142 // 6143 // Both describe the direct values of their associated variables. 6144 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 6145 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6146 } 6147 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 6148 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6149 } 6150 6151 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 6152 switch (Intrinsic) { 6153 case Intrinsic::smul_fix: 6154 return ISD::SMULFIX; 6155 case Intrinsic::umul_fix: 6156 return ISD::UMULFIX; 6157 case Intrinsic::smul_fix_sat: 6158 return ISD::SMULFIXSAT; 6159 case Intrinsic::umul_fix_sat: 6160 return ISD::UMULFIXSAT; 6161 case Intrinsic::sdiv_fix: 6162 return ISD::SDIVFIX; 6163 case Intrinsic::udiv_fix: 6164 return ISD::UDIVFIX; 6165 case Intrinsic::sdiv_fix_sat: 6166 return ISD::SDIVFIXSAT; 6167 case Intrinsic::udiv_fix_sat: 6168 return ISD::UDIVFIXSAT; 6169 default: 6170 llvm_unreachable("Unhandled fixed point intrinsic"); 6171 } 6172 } 6173 6174 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 6175 const char *FunctionName) { 6176 assert(FunctionName && "FunctionName must not be nullptr"); 6177 SDValue Callee = DAG.getExternalSymbol( 6178 FunctionName, 6179 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6180 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 6181 } 6182 6183 /// Given a @llvm.call.preallocated.setup, return the corresponding 6184 /// preallocated call. 6185 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 6186 assert(cast<CallBase>(PreallocatedSetup) 6187 ->getCalledFunction() 6188 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 6189 "expected call_preallocated_setup Value"); 6190 for (const auto *U : PreallocatedSetup->users()) { 6191 auto *UseCall = cast<CallBase>(U); 6192 const Function *Fn = UseCall->getCalledFunction(); 6193 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 6194 return UseCall; 6195 } 6196 } 6197 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 6198 } 6199 6200 /// If DI is a debug value with an EntryValue expression, lower it using the 6201 /// corresponding physical register of the associated Argument value 6202 /// (guaranteed to exist by the verifier). 6203 bool SelectionDAGBuilder::visitEntryValueDbgValue( 6204 ArrayRef<const Value *> Values, DILocalVariable *Variable, 6205 DIExpression *Expr, DebugLoc DbgLoc) { 6206 if (!Expr->isEntryValue() || !hasSingleElement(Values)) 6207 return false; 6208 6209 // These properties are guaranteed by the verifier. 6210 const Argument *Arg = cast<Argument>(Values[0]); 6211 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 6212 6213 auto ArgIt = FuncInfo.ValueMap.find(Arg); 6214 if (ArgIt == FuncInfo.ValueMap.end()) { 6215 LLVM_DEBUG( 6216 dbgs() << "Dropping dbg.value: expression is entry_value but " 6217 "couldn't find an associated register for the Argument\n"); 6218 return true; 6219 } 6220 Register ArgVReg = ArgIt->getSecond(); 6221 6222 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 6223 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 6224 SDDbgValue *SDV = DAG.getVRegDbgValue( 6225 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder); 6226 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 6227 return true; 6228 } 6229 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 6230 "couldn't find a physical register\n"); 6231 return true; 6232 } 6233 6234 /// Lower the call to the specified intrinsic function. 6235 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 6236 unsigned Intrinsic) { 6237 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6238 SDLoc sdl = getCurSDLoc(); 6239 DebugLoc dl = getCurDebugLoc(); 6240 SDValue Res; 6241 6242 SDNodeFlags Flags; 6243 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 6244 Flags.copyFMF(*FPOp); 6245 6246 switch (Intrinsic) { 6247 default: 6248 // By default, turn this into a target intrinsic node. 6249 visitTargetIntrinsic(I, Intrinsic); 6250 return; 6251 case Intrinsic::vscale: { 6252 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6253 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 6254 return; 6255 } 6256 case Intrinsic::vastart: visitVAStart(I); return; 6257 case Intrinsic::vaend: visitVAEnd(I); return; 6258 case Intrinsic::vacopy: visitVACopy(I); return; 6259 case Intrinsic::returnaddress: 6260 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 6261 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6262 getValue(I.getArgOperand(0)))); 6263 return; 6264 case Intrinsic::addressofreturnaddress: 6265 setValue(&I, 6266 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6267 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6268 return; 6269 case Intrinsic::sponentry: 6270 setValue(&I, 6271 DAG.getNode(ISD::SPONENTRY, sdl, 6272 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6273 return; 6274 case Intrinsic::frameaddress: 6275 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6276 TLI.getFrameIndexTy(DAG.getDataLayout()), 6277 getValue(I.getArgOperand(0)))); 6278 return; 6279 case Intrinsic::read_volatile_register: 6280 case Intrinsic::read_register: { 6281 Value *Reg = I.getArgOperand(0); 6282 SDValue Chain = getRoot(); 6283 SDValue RegName = 6284 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6285 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6286 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6287 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6288 setValue(&I, Res); 6289 DAG.setRoot(Res.getValue(1)); 6290 return; 6291 } 6292 case Intrinsic::write_register: { 6293 Value *Reg = I.getArgOperand(0); 6294 Value *RegValue = I.getArgOperand(1); 6295 SDValue Chain = getRoot(); 6296 SDValue RegName = 6297 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6298 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6299 RegName, getValue(RegValue))); 6300 return; 6301 } 6302 case Intrinsic::memcpy: { 6303 const auto &MCI = cast<MemCpyInst>(I); 6304 SDValue Op1 = getValue(I.getArgOperand(0)); 6305 SDValue Op2 = getValue(I.getArgOperand(1)); 6306 SDValue Op3 = getValue(I.getArgOperand(2)); 6307 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6308 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6309 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6310 Align Alignment = std::min(DstAlign, SrcAlign); 6311 bool isVol = MCI.isVolatile(); 6312 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6313 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6314 // node. 6315 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6316 SDValue MC = DAG.getMemcpy( 6317 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6318 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6319 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6320 updateDAGForMaybeTailCall(MC); 6321 return; 6322 } 6323 case Intrinsic::memcpy_inline: { 6324 const auto &MCI = cast<MemCpyInlineInst>(I); 6325 SDValue Dst = getValue(I.getArgOperand(0)); 6326 SDValue Src = getValue(I.getArgOperand(1)); 6327 SDValue Size = getValue(I.getArgOperand(2)); 6328 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6329 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6330 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6331 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6332 Align Alignment = std::min(DstAlign, SrcAlign); 6333 bool isVol = MCI.isVolatile(); 6334 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6335 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6336 // node. 6337 SDValue MC = DAG.getMemcpy( 6338 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6339 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6340 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6341 updateDAGForMaybeTailCall(MC); 6342 return; 6343 } 6344 case Intrinsic::memset: { 6345 const auto &MSI = cast<MemSetInst>(I); 6346 SDValue Op1 = getValue(I.getArgOperand(0)); 6347 SDValue Op2 = getValue(I.getArgOperand(1)); 6348 SDValue Op3 = getValue(I.getArgOperand(2)); 6349 // @llvm.memset defines 0 and 1 to both mean no alignment. 6350 Align Alignment = MSI.getDestAlign().valueOrOne(); 6351 bool isVol = MSI.isVolatile(); 6352 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6353 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6354 SDValue MS = DAG.getMemset( 6355 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6356 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6357 updateDAGForMaybeTailCall(MS); 6358 return; 6359 } 6360 case Intrinsic::memset_inline: { 6361 const auto &MSII = cast<MemSetInlineInst>(I); 6362 SDValue Dst = getValue(I.getArgOperand(0)); 6363 SDValue Value = getValue(I.getArgOperand(1)); 6364 SDValue Size = getValue(I.getArgOperand(2)); 6365 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6366 // @llvm.memset defines 0 and 1 to both mean no alignment. 6367 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6368 bool isVol = MSII.isVolatile(); 6369 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6370 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6371 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6372 /* AlwaysInline */ true, isTC, 6373 MachinePointerInfo(I.getArgOperand(0)), 6374 I.getAAMetadata()); 6375 updateDAGForMaybeTailCall(MC); 6376 return; 6377 } 6378 case Intrinsic::memmove: { 6379 const auto &MMI = cast<MemMoveInst>(I); 6380 SDValue Op1 = getValue(I.getArgOperand(0)); 6381 SDValue Op2 = getValue(I.getArgOperand(1)); 6382 SDValue Op3 = getValue(I.getArgOperand(2)); 6383 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6384 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6385 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6386 Align Alignment = std::min(DstAlign, SrcAlign); 6387 bool isVol = MMI.isVolatile(); 6388 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6389 // FIXME: Support passing different dest/src alignments to the memmove DAG 6390 // node. 6391 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6392 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6393 isTC, MachinePointerInfo(I.getArgOperand(0)), 6394 MachinePointerInfo(I.getArgOperand(1)), 6395 I.getAAMetadata(), AA); 6396 updateDAGForMaybeTailCall(MM); 6397 return; 6398 } 6399 case Intrinsic::memcpy_element_unordered_atomic: { 6400 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6401 SDValue Dst = getValue(MI.getRawDest()); 6402 SDValue Src = getValue(MI.getRawSource()); 6403 SDValue Length = getValue(MI.getLength()); 6404 6405 Type *LengthTy = MI.getLength()->getType(); 6406 unsigned ElemSz = MI.getElementSizeInBytes(); 6407 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6408 SDValue MC = 6409 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6410 isTC, MachinePointerInfo(MI.getRawDest()), 6411 MachinePointerInfo(MI.getRawSource())); 6412 updateDAGForMaybeTailCall(MC); 6413 return; 6414 } 6415 case Intrinsic::memmove_element_unordered_atomic: { 6416 auto &MI = cast<AtomicMemMoveInst>(I); 6417 SDValue Dst = getValue(MI.getRawDest()); 6418 SDValue Src = getValue(MI.getRawSource()); 6419 SDValue Length = getValue(MI.getLength()); 6420 6421 Type *LengthTy = MI.getLength()->getType(); 6422 unsigned ElemSz = MI.getElementSizeInBytes(); 6423 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6424 SDValue MC = 6425 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6426 isTC, MachinePointerInfo(MI.getRawDest()), 6427 MachinePointerInfo(MI.getRawSource())); 6428 updateDAGForMaybeTailCall(MC); 6429 return; 6430 } 6431 case Intrinsic::memset_element_unordered_atomic: { 6432 auto &MI = cast<AtomicMemSetInst>(I); 6433 SDValue Dst = getValue(MI.getRawDest()); 6434 SDValue Val = getValue(MI.getValue()); 6435 SDValue Length = getValue(MI.getLength()); 6436 6437 Type *LengthTy = MI.getLength()->getType(); 6438 unsigned ElemSz = MI.getElementSizeInBytes(); 6439 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6440 SDValue MC = 6441 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6442 isTC, MachinePointerInfo(MI.getRawDest())); 6443 updateDAGForMaybeTailCall(MC); 6444 return; 6445 } 6446 case Intrinsic::call_preallocated_setup: { 6447 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6448 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6449 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6450 getRoot(), SrcValue); 6451 setValue(&I, Res); 6452 DAG.setRoot(Res); 6453 return; 6454 } 6455 case Intrinsic::call_preallocated_arg: { 6456 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6457 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6458 SDValue Ops[3]; 6459 Ops[0] = getRoot(); 6460 Ops[1] = SrcValue; 6461 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6462 MVT::i32); // arg index 6463 SDValue Res = DAG.getNode( 6464 ISD::PREALLOCATED_ARG, sdl, 6465 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6466 setValue(&I, Res); 6467 DAG.setRoot(Res.getValue(1)); 6468 return; 6469 } 6470 case Intrinsic::dbg_declare: { 6471 const auto &DI = cast<DbgDeclareInst>(I); 6472 // Debug intrinsics are handled separately in assignment tracking mode. 6473 // Some intrinsics are handled right after Argument lowering. 6474 if (AssignmentTrackingEnabled || 6475 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6476 return; 6477 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n"); 6478 DILocalVariable *Variable = DI.getVariable(); 6479 DIExpression *Expression = DI.getExpression(); 6480 dropDanglingDebugInfo(Variable, Expression); 6481 // Assume dbg.declare can not currently use DIArgList, i.e. 6482 // it is non-variadic. 6483 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6484 handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression, 6485 DI.getDebugLoc()); 6486 return; 6487 } 6488 case Intrinsic::dbg_label: { 6489 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6490 DILabel *Label = DI.getLabel(); 6491 assert(Label && "Missing label"); 6492 6493 SDDbgLabel *SDV; 6494 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6495 DAG.AddDbgLabel(SDV); 6496 return; 6497 } 6498 case Intrinsic::dbg_assign: { 6499 // Debug intrinsics are handled seperately in assignment tracking mode. 6500 if (AssignmentTrackingEnabled) 6501 return; 6502 // If assignment tracking hasn't been enabled then fall through and treat 6503 // the dbg.assign as a dbg.value. 6504 [[fallthrough]]; 6505 } 6506 case Intrinsic::dbg_value: { 6507 // Debug intrinsics are handled seperately in assignment tracking mode. 6508 if (AssignmentTrackingEnabled) 6509 return; 6510 const DbgValueInst &DI = cast<DbgValueInst>(I); 6511 assert(DI.getVariable() && "Missing variable"); 6512 6513 DILocalVariable *Variable = DI.getVariable(); 6514 DIExpression *Expression = DI.getExpression(); 6515 dropDanglingDebugInfo(Variable, Expression); 6516 6517 if (DI.isKillLocation()) { 6518 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6519 return; 6520 } 6521 6522 SmallVector<Value *, 4> Values(DI.getValues()); 6523 if (Values.empty()) 6524 return; 6525 6526 bool IsVariadic = DI.hasArgList(); 6527 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6528 SDNodeOrder, IsVariadic)) 6529 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 6530 DI.getDebugLoc(), SDNodeOrder); 6531 return; 6532 } 6533 6534 case Intrinsic::eh_typeid_for: { 6535 // Find the type id for the given typeinfo. 6536 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6537 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6538 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6539 setValue(&I, Res); 6540 return; 6541 } 6542 6543 case Intrinsic::eh_return_i32: 6544 case Intrinsic::eh_return_i64: 6545 DAG.getMachineFunction().setCallsEHReturn(true); 6546 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6547 MVT::Other, 6548 getControlRoot(), 6549 getValue(I.getArgOperand(0)), 6550 getValue(I.getArgOperand(1)))); 6551 return; 6552 case Intrinsic::eh_unwind_init: 6553 DAG.getMachineFunction().setCallsUnwindInit(true); 6554 return; 6555 case Intrinsic::eh_dwarf_cfa: 6556 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6557 TLI.getPointerTy(DAG.getDataLayout()), 6558 getValue(I.getArgOperand(0)))); 6559 return; 6560 case Intrinsic::eh_sjlj_callsite: { 6561 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6562 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6563 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6564 6565 MMI.setCurrentCallSite(CI->getZExtValue()); 6566 return; 6567 } 6568 case Intrinsic::eh_sjlj_functioncontext: { 6569 // Get and store the index of the function context. 6570 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6571 AllocaInst *FnCtx = 6572 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6573 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6574 MFI.setFunctionContextIndex(FI); 6575 return; 6576 } 6577 case Intrinsic::eh_sjlj_setjmp: { 6578 SDValue Ops[2]; 6579 Ops[0] = getRoot(); 6580 Ops[1] = getValue(I.getArgOperand(0)); 6581 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6582 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6583 setValue(&I, Op.getValue(0)); 6584 DAG.setRoot(Op.getValue(1)); 6585 return; 6586 } 6587 case Intrinsic::eh_sjlj_longjmp: 6588 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6589 getRoot(), getValue(I.getArgOperand(0)))); 6590 return; 6591 case Intrinsic::eh_sjlj_setup_dispatch: 6592 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6593 getRoot())); 6594 return; 6595 case Intrinsic::masked_gather: 6596 visitMaskedGather(I); 6597 return; 6598 case Intrinsic::masked_load: 6599 visitMaskedLoad(I); 6600 return; 6601 case Intrinsic::masked_scatter: 6602 visitMaskedScatter(I); 6603 return; 6604 case Intrinsic::masked_store: 6605 visitMaskedStore(I); 6606 return; 6607 case Intrinsic::masked_expandload: 6608 visitMaskedLoad(I, true /* IsExpanding */); 6609 return; 6610 case Intrinsic::masked_compressstore: 6611 visitMaskedStore(I, true /* IsCompressing */); 6612 return; 6613 case Intrinsic::powi: 6614 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6615 getValue(I.getArgOperand(1)), DAG)); 6616 return; 6617 case Intrinsic::log: 6618 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6619 return; 6620 case Intrinsic::log2: 6621 setValue(&I, 6622 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6623 return; 6624 case Intrinsic::log10: 6625 setValue(&I, 6626 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6627 return; 6628 case Intrinsic::exp: 6629 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6630 return; 6631 case Intrinsic::exp2: 6632 setValue(&I, 6633 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6634 return; 6635 case Intrinsic::pow: 6636 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6637 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6638 return; 6639 case Intrinsic::sqrt: 6640 case Intrinsic::fabs: 6641 case Intrinsic::sin: 6642 case Intrinsic::cos: 6643 case Intrinsic::exp10: 6644 case Intrinsic::floor: 6645 case Intrinsic::ceil: 6646 case Intrinsic::trunc: 6647 case Intrinsic::rint: 6648 case Intrinsic::nearbyint: 6649 case Intrinsic::round: 6650 case Intrinsic::roundeven: 6651 case Intrinsic::canonicalize: { 6652 unsigned Opcode; 6653 switch (Intrinsic) { 6654 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6655 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6656 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6657 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6658 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6659 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6660 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6661 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6662 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6663 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6664 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6665 case Intrinsic::round: Opcode = ISD::FROUND; break; 6666 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6667 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6668 } 6669 6670 setValue(&I, DAG.getNode(Opcode, sdl, 6671 getValue(I.getArgOperand(0)).getValueType(), 6672 getValue(I.getArgOperand(0)), Flags)); 6673 return; 6674 } 6675 case Intrinsic::lround: 6676 case Intrinsic::llround: 6677 case Intrinsic::lrint: 6678 case Intrinsic::llrint: { 6679 unsigned Opcode; 6680 switch (Intrinsic) { 6681 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6682 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6683 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6684 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6685 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6686 } 6687 6688 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6689 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6690 getValue(I.getArgOperand(0)))); 6691 return; 6692 } 6693 case Intrinsic::minnum: 6694 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6695 getValue(I.getArgOperand(0)).getValueType(), 6696 getValue(I.getArgOperand(0)), 6697 getValue(I.getArgOperand(1)), Flags)); 6698 return; 6699 case Intrinsic::maxnum: 6700 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6701 getValue(I.getArgOperand(0)).getValueType(), 6702 getValue(I.getArgOperand(0)), 6703 getValue(I.getArgOperand(1)), Flags)); 6704 return; 6705 case Intrinsic::minimum: 6706 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6707 getValue(I.getArgOperand(0)).getValueType(), 6708 getValue(I.getArgOperand(0)), 6709 getValue(I.getArgOperand(1)), Flags)); 6710 return; 6711 case Intrinsic::maximum: 6712 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6713 getValue(I.getArgOperand(0)).getValueType(), 6714 getValue(I.getArgOperand(0)), 6715 getValue(I.getArgOperand(1)), Flags)); 6716 return; 6717 case Intrinsic::copysign: 6718 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6719 getValue(I.getArgOperand(0)).getValueType(), 6720 getValue(I.getArgOperand(0)), 6721 getValue(I.getArgOperand(1)), Flags)); 6722 return; 6723 case Intrinsic::ldexp: 6724 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6725 getValue(I.getArgOperand(0)).getValueType(), 6726 getValue(I.getArgOperand(0)), 6727 getValue(I.getArgOperand(1)), Flags)); 6728 return; 6729 case Intrinsic::frexp: { 6730 SmallVector<EVT, 2> ValueVTs; 6731 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6732 SDVTList VTs = DAG.getVTList(ValueVTs); 6733 setValue(&I, 6734 DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0)))); 6735 return; 6736 } 6737 case Intrinsic::arithmetic_fence: { 6738 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6739 getValue(I.getArgOperand(0)).getValueType(), 6740 getValue(I.getArgOperand(0)), Flags)); 6741 return; 6742 } 6743 case Intrinsic::fma: 6744 setValue(&I, DAG.getNode( 6745 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6746 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6747 getValue(I.getArgOperand(2)), Flags)); 6748 return; 6749 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6750 case Intrinsic::INTRINSIC: 6751 #include "llvm/IR/ConstrainedOps.def" 6752 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6753 return; 6754 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6755 #include "llvm/IR/VPIntrinsics.def" 6756 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6757 return; 6758 case Intrinsic::fptrunc_round: { 6759 // Get the last argument, the metadata and convert it to an integer in the 6760 // call 6761 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6762 std::optional<RoundingMode> RoundMode = 6763 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6764 6765 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6766 6767 // Propagate fast-math-flags from IR to node(s). 6768 SDNodeFlags Flags; 6769 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6770 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6771 6772 SDValue Result; 6773 Result = DAG.getNode( 6774 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6775 DAG.getTargetConstant((int)*RoundMode, sdl, 6776 TLI.getPointerTy(DAG.getDataLayout()))); 6777 setValue(&I, Result); 6778 6779 return; 6780 } 6781 case Intrinsic::fmuladd: { 6782 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6783 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6784 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6785 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6786 getValue(I.getArgOperand(0)).getValueType(), 6787 getValue(I.getArgOperand(0)), 6788 getValue(I.getArgOperand(1)), 6789 getValue(I.getArgOperand(2)), Flags)); 6790 } else { 6791 // TODO: Intrinsic calls should have fast-math-flags. 6792 SDValue Mul = DAG.getNode( 6793 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6794 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6795 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6796 getValue(I.getArgOperand(0)).getValueType(), 6797 Mul, getValue(I.getArgOperand(2)), Flags); 6798 setValue(&I, Add); 6799 } 6800 return; 6801 } 6802 case Intrinsic::convert_to_fp16: 6803 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6804 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6805 getValue(I.getArgOperand(0)), 6806 DAG.getTargetConstant(0, sdl, 6807 MVT::i32)))); 6808 return; 6809 case Intrinsic::convert_from_fp16: 6810 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6811 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6812 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6813 getValue(I.getArgOperand(0))))); 6814 return; 6815 case Intrinsic::fptosi_sat: { 6816 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6817 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6818 getValue(I.getArgOperand(0)), 6819 DAG.getValueType(VT.getScalarType()))); 6820 return; 6821 } 6822 case Intrinsic::fptoui_sat: { 6823 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6824 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6825 getValue(I.getArgOperand(0)), 6826 DAG.getValueType(VT.getScalarType()))); 6827 return; 6828 } 6829 case Intrinsic::set_rounding: 6830 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6831 {getRoot(), getValue(I.getArgOperand(0))}); 6832 setValue(&I, Res); 6833 DAG.setRoot(Res.getValue(0)); 6834 return; 6835 case Intrinsic::is_fpclass: { 6836 const DataLayout DLayout = DAG.getDataLayout(); 6837 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6838 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6839 FPClassTest Test = static_cast<FPClassTest>( 6840 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6841 MachineFunction &MF = DAG.getMachineFunction(); 6842 const Function &F = MF.getFunction(); 6843 SDValue Op = getValue(I.getArgOperand(0)); 6844 SDNodeFlags Flags; 6845 Flags.setNoFPExcept( 6846 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6847 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6848 // expansion can use illegal types. Making expansion early allows 6849 // legalizing these types prior to selection. 6850 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6851 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6852 setValue(&I, Result); 6853 return; 6854 } 6855 6856 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6857 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6858 setValue(&I, V); 6859 return; 6860 } 6861 case Intrinsic::get_fpenv: { 6862 const DataLayout DLayout = DAG.getDataLayout(); 6863 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 6864 Align TempAlign = DAG.getEVTAlign(EnvVT); 6865 SDValue Chain = getRoot(); 6866 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 6867 // and temporary storage in stack. 6868 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 6869 Res = DAG.getNode( 6870 ISD::GET_FPENV, sdl, 6871 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6872 MVT::Other), 6873 Chain); 6874 } else { 6875 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6876 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6877 auto MPI = 6878 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6879 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6880 MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize, 6881 TempAlign); 6882 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6883 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 6884 } 6885 setValue(&I, Res); 6886 DAG.setRoot(Res.getValue(1)); 6887 return; 6888 } 6889 case Intrinsic::set_fpenv: { 6890 const DataLayout DLayout = DAG.getDataLayout(); 6891 SDValue Env = getValue(I.getArgOperand(0)); 6892 EVT EnvVT = Env.getValueType(); 6893 Align TempAlign = DAG.getEVTAlign(EnvVT); 6894 SDValue Chain = getRoot(); 6895 // If SET_FPENV is custom or legal, use it. Otherwise use loading 6896 // environment from memory. 6897 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 6898 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 6899 } else { 6900 // Allocate space in stack, copy environment bits into it and use this 6901 // memory in SET_FPENV_MEM. 6902 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6903 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6904 auto MPI = 6905 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6906 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 6907 MachineMemOperand::MOStore); 6908 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6909 MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize, 6910 TempAlign); 6911 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6912 } 6913 DAG.setRoot(Chain); 6914 return; 6915 } 6916 case Intrinsic::reset_fpenv: 6917 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 6918 return; 6919 case Intrinsic::get_fpmode: 6920 Res = DAG.getNode( 6921 ISD::GET_FPMODE, sdl, 6922 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6923 MVT::Other), 6924 DAG.getRoot()); 6925 setValue(&I, Res); 6926 DAG.setRoot(Res.getValue(1)); 6927 return; 6928 case Intrinsic::set_fpmode: 6929 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 6930 getValue(I.getArgOperand(0))); 6931 DAG.setRoot(Res); 6932 return; 6933 case Intrinsic::reset_fpmode: { 6934 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 6935 DAG.setRoot(Res); 6936 return; 6937 } 6938 case Intrinsic::pcmarker: { 6939 SDValue Tmp = getValue(I.getArgOperand(0)); 6940 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6941 return; 6942 } 6943 case Intrinsic::readcyclecounter: { 6944 SDValue Op = getRoot(); 6945 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6946 DAG.getVTList(MVT::i64, MVT::Other), Op); 6947 setValue(&I, Res); 6948 DAG.setRoot(Res.getValue(1)); 6949 return; 6950 } 6951 case Intrinsic::readsteadycounter: { 6952 SDValue Op = getRoot(); 6953 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl, 6954 DAG.getVTList(MVT::i64, MVT::Other), Op); 6955 setValue(&I, Res); 6956 DAG.setRoot(Res.getValue(1)); 6957 return; 6958 } 6959 case Intrinsic::bitreverse: 6960 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6961 getValue(I.getArgOperand(0)).getValueType(), 6962 getValue(I.getArgOperand(0)))); 6963 return; 6964 case Intrinsic::bswap: 6965 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6966 getValue(I.getArgOperand(0)).getValueType(), 6967 getValue(I.getArgOperand(0)))); 6968 return; 6969 case Intrinsic::cttz: { 6970 SDValue Arg = getValue(I.getArgOperand(0)); 6971 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6972 EVT Ty = Arg.getValueType(); 6973 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6974 sdl, Ty, Arg)); 6975 return; 6976 } 6977 case Intrinsic::ctlz: { 6978 SDValue Arg = getValue(I.getArgOperand(0)); 6979 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6980 EVT Ty = Arg.getValueType(); 6981 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6982 sdl, Ty, Arg)); 6983 return; 6984 } 6985 case Intrinsic::ctpop: { 6986 SDValue Arg = getValue(I.getArgOperand(0)); 6987 EVT Ty = Arg.getValueType(); 6988 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6989 return; 6990 } 6991 case Intrinsic::fshl: 6992 case Intrinsic::fshr: { 6993 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6994 SDValue X = getValue(I.getArgOperand(0)); 6995 SDValue Y = getValue(I.getArgOperand(1)); 6996 SDValue Z = getValue(I.getArgOperand(2)); 6997 EVT VT = X.getValueType(); 6998 6999 if (X == Y) { 7000 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 7001 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 7002 } else { 7003 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 7004 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 7005 } 7006 return; 7007 } 7008 case Intrinsic::sadd_sat: { 7009 SDValue Op1 = getValue(I.getArgOperand(0)); 7010 SDValue Op2 = getValue(I.getArgOperand(1)); 7011 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7012 return; 7013 } 7014 case Intrinsic::uadd_sat: { 7015 SDValue Op1 = getValue(I.getArgOperand(0)); 7016 SDValue Op2 = getValue(I.getArgOperand(1)); 7017 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7018 return; 7019 } 7020 case Intrinsic::ssub_sat: { 7021 SDValue Op1 = getValue(I.getArgOperand(0)); 7022 SDValue Op2 = getValue(I.getArgOperand(1)); 7023 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7024 return; 7025 } 7026 case Intrinsic::usub_sat: { 7027 SDValue Op1 = getValue(I.getArgOperand(0)); 7028 SDValue Op2 = getValue(I.getArgOperand(1)); 7029 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7030 return; 7031 } 7032 case Intrinsic::sshl_sat: { 7033 SDValue Op1 = getValue(I.getArgOperand(0)); 7034 SDValue Op2 = getValue(I.getArgOperand(1)); 7035 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7036 return; 7037 } 7038 case Intrinsic::ushl_sat: { 7039 SDValue Op1 = getValue(I.getArgOperand(0)); 7040 SDValue Op2 = getValue(I.getArgOperand(1)); 7041 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7042 return; 7043 } 7044 case Intrinsic::smul_fix: 7045 case Intrinsic::umul_fix: 7046 case Intrinsic::smul_fix_sat: 7047 case Intrinsic::umul_fix_sat: { 7048 SDValue Op1 = getValue(I.getArgOperand(0)); 7049 SDValue Op2 = getValue(I.getArgOperand(1)); 7050 SDValue Op3 = getValue(I.getArgOperand(2)); 7051 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7052 Op1.getValueType(), Op1, Op2, Op3)); 7053 return; 7054 } 7055 case Intrinsic::sdiv_fix: 7056 case Intrinsic::udiv_fix: 7057 case Intrinsic::sdiv_fix_sat: 7058 case Intrinsic::udiv_fix_sat: { 7059 SDValue Op1 = getValue(I.getArgOperand(0)); 7060 SDValue Op2 = getValue(I.getArgOperand(1)); 7061 SDValue Op3 = getValue(I.getArgOperand(2)); 7062 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7063 Op1, Op2, Op3, DAG, TLI)); 7064 return; 7065 } 7066 case Intrinsic::smax: { 7067 SDValue Op1 = getValue(I.getArgOperand(0)); 7068 SDValue Op2 = getValue(I.getArgOperand(1)); 7069 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 7070 return; 7071 } 7072 case Intrinsic::smin: { 7073 SDValue Op1 = getValue(I.getArgOperand(0)); 7074 SDValue Op2 = getValue(I.getArgOperand(1)); 7075 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 7076 return; 7077 } 7078 case Intrinsic::umax: { 7079 SDValue Op1 = getValue(I.getArgOperand(0)); 7080 SDValue Op2 = getValue(I.getArgOperand(1)); 7081 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 7082 return; 7083 } 7084 case Intrinsic::umin: { 7085 SDValue Op1 = getValue(I.getArgOperand(0)); 7086 SDValue Op2 = getValue(I.getArgOperand(1)); 7087 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 7088 return; 7089 } 7090 case Intrinsic::abs: { 7091 // TODO: Preserve "int min is poison" arg in SDAG? 7092 SDValue Op1 = getValue(I.getArgOperand(0)); 7093 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 7094 return; 7095 } 7096 case Intrinsic::stacksave: { 7097 SDValue Op = getRoot(); 7098 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7099 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 7100 setValue(&I, Res); 7101 DAG.setRoot(Res.getValue(1)); 7102 return; 7103 } 7104 case Intrinsic::stackrestore: 7105 Res = getValue(I.getArgOperand(0)); 7106 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 7107 return; 7108 case Intrinsic::get_dynamic_area_offset: { 7109 SDValue Op = getRoot(); 7110 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7111 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7112 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 7113 // target. 7114 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 7115 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 7116 " intrinsic!"); 7117 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 7118 Op); 7119 DAG.setRoot(Op); 7120 setValue(&I, Res); 7121 return; 7122 } 7123 case Intrinsic::stackguard: { 7124 MachineFunction &MF = DAG.getMachineFunction(); 7125 const Module &M = *MF.getFunction().getParent(); 7126 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7127 SDValue Chain = getRoot(); 7128 if (TLI.useLoadStackGuardNode()) { 7129 Res = getLoadStackGuard(DAG, sdl, Chain); 7130 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy); 7131 } else { 7132 const Value *Global = TLI.getSDagStackGuard(M); 7133 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 7134 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 7135 MachinePointerInfo(Global, 0), Align, 7136 MachineMemOperand::MOVolatile); 7137 } 7138 if (TLI.useStackGuardXorFP()) 7139 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 7140 DAG.setRoot(Chain); 7141 setValue(&I, Res); 7142 return; 7143 } 7144 case Intrinsic::stackprotector: { 7145 // Emit code into the DAG to store the stack guard onto the stack. 7146 MachineFunction &MF = DAG.getMachineFunction(); 7147 MachineFrameInfo &MFI = MF.getFrameInfo(); 7148 SDValue Src, Chain = getRoot(); 7149 7150 if (TLI.useLoadStackGuardNode()) 7151 Src = getLoadStackGuard(DAG, sdl, Chain); 7152 else 7153 Src = getValue(I.getArgOperand(0)); // The guard's value. 7154 7155 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 7156 7157 int FI = FuncInfo.StaticAllocaMap[Slot]; 7158 MFI.setStackProtectorIndex(FI); 7159 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7160 7161 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 7162 7163 // Store the stack protector onto the stack. 7164 Res = DAG.getStore( 7165 Chain, sdl, Src, FIN, 7166 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 7167 MaybeAlign(), MachineMemOperand::MOVolatile); 7168 setValue(&I, Res); 7169 DAG.setRoot(Res); 7170 return; 7171 } 7172 case Intrinsic::objectsize: 7173 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 7174 7175 case Intrinsic::is_constant: 7176 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 7177 7178 case Intrinsic::annotation: 7179 case Intrinsic::ptr_annotation: 7180 case Intrinsic::launder_invariant_group: 7181 case Intrinsic::strip_invariant_group: 7182 // Drop the intrinsic, but forward the value 7183 setValue(&I, getValue(I.getOperand(0))); 7184 return; 7185 7186 case Intrinsic::assume: 7187 case Intrinsic::experimental_noalias_scope_decl: 7188 case Intrinsic::var_annotation: 7189 case Intrinsic::sideeffect: 7190 // Discard annotate attributes, noalias scope declarations, assumptions, and 7191 // artificial side-effects. 7192 return; 7193 7194 case Intrinsic::codeview_annotation: { 7195 // Emit a label associated with this metadata. 7196 MachineFunction &MF = DAG.getMachineFunction(); 7197 MCSymbol *Label = 7198 MF.getMMI().getContext().createTempSymbol("annotation", true); 7199 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 7200 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 7201 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 7202 DAG.setRoot(Res); 7203 return; 7204 } 7205 7206 case Intrinsic::init_trampoline: { 7207 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 7208 7209 SDValue Ops[6]; 7210 Ops[0] = getRoot(); 7211 Ops[1] = getValue(I.getArgOperand(0)); 7212 Ops[2] = getValue(I.getArgOperand(1)); 7213 Ops[3] = getValue(I.getArgOperand(2)); 7214 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 7215 Ops[5] = DAG.getSrcValue(F); 7216 7217 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 7218 7219 DAG.setRoot(Res); 7220 return; 7221 } 7222 case Intrinsic::adjust_trampoline: 7223 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7224 TLI.getPointerTy(DAG.getDataLayout()), 7225 getValue(I.getArgOperand(0)))); 7226 return; 7227 case Intrinsic::gcroot: { 7228 assert(DAG.getMachineFunction().getFunction().hasGC() && 7229 "only valid in functions with gc specified, enforced by Verifier"); 7230 assert(GFI && "implied by previous"); 7231 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7232 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7233 7234 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7235 GFI->addStackRoot(FI->getIndex(), TypeMap); 7236 return; 7237 } 7238 case Intrinsic::gcread: 7239 case Intrinsic::gcwrite: 7240 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7241 case Intrinsic::get_rounding: 7242 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7243 setValue(&I, Res); 7244 DAG.setRoot(Res.getValue(1)); 7245 return; 7246 7247 case Intrinsic::expect: 7248 // Just replace __builtin_expect(exp, c) with EXP. 7249 setValue(&I, getValue(I.getArgOperand(0))); 7250 return; 7251 7252 case Intrinsic::ubsantrap: 7253 case Intrinsic::debugtrap: 7254 case Intrinsic::trap: { 7255 StringRef TrapFuncName = 7256 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7257 if (TrapFuncName.empty()) { 7258 switch (Intrinsic) { 7259 case Intrinsic::trap: 7260 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7261 break; 7262 case Intrinsic::debugtrap: 7263 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7264 break; 7265 case Intrinsic::ubsantrap: 7266 DAG.setRoot(DAG.getNode( 7267 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7268 DAG.getTargetConstant( 7269 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7270 MVT::i32))); 7271 break; 7272 default: llvm_unreachable("unknown trap intrinsic"); 7273 } 7274 return; 7275 } 7276 TargetLowering::ArgListTy Args; 7277 if (Intrinsic == Intrinsic::ubsantrap) { 7278 Args.push_back(TargetLoweringBase::ArgListEntry()); 7279 Args[0].Val = I.getArgOperand(0); 7280 Args[0].Node = getValue(Args[0].Val); 7281 Args[0].Ty = Args[0].Val->getType(); 7282 } 7283 7284 TargetLowering::CallLoweringInfo CLI(DAG); 7285 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7286 CallingConv::C, I.getType(), 7287 DAG.getExternalSymbol(TrapFuncName.data(), 7288 TLI.getPointerTy(DAG.getDataLayout())), 7289 std::move(Args)); 7290 7291 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7292 DAG.setRoot(Result.second); 7293 return; 7294 } 7295 7296 case Intrinsic::uadd_with_overflow: 7297 case Intrinsic::sadd_with_overflow: 7298 case Intrinsic::usub_with_overflow: 7299 case Intrinsic::ssub_with_overflow: 7300 case Intrinsic::umul_with_overflow: 7301 case Intrinsic::smul_with_overflow: { 7302 ISD::NodeType Op; 7303 switch (Intrinsic) { 7304 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7305 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7306 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7307 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7308 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7309 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7310 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7311 } 7312 SDValue Op1 = getValue(I.getArgOperand(0)); 7313 SDValue Op2 = getValue(I.getArgOperand(1)); 7314 7315 EVT ResultVT = Op1.getValueType(); 7316 EVT OverflowVT = MVT::i1; 7317 if (ResultVT.isVector()) 7318 OverflowVT = EVT::getVectorVT( 7319 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7320 7321 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7322 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7323 return; 7324 } 7325 case Intrinsic::prefetch: { 7326 SDValue Ops[5]; 7327 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7328 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7329 Ops[0] = DAG.getRoot(); 7330 Ops[1] = getValue(I.getArgOperand(0)); 7331 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7332 MVT::i32); 7333 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7334 MVT::i32); 7335 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7336 MVT::i32); 7337 SDValue Result = DAG.getMemIntrinsicNode( 7338 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7339 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7340 /* align */ std::nullopt, Flags); 7341 7342 // Chain the prefetch in parallel with any pending loads, to stay out of 7343 // the way of later optimizations. 7344 PendingLoads.push_back(Result); 7345 Result = getRoot(); 7346 DAG.setRoot(Result); 7347 return; 7348 } 7349 case Intrinsic::lifetime_start: 7350 case Intrinsic::lifetime_end: { 7351 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7352 // Stack coloring is not enabled in O0, discard region information. 7353 if (TM.getOptLevel() == CodeGenOptLevel::None) 7354 return; 7355 7356 const int64_t ObjectSize = 7357 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7358 Value *const ObjectPtr = I.getArgOperand(1); 7359 SmallVector<const Value *, 4> Allocas; 7360 getUnderlyingObjects(ObjectPtr, Allocas); 7361 7362 for (const Value *Alloca : Allocas) { 7363 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7364 7365 // Could not find an Alloca. 7366 if (!LifetimeObject) 7367 continue; 7368 7369 // First check that the Alloca is static, otherwise it won't have a 7370 // valid frame index. 7371 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7372 if (SI == FuncInfo.StaticAllocaMap.end()) 7373 return; 7374 7375 const int FrameIndex = SI->second; 7376 int64_t Offset; 7377 if (GetPointerBaseWithConstantOffset( 7378 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7379 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7380 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7381 Offset); 7382 DAG.setRoot(Res); 7383 } 7384 return; 7385 } 7386 case Intrinsic::pseudoprobe: { 7387 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7388 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7389 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7390 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7391 DAG.setRoot(Res); 7392 return; 7393 } 7394 case Intrinsic::invariant_start: 7395 // Discard region information. 7396 setValue(&I, 7397 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7398 return; 7399 case Intrinsic::invariant_end: 7400 // Discard region information. 7401 return; 7402 case Intrinsic::clear_cache: 7403 /// FunctionName may be null. 7404 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7405 lowerCallToExternalSymbol(I, FunctionName); 7406 return; 7407 case Intrinsic::donothing: 7408 case Intrinsic::seh_try_begin: 7409 case Intrinsic::seh_scope_begin: 7410 case Intrinsic::seh_try_end: 7411 case Intrinsic::seh_scope_end: 7412 // ignore 7413 return; 7414 case Intrinsic::experimental_stackmap: 7415 visitStackmap(I); 7416 return; 7417 case Intrinsic::experimental_patchpoint_void: 7418 case Intrinsic::experimental_patchpoint_i64: 7419 visitPatchpoint(I); 7420 return; 7421 case Intrinsic::experimental_gc_statepoint: 7422 LowerStatepoint(cast<GCStatepointInst>(I)); 7423 return; 7424 case Intrinsic::experimental_gc_result: 7425 visitGCResult(cast<GCResultInst>(I)); 7426 return; 7427 case Intrinsic::experimental_gc_relocate: 7428 visitGCRelocate(cast<GCRelocateInst>(I)); 7429 return; 7430 case Intrinsic::instrprof_cover: 7431 llvm_unreachable("instrprof failed to lower a cover"); 7432 case Intrinsic::instrprof_increment: 7433 llvm_unreachable("instrprof failed to lower an increment"); 7434 case Intrinsic::instrprof_timestamp: 7435 llvm_unreachable("instrprof failed to lower a timestamp"); 7436 case Intrinsic::instrprof_value_profile: 7437 llvm_unreachable("instrprof failed to lower a value profiling call"); 7438 case Intrinsic::instrprof_mcdc_parameters: 7439 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7440 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7441 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7442 case Intrinsic::instrprof_mcdc_condbitmap_update: 7443 llvm_unreachable("instrprof failed to lower an mcdc condbitmap update"); 7444 case Intrinsic::localescape: { 7445 MachineFunction &MF = DAG.getMachineFunction(); 7446 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7447 7448 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7449 // is the same on all targets. 7450 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7451 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7452 if (isa<ConstantPointerNull>(Arg)) 7453 continue; // Skip null pointers. They represent a hole in index space. 7454 AllocaInst *Slot = cast<AllocaInst>(Arg); 7455 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7456 "can only escape static allocas"); 7457 int FI = FuncInfo.StaticAllocaMap[Slot]; 7458 MCSymbol *FrameAllocSym = 7459 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7460 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7461 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7462 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7463 .addSym(FrameAllocSym) 7464 .addFrameIndex(FI); 7465 } 7466 7467 return; 7468 } 7469 7470 case Intrinsic::localrecover: { 7471 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7472 MachineFunction &MF = DAG.getMachineFunction(); 7473 7474 // Get the symbol that defines the frame offset. 7475 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7476 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7477 unsigned IdxVal = 7478 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7479 MCSymbol *FrameAllocSym = 7480 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7481 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7482 7483 Value *FP = I.getArgOperand(1); 7484 SDValue FPVal = getValue(FP); 7485 EVT PtrVT = FPVal.getValueType(); 7486 7487 // Create a MCSymbol for the label to avoid any target lowering 7488 // that would make this PC relative. 7489 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7490 SDValue OffsetVal = 7491 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7492 7493 // Add the offset to the FP. 7494 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7495 setValue(&I, Add); 7496 7497 return; 7498 } 7499 7500 case Intrinsic::eh_exceptionpointer: 7501 case Intrinsic::eh_exceptioncode: { 7502 // Get the exception pointer vreg, copy from it, and resize it to fit. 7503 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7504 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7505 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7506 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7507 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7508 if (Intrinsic == Intrinsic::eh_exceptioncode) 7509 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7510 setValue(&I, N); 7511 return; 7512 } 7513 case Intrinsic::xray_customevent: { 7514 // Here we want to make sure that the intrinsic behaves as if it has a 7515 // specific calling convention. 7516 const auto &Triple = DAG.getTarget().getTargetTriple(); 7517 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7518 return; 7519 7520 SmallVector<SDValue, 8> Ops; 7521 7522 // We want to say that we always want the arguments in registers. 7523 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7524 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7525 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7526 SDValue Chain = getRoot(); 7527 Ops.push_back(LogEntryVal); 7528 Ops.push_back(StrSizeVal); 7529 Ops.push_back(Chain); 7530 7531 // We need to enforce the calling convention for the callsite, so that 7532 // argument ordering is enforced correctly, and that register allocation can 7533 // see that some registers may be assumed clobbered and have to preserve 7534 // them across calls to the intrinsic. 7535 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7536 sdl, NodeTys, Ops); 7537 SDValue patchableNode = SDValue(MN, 0); 7538 DAG.setRoot(patchableNode); 7539 setValue(&I, patchableNode); 7540 return; 7541 } 7542 case Intrinsic::xray_typedevent: { 7543 // Here we want to make sure that the intrinsic behaves as if it has a 7544 // specific calling convention. 7545 const auto &Triple = DAG.getTarget().getTargetTriple(); 7546 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7547 return; 7548 7549 SmallVector<SDValue, 8> Ops; 7550 7551 // We want to say that we always want the arguments in registers. 7552 // It's unclear to me how manipulating the selection DAG here forces callers 7553 // to provide arguments in registers instead of on the stack. 7554 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7555 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7556 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7557 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7558 SDValue Chain = getRoot(); 7559 Ops.push_back(LogTypeId); 7560 Ops.push_back(LogEntryVal); 7561 Ops.push_back(StrSizeVal); 7562 Ops.push_back(Chain); 7563 7564 // We need to enforce the calling convention for the callsite, so that 7565 // argument ordering is enforced correctly, and that register allocation can 7566 // see that some registers may be assumed clobbered and have to preserve 7567 // them across calls to the intrinsic. 7568 MachineSDNode *MN = DAG.getMachineNode( 7569 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7570 SDValue patchableNode = SDValue(MN, 0); 7571 DAG.setRoot(patchableNode); 7572 setValue(&I, patchableNode); 7573 return; 7574 } 7575 case Intrinsic::experimental_deoptimize: 7576 LowerDeoptimizeCall(&I); 7577 return; 7578 case Intrinsic::experimental_stepvector: 7579 visitStepVector(I); 7580 return; 7581 case Intrinsic::vector_reduce_fadd: 7582 case Intrinsic::vector_reduce_fmul: 7583 case Intrinsic::vector_reduce_add: 7584 case Intrinsic::vector_reduce_mul: 7585 case Intrinsic::vector_reduce_and: 7586 case Intrinsic::vector_reduce_or: 7587 case Intrinsic::vector_reduce_xor: 7588 case Intrinsic::vector_reduce_smax: 7589 case Intrinsic::vector_reduce_smin: 7590 case Intrinsic::vector_reduce_umax: 7591 case Intrinsic::vector_reduce_umin: 7592 case Intrinsic::vector_reduce_fmax: 7593 case Intrinsic::vector_reduce_fmin: 7594 case Intrinsic::vector_reduce_fmaximum: 7595 case Intrinsic::vector_reduce_fminimum: 7596 visitVectorReduce(I, Intrinsic); 7597 return; 7598 7599 case Intrinsic::icall_branch_funnel: { 7600 SmallVector<SDValue, 16> Ops; 7601 Ops.push_back(getValue(I.getArgOperand(0))); 7602 7603 int64_t Offset; 7604 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7605 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7606 if (!Base) 7607 report_fatal_error( 7608 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7609 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7610 7611 struct BranchFunnelTarget { 7612 int64_t Offset; 7613 SDValue Target; 7614 }; 7615 SmallVector<BranchFunnelTarget, 8> Targets; 7616 7617 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7618 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7619 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7620 if (ElemBase != Base) 7621 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7622 "to the same GlobalValue"); 7623 7624 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7625 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7626 if (!GA) 7627 report_fatal_error( 7628 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7629 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7630 GA->getGlobal(), sdl, Val.getValueType(), 7631 GA->getOffset())}); 7632 } 7633 llvm::sort(Targets, 7634 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7635 return T1.Offset < T2.Offset; 7636 }); 7637 7638 for (auto &T : Targets) { 7639 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7640 Ops.push_back(T.Target); 7641 } 7642 7643 Ops.push_back(DAG.getRoot()); // Chain 7644 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7645 MVT::Other, Ops), 7646 0); 7647 DAG.setRoot(N); 7648 setValue(&I, N); 7649 HasTailCall = true; 7650 return; 7651 } 7652 7653 case Intrinsic::wasm_landingpad_index: 7654 // Information this intrinsic contained has been transferred to 7655 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7656 // delete it now. 7657 return; 7658 7659 case Intrinsic::aarch64_settag: 7660 case Intrinsic::aarch64_settag_zero: { 7661 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7662 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7663 SDValue Val = TSI.EmitTargetCodeForSetTag( 7664 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7665 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7666 ZeroMemory); 7667 DAG.setRoot(Val); 7668 setValue(&I, Val); 7669 return; 7670 } 7671 case Intrinsic::amdgcn_cs_chain: { 7672 assert(I.arg_size() == 5 && "Additional args not supported yet"); 7673 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 7674 "Non-zero flags not supported yet"); 7675 7676 // At this point we don't care if it's amdgpu_cs_chain or 7677 // amdgpu_cs_chain_preserve. 7678 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 7679 7680 Type *RetTy = I.getType(); 7681 assert(RetTy->isVoidTy() && "Should not return"); 7682 7683 SDValue Callee = getValue(I.getOperand(0)); 7684 7685 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 7686 // We'll also tack the value of the EXEC mask at the end. 7687 TargetLowering::ArgListTy Args; 7688 Args.reserve(3); 7689 7690 for (unsigned Idx : {2, 3, 1}) { 7691 TargetLowering::ArgListEntry Arg; 7692 Arg.Node = getValue(I.getOperand(Idx)); 7693 Arg.Ty = I.getOperand(Idx)->getType(); 7694 Arg.setAttributes(&I, Idx); 7695 Args.push_back(Arg); 7696 } 7697 7698 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 7699 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 7700 Args[2].IsInReg = true; // EXEC should be inreg 7701 7702 TargetLowering::CallLoweringInfo CLI(DAG); 7703 CLI.setDebugLoc(getCurSDLoc()) 7704 .setChain(getRoot()) 7705 .setCallee(CC, RetTy, Callee, std::move(Args)) 7706 .setNoReturn(true) 7707 .setTailCall(true) 7708 .setConvergent(I.isConvergent()); 7709 CLI.CB = &I; 7710 std::pair<SDValue, SDValue> Result = 7711 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 7712 (void)Result; 7713 assert(!Result.first.getNode() && !Result.second.getNode() && 7714 "Should've lowered as tail call"); 7715 7716 HasTailCall = true; 7717 return; 7718 } 7719 case Intrinsic::ptrmask: { 7720 SDValue Ptr = getValue(I.getOperand(0)); 7721 SDValue Mask = getValue(I.getOperand(1)); 7722 7723 EVT PtrVT = Ptr.getValueType(); 7724 assert(PtrVT == Mask.getValueType() && 7725 "Pointers with different index type are not supported by SDAG"); 7726 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 7727 return; 7728 } 7729 case Intrinsic::threadlocal_address: { 7730 setValue(&I, getValue(I.getOperand(0))); 7731 return; 7732 } 7733 case Intrinsic::get_active_lane_mask: { 7734 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7735 SDValue Index = getValue(I.getOperand(0)); 7736 EVT ElementVT = Index.getValueType(); 7737 7738 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7739 visitTargetIntrinsic(I, Intrinsic); 7740 return; 7741 } 7742 7743 SDValue TripCount = getValue(I.getOperand(1)); 7744 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 7745 CCVT.getVectorElementCount()); 7746 7747 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7748 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7749 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7750 SDValue VectorInduction = DAG.getNode( 7751 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7752 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7753 VectorTripCount, ISD::CondCode::SETULT); 7754 setValue(&I, SetCC); 7755 return; 7756 } 7757 case Intrinsic::experimental_get_vector_length: { 7758 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7759 "Expected positive VF"); 7760 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7761 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7762 7763 SDValue Count = getValue(I.getOperand(0)); 7764 EVT CountVT = Count.getValueType(); 7765 7766 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7767 visitTargetIntrinsic(I, Intrinsic); 7768 return; 7769 } 7770 7771 // Expand to a umin between the trip count and the maximum elements the type 7772 // can hold. 7773 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7774 7775 // Extend the trip count to at least the result VT. 7776 if (CountVT.bitsLT(VT)) { 7777 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7778 CountVT = VT; 7779 } 7780 7781 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7782 ElementCount::get(VF, IsScalable)); 7783 7784 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7785 // Clip to the result type if needed. 7786 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7787 7788 setValue(&I, Trunc); 7789 return; 7790 } 7791 case Intrinsic::experimental_cttz_elts: { 7792 auto DL = getCurSDLoc(); 7793 SDValue Op = getValue(I.getOperand(0)); 7794 EVT OpVT = Op.getValueType(); 7795 7796 if (!TLI.shouldExpandCttzElements(OpVT)) { 7797 visitTargetIntrinsic(I, Intrinsic); 7798 return; 7799 } 7800 7801 if (OpVT.getScalarType() != MVT::i1) { 7802 // Compare the input vector elements to zero & use to count trailing zeros 7803 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 7804 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 7805 OpVT.getVectorElementCount()); 7806 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 7807 } 7808 7809 // Find the smallest "sensible" element type to use for the expansion. 7810 ConstantRange CR( 7811 APInt(64, OpVT.getVectorElementCount().getKnownMinValue())); 7812 if (OpVT.isScalableVT()) 7813 CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64)); 7814 7815 // If the zero-is-poison flag is set, we can assume the upper limit 7816 // of the result is VF-1. 7817 if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero()) 7818 CR = CR.subtract(APInt(64, 1)); 7819 7820 unsigned EltWidth = I.getType()->getScalarSizeInBits(); 7821 EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits()); 7822 EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8); 7823 7824 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 7825 7826 // Create the new vector type & get the vector length 7827 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 7828 OpVT.getVectorElementCount()); 7829 7830 SDValue VL = 7831 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 7832 7833 SDValue StepVec = DAG.getStepVector(DL, NewVT); 7834 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 7835 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 7836 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 7837 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 7838 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 7839 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 7840 7841 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7842 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 7843 7844 setValue(&I, Ret); 7845 return; 7846 } 7847 case Intrinsic::vector_insert: { 7848 SDValue Vec = getValue(I.getOperand(0)); 7849 SDValue SubVec = getValue(I.getOperand(1)); 7850 SDValue Index = getValue(I.getOperand(2)); 7851 7852 // The intrinsic's index type is i64, but the SDNode requires an index type 7853 // suitable for the target. Convert the index as required. 7854 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7855 if (Index.getValueType() != VectorIdxTy) 7856 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7857 7858 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7859 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7860 Index)); 7861 return; 7862 } 7863 case Intrinsic::vector_extract: { 7864 SDValue Vec = getValue(I.getOperand(0)); 7865 SDValue Index = getValue(I.getOperand(1)); 7866 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7867 7868 // The intrinsic's index type is i64, but the SDNode requires an index type 7869 // suitable for the target. Convert the index as required. 7870 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7871 if (Index.getValueType() != VectorIdxTy) 7872 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7873 7874 setValue(&I, 7875 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7876 return; 7877 } 7878 case Intrinsic::experimental_vector_reverse: 7879 visitVectorReverse(I); 7880 return; 7881 case Intrinsic::experimental_vector_splice: 7882 visitVectorSplice(I); 7883 return; 7884 case Intrinsic::callbr_landingpad: 7885 visitCallBrLandingPad(I); 7886 return; 7887 case Intrinsic::experimental_vector_interleave2: 7888 visitVectorInterleave(I); 7889 return; 7890 case Intrinsic::experimental_vector_deinterleave2: 7891 visitVectorDeinterleave(I); 7892 return; 7893 } 7894 } 7895 7896 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7897 const ConstrainedFPIntrinsic &FPI) { 7898 SDLoc sdl = getCurSDLoc(); 7899 7900 // We do not need to serialize constrained FP intrinsics against 7901 // each other or against (nonvolatile) loads, so they can be 7902 // chained like loads. 7903 SDValue Chain = DAG.getRoot(); 7904 SmallVector<SDValue, 4> Opers; 7905 Opers.push_back(Chain); 7906 if (FPI.isUnaryOp()) { 7907 Opers.push_back(getValue(FPI.getArgOperand(0))); 7908 } else if (FPI.isTernaryOp()) { 7909 Opers.push_back(getValue(FPI.getArgOperand(0))); 7910 Opers.push_back(getValue(FPI.getArgOperand(1))); 7911 Opers.push_back(getValue(FPI.getArgOperand(2))); 7912 } else { 7913 Opers.push_back(getValue(FPI.getArgOperand(0))); 7914 Opers.push_back(getValue(FPI.getArgOperand(1))); 7915 } 7916 7917 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7918 assert(Result.getNode()->getNumValues() == 2); 7919 7920 // Push node to the appropriate list so that future instructions can be 7921 // chained up correctly. 7922 SDValue OutChain = Result.getValue(1); 7923 switch (EB) { 7924 case fp::ExceptionBehavior::ebIgnore: 7925 // The only reason why ebIgnore nodes still need to be chained is that 7926 // they might depend on the current rounding mode, and therefore must 7927 // not be moved across instruction that may change that mode. 7928 [[fallthrough]]; 7929 case fp::ExceptionBehavior::ebMayTrap: 7930 // These must not be moved across calls or instructions that may change 7931 // floating-point exception masks. 7932 PendingConstrainedFP.push_back(OutChain); 7933 break; 7934 case fp::ExceptionBehavior::ebStrict: 7935 // These must not be moved across calls or instructions that may change 7936 // floating-point exception masks or read floating-point exception flags. 7937 // In addition, they cannot be optimized out even if unused. 7938 PendingConstrainedFPStrict.push_back(OutChain); 7939 break; 7940 } 7941 }; 7942 7943 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7944 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7945 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7946 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7947 7948 SDNodeFlags Flags; 7949 if (EB == fp::ExceptionBehavior::ebIgnore) 7950 Flags.setNoFPExcept(true); 7951 7952 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7953 Flags.copyFMF(*FPOp); 7954 7955 unsigned Opcode; 7956 switch (FPI.getIntrinsicID()) { 7957 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7958 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7959 case Intrinsic::INTRINSIC: \ 7960 Opcode = ISD::STRICT_##DAGN; \ 7961 break; 7962 #include "llvm/IR/ConstrainedOps.def" 7963 case Intrinsic::experimental_constrained_fmuladd: { 7964 Opcode = ISD::STRICT_FMA; 7965 // Break fmuladd into fmul and fadd. 7966 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7967 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7968 Opers.pop_back(); 7969 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7970 pushOutChain(Mul, EB); 7971 Opcode = ISD::STRICT_FADD; 7972 Opers.clear(); 7973 Opers.push_back(Mul.getValue(1)); 7974 Opers.push_back(Mul.getValue(0)); 7975 Opers.push_back(getValue(FPI.getArgOperand(2))); 7976 } 7977 break; 7978 } 7979 } 7980 7981 // A few strict DAG nodes carry additional operands that are not 7982 // set up by the default code above. 7983 switch (Opcode) { 7984 default: break; 7985 case ISD::STRICT_FP_ROUND: 7986 Opers.push_back( 7987 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7988 break; 7989 case ISD::STRICT_FSETCC: 7990 case ISD::STRICT_FSETCCS: { 7991 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7992 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7993 if (TM.Options.NoNaNsFPMath) 7994 Condition = getFCmpCodeWithoutNaN(Condition); 7995 Opers.push_back(DAG.getCondCode(Condition)); 7996 break; 7997 } 7998 } 7999 8000 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 8001 pushOutChain(Result, EB); 8002 8003 SDValue FPResult = Result.getValue(0); 8004 setValue(&FPI, FPResult); 8005 } 8006 8007 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 8008 std::optional<unsigned> ResOPC; 8009 switch (VPIntrin.getIntrinsicID()) { 8010 case Intrinsic::vp_ctlz: { 8011 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8012 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 8013 break; 8014 } 8015 case Intrinsic::vp_cttz: { 8016 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8017 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 8018 break; 8019 } 8020 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 8021 case Intrinsic::VPID: \ 8022 ResOPC = ISD::VPSD; \ 8023 break; 8024 #include "llvm/IR/VPIntrinsics.def" 8025 } 8026 8027 if (!ResOPC) 8028 llvm_unreachable( 8029 "Inconsistency: no SDNode available for this VPIntrinsic!"); 8030 8031 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 8032 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 8033 if (VPIntrin.getFastMathFlags().allowReassoc()) 8034 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 8035 : ISD::VP_REDUCE_FMUL; 8036 } 8037 8038 return *ResOPC; 8039 } 8040 8041 void SelectionDAGBuilder::visitVPLoad( 8042 const VPIntrinsic &VPIntrin, EVT VT, 8043 const SmallVectorImpl<SDValue> &OpValues) { 8044 SDLoc DL = getCurSDLoc(); 8045 Value *PtrOperand = VPIntrin.getArgOperand(0); 8046 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8047 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8048 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8049 SDValue LD; 8050 // Do not serialize variable-length loads of constant memory with 8051 // anything. 8052 if (!Alignment) 8053 Alignment = DAG.getEVTAlign(VT); 8054 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8055 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8056 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8057 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8058 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 8059 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 8060 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 8061 MMO, false /*IsExpanding */); 8062 if (AddToChain) 8063 PendingLoads.push_back(LD.getValue(1)); 8064 setValue(&VPIntrin, LD); 8065 } 8066 8067 void SelectionDAGBuilder::visitVPGather( 8068 const VPIntrinsic &VPIntrin, EVT VT, 8069 const SmallVectorImpl<SDValue> &OpValues) { 8070 SDLoc DL = getCurSDLoc(); 8071 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8072 Value *PtrOperand = VPIntrin.getArgOperand(0); 8073 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8074 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8075 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8076 SDValue LD; 8077 if (!Alignment) 8078 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8079 unsigned AS = 8080 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8081 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8082 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8083 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 8084 SDValue Base, Index, Scale; 8085 ISD::MemIndexType IndexType; 8086 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8087 this, VPIntrin.getParent(), 8088 VT.getScalarStoreSize()); 8089 if (!UniformBase) { 8090 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8091 Index = getValue(PtrOperand); 8092 IndexType = ISD::SIGNED_SCALED; 8093 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8094 } 8095 EVT IdxVT = Index.getValueType(); 8096 EVT EltTy = IdxVT.getVectorElementType(); 8097 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8098 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8099 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8100 } 8101 LD = DAG.getGatherVP( 8102 DAG.getVTList(VT, MVT::Other), VT, DL, 8103 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 8104 IndexType); 8105 PendingLoads.push_back(LD.getValue(1)); 8106 setValue(&VPIntrin, LD); 8107 } 8108 8109 void SelectionDAGBuilder::visitVPStore( 8110 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8111 SDLoc DL = getCurSDLoc(); 8112 Value *PtrOperand = VPIntrin.getArgOperand(1); 8113 EVT VT = OpValues[0].getValueType(); 8114 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8115 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8116 SDValue ST; 8117 if (!Alignment) 8118 Alignment = DAG.getEVTAlign(VT); 8119 SDValue Ptr = OpValues[1]; 8120 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 8121 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8122 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 8123 MemoryLocation::UnknownSize, *Alignment, AAInfo); 8124 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 8125 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 8126 /* IsTruncating */ false, /*IsCompressing*/ false); 8127 DAG.setRoot(ST); 8128 setValue(&VPIntrin, ST); 8129 } 8130 8131 void SelectionDAGBuilder::visitVPScatter( 8132 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8133 SDLoc DL = getCurSDLoc(); 8134 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8135 Value *PtrOperand = VPIntrin.getArgOperand(1); 8136 EVT VT = OpValues[0].getValueType(); 8137 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8138 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8139 SDValue ST; 8140 if (!Alignment) 8141 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8142 unsigned AS = 8143 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8144 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8145 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8146 MemoryLocation::UnknownSize, *Alignment, AAInfo); 8147 SDValue Base, Index, Scale; 8148 ISD::MemIndexType IndexType; 8149 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8150 this, VPIntrin.getParent(), 8151 VT.getScalarStoreSize()); 8152 if (!UniformBase) { 8153 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8154 Index = getValue(PtrOperand); 8155 IndexType = ISD::SIGNED_SCALED; 8156 Scale = 8157 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8158 } 8159 EVT IdxVT = Index.getValueType(); 8160 EVT EltTy = IdxVT.getVectorElementType(); 8161 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8162 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8163 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8164 } 8165 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 8166 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 8167 OpValues[2], OpValues[3]}, 8168 MMO, IndexType); 8169 DAG.setRoot(ST); 8170 setValue(&VPIntrin, ST); 8171 } 8172 8173 void SelectionDAGBuilder::visitVPStridedLoad( 8174 const VPIntrinsic &VPIntrin, EVT VT, 8175 const SmallVectorImpl<SDValue> &OpValues) { 8176 SDLoc DL = getCurSDLoc(); 8177 Value *PtrOperand = VPIntrin.getArgOperand(0); 8178 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8179 if (!Alignment) 8180 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8181 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8182 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8183 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8184 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8185 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8186 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8187 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8188 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8189 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 8190 8191 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 8192 OpValues[2], OpValues[3], MMO, 8193 false /*IsExpanding*/); 8194 8195 if (AddToChain) 8196 PendingLoads.push_back(LD.getValue(1)); 8197 setValue(&VPIntrin, LD); 8198 } 8199 8200 void SelectionDAGBuilder::visitVPStridedStore( 8201 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8202 SDLoc DL = getCurSDLoc(); 8203 Value *PtrOperand = VPIntrin.getArgOperand(1); 8204 EVT VT = OpValues[0].getValueType(); 8205 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8206 if (!Alignment) 8207 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8208 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8209 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8210 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8211 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8212 MemoryLocation::UnknownSize, *Alignment, AAInfo); 8213 8214 SDValue ST = DAG.getStridedStoreVP( 8215 getMemoryRoot(), DL, OpValues[0], OpValues[1], 8216 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 8217 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 8218 /*IsCompressing*/ false); 8219 8220 DAG.setRoot(ST); 8221 setValue(&VPIntrin, ST); 8222 } 8223 8224 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8225 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8226 SDLoc DL = getCurSDLoc(); 8227 8228 ISD::CondCode Condition; 8229 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8230 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8231 if (IsFP) { 8232 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8233 // flags, but calls that don't return floating-point types can't be 8234 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8235 Condition = getFCmpCondCode(CondCode); 8236 if (TM.Options.NoNaNsFPMath) 8237 Condition = getFCmpCodeWithoutNaN(Condition); 8238 } else { 8239 Condition = getICmpCondCode(CondCode); 8240 } 8241 8242 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8243 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8244 // #2 is the condition code 8245 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8246 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8247 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8248 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8249 "Unexpected target EVL type"); 8250 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8251 8252 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8253 VPIntrin.getType()); 8254 setValue(&VPIntrin, 8255 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8256 } 8257 8258 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8259 const VPIntrinsic &VPIntrin) { 8260 SDLoc DL = getCurSDLoc(); 8261 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8262 8263 auto IID = VPIntrin.getIntrinsicID(); 8264 8265 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8266 return visitVPCmp(*CmpI); 8267 8268 SmallVector<EVT, 4> ValueVTs; 8269 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8270 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8271 SDVTList VTs = DAG.getVTList(ValueVTs); 8272 8273 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8274 8275 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8276 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8277 "Unexpected target EVL type"); 8278 8279 // Request operands. 8280 SmallVector<SDValue, 7> OpValues; 8281 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8282 auto Op = getValue(VPIntrin.getArgOperand(I)); 8283 if (I == EVLParamPos) 8284 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8285 OpValues.push_back(Op); 8286 } 8287 8288 switch (Opcode) { 8289 default: { 8290 SDNodeFlags SDFlags; 8291 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8292 SDFlags.copyFMF(*FPMO); 8293 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8294 setValue(&VPIntrin, Result); 8295 break; 8296 } 8297 case ISD::VP_LOAD: 8298 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8299 break; 8300 case ISD::VP_GATHER: 8301 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8302 break; 8303 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8304 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8305 break; 8306 case ISD::VP_STORE: 8307 visitVPStore(VPIntrin, OpValues); 8308 break; 8309 case ISD::VP_SCATTER: 8310 visitVPScatter(VPIntrin, OpValues); 8311 break; 8312 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8313 visitVPStridedStore(VPIntrin, OpValues); 8314 break; 8315 case ISD::VP_FMULADD: { 8316 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8317 SDNodeFlags SDFlags; 8318 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8319 SDFlags.copyFMF(*FPMO); 8320 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8321 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8322 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8323 } else { 8324 SDValue Mul = DAG.getNode( 8325 ISD::VP_FMUL, DL, VTs, 8326 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8327 SDValue Add = 8328 DAG.getNode(ISD::VP_FADD, DL, VTs, 8329 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8330 setValue(&VPIntrin, Add); 8331 } 8332 break; 8333 } 8334 case ISD::VP_IS_FPCLASS: { 8335 const DataLayout DLayout = DAG.getDataLayout(); 8336 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8337 auto Constant = OpValues[1]->getAsZExtVal(); 8338 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8339 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8340 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8341 setValue(&VPIntrin, V); 8342 return; 8343 } 8344 case ISD::VP_INTTOPTR: { 8345 SDValue N = OpValues[0]; 8346 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8347 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8348 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8349 OpValues[2]); 8350 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8351 OpValues[2]); 8352 setValue(&VPIntrin, N); 8353 break; 8354 } 8355 case ISD::VP_PTRTOINT: { 8356 SDValue N = OpValues[0]; 8357 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8358 VPIntrin.getType()); 8359 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8360 VPIntrin.getOperand(0)->getType()); 8361 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8362 OpValues[2]); 8363 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8364 OpValues[2]); 8365 setValue(&VPIntrin, N); 8366 break; 8367 } 8368 case ISD::VP_ABS: 8369 case ISD::VP_CTLZ: 8370 case ISD::VP_CTLZ_ZERO_UNDEF: 8371 case ISD::VP_CTTZ: 8372 case ISD::VP_CTTZ_ZERO_UNDEF: { 8373 SDValue Result = 8374 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8375 setValue(&VPIntrin, Result); 8376 break; 8377 } 8378 } 8379 } 8380 8381 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8382 const BasicBlock *EHPadBB, 8383 MCSymbol *&BeginLabel) { 8384 MachineFunction &MF = DAG.getMachineFunction(); 8385 MachineModuleInfo &MMI = MF.getMMI(); 8386 8387 // Insert a label before the invoke call to mark the try range. This can be 8388 // used to detect deletion of the invoke via the MachineModuleInfo. 8389 BeginLabel = MMI.getContext().createTempSymbol(); 8390 8391 // For SjLj, keep track of which landing pads go with which invokes 8392 // so as to maintain the ordering of pads in the LSDA. 8393 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 8394 if (CallSiteIndex) { 8395 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8396 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 8397 8398 // Now that the call site is handled, stop tracking it. 8399 MMI.setCurrentCallSite(0); 8400 } 8401 8402 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8403 } 8404 8405 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8406 const BasicBlock *EHPadBB, 8407 MCSymbol *BeginLabel) { 8408 assert(BeginLabel && "BeginLabel should've been set"); 8409 8410 MachineFunction &MF = DAG.getMachineFunction(); 8411 MachineModuleInfo &MMI = MF.getMMI(); 8412 8413 // Insert a label at the end of the invoke call to mark the try range. This 8414 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8415 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 8416 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8417 8418 // Inform MachineModuleInfo of range. 8419 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8420 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8421 // actually use outlined funclets and their LSDA info style. 8422 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8423 assert(II && "II should've been set"); 8424 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8425 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8426 } else if (!isScopedEHPersonality(Pers)) { 8427 assert(EHPadBB); 8428 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 8429 } 8430 8431 return Chain; 8432 } 8433 8434 std::pair<SDValue, SDValue> 8435 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8436 const BasicBlock *EHPadBB) { 8437 MCSymbol *BeginLabel = nullptr; 8438 8439 if (EHPadBB) { 8440 // Both PendingLoads and PendingExports must be flushed here; 8441 // this call might not return. 8442 (void)getRoot(); 8443 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8444 CLI.setChain(getRoot()); 8445 } 8446 8447 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8448 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8449 8450 assert((CLI.IsTailCall || Result.second.getNode()) && 8451 "Non-null chain expected with non-tail call!"); 8452 assert((Result.second.getNode() || !Result.first.getNode()) && 8453 "Null value expected with tail call!"); 8454 8455 if (!Result.second.getNode()) { 8456 // As a special case, a null chain means that a tail call has been emitted 8457 // and the DAG root is already updated. 8458 HasTailCall = true; 8459 8460 // Since there's no actual continuation from this block, nothing can be 8461 // relying on us setting vregs for them. 8462 PendingExports.clear(); 8463 } else { 8464 DAG.setRoot(Result.second); 8465 } 8466 8467 if (EHPadBB) { 8468 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8469 BeginLabel)); 8470 } 8471 8472 return Result; 8473 } 8474 8475 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8476 bool isTailCall, 8477 bool isMustTailCall, 8478 const BasicBlock *EHPadBB) { 8479 auto &DL = DAG.getDataLayout(); 8480 FunctionType *FTy = CB.getFunctionType(); 8481 Type *RetTy = CB.getType(); 8482 8483 TargetLowering::ArgListTy Args; 8484 Args.reserve(CB.arg_size()); 8485 8486 const Value *SwiftErrorVal = nullptr; 8487 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8488 8489 if (isTailCall) { 8490 // Avoid emitting tail calls in functions with the disable-tail-calls 8491 // attribute. 8492 auto *Caller = CB.getParent()->getParent(); 8493 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8494 "true" && !isMustTailCall) 8495 isTailCall = false; 8496 8497 // We can't tail call inside a function with a swifterror argument. Lowering 8498 // does not support this yet. It would have to move into the swifterror 8499 // register before the call. 8500 if (TLI.supportSwiftError() && 8501 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8502 isTailCall = false; 8503 } 8504 8505 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8506 TargetLowering::ArgListEntry Entry; 8507 const Value *V = *I; 8508 8509 // Skip empty types 8510 if (V->getType()->isEmptyTy()) 8511 continue; 8512 8513 SDValue ArgNode = getValue(V); 8514 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8515 8516 Entry.setAttributes(&CB, I - CB.arg_begin()); 8517 8518 // Use swifterror virtual register as input to the call. 8519 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8520 SwiftErrorVal = V; 8521 // We find the virtual register for the actual swifterror argument. 8522 // Instead of using the Value, we use the virtual register instead. 8523 Entry.Node = 8524 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8525 EVT(TLI.getPointerTy(DL))); 8526 } 8527 8528 Args.push_back(Entry); 8529 8530 // If we have an explicit sret argument that is an Instruction, (i.e., it 8531 // might point to function-local memory), we can't meaningfully tail-call. 8532 if (Entry.IsSRet && isa<Instruction>(V)) 8533 isTailCall = false; 8534 } 8535 8536 // If call site has a cfguardtarget operand bundle, create and add an 8537 // additional ArgListEntry. 8538 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8539 TargetLowering::ArgListEntry Entry; 8540 Value *V = Bundle->Inputs[0]; 8541 SDValue ArgNode = getValue(V); 8542 Entry.Node = ArgNode; 8543 Entry.Ty = V->getType(); 8544 Entry.IsCFGuardTarget = true; 8545 Args.push_back(Entry); 8546 } 8547 8548 // Check if target-independent constraints permit a tail call here. 8549 // Target-dependent constraints are checked within TLI->LowerCallTo. 8550 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8551 isTailCall = false; 8552 8553 // Disable tail calls if there is an swifterror argument. Targets have not 8554 // been updated to support tail calls. 8555 if (TLI.supportSwiftError() && SwiftErrorVal) 8556 isTailCall = false; 8557 8558 ConstantInt *CFIType = nullptr; 8559 if (CB.isIndirectCall()) { 8560 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8561 if (!TLI.supportKCFIBundles()) 8562 report_fatal_error( 8563 "Target doesn't support calls with kcfi operand bundles."); 8564 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8565 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8566 } 8567 } 8568 8569 TargetLowering::CallLoweringInfo CLI(DAG); 8570 CLI.setDebugLoc(getCurSDLoc()) 8571 .setChain(getRoot()) 8572 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8573 .setTailCall(isTailCall) 8574 .setConvergent(CB.isConvergent()) 8575 .setIsPreallocated( 8576 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8577 .setCFIType(CFIType); 8578 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8579 8580 if (Result.first.getNode()) { 8581 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8582 setValue(&CB, Result.first); 8583 } 8584 8585 // The last element of CLI.InVals has the SDValue for swifterror return. 8586 // Here we copy it to a virtual register and update SwiftErrorMap for 8587 // book-keeping. 8588 if (SwiftErrorVal && TLI.supportSwiftError()) { 8589 // Get the last element of InVals. 8590 SDValue Src = CLI.InVals.back(); 8591 Register VReg = 8592 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8593 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8594 DAG.setRoot(CopyNode); 8595 } 8596 } 8597 8598 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8599 SelectionDAGBuilder &Builder) { 8600 // Check to see if this load can be trivially constant folded, e.g. if the 8601 // input is from a string literal. 8602 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8603 // Cast pointer to the type we really want to load. 8604 Type *LoadTy = 8605 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8606 if (LoadVT.isVector()) 8607 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8608 8609 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8610 PointerType::getUnqual(LoadTy)); 8611 8612 if (const Constant *LoadCst = 8613 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8614 LoadTy, Builder.DAG.getDataLayout())) 8615 return Builder.getValue(LoadCst); 8616 } 8617 8618 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8619 // still constant memory, the input chain can be the entry node. 8620 SDValue Root; 8621 bool ConstantMemory = false; 8622 8623 // Do not serialize (non-volatile) loads of constant memory with anything. 8624 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8625 Root = Builder.DAG.getEntryNode(); 8626 ConstantMemory = true; 8627 } else { 8628 // Do not serialize non-volatile loads against each other. 8629 Root = Builder.DAG.getRoot(); 8630 } 8631 8632 SDValue Ptr = Builder.getValue(PtrVal); 8633 SDValue LoadVal = 8634 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8635 MachinePointerInfo(PtrVal), Align(1)); 8636 8637 if (!ConstantMemory) 8638 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8639 return LoadVal; 8640 } 8641 8642 /// Record the value for an instruction that produces an integer result, 8643 /// converting the type where necessary. 8644 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8645 SDValue Value, 8646 bool IsSigned) { 8647 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8648 I.getType(), true); 8649 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8650 setValue(&I, Value); 8651 } 8652 8653 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8654 /// true and lower it. Otherwise return false, and it will be lowered like a 8655 /// normal call. 8656 /// The caller already checked that \p I calls the appropriate LibFunc with a 8657 /// correct prototype. 8658 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8659 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8660 const Value *Size = I.getArgOperand(2); 8661 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8662 if (CSize && CSize->getZExtValue() == 0) { 8663 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8664 I.getType(), true); 8665 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8666 return true; 8667 } 8668 8669 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8670 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8671 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8672 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8673 if (Res.first.getNode()) { 8674 processIntegerCallValue(I, Res.first, true); 8675 PendingLoads.push_back(Res.second); 8676 return true; 8677 } 8678 8679 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8680 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8681 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8682 return false; 8683 8684 // If the target has a fast compare for the given size, it will return a 8685 // preferred load type for that size. Require that the load VT is legal and 8686 // that the target supports unaligned loads of that type. Otherwise, return 8687 // INVALID. 8688 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8689 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8690 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8691 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8692 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8693 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8694 // TODO: Check alignment of src and dest ptrs. 8695 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8696 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8697 if (!TLI.isTypeLegal(LVT) || 8698 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8699 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8700 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8701 } 8702 8703 return LVT; 8704 }; 8705 8706 // This turns into unaligned loads. We only do this if the target natively 8707 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8708 // we'll only produce a small number of byte loads. 8709 MVT LoadVT; 8710 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8711 switch (NumBitsToCompare) { 8712 default: 8713 return false; 8714 case 16: 8715 LoadVT = MVT::i16; 8716 break; 8717 case 32: 8718 LoadVT = MVT::i32; 8719 break; 8720 case 64: 8721 case 128: 8722 case 256: 8723 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8724 break; 8725 } 8726 8727 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8728 return false; 8729 8730 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8731 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8732 8733 // Bitcast to a wide integer type if the loads are vectors. 8734 if (LoadVT.isVector()) { 8735 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8736 LoadL = DAG.getBitcast(CmpVT, LoadL); 8737 LoadR = DAG.getBitcast(CmpVT, LoadR); 8738 } 8739 8740 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8741 processIntegerCallValue(I, Cmp, false); 8742 return true; 8743 } 8744 8745 /// See if we can lower a memchr call into an optimized form. If so, return 8746 /// true and lower it. Otherwise return false, and it will be lowered like a 8747 /// normal call. 8748 /// The caller already checked that \p I calls the appropriate LibFunc with a 8749 /// correct prototype. 8750 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8751 const Value *Src = I.getArgOperand(0); 8752 const Value *Char = I.getArgOperand(1); 8753 const Value *Length = I.getArgOperand(2); 8754 8755 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8756 std::pair<SDValue, SDValue> Res = 8757 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8758 getValue(Src), getValue(Char), getValue(Length), 8759 MachinePointerInfo(Src)); 8760 if (Res.first.getNode()) { 8761 setValue(&I, Res.first); 8762 PendingLoads.push_back(Res.second); 8763 return true; 8764 } 8765 8766 return false; 8767 } 8768 8769 /// See if we can lower a mempcpy call into an optimized form. If so, return 8770 /// true and lower it. Otherwise return false, and it will be lowered like a 8771 /// normal call. 8772 /// The caller already checked that \p I calls the appropriate LibFunc with a 8773 /// correct prototype. 8774 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8775 SDValue Dst = getValue(I.getArgOperand(0)); 8776 SDValue Src = getValue(I.getArgOperand(1)); 8777 SDValue Size = getValue(I.getArgOperand(2)); 8778 8779 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8780 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8781 // DAG::getMemcpy needs Alignment to be defined. 8782 Align Alignment = std::min(DstAlign, SrcAlign); 8783 8784 SDLoc sdl = getCurSDLoc(); 8785 8786 // In the mempcpy context we need to pass in a false value for isTailCall 8787 // because the return pointer needs to be adjusted by the size of 8788 // the copied memory. 8789 SDValue Root = getMemoryRoot(); 8790 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8791 /*isTailCall=*/false, 8792 MachinePointerInfo(I.getArgOperand(0)), 8793 MachinePointerInfo(I.getArgOperand(1)), 8794 I.getAAMetadata()); 8795 assert(MC.getNode() != nullptr && 8796 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8797 DAG.setRoot(MC); 8798 8799 // Check if Size needs to be truncated or extended. 8800 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8801 8802 // Adjust return pointer to point just past the last dst byte. 8803 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8804 Dst, Size); 8805 setValue(&I, DstPlusSize); 8806 return true; 8807 } 8808 8809 /// See if we can lower a strcpy call into an optimized form. If so, return 8810 /// true and lower it, otherwise return false and it will be lowered like a 8811 /// normal call. 8812 /// The caller already checked that \p I calls the appropriate LibFunc with a 8813 /// correct prototype. 8814 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8815 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8816 8817 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8818 std::pair<SDValue, SDValue> Res = 8819 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8820 getValue(Arg0), getValue(Arg1), 8821 MachinePointerInfo(Arg0), 8822 MachinePointerInfo(Arg1), isStpcpy); 8823 if (Res.first.getNode()) { 8824 setValue(&I, Res.first); 8825 DAG.setRoot(Res.second); 8826 return true; 8827 } 8828 8829 return false; 8830 } 8831 8832 /// See if we can lower a strcmp call into an optimized form. If so, return 8833 /// true and lower it, otherwise return false and it will be lowered like a 8834 /// normal call. 8835 /// The caller already checked that \p I calls the appropriate LibFunc with a 8836 /// correct prototype. 8837 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8838 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8839 8840 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8841 std::pair<SDValue, SDValue> Res = 8842 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8843 getValue(Arg0), getValue(Arg1), 8844 MachinePointerInfo(Arg0), 8845 MachinePointerInfo(Arg1)); 8846 if (Res.first.getNode()) { 8847 processIntegerCallValue(I, Res.first, true); 8848 PendingLoads.push_back(Res.second); 8849 return true; 8850 } 8851 8852 return false; 8853 } 8854 8855 /// See if we can lower a strlen call into an optimized form. If so, return 8856 /// true and lower it, otherwise return false and it will be lowered like a 8857 /// normal call. 8858 /// The caller already checked that \p I calls the appropriate LibFunc with a 8859 /// correct prototype. 8860 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8861 const Value *Arg0 = I.getArgOperand(0); 8862 8863 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8864 std::pair<SDValue, SDValue> Res = 8865 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8866 getValue(Arg0), MachinePointerInfo(Arg0)); 8867 if (Res.first.getNode()) { 8868 processIntegerCallValue(I, Res.first, false); 8869 PendingLoads.push_back(Res.second); 8870 return true; 8871 } 8872 8873 return false; 8874 } 8875 8876 /// See if we can lower a strnlen call into an optimized form. If so, return 8877 /// true and lower it, otherwise return false and it will be lowered like a 8878 /// normal call. 8879 /// The caller already checked that \p I calls the appropriate LibFunc with a 8880 /// correct prototype. 8881 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8882 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8883 8884 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8885 std::pair<SDValue, SDValue> Res = 8886 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8887 getValue(Arg0), getValue(Arg1), 8888 MachinePointerInfo(Arg0)); 8889 if (Res.first.getNode()) { 8890 processIntegerCallValue(I, Res.first, false); 8891 PendingLoads.push_back(Res.second); 8892 return true; 8893 } 8894 8895 return false; 8896 } 8897 8898 /// See if we can lower a unary floating-point operation into an SDNode with 8899 /// the specified Opcode. If so, return true and lower it, otherwise return 8900 /// false and it will be lowered like a normal call. 8901 /// The caller already checked that \p I calls the appropriate LibFunc with a 8902 /// correct prototype. 8903 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8904 unsigned Opcode) { 8905 // We already checked this call's prototype; verify it doesn't modify errno. 8906 if (!I.onlyReadsMemory()) 8907 return false; 8908 8909 SDNodeFlags Flags; 8910 Flags.copyFMF(cast<FPMathOperator>(I)); 8911 8912 SDValue Tmp = getValue(I.getArgOperand(0)); 8913 setValue(&I, 8914 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8915 return true; 8916 } 8917 8918 /// See if we can lower a binary floating-point operation into an SDNode with 8919 /// the specified Opcode. If so, return true and lower it. Otherwise return 8920 /// false, and it will be lowered like a normal call. 8921 /// The caller already checked that \p I calls the appropriate LibFunc with a 8922 /// correct prototype. 8923 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8924 unsigned Opcode) { 8925 // We already checked this call's prototype; verify it doesn't modify errno. 8926 if (!I.onlyReadsMemory()) 8927 return false; 8928 8929 SDNodeFlags Flags; 8930 Flags.copyFMF(cast<FPMathOperator>(I)); 8931 8932 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8933 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8934 EVT VT = Tmp0.getValueType(); 8935 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8936 return true; 8937 } 8938 8939 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8940 // Handle inline assembly differently. 8941 if (I.isInlineAsm()) { 8942 visitInlineAsm(I); 8943 return; 8944 } 8945 8946 diagnoseDontCall(I); 8947 8948 if (Function *F = I.getCalledFunction()) { 8949 if (F->isDeclaration()) { 8950 // Is this an LLVM intrinsic or a target-specific intrinsic? 8951 unsigned IID = F->getIntrinsicID(); 8952 if (!IID) 8953 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8954 IID = II->getIntrinsicID(F); 8955 8956 if (IID) { 8957 visitIntrinsicCall(I, IID); 8958 return; 8959 } 8960 } 8961 8962 // Check for well-known libc/libm calls. If the function is internal, it 8963 // can't be a library call. Don't do the check if marked as nobuiltin for 8964 // some reason or the call site requires strict floating point semantics. 8965 LibFunc Func; 8966 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8967 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8968 LibInfo->hasOptimizedCodeGen(Func)) { 8969 switch (Func) { 8970 default: break; 8971 case LibFunc_bcmp: 8972 if (visitMemCmpBCmpCall(I)) 8973 return; 8974 break; 8975 case LibFunc_copysign: 8976 case LibFunc_copysignf: 8977 case LibFunc_copysignl: 8978 // We already checked this call's prototype; verify it doesn't modify 8979 // errno. 8980 if (I.onlyReadsMemory()) { 8981 SDValue LHS = getValue(I.getArgOperand(0)); 8982 SDValue RHS = getValue(I.getArgOperand(1)); 8983 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8984 LHS.getValueType(), LHS, RHS)); 8985 return; 8986 } 8987 break; 8988 case LibFunc_fabs: 8989 case LibFunc_fabsf: 8990 case LibFunc_fabsl: 8991 if (visitUnaryFloatCall(I, ISD::FABS)) 8992 return; 8993 break; 8994 case LibFunc_fmin: 8995 case LibFunc_fminf: 8996 case LibFunc_fminl: 8997 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8998 return; 8999 break; 9000 case LibFunc_fmax: 9001 case LibFunc_fmaxf: 9002 case LibFunc_fmaxl: 9003 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 9004 return; 9005 break; 9006 case LibFunc_sin: 9007 case LibFunc_sinf: 9008 case LibFunc_sinl: 9009 if (visitUnaryFloatCall(I, ISD::FSIN)) 9010 return; 9011 break; 9012 case LibFunc_cos: 9013 case LibFunc_cosf: 9014 case LibFunc_cosl: 9015 if (visitUnaryFloatCall(I, ISD::FCOS)) 9016 return; 9017 break; 9018 case LibFunc_sqrt: 9019 case LibFunc_sqrtf: 9020 case LibFunc_sqrtl: 9021 case LibFunc_sqrt_finite: 9022 case LibFunc_sqrtf_finite: 9023 case LibFunc_sqrtl_finite: 9024 if (visitUnaryFloatCall(I, ISD::FSQRT)) 9025 return; 9026 break; 9027 case LibFunc_floor: 9028 case LibFunc_floorf: 9029 case LibFunc_floorl: 9030 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 9031 return; 9032 break; 9033 case LibFunc_nearbyint: 9034 case LibFunc_nearbyintf: 9035 case LibFunc_nearbyintl: 9036 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 9037 return; 9038 break; 9039 case LibFunc_ceil: 9040 case LibFunc_ceilf: 9041 case LibFunc_ceill: 9042 if (visitUnaryFloatCall(I, ISD::FCEIL)) 9043 return; 9044 break; 9045 case LibFunc_rint: 9046 case LibFunc_rintf: 9047 case LibFunc_rintl: 9048 if (visitUnaryFloatCall(I, ISD::FRINT)) 9049 return; 9050 break; 9051 case LibFunc_round: 9052 case LibFunc_roundf: 9053 case LibFunc_roundl: 9054 if (visitUnaryFloatCall(I, ISD::FROUND)) 9055 return; 9056 break; 9057 case LibFunc_trunc: 9058 case LibFunc_truncf: 9059 case LibFunc_truncl: 9060 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 9061 return; 9062 break; 9063 case LibFunc_log2: 9064 case LibFunc_log2f: 9065 case LibFunc_log2l: 9066 if (visitUnaryFloatCall(I, ISD::FLOG2)) 9067 return; 9068 break; 9069 case LibFunc_exp2: 9070 case LibFunc_exp2f: 9071 case LibFunc_exp2l: 9072 if (visitUnaryFloatCall(I, ISD::FEXP2)) 9073 return; 9074 break; 9075 case LibFunc_exp10: 9076 case LibFunc_exp10f: 9077 case LibFunc_exp10l: 9078 if (visitUnaryFloatCall(I, ISD::FEXP10)) 9079 return; 9080 break; 9081 case LibFunc_ldexp: 9082 case LibFunc_ldexpf: 9083 case LibFunc_ldexpl: 9084 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 9085 return; 9086 break; 9087 case LibFunc_memcmp: 9088 if (visitMemCmpBCmpCall(I)) 9089 return; 9090 break; 9091 case LibFunc_mempcpy: 9092 if (visitMemPCpyCall(I)) 9093 return; 9094 break; 9095 case LibFunc_memchr: 9096 if (visitMemChrCall(I)) 9097 return; 9098 break; 9099 case LibFunc_strcpy: 9100 if (visitStrCpyCall(I, false)) 9101 return; 9102 break; 9103 case LibFunc_stpcpy: 9104 if (visitStrCpyCall(I, true)) 9105 return; 9106 break; 9107 case LibFunc_strcmp: 9108 if (visitStrCmpCall(I)) 9109 return; 9110 break; 9111 case LibFunc_strlen: 9112 if (visitStrLenCall(I)) 9113 return; 9114 break; 9115 case LibFunc_strnlen: 9116 if (visitStrNLenCall(I)) 9117 return; 9118 break; 9119 } 9120 } 9121 } 9122 9123 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 9124 // have to do anything here to lower funclet bundles. 9125 // CFGuardTarget bundles are lowered in LowerCallTo. 9126 assert(!I.hasOperandBundlesOtherThan( 9127 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 9128 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 9129 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 9130 "Cannot lower calls with arbitrary operand bundles!"); 9131 9132 SDValue Callee = getValue(I.getCalledOperand()); 9133 9134 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 9135 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 9136 else 9137 // Check if we can potentially perform a tail call. More detailed checking 9138 // is be done within LowerCallTo, after more information about the call is 9139 // known. 9140 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 9141 } 9142 9143 namespace { 9144 9145 /// AsmOperandInfo - This contains information for each constraint that we are 9146 /// lowering. 9147 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 9148 public: 9149 /// CallOperand - If this is the result output operand or a clobber 9150 /// this is null, otherwise it is the incoming operand to the CallInst. 9151 /// This gets modified as the asm is processed. 9152 SDValue CallOperand; 9153 9154 /// AssignedRegs - If this is a register or register class operand, this 9155 /// contains the set of register corresponding to the operand. 9156 RegsForValue AssignedRegs; 9157 9158 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 9159 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 9160 } 9161 9162 /// Whether or not this operand accesses memory 9163 bool hasMemory(const TargetLowering &TLI) const { 9164 // Indirect operand accesses access memory. 9165 if (isIndirect) 9166 return true; 9167 9168 for (const auto &Code : Codes) 9169 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 9170 return true; 9171 9172 return false; 9173 } 9174 }; 9175 9176 9177 } // end anonymous namespace 9178 9179 /// Make sure that the output operand \p OpInfo and its corresponding input 9180 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 9181 /// out). 9182 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 9183 SDISelAsmOperandInfo &MatchingOpInfo, 9184 SelectionDAG &DAG) { 9185 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 9186 return; 9187 9188 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 9189 const auto &TLI = DAG.getTargetLoweringInfo(); 9190 9191 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 9192 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 9193 OpInfo.ConstraintVT); 9194 std::pair<unsigned, const TargetRegisterClass *> InputRC = 9195 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 9196 MatchingOpInfo.ConstraintVT); 9197 if ((OpInfo.ConstraintVT.isInteger() != 9198 MatchingOpInfo.ConstraintVT.isInteger()) || 9199 (MatchRC.second != InputRC.second)) { 9200 // FIXME: error out in a more elegant fashion 9201 report_fatal_error("Unsupported asm: input constraint" 9202 " with a matching output constraint of" 9203 " incompatible type!"); 9204 } 9205 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 9206 } 9207 9208 /// Get a direct memory input to behave well as an indirect operand. 9209 /// This may introduce stores, hence the need for a \p Chain. 9210 /// \return The (possibly updated) chain. 9211 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 9212 SDISelAsmOperandInfo &OpInfo, 9213 SelectionDAG &DAG) { 9214 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9215 9216 // If we don't have an indirect input, put it in the constpool if we can, 9217 // otherwise spill it to a stack slot. 9218 // TODO: This isn't quite right. We need to handle these according to 9219 // the addressing mode that the constraint wants. Also, this may take 9220 // an additional register for the computation and we don't want that 9221 // either. 9222 9223 // If the operand is a float, integer, or vector constant, spill to a 9224 // constant pool entry to get its address. 9225 const Value *OpVal = OpInfo.CallOperandVal; 9226 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9227 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9228 OpInfo.CallOperand = DAG.getConstantPool( 9229 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9230 return Chain; 9231 } 9232 9233 // Otherwise, create a stack slot and emit a store to it before the asm. 9234 Type *Ty = OpVal->getType(); 9235 auto &DL = DAG.getDataLayout(); 9236 uint64_t TySize = DL.getTypeAllocSize(Ty); 9237 MachineFunction &MF = DAG.getMachineFunction(); 9238 int SSFI = MF.getFrameInfo().CreateStackObject( 9239 TySize, DL.getPrefTypeAlign(Ty), false); 9240 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9241 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9242 MachinePointerInfo::getFixedStack(MF, SSFI), 9243 TLI.getMemValueType(DL, Ty)); 9244 OpInfo.CallOperand = StackSlot; 9245 9246 return Chain; 9247 } 9248 9249 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9250 /// specified operand. We prefer to assign virtual registers, to allow the 9251 /// register allocator to handle the assignment process. However, if the asm 9252 /// uses features that we can't model on machineinstrs, we have SDISel do the 9253 /// allocation. This produces generally horrible, but correct, code. 9254 /// 9255 /// OpInfo describes the operand 9256 /// RefOpInfo describes the matching operand if any, the operand otherwise 9257 static std::optional<unsigned> 9258 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9259 SDISelAsmOperandInfo &OpInfo, 9260 SDISelAsmOperandInfo &RefOpInfo) { 9261 LLVMContext &Context = *DAG.getContext(); 9262 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9263 9264 MachineFunction &MF = DAG.getMachineFunction(); 9265 SmallVector<unsigned, 4> Regs; 9266 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9267 9268 // No work to do for memory/address operands. 9269 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9270 OpInfo.ConstraintType == TargetLowering::C_Address) 9271 return std::nullopt; 9272 9273 // If this is a constraint for a single physreg, or a constraint for a 9274 // register class, find it. 9275 unsigned AssignedReg; 9276 const TargetRegisterClass *RC; 9277 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9278 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9279 // RC is unset only on failure. Return immediately. 9280 if (!RC) 9281 return std::nullopt; 9282 9283 // Get the actual register value type. This is important, because the user 9284 // may have asked for (e.g.) the AX register in i32 type. We need to 9285 // remember that AX is actually i16 to get the right extension. 9286 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9287 9288 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9289 // If this is an FP operand in an integer register (or visa versa), or more 9290 // generally if the operand value disagrees with the register class we plan 9291 // to stick it in, fix the operand type. 9292 // 9293 // If this is an input value, the bitcast to the new type is done now. 9294 // Bitcast for output value is done at the end of visitInlineAsm(). 9295 if ((OpInfo.Type == InlineAsm::isOutput || 9296 OpInfo.Type == InlineAsm::isInput) && 9297 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9298 // Try to convert to the first EVT that the reg class contains. If the 9299 // types are identical size, use a bitcast to convert (e.g. two differing 9300 // vector types). Note: output bitcast is done at the end of 9301 // visitInlineAsm(). 9302 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9303 // Exclude indirect inputs while they are unsupported because the code 9304 // to perform the load is missing and thus OpInfo.CallOperand still 9305 // refers to the input address rather than the pointed-to value. 9306 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9307 OpInfo.CallOperand = 9308 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9309 OpInfo.ConstraintVT = RegVT; 9310 // If the operand is an FP value and we want it in integer registers, 9311 // use the corresponding integer type. This turns an f64 value into 9312 // i64, which can be passed with two i32 values on a 32-bit machine. 9313 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9314 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9315 if (OpInfo.Type == InlineAsm::isInput) 9316 OpInfo.CallOperand = 9317 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9318 OpInfo.ConstraintVT = VT; 9319 } 9320 } 9321 } 9322 9323 // No need to allocate a matching input constraint since the constraint it's 9324 // matching to has already been allocated. 9325 if (OpInfo.isMatchingInputConstraint()) 9326 return std::nullopt; 9327 9328 EVT ValueVT = OpInfo.ConstraintVT; 9329 if (OpInfo.ConstraintVT == MVT::Other) 9330 ValueVT = RegVT; 9331 9332 // Initialize NumRegs. 9333 unsigned NumRegs = 1; 9334 if (OpInfo.ConstraintVT != MVT::Other) 9335 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9336 9337 // If this is a constraint for a specific physical register, like {r17}, 9338 // assign it now. 9339 9340 // If this associated to a specific register, initialize iterator to correct 9341 // place. If virtual, make sure we have enough registers 9342 9343 // Initialize iterator if necessary 9344 TargetRegisterClass::iterator I = RC->begin(); 9345 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9346 9347 // Do not check for single registers. 9348 if (AssignedReg) { 9349 I = std::find(I, RC->end(), AssignedReg); 9350 if (I == RC->end()) { 9351 // RC does not contain the selected register, which indicates a 9352 // mismatch between the register and the required type/bitwidth. 9353 return {AssignedReg}; 9354 } 9355 } 9356 9357 for (; NumRegs; --NumRegs, ++I) { 9358 assert(I != RC->end() && "Ran out of registers to allocate!"); 9359 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9360 Regs.push_back(R); 9361 } 9362 9363 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9364 return std::nullopt; 9365 } 9366 9367 static unsigned 9368 findMatchingInlineAsmOperand(unsigned OperandNo, 9369 const std::vector<SDValue> &AsmNodeOperands) { 9370 // Scan until we find the definition we already emitted of this operand. 9371 unsigned CurOp = InlineAsm::Op_FirstOperand; 9372 for (; OperandNo; --OperandNo) { 9373 // Advance to the next operand. 9374 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal(); 9375 const InlineAsm::Flag F(OpFlag); 9376 assert( 9377 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9378 "Skipped past definitions?"); 9379 CurOp += F.getNumOperandRegisters() + 1; 9380 } 9381 return CurOp; 9382 } 9383 9384 namespace { 9385 9386 class ExtraFlags { 9387 unsigned Flags = 0; 9388 9389 public: 9390 explicit ExtraFlags(const CallBase &Call) { 9391 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9392 if (IA->hasSideEffects()) 9393 Flags |= InlineAsm::Extra_HasSideEffects; 9394 if (IA->isAlignStack()) 9395 Flags |= InlineAsm::Extra_IsAlignStack; 9396 if (Call.isConvergent()) 9397 Flags |= InlineAsm::Extra_IsConvergent; 9398 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9399 } 9400 9401 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9402 // Ideally, we would only check against memory constraints. However, the 9403 // meaning of an Other constraint can be target-specific and we can't easily 9404 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9405 // for Other constraints as well. 9406 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9407 OpInfo.ConstraintType == TargetLowering::C_Other) { 9408 if (OpInfo.Type == InlineAsm::isInput) 9409 Flags |= InlineAsm::Extra_MayLoad; 9410 else if (OpInfo.Type == InlineAsm::isOutput) 9411 Flags |= InlineAsm::Extra_MayStore; 9412 else if (OpInfo.Type == InlineAsm::isClobber) 9413 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9414 } 9415 } 9416 9417 unsigned get() const { return Flags; } 9418 }; 9419 9420 } // end anonymous namespace 9421 9422 static bool isFunction(SDValue Op) { 9423 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9424 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9425 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9426 9427 // In normal "call dllimport func" instruction (non-inlineasm) it force 9428 // indirect access by specifing call opcode. And usually specially print 9429 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9430 // not do in this way now. (In fact, this is similar with "Data Access" 9431 // action). So here we ignore dllimport function. 9432 if (Fn && !Fn->hasDLLImportStorageClass()) 9433 return true; 9434 } 9435 } 9436 return false; 9437 } 9438 9439 /// visitInlineAsm - Handle a call to an InlineAsm object. 9440 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9441 const BasicBlock *EHPadBB) { 9442 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9443 9444 /// ConstraintOperands - Information about all of the constraints. 9445 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9446 9447 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9448 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9449 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9450 9451 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9452 // AsmDialect, MayLoad, MayStore). 9453 bool HasSideEffect = IA->hasSideEffects(); 9454 ExtraFlags ExtraInfo(Call); 9455 9456 for (auto &T : TargetConstraints) { 9457 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9458 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9459 9460 if (OpInfo.CallOperandVal) 9461 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9462 9463 if (!HasSideEffect) 9464 HasSideEffect = OpInfo.hasMemory(TLI); 9465 9466 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9467 // FIXME: Could we compute this on OpInfo rather than T? 9468 9469 // Compute the constraint code and ConstraintType to use. 9470 TLI.ComputeConstraintToUse(T, SDValue()); 9471 9472 if (T.ConstraintType == TargetLowering::C_Immediate && 9473 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9474 // We've delayed emitting a diagnostic like the "n" constraint because 9475 // inlining could cause an integer showing up. 9476 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9477 "' expects an integer constant " 9478 "expression"); 9479 9480 ExtraInfo.update(T); 9481 } 9482 9483 // We won't need to flush pending loads if this asm doesn't touch 9484 // memory and is nonvolatile. 9485 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9486 9487 bool EmitEHLabels = isa<InvokeInst>(Call); 9488 if (EmitEHLabels) { 9489 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9490 } 9491 bool IsCallBr = isa<CallBrInst>(Call); 9492 9493 if (IsCallBr || EmitEHLabels) { 9494 // If this is a callbr or invoke we need to flush pending exports since 9495 // inlineasm_br and invoke are terminators. 9496 // We need to do this before nodes are glued to the inlineasm_br node. 9497 Chain = getControlRoot(); 9498 } 9499 9500 MCSymbol *BeginLabel = nullptr; 9501 if (EmitEHLabels) { 9502 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9503 } 9504 9505 int OpNo = -1; 9506 SmallVector<StringRef> AsmStrs; 9507 IA->collectAsmStrs(AsmStrs); 9508 9509 // Second pass over the constraints: compute which constraint option to use. 9510 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9511 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9512 OpNo++; 9513 9514 // If this is an output operand with a matching input operand, look up the 9515 // matching input. If their types mismatch, e.g. one is an integer, the 9516 // other is floating point, or their sizes are different, flag it as an 9517 // error. 9518 if (OpInfo.hasMatchingInput()) { 9519 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9520 patchMatchingInput(OpInfo, Input, DAG); 9521 } 9522 9523 // Compute the constraint code and ConstraintType to use. 9524 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9525 9526 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9527 OpInfo.Type == InlineAsm::isClobber) || 9528 OpInfo.ConstraintType == TargetLowering::C_Address) 9529 continue; 9530 9531 // In Linux PIC model, there are 4 cases about value/label addressing: 9532 // 9533 // 1: Function call or Label jmp inside the module. 9534 // 2: Data access (such as global variable, static variable) inside module. 9535 // 3: Function call or Label jmp outside the module. 9536 // 4: Data access (such as global variable) outside the module. 9537 // 9538 // Due to current llvm inline asm architecture designed to not "recognize" 9539 // the asm code, there are quite troubles for us to treat mem addressing 9540 // differently for same value/adress used in different instuctions. 9541 // For example, in pic model, call a func may in plt way or direclty 9542 // pc-related, but lea/mov a function adress may use got. 9543 // 9544 // Here we try to "recognize" function call for the case 1 and case 3 in 9545 // inline asm. And try to adjust the constraint for them. 9546 // 9547 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9548 // label, so here we don't handle jmp function label now, but we need to 9549 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9550 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9551 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9552 TM.getCodeModel() != CodeModel::Large) { 9553 OpInfo.isIndirect = false; 9554 OpInfo.ConstraintType = TargetLowering::C_Address; 9555 } 9556 9557 // If this is a memory input, and if the operand is not indirect, do what we 9558 // need to provide an address for the memory input. 9559 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9560 !OpInfo.isIndirect) { 9561 assert((OpInfo.isMultipleAlternative || 9562 (OpInfo.Type == InlineAsm::isInput)) && 9563 "Can only indirectify direct input operands!"); 9564 9565 // Memory operands really want the address of the value. 9566 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9567 9568 // There is no longer a Value* corresponding to this operand. 9569 OpInfo.CallOperandVal = nullptr; 9570 9571 // It is now an indirect operand. 9572 OpInfo.isIndirect = true; 9573 } 9574 9575 } 9576 9577 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9578 std::vector<SDValue> AsmNodeOperands; 9579 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9580 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9581 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9582 9583 // If we have a !srcloc metadata node associated with it, we want to attach 9584 // this to the ultimately generated inline asm machineinstr. To do this, we 9585 // pass in the third operand as this (potentially null) inline asm MDNode. 9586 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9587 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9588 9589 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9590 // bits as operand 3. 9591 AsmNodeOperands.push_back(DAG.getTargetConstant( 9592 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9593 9594 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9595 // this, assign virtual and physical registers for inputs and otput. 9596 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9597 // Assign Registers. 9598 SDISelAsmOperandInfo &RefOpInfo = 9599 OpInfo.isMatchingInputConstraint() 9600 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9601 : OpInfo; 9602 const auto RegError = 9603 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9604 if (RegError) { 9605 const MachineFunction &MF = DAG.getMachineFunction(); 9606 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9607 const char *RegName = TRI.getName(*RegError); 9608 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9609 "' allocated for constraint '" + 9610 Twine(OpInfo.ConstraintCode) + 9611 "' does not match required type"); 9612 return; 9613 } 9614 9615 auto DetectWriteToReservedRegister = [&]() { 9616 const MachineFunction &MF = DAG.getMachineFunction(); 9617 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9618 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9619 if (Register::isPhysicalRegister(Reg) && 9620 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9621 const char *RegName = TRI.getName(Reg); 9622 emitInlineAsmError(Call, "write to reserved register '" + 9623 Twine(RegName) + "'"); 9624 return true; 9625 } 9626 } 9627 return false; 9628 }; 9629 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9630 (OpInfo.Type == InlineAsm::isInput && 9631 !OpInfo.isMatchingInputConstraint())) && 9632 "Only address as input operand is allowed."); 9633 9634 switch (OpInfo.Type) { 9635 case InlineAsm::isOutput: 9636 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9637 const InlineAsm::ConstraintCode ConstraintID = 9638 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9639 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9640 "Failed to convert memory constraint code to constraint id."); 9641 9642 // Add information to the INLINEASM node to know about this output. 9643 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 9644 OpFlags.setMemConstraint(ConstraintID); 9645 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9646 MVT::i32)); 9647 AsmNodeOperands.push_back(OpInfo.CallOperand); 9648 } else { 9649 // Otherwise, this outputs to a register (directly for C_Register / 9650 // C_RegisterClass, and a target-defined fashion for 9651 // C_Immediate/C_Other). Find a register that we can use. 9652 if (OpInfo.AssignedRegs.Regs.empty()) { 9653 emitInlineAsmError( 9654 Call, "couldn't allocate output register for constraint '" + 9655 Twine(OpInfo.ConstraintCode) + "'"); 9656 return; 9657 } 9658 9659 if (DetectWriteToReservedRegister()) 9660 return; 9661 9662 // Add information to the INLINEASM node to know that this register is 9663 // set. 9664 OpInfo.AssignedRegs.AddInlineAsmOperands( 9665 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 9666 : InlineAsm::Kind::RegDef, 9667 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9668 } 9669 break; 9670 9671 case InlineAsm::isInput: 9672 case InlineAsm::isLabel: { 9673 SDValue InOperandVal = OpInfo.CallOperand; 9674 9675 if (OpInfo.isMatchingInputConstraint()) { 9676 // If this is required to match an output register we have already set, 9677 // just use its register. 9678 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9679 AsmNodeOperands); 9680 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal()); 9681 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 9682 if (OpInfo.isIndirect) { 9683 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9684 emitInlineAsmError(Call, "inline asm not supported yet: " 9685 "don't know how to handle tied " 9686 "indirect register inputs"); 9687 return; 9688 } 9689 9690 SmallVector<unsigned, 4> Regs; 9691 MachineFunction &MF = DAG.getMachineFunction(); 9692 MachineRegisterInfo &MRI = MF.getRegInfo(); 9693 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9694 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9695 Register TiedReg = R->getReg(); 9696 MVT RegVT = R->getSimpleValueType(0); 9697 const TargetRegisterClass *RC = 9698 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9699 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9700 : TRI.getMinimalPhysRegClass(TiedReg); 9701 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 9702 Regs.push_back(MRI.createVirtualRegister(RC)); 9703 9704 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9705 9706 SDLoc dl = getCurSDLoc(); 9707 // Use the produced MatchedRegs object to 9708 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9709 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 9710 OpInfo.getMatchedOperand(), dl, DAG, 9711 AsmNodeOperands); 9712 break; 9713 } 9714 9715 assert(Flag.isMemKind() && "Unknown matching constraint!"); 9716 assert(Flag.getNumOperandRegisters() == 1 && 9717 "Unexpected number of operands"); 9718 // Add information to the INLINEASM node to know about this input. 9719 // See InlineAsm.h isUseOperandTiedToDef. 9720 Flag.clearMemConstraint(); 9721 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 9722 AsmNodeOperands.push_back(DAG.getTargetConstant( 9723 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9724 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9725 break; 9726 } 9727 9728 // Treat indirect 'X' constraint as memory. 9729 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9730 OpInfo.isIndirect) 9731 OpInfo.ConstraintType = TargetLowering::C_Memory; 9732 9733 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9734 OpInfo.ConstraintType == TargetLowering::C_Other) { 9735 std::vector<SDValue> Ops; 9736 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9737 Ops, DAG); 9738 if (Ops.empty()) { 9739 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9740 if (isa<ConstantSDNode>(InOperandVal)) { 9741 emitInlineAsmError(Call, "value out of range for constraint '" + 9742 Twine(OpInfo.ConstraintCode) + "'"); 9743 return; 9744 } 9745 9746 emitInlineAsmError(Call, 9747 "invalid operand for inline asm constraint '" + 9748 Twine(OpInfo.ConstraintCode) + "'"); 9749 return; 9750 } 9751 9752 // Add information to the INLINEASM node to know about this input. 9753 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 9754 AsmNodeOperands.push_back(DAG.getTargetConstant( 9755 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9756 llvm::append_range(AsmNodeOperands, Ops); 9757 break; 9758 } 9759 9760 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9761 assert((OpInfo.isIndirect || 9762 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9763 "Operand must be indirect to be a mem!"); 9764 assert(InOperandVal.getValueType() == 9765 TLI.getPointerTy(DAG.getDataLayout()) && 9766 "Memory operands expect pointer values"); 9767 9768 const InlineAsm::ConstraintCode ConstraintID = 9769 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9770 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9771 "Failed to convert memory constraint code to constraint id."); 9772 9773 // Add information to the INLINEASM node to know about this input. 9774 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9775 ResOpType.setMemConstraint(ConstraintID); 9776 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9777 getCurSDLoc(), 9778 MVT::i32)); 9779 AsmNodeOperands.push_back(InOperandVal); 9780 break; 9781 } 9782 9783 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9784 const InlineAsm::ConstraintCode ConstraintID = 9785 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9786 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9787 "Failed to convert memory constraint code to constraint id."); 9788 9789 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9790 9791 SDValue AsmOp = InOperandVal; 9792 if (isFunction(InOperandVal)) { 9793 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9794 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 9795 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9796 InOperandVal.getValueType(), 9797 GA->getOffset()); 9798 } 9799 9800 // Add information to the INLINEASM node to know about this input. 9801 ResOpType.setMemConstraint(ConstraintID); 9802 9803 AsmNodeOperands.push_back( 9804 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9805 9806 AsmNodeOperands.push_back(AsmOp); 9807 break; 9808 } 9809 9810 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9811 OpInfo.ConstraintType == TargetLowering::C_Register) && 9812 "Unknown constraint type!"); 9813 9814 // TODO: Support this. 9815 if (OpInfo.isIndirect) { 9816 emitInlineAsmError( 9817 Call, "Don't know how to handle indirect register inputs yet " 9818 "for constraint '" + 9819 Twine(OpInfo.ConstraintCode) + "'"); 9820 return; 9821 } 9822 9823 // Copy the input into the appropriate registers. 9824 if (OpInfo.AssignedRegs.Regs.empty()) { 9825 emitInlineAsmError(Call, 9826 "couldn't allocate input reg for constraint '" + 9827 Twine(OpInfo.ConstraintCode) + "'"); 9828 return; 9829 } 9830 9831 if (DetectWriteToReservedRegister()) 9832 return; 9833 9834 SDLoc dl = getCurSDLoc(); 9835 9836 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9837 &Call); 9838 9839 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 9840 0, dl, DAG, AsmNodeOperands); 9841 break; 9842 } 9843 case InlineAsm::isClobber: 9844 // Add the clobbered value to the operand list, so that the register 9845 // allocator is aware that the physreg got clobbered. 9846 if (!OpInfo.AssignedRegs.Regs.empty()) 9847 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 9848 false, 0, getCurSDLoc(), DAG, 9849 AsmNodeOperands); 9850 break; 9851 } 9852 } 9853 9854 // Finish up input operands. Set the input chain and add the flag last. 9855 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9856 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9857 9858 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9859 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9860 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9861 Glue = Chain.getValue(1); 9862 9863 // Do additional work to generate outputs. 9864 9865 SmallVector<EVT, 1> ResultVTs; 9866 SmallVector<SDValue, 1> ResultValues; 9867 SmallVector<SDValue, 8> OutChains; 9868 9869 llvm::Type *CallResultType = Call.getType(); 9870 ArrayRef<Type *> ResultTypes; 9871 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9872 ResultTypes = StructResult->elements(); 9873 else if (!CallResultType->isVoidTy()) 9874 ResultTypes = ArrayRef(CallResultType); 9875 9876 auto CurResultType = ResultTypes.begin(); 9877 auto handleRegAssign = [&](SDValue V) { 9878 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9879 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9880 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9881 ++CurResultType; 9882 // If the type of the inline asm call site return value is different but has 9883 // same size as the type of the asm output bitcast it. One example of this 9884 // is for vectors with different width / number of elements. This can 9885 // happen for register classes that can contain multiple different value 9886 // types. The preg or vreg allocated may not have the same VT as was 9887 // expected. 9888 // 9889 // This can also happen for a return value that disagrees with the register 9890 // class it is put in, eg. a double in a general-purpose register on a 9891 // 32-bit machine. 9892 if (ResultVT != V.getValueType() && 9893 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9894 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9895 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9896 V.getValueType().isInteger()) { 9897 // If a result value was tied to an input value, the computed result 9898 // may have a wider width than the expected result. Extract the 9899 // relevant portion. 9900 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9901 } 9902 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9903 ResultVTs.push_back(ResultVT); 9904 ResultValues.push_back(V); 9905 }; 9906 9907 // Deal with output operands. 9908 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9909 if (OpInfo.Type == InlineAsm::isOutput) { 9910 SDValue Val; 9911 // Skip trivial output operands. 9912 if (OpInfo.AssignedRegs.Regs.empty()) 9913 continue; 9914 9915 switch (OpInfo.ConstraintType) { 9916 case TargetLowering::C_Register: 9917 case TargetLowering::C_RegisterClass: 9918 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9919 Chain, &Glue, &Call); 9920 break; 9921 case TargetLowering::C_Immediate: 9922 case TargetLowering::C_Other: 9923 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9924 OpInfo, DAG); 9925 break; 9926 case TargetLowering::C_Memory: 9927 break; // Already handled. 9928 case TargetLowering::C_Address: 9929 break; // Silence warning. 9930 case TargetLowering::C_Unknown: 9931 assert(false && "Unexpected unknown constraint"); 9932 } 9933 9934 // Indirect output manifest as stores. Record output chains. 9935 if (OpInfo.isIndirect) { 9936 const Value *Ptr = OpInfo.CallOperandVal; 9937 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9938 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9939 MachinePointerInfo(Ptr)); 9940 OutChains.push_back(Store); 9941 } else { 9942 // generate CopyFromRegs to associated registers. 9943 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9944 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9945 for (const SDValue &V : Val->op_values()) 9946 handleRegAssign(V); 9947 } else 9948 handleRegAssign(Val); 9949 } 9950 } 9951 } 9952 9953 // Set results. 9954 if (!ResultValues.empty()) { 9955 assert(CurResultType == ResultTypes.end() && 9956 "Mismatch in number of ResultTypes"); 9957 assert(ResultValues.size() == ResultTypes.size() && 9958 "Mismatch in number of output operands in asm result"); 9959 9960 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9961 DAG.getVTList(ResultVTs), ResultValues); 9962 setValue(&Call, V); 9963 } 9964 9965 // Collect store chains. 9966 if (!OutChains.empty()) 9967 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9968 9969 if (EmitEHLabels) { 9970 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9971 } 9972 9973 // Only Update Root if inline assembly has a memory effect. 9974 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9975 EmitEHLabels) 9976 DAG.setRoot(Chain); 9977 } 9978 9979 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9980 const Twine &Message) { 9981 LLVMContext &Ctx = *DAG.getContext(); 9982 Ctx.emitError(&Call, Message); 9983 9984 // Make sure we leave the DAG in a valid state 9985 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9986 SmallVector<EVT, 1> ValueVTs; 9987 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9988 9989 if (ValueVTs.empty()) 9990 return; 9991 9992 SmallVector<SDValue, 1> Ops; 9993 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9994 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9995 9996 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9997 } 9998 9999 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 10000 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 10001 MVT::Other, getRoot(), 10002 getValue(I.getArgOperand(0)), 10003 DAG.getSrcValue(I.getArgOperand(0)))); 10004 } 10005 10006 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 10007 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10008 const DataLayout &DL = DAG.getDataLayout(); 10009 SDValue V = DAG.getVAArg( 10010 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 10011 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 10012 DL.getABITypeAlign(I.getType()).value()); 10013 DAG.setRoot(V.getValue(1)); 10014 10015 if (I.getType()->isPointerTy()) 10016 V = DAG.getPtrExtOrTrunc( 10017 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 10018 setValue(&I, V); 10019 } 10020 10021 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 10022 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 10023 MVT::Other, getRoot(), 10024 getValue(I.getArgOperand(0)), 10025 DAG.getSrcValue(I.getArgOperand(0)))); 10026 } 10027 10028 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 10029 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 10030 MVT::Other, getRoot(), 10031 getValue(I.getArgOperand(0)), 10032 getValue(I.getArgOperand(1)), 10033 DAG.getSrcValue(I.getArgOperand(0)), 10034 DAG.getSrcValue(I.getArgOperand(1)))); 10035 } 10036 10037 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 10038 const Instruction &I, 10039 SDValue Op) { 10040 const MDNode *Range = getRangeMetadata(I); 10041 if (!Range) 10042 return Op; 10043 10044 ConstantRange CR = getConstantRangeFromMetadata(*Range); 10045 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 10046 return Op; 10047 10048 APInt Lo = CR.getUnsignedMin(); 10049 if (!Lo.isMinValue()) 10050 return Op; 10051 10052 APInt Hi = CR.getUnsignedMax(); 10053 unsigned Bits = std::max(Hi.getActiveBits(), 10054 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 10055 10056 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 10057 10058 SDLoc SL = getCurSDLoc(); 10059 10060 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 10061 DAG.getValueType(SmallVT)); 10062 unsigned NumVals = Op.getNode()->getNumValues(); 10063 if (NumVals == 1) 10064 return ZExt; 10065 10066 SmallVector<SDValue, 4> Ops; 10067 10068 Ops.push_back(ZExt); 10069 for (unsigned I = 1; I != NumVals; ++I) 10070 Ops.push_back(Op.getValue(I)); 10071 10072 return DAG.getMergeValues(Ops, SL); 10073 } 10074 10075 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 10076 /// the call being lowered. 10077 /// 10078 /// This is a helper for lowering intrinsics that follow a target calling 10079 /// convention or require stack pointer adjustment. Only a subset of the 10080 /// intrinsic's operands need to participate in the calling convention. 10081 void SelectionDAGBuilder::populateCallLoweringInfo( 10082 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 10083 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 10084 AttributeSet RetAttrs, bool IsPatchPoint) { 10085 TargetLowering::ArgListTy Args; 10086 Args.reserve(NumArgs); 10087 10088 // Populate the argument list. 10089 // Attributes for args start at offset 1, after the return attribute. 10090 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 10091 ArgI != ArgE; ++ArgI) { 10092 const Value *V = Call->getOperand(ArgI); 10093 10094 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 10095 10096 TargetLowering::ArgListEntry Entry; 10097 Entry.Node = getValue(V); 10098 Entry.Ty = V->getType(); 10099 Entry.setAttributes(Call, ArgI); 10100 Args.push_back(Entry); 10101 } 10102 10103 CLI.setDebugLoc(getCurSDLoc()) 10104 .setChain(getRoot()) 10105 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 10106 RetAttrs) 10107 .setDiscardResult(Call->use_empty()) 10108 .setIsPatchPoint(IsPatchPoint) 10109 .setIsPreallocated( 10110 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 10111 } 10112 10113 /// Add a stack map intrinsic call's live variable operands to a stackmap 10114 /// or patchpoint target node's operand list. 10115 /// 10116 /// Constants are converted to TargetConstants purely as an optimization to 10117 /// avoid constant materialization and register allocation. 10118 /// 10119 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 10120 /// generate addess computation nodes, and so FinalizeISel can convert the 10121 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 10122 /// address materialization and register allocation, but may also be required 10123 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 10124 /// alloca in the entry block, then the runtime may assume that the alloca's 10125 /// StackMap location can be read immediately after compilation and that the 10126 /// location is valid at any point during execution (this is similar to the 10127 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 10128 /// only available in a register, then the runtime would need to trap when 10129 /// execution reaches the StackMap in order to read the alloca's location. 10130 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 10131 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 10132 SelectionDAGBuilder &Builder) { 10133 SelectionDAG &DAG = Builder.DAG; 10134 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 10135 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 10136 10137 // Things on the stack are pointer-typed, meaning that they are already 10138 // legal and can be emitted directly to target nodes. 10139 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 10140 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 10141 } else { 10142 // Otherwise emit a target independent node to be legalised. 10143 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 10144 } 10145 } 10146 } 10147 10148 /// Lower llvm.experimental.stackmap. 10149 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 10150 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 10151 // [live variables...]) 10152 10153 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 10154 10155 SDValue Chain, InGlue, Callee; 10156 SmallVector<SDValue, 32> Ops; 10157 10158 SDLoc DL = getCurSDLoc(); 10159 Callee = getValue(CI.getCalledOperand()); 10160 10161 // The stackmap intrinsic only records the live variables (the arguments 10162 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 10163 // intrinsic, this won't be lowered to a function call. This means we don't 10164 // have to worry about calling conventions and target specific lowering code. 10165 // Instead we perform the call lowering right here. 10166 // 10167 // chain, flag = CALLSEQ_START(chain, 0, 0) 10168 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 10169 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 10170 // 10171 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 10172 InGlue = Chain.getValue(1); 10173 10174 // Add the STACKMAP operands, starting with DAG house-keeping. 10175 Ops.push_back(Chain); 10176 Ops.push_back(InGlue); 10177 10178 // Add the <id>, <numShadowBytes> operands. 10179 // 10180 // These do not require legalisation, and can be emitted directly to target 10181 // constant nodes. 10182 SDValue ID = getValue(CI.getArgOperand(0)); 10183 assert(ID.getValueType() == MVT::i64); 10184 SDValue IDConst = 10185 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType()); 10186 Ops.push_back(IDConst); 10187 10188 SDValue Shad = getValue(CI.getArgOperand(1)); 10189 assert(Shad.getValueType() == MVT::i32); 10190 SDValue ShadConst = 10191 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType()); 10192 Ops.push_back(ShadConst); 10193 10194 // Add the live variables. 10195 addStackMapLiveVars(CI, 2, DL, Ops, *this); 10196 10197 // Create the STACKMAP node. 10198 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10199 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 10200 InGlue = Chain.getValue(1); 10201 10202 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 10203 10204 // Stackmaps don't generate values, so nothing goes into the NodeMap. 10205 10206 // Set the root to the target-lowered call chain. 10207 DAG.setRoot(Chain); 10208 10209 // Inform the Frame Information that we have a stackmap in this function. 10210 FuncInfo.MF->getFrameInfo().setHasStackMap(); 10211 } 10212 10213 /// Lower llvm.experimental.patchpoint directly to its target opcode. 10214 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 10215 const BasicBlock *EHPadBB) { 10216 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 10217 // i32 <numBytes>, 10218 // i8* <target>, 10219 // i32 <numArgs>, 10220 // [Args...], 10221 // [live variables...]) 10222 10223 CallingConv::ID CC = CB.getCallingConv(); 10224 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10225 bool HasDef = !CB.getType()->isVoidTy(); 10226 SDLoc dl = getCurSDLoc(); 10227 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10228 10229 // Handle immediate and symbolic callees. 10230 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10231 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10232 /*isTarget=*/true); 10233 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10234 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10235 SDLoc(SymbolicCallee), 10236 SymbolicCallee->getValueType(0)); 10237 10238 // Get the real number of arguments participating in the call <numArgs> 10239 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10240 unsigned NumArgs = NArgVal->getAsZExtVal(); 10241 10242 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10243 // Intrinsics include all meta-operands up to but not including CC. 10244 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10245 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10246 "Not enough arguments provided to the patchpoint intrinsic"); 10247 10248 // For AnyRegCC the arguments are lowered later on manually. 10249 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10250 Type *ReturnTy = 10251 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10252 10253 TargetLowering::CallLoweringInfo CLI(DAG); 10254 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10255 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10256 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10257 10258 SDNode *CallEnd = Result.second.getNode(); 10259 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10260 CallEnd = CallEnd->getOperand(0).getNode(); 10261 10262 /// Get a call instruction from the call sequence chain. 10263 /// Tail calls are not allowed. 10264 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10265 "Expected a callseq node."); 10266 SDNode *Call = CallEnd->getOperand(0).getNode(); 10267 bool HasGlue = Call->getGluedNode(); 10268 10269 // Replace the target specific call node with the patchable intrinsic. 10270 SmallVector<SDValue, 8> Ops; 10271 10272 // Push the chain. 10273 Ops.push_back(*(Call->op_begin())); 10274 10275 // Optionally, push the glue (if any). 10276 if (HasGlue) 10277 Ops.push_back(*(Call->op_end() - 1)); 10278 10279 // Push the register mask info. 10280 if (HasGlue) 10281 Ops.push_back(*(Call->op_end() - 2)); 10282 else 10283 Ops.push_back(*(Call->op_end() - 1)); 10284 10285 // Add the <id> and <numBytes> constants. 10286 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10287 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64)); 10288 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10289 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32)); 10290 10291 // Add the callee. 10292 Ops.push_back(Callee); 10293 10294 // Adjust <numArgs> to account for any arguments that have been passed on the 10295 // stack instead. 10296 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10297 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10298 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10299 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10300 10301 // Add the calling convention 10302 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10303 10304 // Add the arguments we omitted previously. The register allocator should 10305 // place these in any free register. 10306 if (IsAnyRegCC) 10307 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10308 Ops.push_back(getValue(CB.getArgOperand(i))); 10309 10310 // Push the arguments from the call instruction. 10311 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10312 Ops.append(Call->op_begin() + 2, e); 10313 10314 // Push live variables for the stack map. 10315 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10316 10317 SDVTList NodeTys; 10318 if (IsAnyRegCC && HasDef) { 10319 // Create the return types based on the intrinsic definition 10320 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10321 SmallVector<EVT, 3> ValueVTs; 10322 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10323 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10324 10325 // There is always a chain and a glue type at the end 10326 ValueVTs.push_back(MVT::Other); 10327 ValueVTs.push_back(MVT::Glue); 10328 NodeTys = DAG.getVTList(ValueVTs); 10329 } else 10330 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10331 10332 // Replace the target specific call node with a PATCHPOINT node. 10333 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10334 10335 // Update the NodeMap. 10336 if (HasDef) { 10337 if (IsAnyRegCC) 10338 setValue(&CB, SDValue(PPV.getNode(), 0)); 10339 else 10340 setValue(&CB, Result.first); 10341 } 10342 10343 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10344 // call sequence. Furthermore the location of the chain and glue can change 10345 // when the AnyReg calling convention is used and the intrinsic returns a 10346 // value. 10347 if (IsAnyRegCC && HasDef) { 10348 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10349 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10350 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10351 } else 10352 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10353 DAG.DeleteNode(Call); 10354 10355 // Inform the Frame Information that we have a patchpoint in this function. 10356 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10357 } 10358 10359 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10360 unsigned Intrinsic) { 10361 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10362 SDValue Op1 = getValue(I.getArgOperand(0)); 10363 SDValue Op2; 10364 if (I.arg_size() > 1) 10365 Op2 = getValue(I.getArgOperand(1)); 10366 SDLoc dl = getCurSDLoc(); 10367 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10368 SDValue Res; 10369 SDNodeFlags SDFlags; 10370 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10371 SDFlags.copyFMF(*FPMO); 10372 10373 switch (Intrinsic) { 10374 case Intrinsic::vector_reduce_fadd: 10375 if (SDFlags.hasAllowReassociation()) 10376 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10377 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10378 SDFlags); 10379 else 10380 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10381 break; 10382 case Intrinsic::vector_reduce_fmul: 10383 if (SDFlags.hasAllowReassociation()) 10384 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10385 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10386 SDFlags); 10387 else 10388 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10389 break; 10390 case Intrinsic::vector_reduce_add: 10391 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10392 break; 10393 case Intrinsic::vector_reduce_mul: 10394 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10395 break; 10396 case Intrinsic::vector_reduce_and: 10397 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10398 break; 10399 case Intrinsic::vector_reduce_or: 10400 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10401 break; 10402 case Intrinsic::vector_reduce_xor: 10403 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10404 break; 10405 case Intrinsic::vector_reduce_smax: 10406 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10407 break; 10408 case Intrinsic::vector_reduce_smin: 10409 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10410 break; 10411 case Intrinsic::vector_reduce_umax: 10412 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10413 break; 10414 case Intrinsic::vector_reduce_umin: 10415 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10416 break; 10417 case Intrinsic::vector_reduce_fmax: 10418 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10419 break; 10420 case Intrinsic::vector_reduce_fmin: 10421 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10422 break; 10423 case Intrinsic::vector_reduce_fmaximum: 10424 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10425 break; 10426 case Intrinsic::vector_reduce_fminimum: 10427 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10428 break; 10429 default: 10430 llvm_unreachable("Unhandled vector reduce intrinsic"); 10431 } 10432 setValue(&I, Res); 10433 } 10434 10435 /// Returns an AttributeList representing the attributes applied to the return 10436 /// value of the given call. 10437 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10438 SmallVector<Attribute::AttrKind, 2> Attrs; 10439 if (CLI.RetSExt) 10440 Attrs.push_back(Attribute::SExt); 10441 if (CLI.RetZExt) 10442 Attrs.push_back(Attribute::ZExt); 10443 if (CLI.IsInReg) 10444 Attrs.push_back(Attribute::InReg); 10445 10446 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10447 Attrs); 10448 } 10449 10450 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10451 /// implementation, which just calls LowerCall. 10452 /// FIXME: When all targets are 10453 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10454 std::pair<SDValue, SDValue> 10455 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10456 // Handle the incoming return values from the call. 10457 CLI.Ins.clear(); 10458 Type *OrigRetTy = CLI.RetTy; 10459 SmallVector<EVT, 4> RetTys; 10460 SmallVector<uint64_t, 4> Offsets; 10461 auto &DL = CLI.DAG.getDataLayout(); 10462 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0); 10463 10464 if (CLI.IsPostTypeLegalization) { 10465 // If we are lowering a libcall after legalization, split the return type. 10466 SmallVector<EVT, 4> OldRetTys; 10467 SmallVector<uint64_t, 4> OldOffsets; 10468 RetTys.swap(OldRetTys); 10469 Offsets.swap(OldOffsets); 10470 10471 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10472 EVT RetVT = OldRetTys[i]; 10473 uint64_t Offset = OldOffsets[i]; 10474 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10475 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10476 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10477 RetTys.append(NumRegs, RegisterVT); 10478 for (unsigned j = 0; j != NumRegs; ++j) 10479 Offsets.push_back(Offset + j * RegisterVTByteSZ); 10480 } 10481 } 10482 10483 SmallVector<ISD::OutputArg, 4> Outs; 10484 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10485 10486 bool CanLowerReturn = 10487 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10488 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10489 10490 SDValue DemoteStackSlot; 10491 int DemoteStackIdx = -100; 10492 if (!CanLowerReturn) { 10493 // FIXME: equivalent assert? 10494 // assert(!CS.hasInAllocaArgument() && 10495 // "sret demotion is incompatible with inalloca"); 10496 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10497 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10498 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10499 DemoteStackIdx = 10500 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10501 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10502 DL.getAllocaAddrSpace()); 10503 10504 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10505 ArgListEntry Entry; 10506 Entry.Node = DemoteStackSlot; 10507 Entry.Ty = StackSlotPtrType; 10508 Entry.IsSExt = false; 10509 Entry.IsZExt = false; 10510 Entry.IsInReg = false; 10511 Entry.IsSRet = true; 10512 Entry.IsNest = false; 10513 Entry.IsByVal = false; 10514 Entry.IsByRef = false; 10515 Entry.IsReturned = false; 10516 Entry.IsSwiftSelf = false; 10517 Entry.IsSwiftAsync = false; 10518 Entry.IsSwiftError = false; 10519 Entry.IsCFGuardTarget = false; 10520 Entry.Alignment = Alignment; 10521 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10522 CLI.NumFixedArgs += 1; 10523 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10524 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10525 10526 // sret demotion isn't compatible with tail-calls, since the sret argument 10527 // points into the callers stack frame. 10528 CLI.IsTailCall = false; 10529 } else { 10530 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10531 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10532 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10533 ISD::ArgFlagsTy Flags; 10534 if (NeedsRegBlock) { 10535 Flags.setInConsecutiveRegs(); 10536 if (I == RetTys.size() - 1) 10537 Flags.setInConsecutiveRegsLast(); 10538 } 10539 EVT VT = RetTys[I]; 10540 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10541 CLI.CallConv, VT); 10542 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10543 CLI.CallConv, VT); 10544 for (unsigned i = 0; i != NumRegs; ++i) { 10545 ISD::InputArg MyFlags; 10546 MyFlags.Flags = Flags; 10547 MyFlags.VT = RegisterVT; 10548 MyFlags.ArgVT = VT; 10549 MyFlags.Used = CLI.IsReturnValueUsed; 10550 if (CLI.RetTy->isPointerTy()) { 10551 MyFlags.Flags.setPointer(); 10552 MyFlags.Flags.setPointerAddrSpace( 10553 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10554 } 10555 if (CLI.RetSExt) 10556 MyFlags.Flags.setSExt(); 10557 if (CLI.RetZExt) 10558 MyFlags.Flags.setZExt(); 10559 if (CLI.IsInReg) 10560 MyFlags.Flags.setInReg(); 10561 CLI.Ins.push_back(MyFlags); 10562 } 10563 } 10564 } 10565 10566 // We push in swifterror return as the last element of CLI.Ins. 10567 ArgListTy &Args = CLI.getArgs(); 10568 if (supportSwiftError()) { 10569 for (const ArgListEntry &Arg : Args) { 10570 if (Arg.IsSwiftError) { 10571 ISD::InputArg MyFlags; 10572 MyFlags.VT = getPointerTy(DL); 10573 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10574 MyFlags.Flags.setSwiftError(); 10575 CLI.Ins.push_back(MyFlags); 10576 } 10577 } 10578 } 10579 10580 // Handle all of the outgoing arguments. 10581 CLI.Outs.clear(); 10582 CLI.OutVals.clear(); 10583 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10584 SmallVector<EVT, 4> ValueVTs; 10585 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10586 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10587 Type *FinalType = Args[i].Ty; 10588 if (Args[i].IsByVal) 10589 FinalType = Args[i].IndirectType; 10590 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10591 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10592 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10593 ++Value) { 10594 EVT VT = ValueVTs[Value]; 10595 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10596 SDValue Op = SDValue(Args[i].Node.getNode(), 10597 Args[i].Node.getResNo() + Value); 10598 ISD::ArgFlagsTy Flags; 10599 10600 // Certain targets (such as MIPS), may have a different ABI alignment 10601 // for a type depending on the context. Give the target a chance to 10602 // specify the alignment it wants. 10603 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10604 Flags.setOrigAlign(OriginalAlignment); 10605 10606 if (Args[i].Ty->isPointerTy()) { 10607 Flags.setPointer(); 10608 Flags.setPointerAddrSpace( 10609 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10610 } 10611 if (Args[i].IsZExt) 10612 Flags.setZExt(); 10613 if (Args[i].IsSExt) 10614 Flags.setSExt(); 10615 if (Args[i].IsInReg) { 10616 // If we are using vectorcall calling convention, a structure that is 10617 // passed InReg - is surely an HVA 10618 if (CLI.CallConv == CallingConv::X86_VectorCall && 10619 isa<StructType>(FinalType)) { 10620 // The first value of a structure is marked 10621 if (0 == Value) 10622 Flags.setHvaStart(); 10623 Flags.setHva(); 10624 } 10625 // Set InReg Flag 10626 Flags.setInReg(); 10627 } 10628 if (Args[i].IsSRet) 10629 Flags.setSRet(); 10630 if (Args[i].IsSwiftSelf) 10631 Flags.setSwiftSelf(); 10632 if (Args[i].IsSwiftAsync) 10633 Flags.setSwiftAsync(); 10634 if (Args[i].IsSwiftError) 10635 Flags.setSwiftError(); 10636 if (Args[i].IsCFGuardTarget) 10637 Flags.setCFGuardTarget(); 10638 if (Args[i].IsByVal) 10639 Flags.setByVal(); 10640 if (Args[i].IsByRef) 10641 Flags.setByRef(); 10642 if (Args[i].IsPreallocated) { 10643 Flags.setPreallocated(); 10644 // Set the byval flag for CCAssignFn callbacks that don't know about 10645 // preallocated. This way we can know how many bytes we should've 10646 // allocated and how many bytes a callee cleanup function will pop. If 10647 // we port preallocated to more targets, we'll have to add custom 10648 // preallocated handling in the various CC lowering callbacks. 10649 Flags.setByVal(); 10650 } 10651 if (Args[i].IsInAlloca) { 10652 Flags.setInAlloca(); 10653 // Set the byval flag for CCAssignFn callbacks that don't know about 10654 // inalloca. This way we can know how many bytes we should've allocated 10655 // and how many bytes a callee cleanup function will pop. If we port 10656 // inalloca to more targets, we'll have to add custom inalloca handling 10657 // in the various CC lowering callbacks. 10658 Flags.setByVal(); 10659 } 10660 Align MemAlign; 10661 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10662 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10663 Flags.setByValSize(FrameSize); 10664 10665 // info is not there but there are cases it cannot get right. 10666 if (auto MA = Args[i].Alignment) 10667 MemAlign = *MA; 10668 else 10669 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10670 } else if (auto MA = Args[i].Alignment) { 10671 MemAlign = *MA; 10672 } else { 10673 MemAlign = OriginalAlignment; 10674 } 10675 Flags.setMemAlign(MemAlign); 10676 if (Args[i].IsNest) 10677 Flags.setNest(); 10678 if (NeedsRegBlock) 10679 Flags.setInConsecutiveRegs(); 10680 10681 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10682 CLI.CallConv, VT); 10683 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10684 CLI.CallConv, VT); 10685 SmallVector<SDValue, 4> Parts(NumParts); 10686 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10687 10688 if (Args[i].IsSExt) 10689 ExtendKind = ISD::SIGN_EXTEND; 10690 else if (Args[i].IsZExt) 10691 ExtendKind = ISD::ZERO_EXTEND; 10692 10693 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10694 // for now. 10695 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10696 CanLowerReturn) { 10697 assert((CLI.RetTy == Args[i].Ty || 10698 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10699 CLI.RetTy->getPointerAddressSpace() == 10700 Args[i].Ty->getPointerAddressSpace())) && 10701 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10702 // Before passing 'returned' to the target lowering code, ensure that 10703 // either the register MVT and the actual EVT are the same size or that 10704 // the return value and argument are extended in the same way; in these 10705 // cases it's safe to pass the argument register value unchanged as the 10706 // return register value (although it's at the target's option whether 10707 // to do so) 10708 // TODO: allow code generation to take advantage of partially preserved 10709 // registers rather than clobbering the entire register when the 10710 // parameter extension method is not compatible with the return 10711 // extension method 10712 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10713 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10714 CLI.RetZExt == Args[i].IsZExt)) 10715 Flags.setReturned(); 10716 } 10717 10718 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10719 CLI.CallConv, ExtendKind); 10720 10721 for (unsigned j = 0; j != NumParts; ++j) { 10722 // if it isn't first piece, alignment must be 1 10723 // For scalable vectors the scalable part is currently handled 10724 // by individual targets, so we just use the known minimum size here. 10725 ISD::OutputArg MyFlags( 10726 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10727 i < CLI.NumFixedArgs, i, 10728 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10729 if (NumParts > 1 && j == 0) 10730 MyFlags.Flags.setSplit(); 10731 else if (j != 0) { 10732 MyFlags.Flags.setOrigAlign(Align(1)); 10733 if (j == NumParts - 1) 10734 MyFlags.Flags.setSplitEnd(); 10735 } 10736 10737 CLI.Outs.push_back(MyFlags); 10738 CLI.OutVals.push_back(Parts[j]); 10739 } 10740 10741 if (NeedsRegBlock && Value == NumValues - 1) 10742 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10743 } 10744 } 10745 10746 SmallVector<SDValue, 4> InVals; 10747 CLI.Chain = LowerCall(CLI, InVals); 10748 10749 // Update CLI.InVals to use outside of this function. 10750 CLI.InVals = InVals; 10751 10752 // Verify that the target's LowerCall behaved as expected. 10753 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10754 "LowerCall didn't return a valid chain!"); 10755 assert((!CLI.IsTailCall || InVals.empty()) && 10756 "LowerCall emitted a return value for a tail call!"); 10757 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10758 "LowerCall didn't emit the correct number of values!"); 10759 10760 // For a tail call, the return value is merely live-out and there aren't 10761 // any nodes in the DAG representing it. Return a special value to 10762 // indicate that a tail call has been emitted and no more Instructions 10763 // should be processed in the current block. 10764 if (CLI.IsTailCall) { 10765 CLI.DAG.setRoot(CLI.Chain); 10766 return std::make_pair(SDValue(), SDValue()); 10767 } 10768 10769 #ifndef NDEBUG 10770 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10771 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10772 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10773 "LowerCall emitted a value with the wrong type!"); 10774 } 10775 #endif 10776 10777 SmallVector<SDValue, 4> ReturnValues; 10778 if (!CanLowerReturn) { 10779 // The instruction result is the result of loading from the 10780 // hidden sret parameter. 10781 SmallVector<EVT, 1> PVTs; 10782 Type *PtrRetTy = 10783 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 10784 10785 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10786 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10787 EVT PtrVT = PVTs[0]; 10788 10789 unsigned NumValues = RetTys.size(); 10790 ReturnValues.resize(NumValues); 10791 SmallVector<SDValue, 4> Chains(NumValues); 10792 10793 // An aggregate return value cannot wrap around the address space, so 10794 // offsets to its parts don't wrap either. 10795 SDNodeFlags Flags; 10796 Flags.setNoUnsignedWrap(true); 10797 10798 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10799 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10800 for (unsigned i = 0; i < NumValues; ++i) { 10801 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10802 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10803 PtrVT), Flags); 10804 SDValue L = CLI.DAG.getLoad( 10805 RetTys[i], CLI.DL, CLI.Chain, Add, 10806 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10807 DemoteStackIdx, Offsets[i]), 10808 HiddenSRetAlign); 10809 ReturnValues[i] = L; 10810 Chains[i] = L.getValue(1); 10811 } 10812 10813 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10814 } else { 10815 // Collect the legal value parts into potentially illegal values 10816 // that correspond to the original function's return values. 10817 std::optional<ISD::NodeType> AssertOp; 10818 if (CLI.RetSExt) 10819 AssertOp = ISD::AssertSext; 10820 else if (CLI.RetZExt) 10821 AssertOp = ISD::AssertZext; 10822 unsigned CurReg = 0; 10823 for (EVT VT : RetTys) { 10824 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10825 CLI.CallConv, VT); 10826 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10827 CLI.CallConv, VT); 10828 10829 ReturnValues.push_back(getCopyFromParts( 10830 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr, 10831 CLI.Chain, CLI.CallConv, AssertOp)); 10832 CurReg += NumRegs; 10833 } 10834 10835 // For a function returning void, there is no return value. We can't create 10836 // such a node, so we just return a null return value in that case. In 10837 // that case, nothing will actually look at the value. 10838 if (ReturnValues.empty()) 10839 return std::make_pair(SDValue(), CLI.Chain); 10840 } 10841 10842 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10843 CLI.DAG.getVTList(RetTys), ReturnValues); 10844 return std::make_pair(Res, CLI.Chain); 10845 } 10846 10847 /// Places new result values for the node in Results (their number 10848 /// and types must exactly match those of the original return values of 10849 /// the node), or leaves Results empty, which indicates that the node is not 10850 /// to be custom lowered after all. 10851 void TargetLowering::LowerOperationWrapper(SDNode *N, 10852 SmallVectorImpl<SDValue> &Results, 10853 SelectionDAG &DAG) const { 10854 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10855 10856 if (!Res.getNode()) 10857 return; 10858 10859 // If the original node has one result, take the return value from 10860 // LowerOperation as is. It might not be result number 0. 10861 if (N->getNumValues() == 1) { 10862 Results.push_back(Res); 10863 return; 10864 } 10865 10866 // If the original node has multiple results, then the return node should 10867 // have the same number of results. 10868 assert((N->getNumValues() == Res->getNumValues()) && 10869 "Lowering returned the wrong number of results!"); 10870 10871 // Places new result values base on N result number. 10872 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10873 Results.push_back(Res.getValue(I)); 10874 } 10875 10876 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10877 llvm_unreachable("LowerOperation not implemented for this target!"); 10878 } 10879 10880 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10881 unsigned Reg, 10882 ISD::NodeType ExtendType) { 10883 SDValue Op = getNonRegisterValue(V); 10884 assert((Op.getOpcode() != ISD::CopyFromReg || 10885 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10886 "Copy from a reg to the same reg!"); 10887 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10888 10889 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10890 // If this is an InlineAsm we have to match the registers required, not the 10891 // notional registers required by the type. 10892 10893 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10894 std::nullopt); // This is not an ABI copy. 10895 SDValue Chain = DAG.getEntryNode(); 10896 10897 if (ExtendType == ISD::ANY_EXTEND) { 10898 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10899 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10900 ExtendType = PreferredExtendIt->second; 10901 } 10902 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10903 PendingExports.push_back(Chain); 10904 } 10905 10906 #include "llvm/CodeGen/SelectionDAGISel.h" 10907 10908 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10909 /// entry block, return true. This includes arguments used by switches, since 10910 /// the switch may expand into multiple basic blocks. 10911 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10912 // With FastISel active, we may be splitting blocks, so force creation 10913 // of virtual registers for all non-dead arguments. 10914 if (FastISel) 10915 return A->use_empty(); 10916 10917 const BasicBlock &Entry = A->getParent()->front(); 10918 for (const User *U : A->users()) 10919 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10920 return false; // Use not in entry block. 10921 10922 return true; 10923 } 10924 10925 using ArgCopyElisionMapTy = 10926 DenseMap<const Argument *, 10927 std::pair<const AllocaInst *, const StoreInst *>>; 10928 10929 /// Scan the entry block of the function in FuncInfo for arguments that look 10930 /// like copies into a local alloca. Record any copied arguments in 10931 /// ArgCopyElisionCandidates. 10932 static void 10933 findArgumentCopyElisionCandidates(const DataLayout &DL, 10934 FunctionLoweringInfo *FuncInfo, 10935 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10936 // Record the state of every static alloca used in the entry block. Argument 10937 // allocas are all used in the entry block, so we need approximately as many 10938 // entries as we have arguments. 10939 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10940 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10941 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10942 StaticAllocas.reserve(NumArgs * 2); 10943 10944 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10945 if (!V) 10946 return nullptr; 10947 V = V->stripPointerCasts(); 10948 const auto *AI = dyn_cast<AllocaInst>(V); 10949 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10950 return nullptr; 10951 auto Iter = StaticAllocas.insert({AI, Unknown}); 10952 return &Iter.first->second; 10953 }; 10954 10955 // Look for stores of arguments to static allocas. Look through bitcasts and 10956 // GEPs to handle type coercions, as long as the alloca is fully initialized 10957 // by the store. Any non-store use of an alloca escapes it and any subsequent 10958 // unanalyzed store might write it. 10959 // FIXME: Handle structs initialized with multiple stores. 10960 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10961 // Look for stores, and handle non-store uses conservatively. 10962 const auto *SI = dyn_cast<StoreInst>(&I); 10963 if (!SI) { 10964 // We will look through cast uses, so ignore them completely. 10965 if (I.isCast()) 10966 continue; 10967 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10968 // to allocas. 10969 if (I.isDebugOrPseudoInst()) 10970 continue; 10971 // This is an unknown instruction. Assume it escapes or writes to all 10972 // static alloca operands. 10973 for (const Use &U : I.operands()) { 10974 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10975 *Info = StaticAllocaInfo::Clobbered; 10976 } 10977 continue; 10978 } 10979 10980 // If the stored value is a static alloca, mark it as escaped. 10981 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10982 *Info = StaticAllocaInfo::Clobbered; 10983 10984 // Check if the destination is a static alloca. 10985 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10986 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10987 if (!Info) 10988 continue; 10989 const AllocaInst *AI = cast<AllocaInst>(Dst); 10990 10991 // Skip allocas that have been initialized or clobbered. 10992 if (*Info != StaticAllocaInfo::Unknown) 10993 continue; 10994 10995 // Check if the stored value is an argument, and that this store fully 10996 // initializes the alloca. 10997 // If the argument type has padding bits we can't directly forward a pointer 10998 // as the upper bits may contain garbage. 10999 // Don't elide copies from the same argument twice. 11000 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 11001 const auto *Arg = dyn_cast<Argument>(Val); 11002 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 11003 Arg->getType()->isEmptyTy() || 11004 DL.getTypeStoreSize(Arg->getType()) != 11005 DL.getTypeAllocSize(AI->getAllocatedType()) || 11006 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 11007 ArgCopyElisionCandidates.count(Arg)) { 11008 *Info = StaticAllocaInfo::Clobbered; 11009 continue; 11010 } 11011 11012 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 11013 << '\n'); 11014 11015 // Mark this alloca and store for argument copy elision. 11016 *Info = StaticAllocaInfo::Elidable; 11017 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 11018 11019 // Stop scanning if we've seen all arguments. This will happen early in -O0 11020 // builds, which is useful, because -O0 builds have large entry blocks and 11021 // many allocas. 11022 if (ArgCopyElisionCandidates.size() == NumArgs) 11023 break; 11024 } 11025 } 11026 11027 /// Try to elide argument copies from memory into a local alloca. Succeeds if 11028 /// ArgVal is a load from a suitable fixed stack object. 11029 static void tryToElideArgumentCopy( 11030 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 11031 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 11032 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 11033 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 11034 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 11035 // Check if this is a load from a fixed stack object. 11036 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 11037 if (!LNode) 11038 return; 11039 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 11040 if (!FINode) 11041 return; 11042 11043 // Check that the fixed stack object is the right size and alignment. 11044 // Look at the alignment that the user wrote on the alloca instead of looking 11045 // at the stack object. 11046 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 11047 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 11048 const AllocaInst *AI = ArgCopyIter->second.first; 11049 int FixedIndex = FINode->getIndex(); 11050 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 11051 int OldIndex = AllocaIndex; 11052 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 11053 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 11054 LLVM_DEBUG( 11055 dbgs() << " argument copy elision failed due to bad fixed stack " 11056 "object size\n"); 11057 return; 11058 } 11059 Align RequiredAlignment = AI->getAlign(); 11060 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 11061 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 11062 "greater than stack argument alignment (" 11063 << DebugStr(RequiredAlignment) << " vs " 11064 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 11065 return; 11066 } 11067 11068 // Perform the elision. Delete the old stack object and replace its only use 11069 // in the variable info map. Mark the stack object as mutable. 11070 LLVM_DEBUG({ 11071 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 11072 << " Replacing frame index " << OldIndex << " with " << FixedIndex 11073 << '\n'; 11074 }); 11075 MFI.RemoveStackObject(OldIndex); 11076 MFI.setIsImmutableObjectIndex(FixedIndex, false); 11077 AllocaIndex = FixedIndex; 11078 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 11079 for (SDValue ArgVal : ArgVals) 11080 Chains.push_back(ArgVal.getValue(1)); 11081 11082 // Avoid emitting code for the store implementing the copy. 11083 const StoreInst *SI = ArgCopyIter->second.second; 11084 ElidedArgCopyInstrs.insert(SI); 11085 11086 // Check for uses of the argument again so that we can avoid exporting ArgVal 11087 // if it is't used by anything other than the store. 11088 for (const Value *U : Arg.users()) { 11089 if (U != SI) { 11090 ArgHasUses = true; 11091 break; 11092 } 11093 } 11094 } 11095 11096 void SelectionDAGISel::LowerArguments(const Function &F) { 11097 SelectionDAG &DAG = SDB->DAG; 11098 SDLoc dl = SDB->getCurSDLoc(); 11099 const DataLayout &DL = DAG.getDataLayout(); 11100 SmallVector<ISD::InputArg, 16> Ins; 11101 11102 // In Naked functions we aren't going to save any registers. 11103 if (F.hasFnAttribute(Attribute::Naked)) 11104 return; 11105 11106 if (!FuncInfo->CanLowerReturn) { 11107 // Put in an sret pointer parameter before all the other parameters. 11108 SmallVector<EVT, 1> ValueVTs; 11109 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11110 PointerType::get(F.getContext(), 11111 DAG.getDataLayout().getAllocaAddrSpace()), 11112 ValueVTs); 11113 11114 // NOTE: Assuming that a pointer will never break down to more than one VT 11115 // or one register. 11116 ISD::ArgFlagsTy Flags; 11117 Flags.setSRet(); 11118 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 11119 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 11120 ISD::InputArg::NoArgIndex, 0); 11121 Ins.push_back(RetArg); 11122 } 11123 11124 // Look for stores of arguments to static allocas. Mark such arguments with a 11125 // flag to ask the target to give us the memory location of that argument if 11126 // available. 11127 ArgCopyElisionMapTy ArgCopyElisionCandidates; 11128 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 11129 ArgCopyElisionCandidates); 11130 11131 // Set up the incoming argument description vector. 11132 for (const Argument &Arg : F.args()) { 11133 unsigned ArgNo = Arg.getArgNo(); 11134 SmallVector<EVT, 4> ValueVTs; 11135 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11136 bool isArgValueUsed = !Arg.use_empty(); 11137 unsigned PartBase = 0; 11138 Type *FinalType = Arg.getType(); 11139 if (Arg.hasAttribute(Attribute::ByVal)) 11140 FinalType = Arg.getParamByValType(); 11141 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 11142 FinalType, F.getCallingConv(), F.isVarArg(), DL); 11143 for (unsigned Value = 0, NumValues = ValueVTs.size(); 11144 Value != NumValues; ++Value) { 11145 EVT VT = ValueVTs[Value]; 11146 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 11147 ISD::ArgFlagsTy Flags; 11148 11149 11150 if (Arg.getType()->isPointerTy()) { 11151 Flags.setPointer(); 11152 Flags.setPointerAddrSpace( 11153 cast<PointerType>(Arg.getType())->getAddressSpace()); 11154 } 11155 if (Arg.hasAttribute(Attribute::ZExt)) 11156 Flags.setZExt(); 11157 if (Arg.hasAttribute(Attribute::SExt)) 11158 Flags.setSExt(); 11159 if (Arg.hasAttribute(Attribute::InReg)) { 11160 // If we are using vectorcall calling convention, a structure that is 11161 // passed InReg - is surely an HVA 11162 if (F.getCallingConv() == CallingConv::X86_VectorCall && 11163 isa<StructType>(Arg.getType())) { 11164 // The first value of a structure is marked 11165 if (0 == Value) 11166 Flags.setHvaStart(); 11167 Flags.setHva(); 11168 } 11169 // Set InReg Flag 11170 Flags.setInReg(); 11171 } 11172 if (Arg.hasAttribute(Attribute::StructRet)) 11173 Flags.setSRet(); 11174 if (Arg.hasAttribute(Attribute::SwiftSelf)) 11175 Flags.setSwiftSelf(); 11176 if (Arg.hasAttribute(Attribute::SwiftAsync)) 11177 Flags.setSwiftAsync(); 11178 if (Arg.hasAttribute(Attribute::SwiftError)) 11179 Flags.setSwiftError(); 11180 if (Arg.hasAttribute(Attribute::ByVal)) 11181 Flags.setByVal(); 11182 if (Arg.hasAttribute(Attribute::ByRef)) 11183 Flags.setByRef(); 11184 if (Arg.hasAttribute(Attribute::InAlloca)) { 11185 Flags.setInAlloca(); 11186 // Set the byval flag for CCAssignFn callbacks that don't know about 11187 // inalloca. This way we can know how many bytes we should've allocated 11188 // and how many bytes a callee cleanup function will pop. If we port 11189 // inalloca to more targets, we'll have to add custom inalloca handling 11190 // in the various CC lowering callbacks. 11191 Flags.setByVal(); 11192 } 11193 if (Arg.hasAttribute(Attribute::Preallocated)) { 11194 Flags.setPreallocated(); 11195 // Set the byval flag for CCAssignFn callbacks that don't know about 11196 // preallocated. This way we can know how many bytes we should've 11197 // allocated and how many bytes a callee cleanup function will pop. If 11198 // we port preallocated to more targets, we'll have to add custom 11199 // preallocated handling in the various CC lowering callbacks. 11200 Flags.setByVal(); 11201 } 11202 11203 // Certain targets (such as MIPS), may have a different ABI alignment 11204 // for a type depending on the context. Give the target a chance to 11205 // specify the alignment it wants. 11206 const Align OriginalAlignment( 11207 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 11208 Flags.setOrigAlign(OriginalAlignment); 11209 11210 Align MemAlign; 11211 Type *ArgMemTy = nullptr; 11212 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 11213 Flags.isByRef()) { 11214 if (!ArgMemTy) 11215 ArgMemTy = Arg.getPointeeInMemoryValueType(); 11216 11217 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11218 11219 // For in-memory arguments, size and alignment should be passed from FE. 11220 // BE will guess if this info is not there but there are cases it cannot 11221 // get right. 11222 if (auto ParamAlign = Arg.getParamStackAlign()) 11223 MemAlign = *ParamAlign; 11224 else if ((ParamAlign = Arg.getParamAlign())) 11225 MemAlign = *ParamAlign; 11226 else 11227 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11228 if (Flags.isByRef()) 11229 Flags.setByRefSize(MemSize); 11230 else 11231 Flags.setByValSize(MemSize); 11232 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11233 MemAlign = *ParamAlign; 11234 } else { 11235 MemAlign = OriginalAlignment; 11236 } 11237 Flags.setMemAlign(MemAlign); 11238 11239 if (Arg.hasAttribute(Attribute::Nest)) 11240 Flags.setNest(); 11241 if (NeedsRegBlock) 11242 Flags.setInConsecutiveRegs(); 11243 if (ArgCopyElisionCandidates.count(&Arg)) 11244 Flags.setCopyElisionCandidate(); 11245 if (Arg.hasAttribute(Attribute::Returned)) 11246 Flags.setReturned(); 11247 11248 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11249 *CurDAG->getContext(), F.getCallingConv(), VT); 11250 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11251 *CurDAG->getContext(), F.getCallingConv(), VT); 11252 for (unsigned i = 0; i != NumRegs; ++i) { 11253 // For scalable vectors, use the minimum size; individual targets 11254 // are responsible for handling scalable vector arguments and 11255 // return values. 11256 ISD::InputArg MyFlags( 11257 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11258 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11259 if (NumRegs > 1 && i == 0) 11260 MyFlags.Flags.setSplit(); 11261 // if it isn't first piece, alignment must be 1 11262 else if (i > 0) { 11263 MyFlags.Flags.setOrigAlign(Align(1)); 11264 if (i == NumRegs - 1) 11265 MyFlags.Flags.setSplitEnd(); 11266 } 11267 Ins.push_back(MyFlags); 11268 } 11269 if (NeedsRegBlock && Value == NumValues - 1) 11270 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11271 PartBase += VT.getStoreSize().getKnownMinValue(); 11272 } 11273 } 11274 11275 // Call the target to set up the argument values. 11276 SmallVector<SDValue, 8> InVals; 11277 SDValue NewRoot = TLI->LowerFormalArguments( 11278 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11279 11280 // Verify that the target's LowerFormalArguments behaved as expected. 11281 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11282 "LowerFormalArguments didn't return a valid chain!"); 11283 assert(InVals.size() == Ins.size() && 11284 "LowerFormalArguments didn't emit the correct number of values!"); 11285 LLVM_DEBUG({ 11286 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11287 assert(InVals[i].getNode() && 11288 "LowerFormalArguments emitted a null value!"); 11289 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11290 "LowerFormalArguments emitted a value with the wrong type!"); 11291 } 11292 }); 11293 11294 // Update the DAG with the new chain value resulting from argument lowering. 11295 DAG.setRoot(NewRoot); 11296 11297 // Set up the argument values. 11298 unsigned i = 0; 11299 if (!FuncInfo->CanLowerReturn) { 11300 // Create a virtual register for the sret pointer, and put in a copy 11301 // from the sret argument into it. 11302 SmallVector<EVT, 1> ValueVTs; 11303 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11304 PointerType::get(F.getContext(), 11305 DAG.getDataLayout().getAllocaAddrSpace()), 11306 ValueVTs); 11307 MVT VT = ValueVTs[0].getSimpleVT(); 11308 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11309 std::optional<ISD::NodeType> AssertOp; 11310 SDValue ArgValue = 11311 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot, 11312 F.getCallingConv(), AssertOp); 11313 11314 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11315 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11316 Register SRetReg = 11317 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11318 FuncInfo->DemoteRegister = SRetReg; 11319 NewRoot = 11320 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11321 DAG.setRoot(NewRoot); 11322 11323 // i indexes lowered arguments. Bump it past the hidden sret argument. 11324 ++i; 11325 } 11326 11327 SmallVector<SDValue, 4> Chains; 11328 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11329 for (const Argument &Arg : F.args()) { 11330 SmallVector<SDValue, 4> ArgValues; 11331 SmallVector<EVT, 4> ValueVTs; 11332 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11333 unsigned NumValues = ValueVTs.size(); 11334 if (NumValues == 0) 11335 continue; 11336 11337 bool ArgHasUses = !Arg.use_empty(); 11338 11339 // Elide the copying store if the target loaded this argument from a 11340 // suitable fixed stack object. 11341 if (Ins[i].Flags.isCopyElisionCandidate()) { 11342 unsigned NumParts = 0; 11343 for (EVT VT : ValueVTs) 11344 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11345 F.getCallingConv(), VT); 11346 11347 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11348 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11349 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11350 } 11351 11352 // If this argument is unused then remember its value. It is used to generate 11353 // debugging information. 11354 bool isSwiftErrorArg = 11355 TLI->supportSwiftError() && 11356 Arg.hasAttribute(Attribute::SwiftError); 11357 if (!ArgHasUses && !isSwiftErrorArg) { 11358 SDB->setUnusedArgValue(&Arg, InVals[i]); 11359 11360 // Also remember any frame index for use in FastISel. 11361 if (FrameIndexSDNode *FI = 11362 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11363 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11364 } 11365 11366 for (unsigned Val = 0; Val != NumValues; ++Val) { 11367 EVT VT = ValueVTs[Val]; 11368 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11369 F.getCallingConv(), VT); 11370 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11371 *CurDAG->getContext(), F.getCallingConv(), VT); 11372 11373 // Even an apparent 'unused' swifterror argument needs to be returned. So 11374 // we do generate a copy for it that can be used on return from the 11375 // function. 11376 if (ArgHasUses || isSwiftErrorArg) { 11377 std::optional<ISD::NodeType> AssertOp; 11378 if (Arg.hasAttribute(Attribute::SExt)) 11379 AssertOp = ISD::AssertSext; 11380 else if (Arg.hasAttribute(Attribute::ZExt)) 11381 AssertOp = ISD::AssertZext; 11382 11383 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11384 PartVT, VT, nullptr, NewRoot, 11385 F.getCallingConv(), AssertOp)); 11386 } 11387 11388 i += NumParts; 11389 } 11390 11391 // We don't need to do anything else for unused arguments. 11392 if (ArgValues.empty()) 11393 continue; 11394 11395 // Note down frame index. 11396 if (FrameIndexSDNode *FI = 11397 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11398 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11399 11400 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11401 SDB->getCurSDLoc()); 11402 11403 SDB->setValue(&Arg, Res); 11404 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11405 // We want to associate the argument with the frame index, among 11406 // involved operands, that correspond to the lowest address. The 11407 // getCopyFromParts function, called earlier, is swapping the order of 11408 // the operands to BUILD_PAIR depending on endianness. The result of 11409 // that swapping is that the least significant bits of the argument will 11410 // be in the first operand of the BUILD_PAIR node, and the most 11411 // significant bits will be in the second operand. 11412 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11413 if (LoadSDNode *LNode = 11414 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11415 if (FrameIndexSDNode *FI = 11416 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11417 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11418 } 11419 11420 // Analyses past this point are naive and don't expect an assertion. 11421 if (Res.getOpcode() == ISD::AssertZext) 11422 Res = Res.getOperand(0); 11423 11424 // Update the SwiftErrorVRegDefMap. 11425 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11426 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11427 if (Register::isVirtualRegister(Reg)) 11428 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11429 Reg); 11430 } 11431 11432 // If this argument is live outside of the entry block, insert a copy from 11433 // wherever we got it to the vreg that other BB's will reference it as. 11434 if (Res.getOpcode() == ISD::CopyFromReg) { 11435 // If we can, though, try to skip creating an unnecessary vreg. 11436 // FIXME: This isn't very clean... it would be nice to make this more 11437 // general. 11438 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11439 if (Register::isVirtualRegister(Reg)) { 11440 FuncInfo->ValueMap[&Arg] = Reg; 11441 continue; 11442 } 11443 } 11444 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11445 FuncInfo->InitializeRegForValue(&Arg); 11446 SDB->CopyToExportRegsIfNeeded(&Arg); 11447 } 11448 } 11449 11450 if (!Chains.empty()) { 11451 Chains.push_back(NewRoot); 11452 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11453 } 11454 11455 DAG.setRoot(NewRoot); 11456 11457 assert(i == InVals.size() && "Argument register count mismatch!"); 11458 11459 // If any argument copy elisions occurred and we have debug info, update the 11460 // stale frame indices used in the dbg.declare variable info table. 11461 if (!ArgCopyElisionFrameIndexMap.empty()) { 11462 for (MachineFunction::VariableDbgInfo &VI : 11463 MF->getInStackSlotVariableDbgInfo()) { 11464 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11465 if (I != ArgCopyElisionFrameIndexMap.end()) 11466 VI.updateStackSlot(I->second); 11467 } 11468 } 11469 11470 // Finally, if the target has anything special to do, allow it to do so. 11471 emitFunctionEntryCode(); 11472 } 11473 11474 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11475 /// ensure constants are generated when needed. Remember the virtual registers 11476 /// that need to be added to the Machine PHI nodes as input. We cannot just 11477 /// directly add them, because expansion might result in multiple MBB's for one 11478 /// BB. As such, the start of the BB might correspond to a different MBB than 11479 /// the end. 11480 void 11481 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11482 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11483 11484 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11485 11486 // Check PHI nodes in successors that expect a value to be available from this 11487 // block. 11488 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11489 if (!isa<PHINode>(SuccBB->begin())) continue; 11490 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 11491 11492 // If this terminator has multiple identical successors (common for 11493 // switches), only handle each succ once. 11494 if (!SuccsHandled.insert(SuccMBB).second) 11495 continue; 11496 11497 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11498 11499 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11500 // nodes and Machine PHI nodes, but the incoming operands have not been 11501 // emitted yet. 11502 for (const PHINode &PN : SuccBB->phis()) { 11503 // Ignore dead phi's. 11504 if (PN.use_empty()) 11505 continue; 11506 11507 // Skip empty types 11508 if (PN.getType()->isEmptyTy()) 11509 continue; 11510 11511 unsigned Reg; 11512 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11513 11514 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11515 unsigned &RegOut = ConstantsOut[C]; 11516 if (RegOut == 0) { 11517 RegOut = FuncInfo.CreateRegs(C); 11518 // We need to zero/sign extend ConstantInt phi operands to match 11519 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11520 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11521 if (auto *CI = dyn_cast<ConstantInt>(C)) 11522 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11523 : ISD::ZERO_EXTEND; 11524 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11525 } 11526 Reg = RegOut; 11527 } else { 11528 DenseMap<const Value *, Register>::iterator I = 11529 FuncInfo.ValueMap.find(PHIOp); 11530 if (I != FuncInfo.ValueMap.end()) 11531 Reg = I->second; 11532 else { 11533 assert(isa<AllocaInst>(PHIOp) && 11534 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11535 "Didn't codegen value into a register!??"); 11536 Reg = FuncInfo.CreateRegs(PHIOp); 11537 CopyValueToVirtualRegister(PHIOp, Reg); 11538 } 11539 } 11540 11541 // Remember that this register needs to added to the machine PHI node as 11542 // the input for this MBB. 11543 SmallVector<EVT, 4> ValueVTs; 11544 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11545 for (EVT VT : ValueVTs) { 11546 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11547 for (unsigned i = 0; i != NumRegisters; ++i) 11548 FuncInfo.PHINodesToUpdate.push_back( 11549 std::make_pair(&*MBBI++, Reg + i)); 11550 Reg += NumRegisters; 11551 } 11552 } 11553 } 11554 11555 ConstantsOut.clear(); 11556 } 11557 11558 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11559 MachineFunction::iterator I(MBB); 11560 if (++I == FuncInfo.MF->end()) 11561 return nullptr; 11562 return &*I; 11563 } 11564 11565 /// During lowering new call nodes can be created (such as memset, etc.). 11566 /// Those will become new roots of the current DAG, but complications arise 11567 /// when they are tail calls. In such cases, the call lowering will update 11568 /// the root, but the builder still needs to know that a tail call has been 11569 /// lowered in order to avoid generating an additional return. 11570 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11571 // If the node is null, we do have a tail call. 11572 if (MaybeTC.getNode() != nullptr) 11573 DAG.setRoot(MaybeTC); 11574 else 11575 HasTailCall = true; 11576 } 11577 11578 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11579 MachineBasicBlock *SwitchMBB, 11580 MachineBasicBlock *DefaultMBB) { 11581 MachineFunction *CurMF = FuncInfo.MF; 11582 MachineBasicBlock *NextMBB = nullptr; 11583 MachineFunction::iterator BBI(W.MBB); 11584 if (++BBI != FuncInfo.MF->end()) 11585 NextMBB = &*BBI; 11586 11587 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11588 11589 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11590 11591 if (Size == 2 && W.MBB == SwitchMBB) { 11592 // If any two of the cases has the same destination, and if one value 11593 // is the same as the other, but has one bit unset that the other has set, 11594 // use bit manipulation to do two compares at once. For example: 11595 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11596 // TODO: This could be extended to merge any 2 cases in switches with 3 11597 // cases. 11598 // TODO: Handle cases where W.CaseBB != SwitchBB. 11599 CaseCluster &Small = *W.FirstCluster; 11600 CaseCluster &Big = *W.LastCluster; 11601 11602 if (Small.Low == Small.High && Big.Low == Big.High && 11603 Small.MBB == Big.MBB) { 11604 const APInt &SmallValue = Small.Low->getValue(); 11605 const APInt &BigValue = Big.Low->getValue(); 11606 11607 // Check that there is only one bit different. 11608 APInt CommonBit = BigValue ^ SmallValue; 11609 if (CommonBit.isPowerOf2()) { 11610 SDValue CondLHS = getValue(Cond); 11611 EVT VT = CondLHS.getValueType(); 11612 SDLoc DL = getCurSDLoc(); 11613 11614 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11615 DAG.getConstant(CommonBit, DL, VT)); 11616 SDValue Cond = DAG.getSetCC( 11617 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11618 ISD::SETEQ); 11619 11620 // Update successor info. 11621 // Both Small and Big will jump to Small.BB, so we sum up the 11622 // probabilities. 11623 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11624 if (BPI) 11625 addSuccessorWithProb( 11626 SwitchMBB, DefaultMBB, 11627 // The default destination is the first successor in IR. 11628 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11629 else 11630 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11631 11632 // Insert the true branch. 11633 SDValue BrCond = 11634 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11635 DAG.getBasicBlock(Small.MBB)); 11636 // Insert the false branch. 11637 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11638 DAG.getBasicBlock(DefaultMBB)); 11639 11640 DAG.setRoot(BrCond); 11641 return; 11642 } 11643 } 11644 } 11645 11646 if (TM.getOptLevel() != CodeGenOptLevel::None) { 11647 // Here, we order cases by probability so the most likely case will be 11648 // checked first. However, two clusters can have the same probability in 11649 // which case their relative ordering is non-deterministic. So we use Low 11650 // as a tie-breaker as clusters are guaranteed to never overlap. 11651 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11652 [](const CaseCluster &a, const CaseCluster &b) { 11653 return a.Prob != b.Prob ? 11654 a.Prob > b.Prob : 11655 a.Low->getValue().slt(b.Low->getValue()); 11656 }); 11657 11658 // Rearrange the case blocks so that the last one falls through if possible 11659 // without changing the order of probabilities. 11660 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11661 --I; 11662 if (I->Prob > W.LastCluster->Prob) 11663 break; 11664 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11665 std::swap(*I, *W.LastCluster); 11666 break; 11667 } 11668 } 11669 } 11670 11671 // Compute total probability. 11672 BranchProbability DefaultProb = W.DefaultProb; 11673 BranchProbability UnhandledProbs = DefaultProb; 11674 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11675 UnhandledProbs += I->Prob; 11676 11677 MachineBasicBlock *CurMBB = W.MBB; 11678 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11679 bool FallthroughUnreachable = false; 11680 MachineBasicBlock *Fallthrough; 11681 if (I == W.LastCluster) { 11682 // For the last cluster, fall through to the default destination. 11683 Fallthrough = DefaultMBB; 11684 FallthroughUnreachable = isa<UnreachableInst>( 11685 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11686 } else { 11687 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11688 CurMF->insert(BBI, Fallthrough); 11689 // Put Cond in a virtual register to make it available from the new blocks. 11690 ExportFromCurrentBlock(Cond); 11691 } 11692 UnhandledProbs -= I->Prob; 11693 11694 switch (I->Kind) { 11695 case CC_JumpTable: { 11696 // FIXME: Optimize away range check based on pivot comparisons. 11697 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11698 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11699 11700 // The jump block hasn't been inserted yet; insert it here. 11701 MachineBasicBlock *JumpMBB = JT->MBB; 11702 CurMF->insert(BBI, JumpMBB); 11703 11704 auto JumpProb = I->Prob; 11705 auto FallthroughProb = UnhandledProbs; 11706 11707 // If the default statement is a target of the jump table, we evenly 11708 // distribute the default probability to successors of CurMBB. Also 11709 // update the probability on the edge from JumpMBB to Fallthrough. 11710 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11711 SE = JumpMBB->succ_end(); 11712 SI != SE; ++SI) { 11713 if (*SI == DefaultMBB) { 11714 JumpProb += DefaultProb / 2; 11715 FallthroughProb -= DefaultProb / 2; 11716 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11717 JumpMBB->normalizeSuccProbs(); 11718 break; 11719 } 11720 } 11721 11722 // If the default clause is unreachable, propagate that knowledge into 11723 // JTH->FallthroughUnreachable which will use it to suppress the range 11724 // check. 11725 // 11726 // However, don't do this if we're doing branch target enforcement, 11727 // because a table branch _without_ a range check can be a tempting JOP 11728 // gadget - out-of-bounds inputs that are impossible in correct 11729 // execution become possible again if an attacker can influence the 11730 // control flow. So if an attacker doesn't already have a BTI bypass 11731 // available, we don't want them to be able to get one out of this 11732 // table branch. 11733 if (FallthroughUnreachable) { 11734 Function &CurFunc = CurMF->getFunction(); 11735 bool HasBranchTargetEnforcement = false; 11736 if (CurFunc.hasFnAttribute("branch-target-enforcement")) { 11737 HasBranchTargetEnforcement = 11738 CurFunc.getFnAttribute("branch-target-enforcement") 11739 .getValueAsBool(); 11740 } else { 11741 HasBranchTargetEnforcement = 11742 CurMF->getMMI().getModule()->getModuleFlag( 11743 "branch-target-enforcement"); 11744 } 11745 if (!HasBranchTargetEnforcement) 11746 JTH->FallthroughUnreachable = true; 11747 } 11748 11749 if (!JTH->FallthroughUnreachable) 11750 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11751 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11752 CurMBB->normalizeSuccProbs(); 11753 11754 // The jump table header will be inserted in our current block, do the 11755 // range check, and fall through to our fallthrough block. 11756 JTH->HeaderBB = CurMBB; 11757 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11758 11759 // If we're in the right place, emit the jump table header right now. 11760 if (CurMBB == SwitchMBB) { 11761 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11762 JTH->Emitted = true; 11763 } 11764 break; 11765 } 11766 case CC_BitTests: { 11767 // FIXME: Optimize away range check based on pivot comparisons. 11768 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11769 11770 // The bit test blocks haven't been inserted yet; insert them here. 11771 for (BitTestCase &BTC : BTB->Cases) 11772 CurMF->insert(BBI, BTC.ThisBB); 11773 11774 // Fill in fields of the BitTestBlock. 11775 BTB->Parent = CurMBB; 11776 BTB->Default = Fallthrough; 11777 11778 BTB->DefaultProb = UnhandledProbs; 11779 // If the cases in bit test don't form a contiguous range, we evenly 11780 // distribute the probability on the edge to Fallthrough to two 11781 // successors of CurMBB. 11782 if (!BTB->ContiguousRange) { 11783 BTB->Prob += DefaultProb / 2; 11784 BTB->DefaultProb -= DefaultProb / 2; 11785 } 11786 11787 if (FallthroughUnreachable) 11788 BTB->FallthroughUnreachable = true; 11789 11790 // If we're in the right place, emit the bit test header right now. 11791 if (CurMBB == SwitchMBB) { 11792 visitBitTestHeader(*BTB, SwitchMBB); 11793 BTB->Emitted = true; 11794 } 11795 break; 11796 } 11797 case CC_Range: { 11798 const Value *RHS, *LHS, *MHS; 11799 ISD::CondCode CC; 11800 if (I->Low == I->High) { 11801 // Check Cond == I->Low. 11802 CC = ISD::SETEQ; 11803 LHS = Cond; 11804 RHS=I->Low; 11805 MHS = nullptr; 11806 } else { 11807 // Check I->Low <= Cond <= I->High. 11808 CC = ISD::SETLE; 11809 LHS = I->Low; 11810 MHS = Cond; 11811 RHS = I->High; 11812 } 11813 11814 // If Fallthrough is unreachable, fold away the comparison. 11815 if (FallthroughUnreachable) 11816 CC = ISD::SETTRUE; 11817 11818 // The false probability is the sum of all unhandled cases. 11819 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11820 getCurSDLoc(), I->Prob, UnhandledProbs); 11821 11822 if (CurMBB == SwitchMBB) 11823 visitSwitchCase(CB, SwitchMBB); 11824 else 11825 SL->SwitchCases.push_back(CB); 11826 11827 break; 11828 } 11829 } 11830 CurMBB = Fallthrough; 11831 } 11832 } 11833 11834 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11835 const SwitchWorkListItem &W, 11836 Value *Cond, 11837 MachineBasicBlock *SwitchMBB) { 11838 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11839 "Clusters not sorted?"); 11840 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11841 11842 auto [LastLeft, FirstRight, LeftProb, RightProb] = 11843 SL->computeSplitWorkItemInfo(W); 11844 11845 // Use the first element on the right as pivot since we will make less-than 11846 // comparisons against it. 11847 CaseClusterIt PivotCluster = FirstRight; 11848 assert(PivotCluster > W.FirstCluster); 11849 assert(PivotCluster <= W.LastCluster); 11850 11851 CaseClusterIt FirstLeft = W.FirstCluster; 11852 CaseClusterIt LastRight = W.LastCluster; 11853 11854 const ConstantInt *Pivot = PivotCluster->Low; 11855 11856 // New blocks will be inserted immediately after the current one. 11857 MachineFunction::iterator BBI(W.MBB); 11858 ++BBI; 11859 11860 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11861 // we can branch to its destination directly if it's squeezed exactly in 11862 // between the known lower bound and Pivot - 1. 11863 MachineBasicBlock *LeftMBB; 11864 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11865 FirstLeft->Low == W.GE && 11866 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11867 LeftMBB = FirstLeft->MBB; 11868 } else { 11869 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11870 FuncInfo.MF->insert(BBI, LeftMBB); 11871 WorkList.push_back( 11872 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11873 // Put Cond in a virtual register to make it available from the new blocks. 11874 ExportFromCurrentBlock(Cond); 11875 } 11876 11877 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11878 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11879 // directly if RHS.High equals the current upper bound. 11880 MachineBasicBlock *RightMBB; 11881 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11882 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11883 RightMBB = FirstRight->MBB; 11884 } else { 11885 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11886 FuncInfo.MF->insert(BBI, RightMBB); 11887 WorkList.push_back( 11888 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11889 // Put Cond in a virtual register to make it available from the new blocks. 11890 ExportFromCurrentBlock(Cond); 11891 } 11892 11893 // Create the CaseBlock record that will be used to lower the branch. 11894 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11895 getCurSDLoc(), LeftProb, RightProb); 11896 11897 if (W.MBB == SwitchMBB) 11898 visitSwitchCase(CB, SwitchMBB); 11899 else 11900 SL->SwitchCases.push_back(CB); 11901 } 11902 11903 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11904 // from the swith statement. 11905 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11906 BranchProbability PeeledCaseProb) { 11907 if (PeeledCaseProb == BranchProbability::getOne()) 11908 return BranchProbability::getZero(); 11909 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11910 11911 uint32_t Numerator = CaseProb.getNumerator(); 11912 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11913 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11914 } 11915 11916 // Try to peel the top probability case if it exceeds the threshold. 11917 // Return current MachineBasicBlock for the switch statement if the peeling 11918 // does not occur. 11919 // If the peeling is performed, return the newly created MachineBasicBlock 11920 // for the peeled switch statement. Also update Clusters to remove the peeled 11921 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11922 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11923 const SwitchInst &SI, CaseClusterVector &Clusters, 11924 BranchProbability &PeeledCaseProb) { 11925 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11926 // Don't perform if there is only one cluster or optimizing for size. 11927 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11928 TM.getOptLevel() == CodeGenOptLevel::None || 11929 SwitchMBB->getParent()->getFunction().hasMinSize()) 11930 return SwitchMBB; 11931 11932 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11933 unsigned PeeledCaseIndex = 0; 11934 bool SwitchPeeled = false; 11935 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11936 CaseCluster &CC = Clusters[Index]; 11937 if (CC.Prob < TopCaseProb) 11938 continue; 11939 TopCaseProb = CC.Prob; 11940 PeeledCaseIndex = Index; 11941 SwitchPeeled = true; 11942 } 11943 if (!SwitchPeeled) 11944 return SwitchMBB; 11945 11946 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11947 << TopCaseProb << "\n"); 11948 11949 // Record the MBB for the peeled switch statement. 11950 MachineFunction::iterator BBI(SwitchMBB); 11951 ++BBI; 11952 MachineBasicBlock *PeeledSwitchMBB = 11953 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11954 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11955 11956 ExportFromCurrentBlock(SI.getCondition()); 11957 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11958 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11959 nullptr, nullptr, TopCaseProb.getCompl()}; 11960 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11961 11962 Clusters.erase(PeeledCaseIt); 11963 for (CaseCluster &CC : Clusters) { 11964 LLVM_DEBUG( 11965 dbgs() << "Scale the probablity for one cluster, before scaling: " 11966 << CC.Prob << "\n"); 11967 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11968 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11969 } 11970 PeeledCaseProb = TopCaseProb; 11971 return PeeledSwitchMBB; 11972 } 11973 11974 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11975 // Extract cases from the switch. 11976 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11977 CaseClusterVector Clusters; 11978 Clusters.reserve(SI.getNumCases()); 11979 for (auto I : SI.cases()) { 11980 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11981 const ConstantInt *CaseVal = I.getCaseValue(); 11982 BranchProbability Prob = 11983 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11984 : BranchProbability(1, SI.getNumCases() + 1); 11985 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11986 } 11987 11988 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11989 11990 // Cluster adjacent cases with the same destination. We do this at all 11991 // optimization levels because it's cheap to do and will make codegen faster 11992 // if there are many clusters. 11993 sortAndRangeify(Clusters); 11994 11995 // The branch probablity of the peeled case. 11996 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11997 MachineBasicBlock *PeeledSwitchMBB = 11998 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11999 12000 // If there is only the default destination, jump there directly. 12001 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12002 if (Clusters.empty()) { 12003 assert(PeeledSwitchMBB == SwitchMBB); 12004 SwitchMBB->addSuccessor(DefaultMBB); 12005 if (DefaultMBB != NextBlock(SwitchMBB)) { 12006 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 12007 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 12008 } 12009 return; 12010 } 12011 12012 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(), 12013 DAG.getBFI()); 12014 SL->findBitTestClusters(Clusters, &SI); 12015 12016 LLVM_DEBUG({ 12017 dbgs() << "Case clusters: "; 12018 for (const CaseCluster &C : Clusters) { 12019 if (C.Kind == CC_JumpTable) 12020 dbgs() << "JT:"; 12021 if (C.Kind == CC_BitTests) 12022 dbgs() << "BT:"; 12023 12024 C.Low->getValue().print(dbgs(), true); 12025 if (C.Low != C.High) { 12026 dbgs() << '-'; 12027 C.High->getValue().print(dbgs(), true); 12028 } 12029 dbgs() << ' '; 12030 } 12031 dbgs() << '\n'; 12032 }); 12033 12034 assert(!Clusters.empty()); 12035 SwitchWorkList WorkList; 12036 CaseClusterIt First = Clusters.begin(); 12037 CaseClusterIt Last = Clusters.end() - 1; 12038 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 12039 // Scale the branchprobability for DefaultMBB if the peel occurs and 12040 // DefaultMBB is not replaced. 12041 if (PeeledCaseProb != BranchProbability::getZero() && 12042 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 12043 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 12044 WorkList.push_back( 12045 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 12046 12047 while (!WorkList.empty()) { 12048 SwitchWorkListItem W = WorkList.pop_back_val(); 12049 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 12050 12051 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 12052 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 12053 // For optimized builds, lower large range as a balanced binary tree. 12054 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 12055 continue; 12056 } 12057 12058 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 12059 } 12060 } 12061 12062 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 12063 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12064 auto DL = getCurSDLoc(); 12065 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12066 setValue(&I, DAG.getStepVector(DL, ResultVT)); 12067 } 12068 12069 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 12070 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12071 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12072 12073 SDLoc DL = getCurSDLoc(); 12074 SDValue V = getValue(I.getOperand(0)); 12075 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 12076 12077 if (VT.isScalableVector()) { 12078 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 12079 return; 12080 } 12081 12082 // Use VECTOR_SHUFFLE for the fixed-length vector 12083 // to maintain existing behavior. 12084 SmallVector<int, 8> Mask; 12085 unsigned NumElts = VT.getVectorMinNumElements(); 12086 for (unsigned i = 0; i != NumElts; ++i) 12087 Mask.push_back(NumElts - 1 - i); 12088 12089 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 12090 } 12091 12092 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 12093 auto DL = getCurSDLoc(); 12094 SDValue InVec = getValue(I.getOperand(0)); 12095 EVT OutVT = 12096 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 12097 12098 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 12099 12100 // ISD Node needs the input vectors split into two equal parts 12101 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12102 DAG.getVectorIdxConstant(0, DL)); 12103 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12104 DAG.getVectorIdxConstant(OutNumElts, DL)); 12105 12106 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12107 // legalisation and combines. 12108 if (OutVT.isFixedLengthVector()) { 12109 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12110 createStrideMask(0, 2, OutNumElts)); 12111 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12112 createStrideMask(1, 2, OutNumElts)); 12113 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 12114 setValue(&I, Res); 12115 return; 12116 } 12117 12118 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 12119 DAG.getVTList(OutVT, OutVT), Lo, Hi); 12120 setValue(&I, Res); 12121 } 12122 12123 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 12124 auto DL = getCurSDLoc(); 12125 EVT InVT = getValue(I.getOperand(0)).getValueType(); 12126 SDValue InVec0 = getValue(I.getOperand(0)); 12127 SDValue InVec1 = getValue(I.getOperand(1)); 12128 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12129 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12130 12131 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12132 // legalisation and combines. 12133 if (OutVT.isFixedLengthVector()) { 12134 unsigned NumElts = InVT.getVectorMinNumElements(); 12135 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 12136 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 12137 createInterleaveMask(NumElts, 2))); 12138 return; 12139 } 12140 12141 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 12142 DAG.getVTList(InVT, InVT), InVec0, InVec1); 12143 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 12144 Res.getValue(1)); 12145 setValue(&I, Res); 12146 } 12147 12148 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 12149 SmallVector<EVT, 4> ValueVTs; 12150 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 12151 ValueVTs); 12152 unsigned NumValues = ValueVTs.size(); 12153 if (NumValues == 0) return; 12154 12155 SmallVector<SDValue, 4> Values(NumValues); 12156 SDValue Op = getValue(I.getOperand(0)); 12157 12158 for (unsigned i = 0; i != NumValues; ++i) 12159 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 12160 SDValue(Op.getNode(), Op.getResNo() + i)); 12161 12162 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12163 DAG.getVTList(ValueVTs), Values)); 12164 } 12165 12166 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 12167 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12168 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12169 12170 SDLoc DL = getCurSDLoc(); 12171 SDValue V1 = getValue(I.getOperand(0)); 12172 SDValue V2 = getValue(I.getOperand(1)); 12173 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12174 12175 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12176 if (VT.isScalableVector()) { 12177 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 12178 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12179 DAG.getConstant(Imm, DL, IdxVT))); 12180 return; 12181 } 12182 12183 unsigned NumElts = VT.getVectorNumElements(); 12184 12185 uint64_t Idx = (NumElts + Imm) % NumElts; 12186 12187 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12188 SmallVector<int, 8> Mask; 12189 for (unsigned i = 0; i < NumElts; ++i) 12190 Mask.push_back(Idx + i); 12191 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12192 } 12193 12194 // Consider the following MIR after SelectionDAG, which produces output in 12195 // phyregs in the first case or virtregs in the second case. 12196 // 12197 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12198 // %5:gr32 = COPY $ebx 12199 // %6:gr32 = COPY $edx 12200 // %1:gr32 = COPY %6:gr32 12201 // %0:gr32 = COPY %5:gr32 12202 // 12203 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12204 // %1:gr32 = COPY %6:gr32 12205 // %0:gr32 = COPY %5:gr32 12206 // 12207 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12208 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12209 // 12210 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12211 // to a single virtreg (such as %0). The remaining outputs monotonically 12212 // increase in virtreg number from there. If a callbr has no outputs, then it 12213 // should not have a corresponding callbr landingpad; in fact, the callbr 12214 // landingpad would not even be able to refer to such a callbr. 12215 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12216 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12217 // There is definitely at least one copy. 12218 assert(MI->getOpcode() == TargetOpcode::COPY && 12219 "start of copy chain MUST be COPY"); 12220 Reg = MI->getOperand(1).getReg(); 12221 MI = MRI.def_begin(Reg)->getParent(); 12222 // There may be an optional second copy. 12223 if (MI->getOpcode() == TargetOpcode::COPY) { 12224 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12225 Reg = MI->getOperand(1).getReg(); 12226 assert(Reg.isPhysical() && "expected COPY of physical register"); 12227 MI = MRI.def_begin(Reg)->getParent(); 12228 } 12229 // The start of the chain must be an INLINEASM_BR. 12230 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12231 "end of copy chain MUST be INLINEASM_BR"); 12232 return Reg; 12233 } 12234 12235 // We must do this walk rather than the simpler 12236 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12237 // otherwise we will end up with copies of virtregs only valid along direct 12238 // edges. 12239 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12240 SmallVector<EVT, 8> ResultVTs; 12241 SmallVector<SDValue, 8> ResultValues; 12242 const auto *CBR = 12243 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12244 12245 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12246 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12247 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12248 12249 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12250 SDValue Chain = DAG.getRoot(); 12251 12252 // Re-parse the asm constraints string. 12253 TargetLowering::AsmOperandInfoVector TargetConstraints = 12254 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12255 for (auto &T : TargetConstraints) { 12256 SDISelAsmOperandInfo OpInfo(T); 12257 if (OpInfo.Type != InlineAsm::isOutput) 12258 continue; 12259 12260 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12261 // individual constraint. 12262 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12263 12264 switch (OpInfo.ConstraintType) { 12265 case TargetLowering::C_Register: 12266 case TargetLowering::C_RegisterClass: { 12267 // Fill in OpInfo.AssignedRegs.Regs. 12268 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12269 12270 // getRegistersForValue may produce 1 to many registers based on whether 12271 // the OpInfo.ConstraintVT is legal on the target or not. 12272 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 12273 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12274 if (Register::isPhysicalRegister(OriginalDef)) 12275 FuncInfo.MBB->addLiveIn(OriginalDef); 12276 // Update the assigned registers to use the original defs. 12277 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 12278 } 12279 12280 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12281 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12282 ResultValues.push_back(V); 12283 ResultVTs.push_back(OpInfo.ConstraintVT); 12284 break; 12285 } 12286 case TargetLowering::C_Other: { 12287 SDValue Flag; 12288 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12289 OpInfo, DAG); 12290 ++InitialDef; 12291 ResultValues.push_back(V); 12292 ResultVTs.push_back(OpInfo.ConstraintVT); 12293 break; 12294 } 12295 default: 12296 break; 12297 } 12298 } 12299 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12300 DAG.getVTList(ResultVTs), ResultValues); 12301 setValue(&I, V); 12302 } 12303