1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/Loads.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/Analysis/VectorUtils.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 33 #include "llvm/CodeGen/CodeGenCommonISel.h" 34 #include "llvm/CodeGen/FunctionLoweringInfo.h" 35 #include "llvm/CodeGen/GCMetadata.h" 36 #include "llvm/CodeGen/ISDOpcodes.h" 37 #include "llvm/CodeGen/MachineBasicBlock.h" 38 #include "llvm/CodeGen/MachineFrameInfo.h" 39 #include "llvm/CodeGen/MachineFunction.h" 40 #include "llvm/CodeGen/MachineInstrBuilder.h" 41 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 42 #include "llvm/CodeGen/MachineMemOperand.h" 43 #include "llvm/CodeGen/MachineModuleInfo.h" 44 #include "llvm/CodeGen/MachineOperand.h" 45 #include "llvm/CodeGen/MachineRegisterInfo.h" 46 #include "llvm/CodeGen/RuntimeLibcalls.h" 47 #include "llvm/CodeGen/SelectionDAG.h" 48 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 49 #include "llvm/CodeGen/StackMaps.h" 50 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 51 #include "llvm/CodeGen/TargetFrameLowering.h" 52 #include "llvm/CodeGen/TargetInstrInfo.h" 53 #include "llvm/CodeGen/TargetOpcodes.h" 54 #include "llvm/CodeGen/TargetRegisterInfo.h" 55 #include "llvm/CodeGen/TargetSubtargetInfo.h" 56 #include "llvm/CodeGen/WinEHFuncInfo.h" 57 #include "llvm/IR/Argument.h" 58 #include "llvm/IR/Attributes.h" 59 #include "llvm/IR/BasicBlock.h" 60 #include "llvm/IR/CFG.h" 61 #include "llvm/IR/CallingConv.h" 62 #include "llvm/IR/Constant.h" 63 #include "llvm/IR/ConstantRange.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DebugInfo.h" 67 #include "llvm/IR/DebugInfoMetadata.h" 68 #include "llvm/IR/DerivedTypes.h" 69 #include "llvm/IR/DiagnosticInfo.h" 70 #include "llvm/IR/EHPersonalities.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GetElementPtrTypeIterator.h" 73 #include "llvm/IR/InlineAsm.h" 74 #include "llvm/IR/InstrTypes.h" 75 #include "llvm/IR/Instructions.h" 76 #include "llvm/IR/IntrinsicInst.h" 77 #include "llvm/IR/Intrinsics.h" 78 #include "llvm/IR/IntrinsicsAArch64.h" 79 #include "llvm/IR/IntrinsicsAMDGPU.h" 80 #include "llvm/IR/IntrinsicsWebAssembly.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Operator.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Statepoint.h" 87 #include "llvm/IR/Type.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/MC/MCContext.h" 91 #include "llvm/Support/AtomicOrdering.h" 92 #include "llvm/Support/Casting.h" 93 #include "llvm/Support/CommandLine.h" 94 #include "llvm/Support/Compiler.h" 95 #include "llvm/Support/Debug.h" 96 #include "llvm/Support/MathExtras.h" 97 #include "llvm/Support/raw_ostream.h" 98 #include "llvm/Target/TargetIntrinsicInfo.h" 99 #include "llvm/Target/TargetMachine.h" 100 #include "llvm/Target/TargetOptions.h" 101 #include "llvm/TargetParser/Triple.h" 102 #include "llvm/Transforms/Utils/Local.h" 103 #include <cstddef> 104 #include <iterator> 105 #include <limits> 106 #include <optional> 107 #include <tuple> 108 109 using namespace llvm; 110 using namespace PatternMatch; 111 using namespace SwitchCG; 112 113 #define DEBUG_TYPE "isel" 114 115 /// LimitFloatPrecision - Generate low-precision inline sequences for 116 /// some float libcalls (6, 8 or 12 bits). 117 static unsigned LimitFloatPrecision; 118 119 static cl::opt<bool> 120 InsertAssertAlign("insert-assert-align", cl::init(true), 121 cl::desc("Insert the experimental `assertalign` node."), 122 cl::ReallyHidden); 123 124 static cl::opt<unsigned, true> 125 LimitFPPrecision("limit-float-precision", 126 cl::desc("Generate low-precision inline sequences " 127 "for some float libcalls"), 128 cl::location(LimitFloatPrecision), cl::Hidden, 129 cl::init(0)); 130 131 static cl::opt<unsigned> SwitchPeelThreshold( 132 "switch-peel-threshold", cl::Hidden, cl::init(66), 133 cl::desc("Set the case probability threshold for peeling the case from a " 134 "switch statement. A value greater than 100 will void this " 135 "optimization")); 136 137 // Limit the width of DAG chains. This is important in general to prevent 138 // DAG-based analysis from blowing up. For example, alias analysis and 139 // load clustering may not complete in reasonable time. It is difficult to 140 // recognize and avoid this situation within each individual analysis, and 141 // future analyses are likely to have the same behavior. Limiting DAG width is 142 // the safe approach and will be especially important with global DAGs. 143 // 144 // MaxParallelChains default is arbitrarily high to avoid affecting 145 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 146 // sequence over this should have been converted to llvm.memcpy by the 147 // frontend. It is easy to induce this behavior with .ll code such as: 148 // %buffer = alloca [4096 x i8] 149 // %data = load [4096 x i8]* %argPtr 150 // store [4096 x i8] %data, [4096 x i8]* %buffer 151 static const unsigned MaxParallelChains = 64; 152 153 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 154 const SDValue *Parts, unsigned NumParts, 155 MVT PartVT, EVT ValueVT, const Value *V, 156 SDValue InChain, 157 std::optional<CallingConv::ID> CC); 158 159 /// getCopyFromParts - Create a value that contains the specified legal parts 160 /// combined into the value they represent. If the parts combine to a type 161 /// larger than ValueVT then AssertOp can be used to specify whether the extra 162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 163 /// (ISD::AssertSext). 164 static SDValue 165 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 166 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 167 SDValue InChain, 168 std::optional<CallingConv::ID> CC = std::nullopt, 169 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 170 // Let the target assemble the parts if it wants to 171 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 172 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 173 PartVT, ValueVT, CC)) 174 return Val; 175 176 if (ValueVT.isVector()) 177 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 178 InChain, CC); 179 180 assert(NumParts > 0 && "No parts to assemble!"); 181 SDValue Val = Parts[0]; 182 183 if (NumParts > 1) { 184 // Assemble the value from multiple parts. 185 if (ValueVT.isInteger()) { 186 unsigned PartBits = PartVT.getSizeInBits(); 187 unsigned ValueBits = ValueVT.getSizeInBits(); 188 189 // Assemble the power of 2 part. 190 unsigned RoundParts = llvm::bit_floor(NumParts); 191 unsigned RoundBits = PartBits * RoundParts; 192 EVT RoundVT = RoundBits == ValueBits ? 193 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 194 SDValue Lo, Hi; 195 196 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 197 198 if (RoundParts > 2) { 199 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V, 200 InChain); 201 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2, 202 PartVT, HalfVT, V, InChain); 203 } else { 204 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 205 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 206 } 207 208 if (DAG.getDataLayout().isBigEndian()) 209 std::swap(Lo, Hi); 210 211 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 212 213 if (RoundParts < NumParts) { 214 // Assemble the trailing non-power-of-2 part. 215 unsigned OddParts = NumParts - RoundParts; 216 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 217 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 218 OddVT, V, InChain, CC); 219 220 // Combine the round and odd parts. 221 Lo = Val; 222 if (DAG.getDataLayout().isBigEndian()) 223 std::swap(Lo, Hi); 224 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 225 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 226 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 227 DAG.getConstant(Lo.getValueSizeInBits(), DL, 228 TLI.getShiftAmountTy( 229 TotalVT, DAG.getDataLayout()))); 230 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 231 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 232 } 233 } else if (PartVT.isFloatingPoint()) { 234 // FP split into multiple FP parts (for ppcf128) 235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 236 "Unexpected split"); 237 SDValue Lo, Hi; 238 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 239 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 240 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 241 std::swap(Lo, Hi); 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 243 } else { 244 // FP split into integer parts (soft fp) 245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 246 !PartVT.isVector() && "Unexpected split"); 247 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, 249 InChain, CC); 250 } 251 } 252 253 // There is now one part, held in Val. Correct it to match ValueVT. 254 // PartEVT is the type of the register class that holds the value. 255 // ValueVT is the type of the inline asm operation. 256 EVT PartEVT = Val.getValueType(); 257 258 if (PartEVT == ValueVT) 259 return Val; 260 261 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 262 ValueVT.bitsLT(PartEVT)) { 263 // For an FP value in an integer part, we need to truncate to the right 264 // width first. 265 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 266 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 267 } 268 269 // Handle types that have the same size. 270 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 271 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 272 273 // Handle types with different sizes. 274 if (PartEVT.isInteger() && ValueVT.isInteger()) { 275 if (ValueVT.bitsLT(PartEVT)) { 276 // For a truncate, see if we have any information to 277 // indicate whether the truncated bits will always be 278 // zero or sign-extension. 279 if (AssertOp) 280 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 281 DAG.getValueType(ValueVT)); 282 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 283 } 284 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 285 } 286 287 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 288 // FP_ROUND's are always exact here. 289 if (ValueVT.bitsLT(Val.getValueType())) { 290 291 SDValue NoChange = 292 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 293 294 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr( 295 llvm::Attribute::StrictFP)) { 296 return DAG.getNode(ISD::STRICT_FP_ROUND, DL, 297 DAG.getVTList(ValueVT, MVT::Other), InChain, Val, 298 NoChange); 299 } 300 301 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange); 302 } 303 304 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 305 } 306 307 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 308 // then truncating. 309 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 310 ValueVT.bitsLT(PartEVT)) { 311 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 312 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 313 } 314 315 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 316 } 317 318 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 319 const Twine &ErrMsg) { 320 const Instruction *I = dyn_cast_or_null<Instruction>(V); 321 if (!V) 322 return Ctx.emitError(ErrMsg); 323 324 const char *AsmError = ", possible invalid constraint for vector type"; 325 if (const CallInst *CI = dyn_cast<CallInst>(I)) 326 if (CI->isInlineAsm()) 327 return Ctx.emitError(I, ErrMsg + AsmError); 328 329 return Ctx.emitError(I, ErrMsg); 330 } 331 332 /// getCopyFromPartsVector - Create a value that contains the specified legal 333 /// parts combined into the value they represent. If the parts combine to a 334 /// type larger than ValueVT then AssertOp can be used to specify whether the 335 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 336 /// ValueVT (ISD::AssertSext). 337 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 338 const SDValue *Parts, unsigned NumParts, 339 MVT PartVT, EVT ValueVT, const Value *V, 340 SDValue InChain, 341 std::optional<CallingConv::ID> CallConv) { 342 assert(ValueVT.isVector() && "Not a vector value"); 343 assert(NumParts > 0 && "No parts to assemble!"); 344 const bool IsABIRegCopy = CallConv.has_value(); 345 346 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 347 SDValue Val = Parts[0]; 348 349 // Handle a multi-element vector. 350 if (NumParts > 1) { 351 EVT IntermediateVT; 352 MVT RegisterVT; 353 unsigned NumIntermediates; 354 unsigned NumRegs; 355 356 if (IsABIRegCopy) { 357 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 358 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 359 NumIntermediates, RegisterVT); 360 } else { 361 NumRegs = 362 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 363 NumIntermediates, RegisterVT); 364 } 365 366 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 367 NumParts = NumRegs; // Silence a compiler warning. 368 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 369 assert(RegisterVT.getSizeInBits() == 370 Parts[0].getSimpleValueType().getSizeInBits() && 371 "Part type sizes don't match!"); 372 373 // Assemble the parts into intermediate operands. 374 SmallVector<SDValue, 8> Ops(NumIntermediates); 375 if (NumIntermediates == NumParts) { 376 // If the register was not expanded, truncate or copy the value, 377 // as appropriate. 378 for (unsigned i = 0; i != NumParts; ++i) 379 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT, 380 V, InChain, CallConv); 381 } else if (NumParts > 0) { 382 // If the intermediate type was expanded, build the intermediate 383 // operands from the parts. 384 assert(NumParts % NumIntermediates == 0 && 385 "Must expand into a divisible number of parts!"); 386 unsigned Factor = NumParts / NumIntermediates; 387 for (unsigned i = 0; i != NumIntermediates; ++i) 388 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT, 389 IntermediateVT, V, InChain, CallConv); 390 } 391 392 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 393 // intermediate operands. 394 EVT BuiltVectorTy = 395 IntermediateVT.isVector() 396 ? EVT::getVectorVT( 397 *DAG.getContext(), IntermediateVT.getScalarType(), 398 IntermediateVT.getVectorElementCount() * NumParts) 399 : EVT::getVectorVT(*DAG.getContext(), 400 IntermediateVT.getScalarType(), 401 NumIntermediates); 402 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 403 : ISD::BUILD_VECTOR, 404 DL, BuiltVectorTy, Ops); 405 } 406 407 // There is now one part, held in Val. Correct it to match ValueVT. 408 EVT PartEVT = Val.getValueType(); 409 410 if (PartEVT == ValueVT) 411 return Val; 412 413 if (PartEVT.isVector()) { 414 // Vector/Vector bitcast. 415 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 416 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 417 418 // If the parts vector has more elements than the value vector, then we 419 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 420 // Extract the elements we want. 421 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 422 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 423 ValueVT.getVectorElementCount().getKnownMinValue()) && 424 (PartEVT.getVectorElementCount().isScalable() == 425 ValueVT.getVectorElementCount().isScalable()) && 426 "Cannot narrow, it would be a lossy transformation"); 427 PartEVT = 428 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 429 ValueVT.getVectorElementCount()); 430 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 431 DAG.getVectorIdxConstant(0, DL)); 432 if (PartEVT == ValueVT) 433 return Val; 434 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 435 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 436 437 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 438 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 439 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 440 } 441 442 // Promoted vector extract 443 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 444 } 445 446 // Trivial bitcast if the types are the same size and the destination 447 // vector type is legal. 448 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 449 TLI.isTypeLegal(ValueVT)) 450 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 451 452 if (ValueVT.getVectorNumElements() != 1) { 453 // Certain ABIs require that vectors are passed as integers. For vectors 454 // are the same size, this is an obvious bitcast. 455 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 456 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 457 } else if (ValueVT.bitsLT(PartEVT)) { 458 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 459 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 460 // Drop the extra bits. 461 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 462 return DAG.getBitcast(ValueVT, Val); 463 } 464 465 diagnosePossiblyInvalidConstraint( 466 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 467 return DAG.getUNDEF(ValueVT); 468 } 469 470 // Handle cases such as i8 -> <1 x i1> 471 EVT ValueSVT = ValueVT.getVectorElementType(); 472 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 473 unsigned ValueSize = ValueSVT.getSizeInBits(); 474 if (ValueSize == PartEVT.getSizeInBits()) { 475 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 476 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 477 // It's possible a scalar floating point type gets softened to integer and 478 // then promoted to a larger integer. If PartEVT is the larger integer 479 // we need to truncate it and then bitcast to the FP type. 480 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 481 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 482 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 483 Val = DAG.getBitcast(ValueSVT, Val); 484 } else { 485 Val = ValueVT.isFloatingPoint() 486 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 487 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 488 } 489 } 490 491 return DAG.getBuildVector(ValueVT, DL, Val); 492 } 493 494 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 495 SDValue Val, SDValue *Parts, unsigned NumParts, 496 MVT PartVT, const Value *V, 497 std::optional<CallingConv::ID> CallConv); 498 499 /// getCopyToParts - Create a series of nodes that contain the specified value 500 /// split into legal parts. If the parts contain more bits than Val, then, for 501 /// integers, ExtendKind can be used to specify how to generate the extra bits. 502 static void 503 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 504 unsigned NumParts, MVT PartVT, const Value *V, 505 std::optional<CallingConv::ID> CallConv = std::nullopt, 506 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 507 // Let the target split the parts if it wants to 508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 509 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 510 CallConv)) 511 return; 512 EVT ValueVT = Val.getValueType(); 513 514 // Handle the vector case separately. 515 if (ValueVT.isVector()) 516 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 517 CallConv); 518 519 unsigned OrigNumParts = NumParts; 520 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 521 "Copying to an illegal type!"); 522 523 if (NumParts == 0) 524 return; 525 526 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 527 EVT PartEVT = PartVT; 528 if (PartEVT == ValueVT) { 529 assert(NumParts == 1 && "No-op copy with multiple parts!"); 530 Parts[0] = Val; 531 return; 532 } 533 534 unsigned PartBits = PartVT.getSizeInBits(); 535 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 536 // If the parts cover more bits than the value has, promote the value. 537 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 538 assert(NumParts == 1 && "Do not know what to promote to!"); 539 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 540 } else { 541 if (ValueVT.isFloatingPoint()) { 542 // FP values need to be bitcast, then extended if they are being put 543 // into a larger container. 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 545 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 546 } 547 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 548 ValueVT.isInteger() && 549 "Unknown mismatch!"); 550 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 551 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 552 if (PartVT == MVT::x86mmx) 553 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 554 } 555 } else if (PartBits == ValueVT.getSizeInBits()) { 556 // Different types of the same size. 557 assert(NumParts == 1 && PartEVT != ValueVT); 558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 559 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 560 // If the parts cover less bits than value has, truncate the value. 561 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 562 ValueVT.isInteger() && 563 "Unknown mismatch!"); 564 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 565 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 566 if (PartVT == MVT::x86mmx) 567 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 568 } 569 570 // The value may have changed - recompute ValueVT. 571 ValueVT = Val.getValueType(); 572 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 573 "Failed to tile the value with PartVT!"); 574 575 if (NumParts == 1) { 576 if (PartEVT != ValueVT) { 577 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 578 "scalar-to-vector conversion failed"); 579 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 580 } 581 582 Parts[0] = Val; 583 return; 584 } 585 586 // Expand the value into multiple parts. 587 if (NumParts & (NumParts - 1)) { 588 // The number of parts is not a power of 2. Split off and copy the tail. 589 assert(PartVT.isInteger() && ValueVT.isInteger() && 590 "Do not know what to expand to!"); 591 unsigned RoundParts = llvm::bit_floor(NumParts); 592 unsigned RoundBits = RoundParts * PartBits; 593 unsigned OddParts = NumParts - RoundParts; 594 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 595 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 596 597 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 598 CallConv); 599 600 if (DAG.getDataLayout().isBigEndian()) 601 // The odd parts were reversed by getCopyToParts - unreverse them. 602 std::reverse(Parts + RoundParts, Parts + NumParts); 603 604 NumParts = RoundParts; 605 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 606 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 607 } 608 609 // The number of parts is a power of 2. Repeatedly bisect the value using 610 // EXTRACT_ELEMENT. 611 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 612 EVT::getIntegerVT(*DAG.getContext(), 613 ValueVT.getSizeInBits()), 614 Val); 615 616 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 617 for (unsigned i = 0; i < NumParts; i += StepSize) { 618 unsigned ThisBits = StepSize * PartBits / 2; 619 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 620 SDValue &Part0 = Parts[i]; 621 SDValue &Part1 = Parts[i+StepSize/2]; 622 623 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 624 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 625 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 626 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 627 628 if (ThisBits == PartBits && ThisVT != PartVT) { 629 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 630 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 631 } 632 } 633 } 634 635 if (DAG.getDataLayout().isBigEndian()) 636 std::reverse(Parts, Parts + OrigNumParts); 637 } 638 639 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 640 const SDLoc &DL, EVT PartVT) { 641 if (!PartVT.isVector()) 642 return SDValue(); 643 644 EVT ValueVT = Val.getValueType(); 645 EVT PartEVT = PartVT.getVectorElementType(); 646 EVT ValueEVT = ValueVT.getVectorElementType(); 647 ElementCount PartNumElts = PartVT.getVectorElementCount(); 648 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 649 650 // We only support widening vectors with equivalent element types and 651 // fixed/scalable properties. If a target needs to widen a fixed-length type 652 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 653 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 654 PartNumElts.isScalable() != ValueNumElts.isScalable()) 655 return SDValue(); 656 657 // Have a try for bf16 because some targets share its ABI with fp16. 658 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 659 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 660 "Cannot widen to illegal type"); 661 Val = DAG.getNode(ISD::BITCAST, DL, 662 ValueVT.changeVectorElementType(MVT::f16), Val); 663 } else if (PartEVT != ValueEVT) { 664 return SDValue(); 665 } 666 667 // Widening a scalable vector to another scalable vector is done by inserting 668 // the vector into a larger undef one. 669 if (PartNumElts.isScalable()) 670 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 671 Val, DAG.getVectorIdxConstant(0, DL)); 672 673 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 674 // undef elements. 675 SmallVector<SDValue, 16> Ops; 676 DAG.ExtractVectorElements(Val, Ops); 677 SDValue EltUndef = DAG.getUNDEF(PartEVT); 678 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 679 680 // FIXME: Use CONCAT for 2x -> 4x. 681 return DAG.getBuildVector(PartVT, DL, Ops); 682 } 683 684 /// getCopyToPartsVector - Create a series of nodes that contain the specified 685 /// value split into legal parts. 686 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 687 SDValue Val, SDValue *Parts, unsigned NumParts, 688 MVT PartVT, const Value *V, 689 std::optional<CallingConv::ID> CallConv) { 690 EVT ValueVT = Val.getValueType(); 691 assert(ValueVT.isVector() && "Not a vector"); 692 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 693 const bool IsABIRegCopy = CallConv.has_value(); 694 695 if (NumParts == 1) { 696 EVT PartEVT = PartVT; 697 if (PartEVT == ValueVT) { 698 // Nothing to do. 699 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 700 // Bitconvert vector->vector case. 701 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 702 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 703 Val = Widened; 704 } else if (PartVT.isVector() && 705 PartEVT.getVectorElementType().bitsGE( 706 ValueVT.getVectorElementType()) && 707 PartEVT.getVectorElementCount() == 708 ValueVT.getVectorElementCount()) { 709 710 // Promoted vector extract 711 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 712 } else if (PartEVT.isVector() && 713 PartEVT.getVectorElementType() != 714 ValueVT.getVectorElementType() && 715 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 716 TargetLowering::TypeWidenVector) { 717 // Combination of widening and promotion. 718 EVT WidenVT = 719 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 720 PartVT.getVectorElementCount()); 721 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 722 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 723 } else { 724 // Don't extract an integer from a float vector. This can happen if the 725 // FP type gets softened to integer and then promoted. The promotion 726 // prevents it from being picked up by the earlier bitcast case. 727 if (ValueVT.getVectorElementCount().isScalar() && 728 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 729 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 730 DAG.getVectorIdxConstant(0, DL)); 731 } else { 732 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 733 assert(PartVT.getFixedSizeInBits() > ValueSize && 734 "lossy conversion of vector to scalar type"); 735 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 736 Val = DAG.getBitcast(IntermediateType, Val); 737 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 738 } 739 } 740 741 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 742 Parts[0] = Val; 743 return; 744 } 745 746 // Handle a multi-element vector. 747 EVT IntermediateVT; 748 MVT RegisterVT; 749 unsigned NumIntermediates; 750 unsigned NumRegs; 751 if (IsABIRegCopy) { 752 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 753 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 754 RegisterVT); 755 } else { 756 NumRegs = 757 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 758 NumIntermediates, RegisterVT); 759 } 760 761 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 762 NumParts = NumRegs; // Silence a compiler warning. 763 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 764 765 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 766 "Mixing scalable and fixed vectors when copying in parts"); 767 768 std::optional<ElementCount> DestEltCnt; 769 770 if (IntermediateVT.isVector()) 771 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 772 else 773 DestEltCnt = ElementCount::getFixed(NumIntermediates); 774 775 EVT BuiltVectorTy = EVT::getVectorVT( 776 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 777 778 if (ValueVT == BuiltVectorTy) { 779 // Nothing to do. 780 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 781 // Bitconvert vector->vector case. 782 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 783 } else { 784 if (BuiltVectorTy.getVectorElementType().bitsGT( 785 ValueVT.getVectorElementType())) { 786 // Integer promotion. 787 ValueVT = EVT::getVectorVT(*DAG.getContext(), 788 BuiltVectorTy.getVectorElementType(), 789 ValueVT.getVectorElementCount()); 790 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 791 } 792 793 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 794 Val = Widened; 795 } 796 } 797 798 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 799 800 // Split the vector into intermediate operands. 801 SmallVector<SDValue, 8> Ops(NumIntermediates); 802 for (unsigned i = 0; i != NumIntermediates; ++i) { 803 if (IntermediateVT.isVector()) { 804 // This does something sensible for scalable vectors - see the 805 // definition of EXTRACT_SUBVECTOR for further details. 806 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 807 Ops[i] = 808 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 809 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 810 } else { 811 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 812 DAG.getVectorIdxConstant(i, DL)); 813 } 814 } 815 816 // Split the intermediate operands into legal parts. 817 if (NumParts == NumIntermediates) { 818 // If the register was not expanded, promote or copy the value, 819 // as appropriate. 820 for (unsigned i = 0; i != NumParts; ++i) 821 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 822 } else if (NumParts > 0) { 823 // If the intermediate type was expanded, split each the value into 824 // legal parts. 825 assert(NumIntermediates != 0 && "division by zero"); 826 assert(NumParts % NumIntermediates == 0 && 827 "Must expand into a divisible number of parts!"); 828 unsigned Factor = NumParts / NumIntermediates; 829 for (unsigned i = 0; i != NumIntermediates; ++i) 830 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 831 CallConv); 832 } 833 } 834 835 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 836 EVT valuevt, std::optional<CallingConv::ID> CC) 837 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 838 RegCount(1, regs.size()), CallConv(CC) {} 839 840 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 841 const DataLayout &DL, unsigned Reg, Type *Ty, 842 std::optional<CallingConv::ID> CC) { 843 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 844 845 CallConv = CC; 846 847 for (EVT ValueVT : ValueVTs) { 848 unsigned NumRegs = 849 isABIMangled() 850 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 851 : TLI.getNumRegisters(Context, ValueVT); 852 MVT RegisterVT = 853 isABIMangled() 854 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 855 : TLI.getRegisterType(Context, ValueVT); 856 for (unsigned i = 0; i != NumRegs; ++i) 857 Regs.push_back(Reg + i); 858 RegVTs.push_back(RegisterVT); 859 RegCount.push_back(NumRegs); 860 Reg += NumRegs; 861 } 862 } 863 864 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 865 FunctionLoweringInfo &FuncInfo, 866 const SDLoc &dl, SDValue &Chain, 867 SDValue *Glue, const Value *V) const { 868 // A Value with type {} or [0 x %t] needs no registers. 869 if (ValueVTs.empty()) 870 return SDValue(); 871 872 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 873 874 // Assemble the legal parts into the final values. 875 SmallVector<SDValue, 4> Values(ValueVTs.size()); 876 SmallVector<SDValue, 8> Parts; 877 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 878 // Copy the legal parts from the registers. 879 EVT ValueVT = ValueVTs[Value]; 880 unsigned NumRegs = RegCount[Value]; 881 MVT RegisterVT = isABIMangled() 882 ? TLI.getRegisterTypeForCallingConv( 883 *DAG.getContext(), *CallConv, RegVTs[Value]) 884 : RegVTs[Value]; 885 886 Parts.resize(NumRegs); 887 for (unsigned i = 0; i != NumRegs; ++i) { 888 SDValue P; 889 if (!Glue) { 890 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 891 } else { 892 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 893 *Glue = P.getValue(2); 894 } 895 896 Chain = P.getValue(1); 897 Parts[i] = P; 898 899 // If the source register was virtual and if we know something about it, 900 // add an assert node. 901 if (!Register::isVirtualRegister(Regs[Part + i]) || 902 !RegisterVT.isInteger()) 903 continue; 904 905 const FunctionLoweringInfo::LiveOutInfo *LOI = 906 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 907 if (!LOI) 908 continue; 909 910 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 911 unsigned NumSignBits = LOI->NumSignBits; 912 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 913 914 if (NumZeroBits == RegSize) { 915 // The current value is a zero. 916 // Explicitly express that as it would be easier for 917 // optimizations to kick in. 918 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 919 continue; 920 } 921 922 // FIXME: We capture more information than the dag can represent. For 923 // now, just use the tightest assertzext/assertsext possible. 924 bool isSExt; 925 EVT FromVT(MVT::Other); 926 if (NumZeroBits) { 927 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 928 isSExt = false; 929 } else if (NumSignBits > 1) { 930 FromVT = 931 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 932 isSExt = true; 933 } else { 934 continue; 935 } 936 // Add an assertion node. 937 assert(FromVT != MVT::Other); 938 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 939 RegisterVT, P, DAG.getValueType(FromVT)); 940 } 941 942 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 943 RegisterVT, ValueVT, V, Chain, CallConv); 944 Part += NumRegs; 945 Parts.clear(); 946 } 947 948 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 949 } 950 951 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 952 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 953 const Value *V, 954 ISD::NodeType PreferredExtendType) const { 955 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 956 ISD::NodeType ExtendKind = PreferredExtendType; 957 958 // Get the list of the values's legal parts. 959 unsigned NumRegs = Regs.size(); 960 SmallVector<SDValue, 8> Parts(NumRegs); 961 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 962 unsigned NumParts = RegCount[Value]; 963 964 MVT RegisterVT = isABIMangled() 965 ? TLI.getRegisterTypeForCallingConv( 966 *DAG.getContext(), *CallConv, RegVTs[Value]) 967 : RegVTs[Value]; 968 969 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 970 ExtendKind = ISD::ZERO_EXTEND; 971 972 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 973 NumParts, RegisterVT, V, CallConv, ExtendKind); 974 Part += NumParts; 975 } 976 977 // Copy the parts into the registers. 978 SmallVector<SDValue, 8> Chains(NumRegs); 979 for (unsigned i = 0; i != NumRegs; ++i) { 980 SDValue Part; 981 if (!Glue) { 982 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 983 } else { 984 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 985 *Glue = Part.getValue(1); 986 } 987 988 Chains[i] = Part.getValue(0); 989 } 990 991 if (NumRegs == 1 || Glue) 992 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 993 // flagged to it. That is the CopyToReg nodes and the user are considered 994 // a single scheduling unit. If we create a TokenFactor and return it as 995 // chain, then the TokenFactor is both a predecessor (operand) of the 996 // user as well as a successor (the TF operands are flagged to the user). 997 // c1, f1 = CopyToReg 998 // c2, f2 = CopyToReg 999 // c3 = TokenFactor c1, c2 1000 // ... 1001 // = op c3, ..., f2 1002 Chain = Chains[NumRegs-1]; 1003 else 1004 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 1005 } 1006 1007 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, 1008 unsigned MatchingIdx, const SDLoc &dl, 1009 SelectionDAG &DAG, 1010 std::vector<SDValue> &Ops) const { 1011 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1012 1013 InlineAsm::Flag Flag(Code, Regs.size()); 1014 if (HasMatching) 1015 Flag.setMatchingOp(MatchingIdx); 1016 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1017 // Put the register class of the virtual registers in the flag word. That 1018 // way, later passes can recompute register class constraints for inline 1019 // assembly as well as normal instructions. 1020 // Don't do this for tied operands that can use the regclass information 1021 // from the def. 1022 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1023 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1024 Flag.setRegClass(RC->getID()); 1025 } 1026 1027 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1028 Ops.push_back(Res); 1029 1030 if (Code == InlineAsm::Kind::Clobber) { 1031 // Clobbers should always have a 1:1 mapping with registers, and may 1032 // reference registers that have illegal (e.g. vector) types. Hence, we 1033 // shouldn't try to apply any sort of splitting logic to them. 1034 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1035 "No 1:1 mapping from clobbers to regs?"); 1036 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1037 (void)SP; 1038 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1039 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1040 assert( 1041 (Regs[I] != SP || 1042 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1043 "If we clobbered the stack pointer, MFI should know about it."); 1044 } 1045 return; 1046 } 1047 1048 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1049 MVT RegisterVT = RegVTs[Value]; 1050 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1051 RegisterVT); 1052 for (unsigned i = 0; i != NumRegs; ++i) { 1053 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1054 unsigned TheReg = Regs[Reg++]; 1055 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1056 } 1057 } 1058 } 1059 1060 SmallVector<std::pair<unsigned, TypeSize>, 4> 1061 RegsForValue::getRegsAndSizes() const { 1062 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1063 unsigned I = 0; 1064 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1065 unsigned RegCount = std::get<0>(CountAndVT); 1066 MVT RegisterVT = std::get<1>(CountAndVT); 1067 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1068 for (unsigned E = I + RegCount; I != E; ++I) 1069 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1070 } 1071 return OutVec; 1072 } 1073 1074 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1075 AssumptionCache *ac, 1076 const TargetLibraryInfo *li) { 1077 AA = aa; 1078 AC = ac; 1079 GFI = gfi; 1080 LibInfo = li; 1081 Context = DAG.getContext(); 1082 LPadToCallSiteMap.clear(); 1083 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1084 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1085 *DAG.getMachineFunction().getFunction().getParent()); 1086 } 1087 1088 void SelectionDAGBuilder::clear() { 1089 NodeMap.clear(); 1090 UnusedArgNodeMap.clear(); 1091 PendingLoads.clear(); 1092 PendingExports.clear(); 1093 PendingConstrainedFP.clear(); 1094 PendingConstrainedFPStrict.clear(); 1095 CurInst = nullptr; 1096 HasTailCall = false; 1097 SDNodeOrder = LowestSDNodeOrder; 1098 StatepointLowering.clear(); 1099 } 1100 1101 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1102 DanglingDebugInfoMap.clear(); 1103 } 1104 1105 // Update DAG root to include dependencies on Pending chains. 1106 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1107 SDValue Root = DAG.getRoot(); 1108 1109 if (Pending.empty()) 1110 return Root; 1111 1112 // Add current root to PendingChains, unless we already indirectly 1113 // depend on it. 1114 if (Root.getOpcode() != ISD::EntryToken) { 1115 unsigned i = 0, e = Pending.size(); 1116 for (; i != e; ++i) { 1117 assert(Pending[i].getNode()->getNumOperands() > 1); 1118 if (Pending[i].getNode()->getOperand(0) == Root) 1119 break; // Don't add the root if we already indirectly depend on it. 1120 } 1121 1122 if (i == e) 1123 Pending.push_back(Root); 1124 } 1125 1126 if (Pending.size() == 1) 1127 Root = Pending[0]; 1128 else 1129 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1130 1131 DAG.setRoot(Root); 1132 Pending.clear(); 1133 return Root; 1134 } 1135 1136 SDValue SelectionDAGBuilder::getMemoryRoot() { 1137 return updateRoot(PendingLoads); 1138 } 1139 1140 SDValue SelectionDAGBuilder::getRoot() { 1141 // Chain up all pending constrained intrinsics together with all 1142 // pending loads, by simply appending them to PendingLoads and 1143 // then calling getMemoryRoot(). 1144 PendingLoads.reserve(PendingLoads.size() + 1145 PendingConstrainedFP.size() + 1146 PendingConstrainedFPStrict.size()); 1147 PendingLoads.append(PendingConstrainedFP.begin(), 1148 PendingConstrainedFP.end()); 1149 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1150 PendingConstrainedFPStrict.end()); 1151 PendingConstrainedFP.clear(); 1152 PendingConstrainedFPStrict.clear(); 1153 return getMemoryRoot(); 1154 } 1155 1156 SDValue SelectionDAGBuilder::getControlRoot() { 1157 // We need to emit pending fpexcept.strict constrained intrinsics, 1158 // so append them to the PendingExports list. 1159 PendingExports.append(PendingConstrainedFPStrict.begin(), 1160 PendingConstrainedFPStrict.end()); 1161 PendingConstrainedFPStrict.clear(); 1162 return updateRoot(PendingExports); 1163 } 1164 1165 void SelectionDAGBuilder::handleDebugDeclare(Value *Address, 1166 DILocalVariable *Variable, 1167 DIExpression *Expression, 1168 DebugLoc DL) { 1169 assert(Variable && "Missing variable"); 1170 1171 // Check if address has undef value. 1172 if (!Address || isa<UndefValue>(Address) || 1173 (Address->use_empty() && !isa<Argument>(Address))) { 1174 LLVM_DEBUG( 1175 dbgs() 1176 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n"); 1177 return; 1178 } 1179 1180 bool IsParameter = Variable->isParameter() || isa<Argument>(Address); 1181 1182 SDValue &N = NodeMap[Address]; 1183 if (!N.getNode() && isa<Argument>(Address)) 1184 // Check unused arguments map. 1185 N = UnusedArgNodeMap[Address]; 1186 SDDbgValue *SDV; 1187 if (N.getNode()) { 1188 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 1189 Address = BCI->getOperand(0); 1190 // Parameters are handled specially. 1191 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 1192 if (IsParameter && FINode) { 1193 // Byval parameter. We have a frame index at this point. 1194 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 1195 /*IsIndirect*/ true, DL, SDNodeOrder); 1196 } else if (isa<Argument>(Address)) { 1197 // Address is an argument, so try to emit its dbg value using 1198 // virtual register info from the FuncInfo.ValueMap. 1199 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1200 FuncArgumentDbgValueKind::Declare, N); 1201 return; 1202 } else { 1203 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 1204 true, DL, SDNodeOrder); 1205 } 1206 DAG.AddDbgValue(SDV, IsParameter); 1207 } else { 1208 // If Address is an argument then try to emit its dbg value using 1209 // virtual register info from the FuncInfo.ValueMap. 1210 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1211 FuncArgumentDbgValueKind::Declare, N)) { 1212 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info" 1213 << " (could not emit func-arg dbg_value)\n"); 1214 } 1215 } 1216 return; 1217 } 1218 1219 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) { 1220 // Add SDDbgValue nodes for any var locs here. Do so before updating 1221 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1222 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1223 // Add SDDbgValue nodes for any var locs here. Do so before updating 1224 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1225 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1226 It != End; ++It) { 1227 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1228 dropDanglingDebugInfo(Var, It->Expr); 1229 if (It->Values.isKillLocation(It->Expr)) { 1230 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1231 continue; 1232 } 1233 SmallVector<Value *> Values(It->Values.location_ops()); 1234 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1235 It->Values.hasArgList())) { 1236 SmallVector<Value *, 4> Vals; 1237 for (Value *V : It->Values.location_ops()) 1238 Vals.push_back(V); 1239 addDanglingDebugInfo(Vals, 1240 FnVarLocs->getDILocalVariable(It->VariableID), 1241 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder); 1242 } 1243 } 1244 } 1245 1246 // We must skip DPValues if they've already been processed above as we 1247 // have just emitted the debug values resulting from assignment tracking 1248 // analysis, making any existing DPValues redundant (and probably less 1249 // correct). We still need to process DPLabels. This does sink DPLabels 1250 // to the bottom of the group of debug records. That sholdn't be important 1251 // as it does so deterministcally and ordering between DPLabels and DPValues 1252 // is immaterial (other than for MIR/IR printing). 1253 bool SkipDPValues = DAG.getFunctionVarLocs(); 1254 // Is there is any debug-info attached to this instruction, in the form of 1255 // DbgRecord non-instruction debug-info records. 1256 for (DbgRecord &DR : I.getDbgValueRange()) { 1257 if (DPLabel *DPL = dyn_cast<DPLabel>(&DR)) { 1258 assert(DPL->getLabel() && "Missing label"); 1259 SDDbgLabel *SDV = 1260 DAG.getDbgLabel(DPL->getLabel(), DPL->getDebugLoc(), SDNodeOrder); 1261 DAG.AddDbgLabel(SDV); 1262 continue; 1263 } 1264 1265 if (SkipDPValues) 1266 continue; 1267 DPValue &DPV = cast<DPValue>(DR); 1268 DILocalVariable *Variable = DPV.getVariable(); 1269 DIExpression *Expression = DPV.getExpression(); 1270 dropDanglingDebugInfo(Variable, Expression); 1271 1272 if (DPV.getType() == DPValue::LocationType::Declare) { 1273 if (FuncInfo.PreprocessedDPVDeclares.contains(&DPV)) 1274 continue; 1275 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DPV 1276 << "\n"); 1277 handleDebugDeclare(DPV.getVariableLocationOp(0), Variable, Expression, 1278 DPV.getDebugLoc()); 1279 continue; 1280 } 1281 1282 // A DPValue with no locations is a kill location. 1283 SmallVector<Value *, 4> Values(DPV.location_ops()); 1284 if (Values.empty()) { 1285 handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(), 1286 SDNodeOrder); 1287 continue; 1288 } 1289 1290 // A DPValue with an undef or absent location is also a kill location. 1291 if (llvm::any_of(Values, 1292 [](Value *V) { return !V || isa<UndefValue>(V); })) { 1293 handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(), 1294 SDNodeOrder); 1295 continue; 1296 } 1297 1298 bool IsVariadic = DPV.hasArgList(); 1299 if (!handleDebugValue(Values, Variable, Expression, DPV.getDebugLoc(), 1300 SDNodeOrder, IsVariadic)) { 1301 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 1302 DPV.getDebugLoc(), SDNodeOrder); 1303 } 1304 } 1305 } 1306 1307 void SelectionDAGBuilder::visit(const Instruction &I) { 1308 visitDbgInfo(I); 1309 1310 // Set up outgoing PHI node register values before emitting the terminator. 1311 if (I.isTerminator()) { 1312 HandlePHINodesInSuccessorBlocks(I.getParent()); 1313 } 1314 1315 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1316 if (!isa<DbgInfoIntrinsic>(I)) 1317 ++SDNodeOrder; 1318 1319 CurInst = &I; 1320 1321 // Set inserted listener only if required. 1322 bool NodeInserted = false; 1323 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1324 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1325 if (PCSectionsMD) { 1326 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1327 DAG, [&](SDNode *) { NodeInserted = true; }); 1328 } 1329 1330 visit(I.getOpcode(), I); 1331 1332 if (!I.isTerminator() && !HasTailCall && 1333 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1334 CopyToExportRegsIfNeeded(&I); 1335 1336 // Handle metadata. 1337 if (PCSectionsMD) { 1338 auto It = NodeMap.find(&I); 1339 if (It != NodeMap.end()) { 1340 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1341 } else if (NodeInserted) { 1342 // This should not happen; if it does, don't let it go unnoticed so we can 1343 // fix it. Relevant visit*() function is probably missing a setValue(). 1344 errs() << "warning: loosing !pcsections metadata [" 1345 << I.getModule()->getName() << "]\n"; 1346 LLVM_DEBUG(I.dump()); 1347 assert(false); 1348 } 1349 } 1350 1351 CurInst = nullptr; 1352 } 1353 1354 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1355 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1356 } 1357 1358 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1359 // Note: this doesn't use InstVisitor, because it has to work with 1360 // ConstantExpr's in addition to instructions. 1361 switch (Opcode) { 1362 default: llvm_unreachable("Unknown instruction type encountered!"); 1363 // Build the switch statement using the Instruction.def file. 1364 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1365 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1366 #include "llvm/IR/Instruction.def" 1367 } 1368 } 1369 1370 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1371 DILocalVariable *Variable, 1372 DebugLoc DL, unsigned Order, 1373 SmallVectorImpl<Value *> &Values, 1374 DIExpression *Expression) { 1375 // For variadic dbg_values we will now insert an undef. 1376 // FIXME: We can potentially recover these! 1377 SmallVector<SDDbgOperand, 2> Locs; 1378 for (const Value *V : Values) { 1379 auto *Undef = UndefValue::get(V->getType()); 1380 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1381 } 1382 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1383 /*IsIndirect=*/false, DL, Order, 1384 /*IsVariadic=*/true); 1385 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1386 return true; 1387 } 1388 1389 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values, 1390 DILocalVariable *Var, 1391 DIExpression *Expr, 1392 bool IsVariadic, DebugLoc DL, 1393 unsigned Order) { 1394 if (IsVariadic) { 1395 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr); 1396 return; 1397 } 1398 // TODO: Dangling debug info will eventually either be resolved or produce 1399 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1400 // between the original dbg.value location and its resolved DBG_VALUE, 1401 // which we should ideally fill with an extra Undef DBG_VALUE. 1402 assert(Values.size() == 1); 1403 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order); 1404 } 1405 1406 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1407 const DIExpression *Expr) { 1408 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1409 DIVariable *DanglingVariable = DDI.getVariable(); 1410 DIExpression *DanglingExpr = DDI.getExpression(); 1411 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1412 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " 1413 << printDDI(nullptr, DDI) << "\n"); 1414 return true; 1415 } 1416 return false; 1417 }; 1418 1419 for (auto &DDIMI : DanglingDebugInfoMap) { 1420 DanglingDebugInfoVector &DDIV = DDIMI.second; 1421 1422 // If debug info is to be dropped, run it through final checks to see 1423 // whether it can be salvaged. 1424 for (auto &DDI : DDIV) 1425 if (isMatchingDbgValue(DDI)) 1426 salvageUnresolvedDbgValue(DDIMI.first, DDI); 1427 1428 erase_if(DDIV, isMatchingDbgValue); 1429 } 1430 } 1431 1432 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1433 // generate the debug data structures now that we've seen its definition. 1434 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1435 SDValue Val) { 1436 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1437 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1438 return; 1439 1440 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1441 for (auto &DDI : DDIV) { 1442 DebugLoc DL = DDI.getDebugLoc(); 1443 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1444 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1445 DILocalVariable *Variable = DDI.getVariable(); 1446 DIExpression *Expr = DDI.getExpression(); 1447 assert(Variable->isValidLocationForIntrinsic(DL) && 1448 "Expected inlined-at fields to agree"); 1449 SDDbgValue *SDV; 1450 if (Val.getNode()) { 1451 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1452 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1453 // we couldn't resolve it directly when examining the DbgValue intrinsic 1454 // in the first place we should not be more successful here). Unless we 1455 // have some test case that prove this to be correct we should avoid 1456 // calling EmitFuncArgumentDbgValue here. 1457 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1458 FuncArgumentDbgValueKind::Value, Val)) { 1459 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " 1460 << printDDI(V, DDI) << "\n"); 1461 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1462 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1463 // inserted after the definition of Val when emitting the instructions 1464 // after ISel. An alternative could be to teach 1465 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1466 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1467 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1468 << ValSDNodeOrder << "\n"); 1469 SDV = getDbgValue(Val, Variable, Expr, DL, 1470 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1471 DAG.AddDbgValue(SDV, false); 1472 } else 1473 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1474 << printDDI(V, DDI) 1475 << " in EmitFuncArgumentDbgValue\n"); 1476 } else { 1477 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI) 1478 << "\n"); 1479 auto Undef = UndefValue::get(V->getType()); 1480 auto SDV = 1481 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1482 DAG.AddDbgValue(SDV, false); 1483 } 1484 } 1485 DDIV.clear(); 1486 } 1487 1488 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V, 1489 DanglingDebugInfo &DDI) { 1490 // TODO: For the variadic implementation, instead of only checking the fail 1491 // state of `handleDebugValue`, we need know specifically which values were 1492 // invalid, so that we attempt to salvage only those values when processing 1493 // a DIArgList. 1494 const Value *OrigV = V; 1495 DILocalVariable *Var = DDI.getVariable(); 1496 DIExpression *Expr = DDI.getExpression(); 1497 DebugLoc DL = DDI.getDebugLoc(); 1498 unsigned SDOrder = DDI.getSDNodeOrder(); 1499 1500 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1501 // that DW_OP_stack_value is desired. 1502 bool StackValue = true; 1503 1504 // Can this Value can be encoded without any further work? 1505 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1506 return; 1507 1508 // Attempt to salvage back through as many instructions as possible. Bail if 1509 // a non-instruction is seen, such as a constant expression or global 1510 // variable. FIXME: Further work could recover those too. 1511 while (isa<Instruction>(V)) { 1512 const Instruction &VAsInst = *cast<const Instruction>(V); 1513 // Temporary "0", awaiting real implementation. 1514 SmallVector<uint64_t, 16> Ops; 1515 SmallVector<Value *, 4> AdditionalValues; 1516 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst), 1517 Expr->getNumLocationOperands(), Ops, 1518 AdditionalValues); 1519 // If we cannot salvage any further, and haven't yet found a suitable debug 1520 // expression, bail out. 1521 if (!V) 1522 break; 1523 1524 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1525 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1526 // here for variadic dbg_values, remove that condition. 1527 if (!AdditionalValues.empty()) 1528 break; 1529 1530 // New value and expr now represent this debuginfo. 1531 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1532 1533 // Some kind of simplification occurred: check whether the operand of the 1534 // salvaged debug expression can be encoded in this DAG. 1535 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1536 LLVM_DEBUG( 1537 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1538 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1539 return; 1540 } 1541 } 1542 1543 // This was the final opportunity to salvage this debug information, and it 1544 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1545 // any earlier variable location. 1546 assert(OrigV && "V shouldn't be null"); 1547 auto *Undef = UndefValue::get(OrigV->getType()); 1548 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1549 DAG.AddDbgValue(SDV, false); 1550 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " 1551 << printDDI(OrigV, DDI) << "\n"); 1552 } 1553 1554 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1555 DIExpression *Expr, 1556 DebugLoc DbgLoc, 1557 unsigned Order) { 1558 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1559 DIExpression *NewExpr = 1560 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1561 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1562 /*IsVariadic*/ false); 1563 } 1564 1565 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1566 DILocalVariable *Var, 1567 DIExpression *Expr, DebugLoc DbgLoc, 1568 unsigned Order, bool IsVariadic) { 1569 if (Values.empty()) 1570 return true; 1571 1572 // Filter EntryValue locations out early. 1573 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc)) 1574 return true; 1575 1576 SmallVector<SDDbgOperand> LocationOps; 1577 SmallVector<SDNode *> Dependencies; 1578 for (const Value *V : Values) { 1579 // Constant value. 1580 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1581 isa<ConstantPointerNull>(V)) { 1582 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1583 continue; 1584 } 1585 1586 // Look through IntToPtr constants. 1587 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1588 if (CE->getOpcode() == Instruction::IntToPtr) { 1589 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1590 continue; 1591 } 1592 1593 // If the Value is a frame index, we can create a FrameIndex debug value 1594 // without relying on the DAG at all. 1595 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1596 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1597 if (SI != FuncInfo.StaticAllocaMap.end()) { 1598 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1599 continue; 1600 } 1601 } 1602 1603 // Do not use getValue() in here; we don't want to generate code at 1604 // this point if it hasn't been done yet. 1605 SDValue N = NodeMap[V]; 1606 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1607 N = UnusedArgNodeMap[V]; 1608 if (N.getNode()) { 1609 // Only emit func arg dbg value for non-variadic dbg.values for now. 1610 if (!IsVariadic && 1611 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1612 FuncArgumentDbgValueKind::Value, N)) 1613 return true; 1614 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1615 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1616 // describe stack slot locations. 1617 // 1618 // Consider "int x = 0; int *px = &x;". There are two kinds of 1619 // interesting debug values here after optimization: 1620 // 1621 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1622 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1623 // 1624 // Both describe the direct values of their associated variables. 1625 Dependencies.push_back(N.getNode()); 1626 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1627 continue; 1628 } 1629 LocationOps.emplace_back( 1630 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1631 continue; 1632 } 1633 1634 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1635 // Special rules apply for the first dbg.values of parameter variables in a 1636 // function. Identify them by the fact they reference Argument Values, that 1637 // they're parameters, and they are parameters of the current function. We 1638 // need to let them dangle until they get an SDNode. 1639 bool IsParamOfFunc = 1640 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1641 if (IsParamOfFunc) 1642 return false; 1643 1644 // The value is not used in this block yet (or it would have an SDNode). 1645 // We still want the value to appear for the user if possible -- if it has 1646 // an associated VReg, we can refer to that instead. 1647 auto VMI = FuncInfo.ValueMap.find(V); 1648 if (VMI != FuncInfo.ValueMap.end()) { 1649 unsigned Reg = VMI->second; 1650 // If this is a PHI node, it may be split up into several MI PHI nodes 1651 // (in FunctionLoweringInfo::set). 1652 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1653 V->getType(), std::nullopt); 1654 if (RFV.occupiesMultipleRegs()) { 1655 // FIXME: We could potentially support variadic dbg_values here. 1656 if (IsVariadic) 1657 return false; 1658 unsigned Offset = 0; 1659 unsigned BitsToDescribe = 0; 1660 if (auto VarSize = Var->getSizeInBits()) 1661 BitsToDescribe = *VarSize; 1662 if (auto Fragment = Expr->getFragmentInfo()) 1663 BitsToDescribe = Fragment->SizeInBits; 1664 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1665 // Bail out if all bits are described already. 1666 if (Offset >= BitsToDescribe) 1667 break; 1668 // TODO: handle scalable vectors. 1669 unsigned RegisterSize = RegAndSize.second; 1670 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1671 ? BitsToDescribe - Offset 1672 : RegisterSize; 1673 auto FragmentExpr = DIExpression::createFragmentExpression( 1674 Expr, Offset, FragmentSize); 1675 if (!FragmentExpr) 1676 continue; 1677 SDDbgValue *SDV = DAG.getVRegDbgValue( 1678 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1679 DAG.AddDbgValue(SDV, false); 1680 Offset += RegisterSize; 1681 } 1682 return true; 1683 } 1684 // We can use simple vreg locations for variadic dbg_values as well. 1685 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1686 continue; 1687 } 1688 // We failed to create a SDDbgOperand for V. 1689 return false; 1690 } 1691 1692 // We have created a SDDbgOperand for each Value in Values. 1693 // Should use Order instead of SDNodeOrder? 1694 assert(!LocationOps.empty()); 1695 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1696 /*IsIndirect=*/false, DbgLoc, 1697 SDNodeOrder, IsVariadic); 1698 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1699 return true; 1700 } 1701 1702 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1703 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1704 for (auto &Pair : DanglingDebugInfoMap) 1705 for (auto &DDI : Pair.second) 1706 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI); 1707 clearDanglingDebugInfo(); 1708 } 1709 1710 /// getCopyFromRegs - If there was virtual register allocated for the value V 1711 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1712 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1713 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1714 SDValue Result; 1715 1716 if (It != FuncInfo.ValueMap.end()) { 1717 Register InReg = It->second; 1718 1719 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1720 DAG.getDataLayout(), InReg, Ty, 1721 std::nullopt); // This is not an ABI copy. 1722 SDValue Chain = DAG.getEntryNode(); 1723 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1724 V); 1725 resolveDanglingDebugInfo(V, Result); 1726 } 1727 1728 return Result; 1729 } 1730 1731 /// getValue - Return an SDValue for the given Value. 1732 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1733 // If we already have an SDValue for this value, use it. It's important 1734 // to do this first, so that we don't create a CopyFromReg if we already 1735 // have a regular SDValue. 1736 SDValue &N = NodeMap[V]; 1737 if (N.getNode()) return N; 1738 1739 // If there's a virtual register allocated and initialized for this 1740 // value, use it. 1741 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1742 return copyFromReg; 1743 1744 // Otherwise create a new SDValue and remember it. 1745 SDValue Val = getValueImpl(V); 1746 NodeMap[V] = Val; 1747 resolveDanglingDebugInfo(V, Val); 1748 return Val; 1749 } 1750 1751 /// getNonRegisterValue - Return an SDValue for the given Value, but 1752 /// don't look in FuncInfo.ValueMap for a virtual register. 1753 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1754 // If we already have an SDValue for this value, use it. 1755 SDValue &N = NodeMap[V]; 1756 if (N.getNode()) { 1757 if (isIntOrFPConstant(N)) { 1758 // Remove the debug location from the node as the node is about to be used 1759 // in a location which may differ from the original debug location. This 1760 // is relevant to Constant and ConstantFP nodes because they can appear 1761 // as constant expressions inside PHI nodes. 1762 N->setDebugLoc(DebugLoc()); 1763 } 1764 return N; 1765 } 1766 1767 // Otherwise create a new SDValue and remember it. 1768 SDValue Val = getValueImpl(V); 1769 NodeMap[V] = Val; 1770 resolveDanglingDebugInfo(V, Val); 1771 return Val; 1772 } 1773 1774 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1775 /// Create an SDValue for the given value. 1776 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1777 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1778 1779 if (const Constant *C = dyn_cast<Constant>(V)) { 1780 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1781 1782 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1783 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1784 1785 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1786 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1787 1788 if (isa<ConstantPointerNull>(C)) { 1789 unsigned AS = V->getType()->getPointerAddressSpace(); 1790 return DAG.getConstant(0, getCurSDLoc(), 1791 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1792 } 1793 1794 if (match(C, m_VScale())) 1795 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1796 1797 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1798 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1799 1800 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1801 return DAG.getUNDEF(VT); 1802 1803 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1804 visit(CE->getOpcode(), *CE); 1805 SDValue N1 = NodeMap[V]; 1806 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1807 return N1; 1808 } 1809 1810 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1811 SmallVector<SDValue, 4> Constants; 1812 for (const Use &U : C->operands()) { 1813 SDNode *Val = getValue(U).getNode(); 1814 // If the operand is an empty aggregate, there are no values. 1815 if (!Val) continue; 1816 // Add each leaf value from the operand to the Constants list 1817 // to form a flattened list of all the values. 1818 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1819 Constants.push_back(SDValue(Val, i)); 1820 } 1821 1822 return DAG.getMergeValues(Constants, getCurSDLoc()); 1823 } 1824 1825 if (const ConstantDataSequential *CDS = 1826 dyn_cast<ConstantDataSequential>(C)) { 1827 SmallVector<SDValue, 4> Ops; 1828 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1829 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1830 // Add each leaf value from the operand to the Constants list 1831 // to form a flattened list of all the values. 1832 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1833 Ops.push_back(SDValue(Val, i)); 1834 } 1835 1836 if (isa<ArrayType>(CDS->getType())) 1837 return DAG.getMergeValues(Ops, getCurSDLoc()); 1838 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1839 } 1840 1841 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1842 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1843 "Unknown struct or array constant!"); 1844 1845 SmallVector<EVT, 4> ValueVTs; 1846 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1847 unsigned NumElts = ValueVTs.size(); 1848 if (NumElts == 0) 1849 return SDValue(); // empty struct 1850 SmallVector<SDValue, 4> Constants(NumElts); 1851 for (unsigned i = 0; i != NumElts; ++i) { 1852 EVT EltVT = ValueVTs[i]; 1853 if (isa<UndefValue>(C)) 1854 Constants[i] = DAG.getUNDEF(EltVT); 1855 else if (EltVT.isFloatingPoint()) 1856 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1857 else 1858 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1859 } 1860 1861 return DAG.getMergeValues(Constants, getCurSDLoc()); 1862 } 1863 1864 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1865 return DAG.getBlockAddress(BA, VT); 1866 1867 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1868 return getValue(Equiv->getGlobalValue()); 1869 1870 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1871 return getValue(NC->getGlobalValue()); 1872 1873 if (VT == MVT::aarch64svcount) { 1874 assert(C->isNullValue() && "Can only zero this target type!"); 1875 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, 1876 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1)); 1877 } 1878 1879 VectorType *VecTy = cast<VectorType>(V->getType()); 1880 1881 // Now that we know the number and type of the elements, get that number of 1882 // elements into the Ops array based on what kind of constant it is. 1883 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1884 SmallVector<SDValue, 16> Ops; 1885 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1886 for (unsigned i = 0; i != NumElements; ++i) 1887 Ops.push_back(getValue(CV->getOperand(i))); 1888 1889 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1890 } 1891 1892 if (isa<ConstantAggregateZero>(C)) { 1893 EVT EltVT = 1894 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1895 1896 SDValue Op; 1897 if (EltVT.isFloatingPoint()) 1898 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1899 else 1900 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1901 1902 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1903 } 1904 1905 llvm_unreachable("Unknown vector constant"); 1906 } 1907 1908 // If this is a static alloca, generate it as the frameindex instead of 1909 // computation. 1910 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1911 DenseMap<const AllocaInst*, int>::iterator SI = 1912 FuncInfo.StaticAllocaMap.find(AI); 1913 if (SI != FuncInfo.StaticAllocaMap.end()) 1914 return DAG.getFrameIndex( 1915 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1916 } 1917 1918 // If this is an instruction which fast-isel has deferred, select it now. 1919 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1920 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1921 1922 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1923 Inst->getType(), std::nullopt); 1924 SDValue Chain = DAG.getEntryNode(); 1925 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1926 } 1927 1928 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1929 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1930 1931 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1932 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1933 1934 llvm_unreachable("Can't get register for value!"); 1935 } 1936 1937 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1938 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1939 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1940 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1941 bool IsSEH = isAsynchronousEHPersonality(Pers); 1942 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1943 if (!IsSEH) 1944 CatchPadMBB->setIsEHScopeEntry(); 1945 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1946 if (IsMSVCCXX || IsCoreCLR) 1947 CatchPadMBB->setIsEHFuncletEntry(); 1948 } 1949 1950 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1951 // Update machine-CFG edge. 1952 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1953 FuncInfo.MBB->addSuccessor(TargetMBB); 1954 TargetMBB->setIsEHCatchretTarget(true); 1955 DAG.getMachineFunction().setHasEHCatchret(true); 1956 1957 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1958 bool IsSEH = isAsynchronousEHPersonality(Pers); 1959 if (IsSEH) { 1960 // If this is not a fall-through branch or optimizations are switched off, 1961 // emit the branch. 1962 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1963 TM.getOptLevel() == CodeGenOptLevel::None) 1964 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1965 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1966 return; 1967 } 1968 1969 // Figure out the funclet membership for the catchret's successor. 1970 // This will be used by the FuncletLayout pass to determine how to order the 1971 // BB's. 1972 // A 'catchret' returns to the outer scope's color. 1973 Value *ParentPad = I.getCatchSwitchParentPad(); 1974 const BasicBlock *SuccessorColor; 1975 if (isa<ConstantTokenNone>(ParentPad)) 1976 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1977 else 1978 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1979 assert(SuccessorColor && "No parent funclet for catchret!"); 1980 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1981 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1982 1983 // Create the terminator node. 1984 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1985 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1986 DAG.getBasicBlock(SuccessorColorMBB)); 1987 DAG.setRoot(Ret); 1988 } 1989 1990 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1991 // Don't emit any special code for the cleanuppad instruction. It just marks 1992 // the start of an EH scope/funclet. 1993 FuncInfo.MBB->setIsEHScopeEntry(); 1994 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1995 if (Pers != EHPersonality::Wasm_CXX) { 1996 FuncInfo.MBB->setIsEHFuncletEntry(); 1997 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1998 } 1999 } 2000 2001 // In wasm EH, even though a catchpad may not catch an exception if a tag does 2002 // not match, it is OK to add only the first unwind destination catchpad to the 2003 // successors, because there will be at least one invoke instruction within the 2004 // catch scope that points to the next unwind destination, if one exists, so 2005 // CFGSort cannot mess up with BB sorting order. 2006 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 2007 // call within them, and catchpads only consisting of 'catch (...)' have a 2008 // '__cxa_end_catch' call within them, both of which generate invokes in case 2009 // the next unwind destination exists, i.e., the next unwind destination is not 2010 // the caller.) 2011 // 2012 // Having at most one EH pad successor is also simpler and helps later 2013 // transformations. 2014 // 2015 // For example, 2016 // current: 2017 // invoke void @foo to ... unwind label %catch.dispatch 2018 // catch.dispatch: 2019 // %0 = catchswitch within ... [label %catch.start] unwind label %next 2020 // catch.start: 2021 // ... 2022 // ... in this BB or some other child BB dominated by this BB there will be an 2023 // invoke that points to 'next' BB as an unwind destination 2024 // 2025 // next: ; We don't need to add this to 'current' BB's successor 2026 // ... 2027 static void findWasmUnwindDestinations( 2028 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2029 BranchProbability Prob, 2030 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2031 &UnwindDests) { 2032 while (EHPadBB) { 2033 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2034 if (isa<CleanupPadInst>(Pad)) { 2035 // Stop on cleanup pads. 2036 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2037 UnwindDests.back().first->setIsEHScopeEntry(); 2038 break; 2039 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2040 // Add the catchpad handlers to the possible destinations. We don't 2041 // continue to the unwind destination of the catchswitch for wasm. 2042 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2043 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2044 UnwindDests.back().first->setIsEHScopeEntry(); 2045 } 2046 break; 2047 } else { 2048 continue; 2049 } 2050 } 2051 } 2052 2053 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 2054 /// many places it could ultimately go. In the IR, we have a single unwind 2055 /// destination, but in the machine CFG, we enumerate all the possible blocks. 2056 /// This function skips over imaginary basic blocks that hold catchswitch 2057 /// instructions, and finds all the "real" machine 2058 /// basic block destinations. As those destinations may not be successors of 2059 /// EHPadBB, here we also calculate the edge probability to those destinations. 2060 /// The passed-in Prob is the edge probability to EHPadBB. 2061 static void findUnwindDestinations( 2062 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2063 BranchProbability Prob, 2064 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2065 &UnwindDests) { 2066 EHPersonality Personality = 2067 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2068 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 2069 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 2070 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 2071 bool IsSEH = isAsynchronousEHPersonality(Personality); 2072 2073 if (IsWasmCXX) { 2074 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 2075 assert(UnwindDests.size() <= 1 && 2076 "There should be at most one unwind destination for wasm"); 2077 return; 2078 } 2079 2080 while (EHPadBB) { 2081 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2082 BasicBlock *NewEHPadBB = nullptr; 2083 if (isa<LandingPadInst>(Pad)) { 2084 // Stop on landingpads. They are not funclets. 2085 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2086 break; 2087 } else if (isa<CleanupPadInst>(Pad)) { 2088 // Stop on cleanup pads. Cleanups are always funclet entries for all known 2089 // personalities. 2090 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2091 UnwindDests.back().first->setIsEHScopeEntry(); 2092 UnwindDests.back().first->setIsEHFuncletEntry(); 2093 break; 2094 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2095 // Add the catchpad handlers to the possible destinations. 2096 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2097 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2098 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 2099 if (IsMSVCCXX || IsCoreCLR) 2100 UnwindDests.back().first->setIsEHFuncletEntry(); 2101 if (!IsSEH) 2102 UnwindDests.back().first->setIsEHScopeEntry(); 2103 } 2104 NewEHPadBB = CatchSwitch->getUnwindDest(); 2105 } else { 2106 continue; 2107 } 2108 2109 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2110 if (BPI && NewEHPadBB) 2111 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 2112 EHPadBB = NewEHPadBB; 2113 } 2114 } 2115 2116 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 2117 // Update successor info. 2118 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2119 auto UnwindDest = I.getUnwindDest(); 2120 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2121 BranchProbability UnwindDestProb = 2122 (BPI && UnwindDest) 2123 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 2124 : BranchProbability::getZero(); 2125 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 2126 for (auto &UnwindDest : UnwindDests) { 2127 UnwindDest.first->setIsEHPad(); 2128 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 2129 } 2130 FuncInfo.MBB->normalizeSuccProbs(); 2131 2132 // Create the terminator node. 2133 SDValue Ret = 2134 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 2135 DAG.setRoot(Ret); 2136 } 2137 2138 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2139 report_fatal_error("visitCatchSwitch not yet implemented!"); 2140 } 2141 2142 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2143 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2144 auto &DL = DAG.getDataLayout(); 2145 SDValue Chain = getControlRoot(); 2146 SmallVector<ISD::OutputArg, 8> Outs; 2147 SmallVector<SDValue, 8> OutVals; 2148 2149 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2150 // lower 2151 // 2152 // %val = call <ty> @llvm.experimental.deoptimize() 2153 // ret <ty> %val 2154 // 2155 // differently. 2156 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2157 LowerDeoptimizingReturn(); 2158 return; 2159 } 2160 2161 if (!FuncInfo.CanLowerReturn) { 2162 unsigned DemoteReg = FuncInfo.DemoteRegister; 2163 const Function *F = I.getParent()->getParent(); 2164 2165 // Emit a store of the return value through the virtual register. 2166 // Leave Outs empty so that LowerReturn won't try to load return 2167 // registers the usual way. 2168 SmallVector<EVT, 1> PtrValueVTs; 2169 ComputeValueVTs(TLI, DL, 2170 PointerType::get(F->getContext(), 2171 DAG.getDataLayout().getAllocaAddrSpace()), 2172 PtrValueVTs); 2173 2174 SDValue RetPtr = 2175 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2176 SDValue RetOp = getValue(I.getOperand(0)); 2177 2178 SmallVector<EVT, 4> ValueVTs, MemVTs; 2179 SmallVector<uint64_t, 4> Offsets; 2180 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2181 &Offsets, 0); 2182 unsigned NumValues = ValueVTs.size(); 2183 2184 SmallVector<SDValue, 4> Chains(NumValues); 2185 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2186 for (unsigned i = 0; i != NumValues; ++i) { 2187 // An aggregate return value cannot wrap around the address space, so 2188 // offsets to its parts don't wrap either. 2189 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2190 TypeSize::getFixed(Offsets[i])); 2191 2192 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2193 if (MemVTs[i] != ValueVTs[i]) 2194 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2195 Chains[i] = DAG.getStore( 2196 Chain, getCurSDLoc(), Val, 2197 // FIXME: better loc info would be nice. 2198 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2199 commonAlignment(BaseAlign, Offsets[i])); 2200 } 2201 2202 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2203 MVT::Other, Chains); 2204 } else if (I.getNumOperands() != 0) { 2205 SmallVector<EVT, 4> ValueVTs; 2206 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2207 unsigned NumValues = ValueVTs.size(); 2208 if (NumValues) { 2209 SDValue RetOp = getValue(I.getOperand(0)); 2210 2211 const Function *F = I.getParent()->getParent(); 2212 2213 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2214 I.getOperand(0)->getType(), F->getCallingConv(), 2215 /*IsVarArg*/ false, DL); 2216 2217 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2218 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2219 ExtendKind = ISD::SIGN_EXTEND; 2220 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2221 ExtendKind = ISD::ZERO_EXTEND; 2222 2223 LLVMContext &Context = F->getContext(); 2224 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2225 2226 for (unsigned j = 0; j != NumValues; ++j) { 2227 EVT VT = ValueVTs[j]; 2228 2229 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2230 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2231 2232 CallingConv::ID CC = F->getCallingConv(); 2233 2234 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2235 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2236 SmallVector<SDValue, 4> Parts(NumParts); 2237 getCopyToParts(DAG, getCurSDLoc(), 2238 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2239 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2240 2241 // 'inreg' on function refers to return value 2242 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2243 if (RetInReg) 2244 Flags.setInReg(); 2245 2246 if (I.getOperand(0)->getType()->isPointerTy()) { 2247 Flags.setPointer(); 2248 Flags.setPointerAddrSpace( 2249 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2250 } 2251 2252 if (NeedsRegBlock) { 2253 Flags.setInConsecutiveRegs(); 2254 if (j == NumValues - 1) 2255 Flags.setInConsecutiveRegsLast(); 2256 } 2257 2258 // Propagate extension type if any 2259 if (ExtendKind == ISD::SIGN_EXTEND) 2260 Flags.setSExt(); 2261 else if (ExtendKind == ISD::ZERO_EXTEND) 2262 Flags.setZExt(); 2263 2264 for (unsigned i = 0; i < NumParts; ++i) { 2265 Outs.push_back(ISD::OutputArg(Flags, 2266 Parts[i].getValueType().getSimpleVT(), 2267 VT, /*isfixed=*/true, 0, 0)); 2268 OutVals.push_back(Parts[i]); 2269 } 2270 } 2271 } 2272 } 2273 2274 // Push in swifterror virtual register as the last element of Outs. This makes 2275 // sure swifterror virtual register will be returned in the swifterror 2276 // physical register. 2277 const Function *F = I.getParent()->getParent(); 2278 if (TLI.supportSwiftError() && 2279 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2280 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2281 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2282 Flags.setSwiftError(); 2283 Outs.push_back(ISD::OutputArg( 2284 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2285 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2286 // Create SDNode for the swifterror virtual register. 2287 OutVals.push_back( 2288 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2289 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2290 EVT(TLI.getPointerTy(DL)))); 2291 } 2292 2293 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2294 CallingConv::ID CallConv = 2295 DAG.getMachineFunction().getFunction().getCallingConv(); 2296 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2297 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2298 2299 // Verify that the target's LowerReturn behaved as expected. 2300 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2301 "LowerReturn didn't return a valid chain!"); 2302 2303 // Update the DAG with the new chain value resulting from return lowering. 2304 DAG.setRoot(Chain); 2305 } 2306 2307 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2308 /// created for it, emit nodes to copy the value into the virtual 2309 /// registers. 2310 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2311 // Skip empty types 2312 if (V->getType()->isEmptyTy()) 2313 return; 2314 2315 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2316 if (VMI != FuncInfo.ValueMap.end()) { 2317 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2318 "Unused value assigned virtual registers!"); 2319 CopyValueToVirtualRegister(V, VMI->second); 2320 } 2321 } 2322 2323 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2324 /// the current basic block, add it to ValueMap now so that we'll get a 2325 /// CopyTo/FromReg. 2326 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2327 // No need to export constants. 2328 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2329 2330 // Already exported? 2331 if (FuncInfo.isExportedInst(V)) return; 2332 2333 Register Reg = FuncInfo.InitializeRegForValue(V); 2334 CopyValueToVirtualRegister(V, Reg); 2335 } 2336 2337 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2338 const BasicBlock *FromBB) { 2339 // The operands of the setcc have to be in this block. We don't know 2340 // how to export them from some other block. 2341 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2342 // Can export from current BB. 2343 if (VI->getParent() == FromBB) 2344 return true; 2345 2346 // Is already exported, noop. 2347 return FuncInfo.isExportedInst(V); 2348 } 2349 2350 // If this is an argument, we can export it if the BB is the entry block or 2351 // if it is already exported. 2352 if (isa<Argument>(V)) { 2353 if (FromBB->isEntryBlock()) 2354 return true; 2355 2356 // Otherwise, can only export this if it is already exported. 2357 return FuncInfo.isExportedInst(V); 2358 } 2359 2360 // Otherwise, constants can always be exported. 2361 return true; 2362 } 2363 2364 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2365 BranchProbability 2366 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2367 const MachineBasicBlock *Dst) const { 2368 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2369 const BasicBlock *SrcBB = Src->getBasicBlock(); 2370 const BasicBlock *DstBB = Dst->getBasicBlock(); 2371 if (!BPI) { 2372 // If BPI is not available, set the default probability as 1 / N, where N is 2373 // the number of successors. 2374 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2375 return BranchProbability(1, SuccSize); 2376 } 2377 return BPI->getEdgeProbability(SrcBB, DstBB); 2378 } 2379 2380 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2381 MachineBasicBlock *Dst, 2382 BranchProbability Prob) { 2383 if (!FuncInfo.BPI) 2384 Src->addSuccessorWithoutProb(Dst); 2385 else { 2386 if (Prob.isUnknown()) 2387 Prob = getEdgeProbability(Src, Dst); 2388 Src->addSuccessor(Dst, Prob); 2389 } 2390 } 2391 2392 static bool InBlock(const Value *V, const BasicBlock *BB) { 2393 if (const Instruction *I = dyn_cast<Instruction>(V)) 2394 return I->getParent() == BB; 2395 return true; 2396 } 2397 2398 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2399 /// This function emits a branch and is used at the leaves of an OR or an 2400 /// AND operator tree. 2401 void 2402 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2403 MachineBasicBlock *TBB, 2404 MachineBasicBlock *FBB, 2405 MachineBasicBlock *CurBB, 2406 MachineBasicBlock *SwitchBB, 2407 BranchProbability TProb, 2408 BranchProbability FProb, 2409 bool InvertCond) { 2410 const BasicBlock *BB = CurBB->getBasicBlock(); 2411 2412 // If the leaf of the tree is a comparison, merge the condition into 2413 // the caseblock. 2414 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2415 // The operands of the cmp have to be in this block. We don't know 2416 // how to export them from some other block. If this is the first block 2417 // of the sequence, no exporting is needed. 2418 if (CurBB == SwitchBB || 2419 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2420 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2421 ISD::CondCode Condition; 2422 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2423 ICmpInst::Predicate Pred = 2424 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2425 Condition = getICmpCondCode(Pred); 2426 } else { 2427 const FCmpInst *FC = cast<FCmpInst>(Cond); 2428 FCmpInst::Predicate Pred = 2429 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2430 Condition = getFCmpCondCode(Pred); 2431 if (TM.Options.NoNaNsFPMath) 2432 Condition = getFCmpCodeWithoutNaN(Condition); 2433 } 2434 2435 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2436 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2437 SL->SwitchCases.push_back(CB); 2438 return; 2439 } 2440 } 2441 2442 // Create a CaseBlock record representing this branch. 2443 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2444 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2445 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2446 SL->SwitchCases.push_back(CB); 2447 } 2448 2449 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2450 MachineBasicBlock *TBB, 2451 MachineBasicBlock *FBB, 2452 MachineBasicBlock *CurBB, 2453 MachineBasicBlock *SwitchBB, 2454 Instruction::BinaryOps Opc, 2455 BranchProbability TProb, 2456 BranchProbability FProb, 2457 bool InvertCond) { 2458 // Skip over not part of the tree and remember to invert op and operands at 2459 // next level. 2460 Value *NotCond; 2461 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2462 InBlock(NotCond, CurBB->getBasicBlock())) { 2463 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2464 !InvertCond); 2465 return; 2466 } 2467 2468 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2469 const Value *BOpOp0, *BOpOp1; 2470 // Compute the effective opcode for Cond, taking into account whether it needs 2471 // to be inverted, e.g. 2472 // and (not (or A, B)), C 2473 // gets lowered as 2474 // and (and (not A, not B), C) 2475 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2476 if (BOp) { 2477 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2478 ? Instruction::And 2479 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2480 ? Instruction::Or 2481 : (Instruction::BinaryOps)0); 2482 if (InvertCond) { 2483 if (BOpc == Instruction::And) 2484 BOpc = Instruction::Or; 2485 else if (BOpc == Instruction::Or) 2486 BOpc = Instruction::And; 2487 } 2488 } 2489 2490 // If this node is not part of the or/and tree, emit it as a branch. 2491 // Note that all nodes in the tree should have same opcode. 2492 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2493 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2494 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2495 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2496 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2497 TProb, FProb, InvertCond); 2498 return; 2499 } 2500 2501 // Create TmpBB after CurBB. 2502 MachineFunction::iterator BBI(CurBB); 2503 MachineFunction &MF = DAG.getMachineFunction(); 2504 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2505 CurBB->getParent()->insert(++BBI, TmpBB); 2506 2507 if (Opc == Instruction::Or) { 2508 // Codegen X | Y as: 2509 // BB1: 2510 // jmp_if_X TBB 2511 // jmp TmpBB 2512 // TmpBB: 2513 // jmp_if_Y TBB 2514 // jmp FBB 2515 // 2516 2517 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2518 // The requirement is that 2519 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2520 // = TrueProb for original BB. 2521 // Assuming the original probabilities are A and B, one choice is to set 2522 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2523 // A/(1+B) and 2B/(1+B). This choice assumes that 2524 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2525 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2526 // TmpBB, but the math is more complicated. 2527 2528 auto NewTrueProb = TProb / 2; 2529 auto NewFalseProb = TProb / 2 + FProb; 2530 // Emit the LHS condition. 2531 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2532 NewFalseProb, InvertCond); 2533 2534 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2535 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2536 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2537 // Emit the RHS condition into TmpBB. 2538 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2539 Probs[1], InvertCond); 2540 } else { 2541 assert(Opc == Instruction::And && "Unknown merge op!"); 2542 // Codegen X & Y as: 2543 // BB1: 2544 // jmp_if_X TmpBB 2545 // jmp FBB 2546 // TmpBB: 2547 // jmp_if_Y TBB 2548 // jmp FBB 2549 // 2550 // This requires creation of TmpBB after CurBB. 2551 2552 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2553 // The requirement is that 2554 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2555 // = FalseProb for original BB. 2556 // Assuming the original probabilities are A and B, one choice is to set 2557 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2558 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2559 // TrueProb for BB1 * FalseProb for TmpBB. 2560 2561 auto NewTrueProb = TProb + FProb / 2; 2562 auto NewFalseProb = FProb / 2; 2563 // Emit the LHS condition. 2564 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2565 NewFalseProb, InvertCond); 2566 2567 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2568 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2569 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2570 // Emit the RHS condition into TmpBB. 2571 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2572 Probs[1], InvertCond); 2573 } 2574 } 2575 2576 /// If the set of cases should be emitted as a series of branches, return true. 2577 /// If we should emit this as a bunch of and/or'd together conditions, return 2578 /// false. 2579 bool 2580 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2581 if (Cases.size() != 2) return true; 2582 2583 // If this is two comparisons of the same values or'd or and'd together, they 2584 // will get folded into a single comparison, so don't emit two blocks. 2585 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2586 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2587 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2588 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2589 return false; 2590 } 2591 2592 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2593 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2594 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2595 Cases[0].CC == Cases[1].CC && 2596 isa<Constant>(Cases[0].CmpRHS) && 2597 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2598 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2599 return false; 2600 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2601 return false; 2602 } 2603 2604 return true; 2605 } 2606 2607 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2608 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2609 2610 // Update machine-CFG edges. 2611 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2612 2613 if (I.isUnconditional()) { 2614 // Update machine-CFG edges. 2615 BrMBB->addSuccessor(Succ0MBB); 2616 2617 // If this is not a fall-through branch or optimizations are switched off, 2618 // emit the branch. 2619 if (Succ0MBB != NextBlock(BrMBB) || 2620 TM.getOptLevel() == CodeGenOptLevel::None) { 2621 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2622 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2623 setValue(&I, Br); 2624 DAG.setRoot(Br); 2625 } 2626 2627 return; 2628 } 2629 2630 // If this condition is one of the special cases we handle, do special stuff 2631 // now. 2632 const Value *CondVal = I.getCondition(); 2633 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2634 2635 // If this is a series of conditions that are or'd or and'd together, emit 2636 // this as a sequence of branches instead of setcc's with and/or operations. 2637 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2638 // unpredictable branches, and vector extracts because those jumps are likely 2639 // expensive for any target), this should improve performance. 2640 // For example, instead of something like: 2641 // cmp A, B 2642 // C = seteq 2643 // cmp D, E 2644 // F = setle 2645 // or C, F 2646 // jnz foo 2647 // Emit: 2648 // cmp A, B 2649 // je foo 2650 // cmp D, E 2651 // jle foo 2652 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2653 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2654 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2655 Value *Vec; 2656 const Value *BOp0, *BOp1; 2657 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2658 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2659 Opcode = Instruction::And; 2660 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2661 Opcode = Instruction::Or; 2662 2663 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2664 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2665 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2666 getEdgeProbability(BrMBB, Succ0MBB), 2667 getEdgeProbability(BrMBB, Succ1MBB), 2668 /*InvertCond=*/false); 2669 // If the compares in later blocks need to use values not currently 2670 // exported from this block, export them now. This block should always 2671 // be the first entry. 2672 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2673 2674 // Allow some cases to be rejected. 2675 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2676 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2677 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2678 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2679 } 2680 2681 // Emit the branch for this block. 2682 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2683 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2684 return; 2685 } 2686 2687 // Okay, we decided not to do this, remove any inserted MBB's and clear 2688 // SwitchCases. 2689 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2690 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2691 2692 SL->SwitchCases.clear(); 2693 } 2694 } 2695 2696 // Create a CaseBlock record representing this branch. 2697 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2698 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2699 2700 // Use visitSwitchCase to actually insert the fast branch sequence for this 2701 // cond branch. 2702 visitSwitchCase(CB, BrMBB); 2703 } 2704 2705 /// visitSwitchCase - Emits the necessary code to represent a single node in 2706 /// the binary search tree resulting from lowering a switch instruction. 2707 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2708 MachineBasicBlock *SwitchBB) { 2709 SDValue Cond; 2710 SDValue CondLHS = getValue(CB.CmpLHS); 2711 SDLoc dl = CB.DL; 2712 2713 if (CB.CC == ISD::SETTRUE) { 2714 // Branch or fall through to TrueBB. 2715 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2716 SwitchBB->normalizeSuccProbs(); 2717 if (CB.TrueBB != NextBlock(SwitchBB)) { 2718 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2719 DAG.getBasicBlock(CB.TrueBB))); 2720 } 2721 return; 2722 } 2723 2724 auto &TLI = DAG.getTargetLoweringInfo(); 2725 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2726 2727 // Build the setcc now. 2728 if (!CB.CmpMHS) { 2729 // Fold "(X == true)" to X and "(X == false)" to !X to 2730 // handle common cases produced by branch lowering. 2731 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2732 CB.CC == ISD::SETEQ) 2733 Cond = CondLHS; 2734 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2735 CB.CC == ISD::SETEQ) { 2736 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2737 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2738 } else { 2739 SDValue CondRHS = getValue(CB.CmpRHS); 2740 2741 // If a pointer's DAG type is larger than its memory type then the DAG 2742 // values are zero-extended. This breaks signed comparisons so truncate 2743 // back to the underlying type before doing the compare. 2744 if (CondLHS.getValueType() != MemVT) { 2745 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2746 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2747 } 2748 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2749 } 2750 } else { 2751 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2752 2753 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2754 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2755 2756 SDValue CmpOp = getValue(CB.CmpMHS); 2757 EVT VT = CmpOp.getValueType(); 2758 2759 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2760 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2761 ISD::SETLE); 2762 } else { 2763 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2764 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2765 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2766 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2767 } 2768 } 2769 2770 // Update successor info 2771 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2772 // TrueBB and FalseBB are always different unless the incoming IR is 2773 // degenerate. This only happens when running llc on weird IR. 2774 if (CB.TrueBB != CB.FalseBB) 2775 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2776 SwitchBB->normalizeSuccProbs(); 2777 2778 // If the lhs block is the next block, invert the condition so that we can 2779 // fall through to the lhs instead of the rhs block. 2780 if (CB.TrueBB == NextBlock(SwitchBB)) { 2781 std::swap(CB.TrueBB, CB.FalseBB); 2782 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2783 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2784 } 2785 2786 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2787 MVT::Other, getControlRoot(), Cond, 2788 DAG.getBasicBlock(CB.TrueBB)); 2789 2790 setValue(CurInst, BrCond); 2791 2792 // Insert the false branch. Do this even if it's a fall through branch, 2793 // this makes it easier to do DAG optimizations which require inverting 2794 // the branch condition. 2795 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2796 DAG.getBasicBlock(CB.FalseBB)); 2797 2798 DAG.setRoot(BrCond); 2799 } 2800 2801 /// visitJumpTable - Emit JumpTable node in the current MBB 2802 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2803 // Emit the code for the jump table 2804 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2805 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2806 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2807 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy); 2808 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2809 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other, 2810 Index.getValue(1), Table, Index); 2811 DAG.setRoot(BrJumpTable); 2812 } 2813 2814 /// visitJumpTableHeader - This function emits necessary code to produce index 2815 /// in the JumpTable from switch case. 2816 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2817 JumpTableHeader &JTH, 2818 MachineBasicBlock *SwitchBB) { 2819 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2820 const SDLoc &dl = *JT.SL; 2821 2822 // Subtract the lowest switch case value from the value being switched on. 2823 SDValue SwitchOp = getValue(JTH.SValue); 2824 EVT VT = SwitchOp.getValueType(); 2825 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2826 DAG.getConstant(JTH.First, dl, VT)); 2827 2828 // The SDNode we just created, which holds the value being switched on minus 2829 // the smallest case value, needs to be copied to a virtual register so it 2830 // can be used as an index into the jump table in a subsequent basic block. 2831 // This value may be smaller or larger than the target's pointer type, and 2832 // therefore require extension or truncating. 2833 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2834 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2835 2836 unsigned JumpTableReg = 2837 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2838 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2839 JumpTableReg, SwitchOp); 2840 JT.Reg = JumpTableReg; 2841 2842 if (!JTH.FallthroughUnreachable) { 2843 // Emit the range check for the jump table, and branch to the default block 2844 // for the switch statement if the value being switched on exceeds the 2845 // largest case in the switch. 2846 SDValue CMP = DAG.getSetCC( 2847 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2848 Sub.getValueType()), 2849 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2850 2851 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2852 MVT::Other, CopyTo, CMP, 2853 DAG.getBasicBlock(JT.Default)); 2854 2855 // Avoid emitting unnecessary branches to the next block. 2856 if (JT.MBB != NextBlock(SwitchBB)) 2857 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2858 DAG.getBasicBlock(JT.MBB)); 2859 2860 DAG.setRoot(BrCond); 2861 } else { 2862 // Avoid emitting unnecessary branches to the next block. 2863 if (JT.MBB != NextBlock(SwitchBB)) 2864 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2865 DAG.getBasicBlock(JT.MBB))); 2866 else 2867 DAG.setRoot(CopyTo); 2868 } 2869 } 2870 2871 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2872 /// variable if there exists one. 2873 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2874 SDValue &Chain) { 2875 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2876 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2877 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2878 MachineFunction &MF = DAG.getMachineFunction(); 2879 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2880 MachineSDNode *Node = 2881 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2882 if (Global) { 2883 MachinePointerInfo MPInfo(Global); 2884 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2885 MachineMemOperand::MODereferenceable; 2886 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2887 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2888 DAG.setNodeMemRefs(Node, {MemRef}); 2889 } 2890 if (PtrTy != PtrMemTy) 2891 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2892 return SDValue(Node, 0); 2893 } 2894 2895 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2896 /// tail spliced into a stack protector check success bb. 2897 /// 2898 /// For a high level explanation of how this fits into the stack protector 2899 /// generation see the comment on the declaration of class 2900 /// StackProtectorDescriptor. 2901 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2902 MachineBasicBlock *ParentBB) { 2903 2904 // First create the loads to the guard/stack slot for the comparison. 2905 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2906 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2907 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2908 2909 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2910 int FI = MFI.getStackProtectorIndex(); 2911 2912 SDValue Guard; 2913 SDLoc dl = getCurSDLoc(); 2914 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2915 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2916 Align Align = 2917 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 2918 2919 // Generate code to load the content of the guard slot. 2920 SDValue GuardVal = DAG.getLoad( 2921 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2922 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2923 MachineMemOperand::MOVolatile); 2924 2925 if (TLI.useStackGuardXorFP()) 2926 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2927 2928 // Retrieve guard check function, nullptr if instrumentation is inlined. 2929 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2930 // The target provides a guard check function to validate the guard value. 2931 // Generate a call to that function with the content of the guard slot as 2932 // argument. 2933 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2934 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2935 2936 TargetLowering::ArgListTy Args; 2937 TargetLowering::ArgListEntry Entry; 2938 Entry.Node = GuardVal; 2939 Entry.Ty = FnTy->getParamType(0); 2940 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2941 Entry.IsInReg = true; 2942 Args.push_back(Entry); 2943 2944 TargetLowering::CallLoweringInfo CLI(DAG); 2945 CLI.setDebugLoc(getCurSDLoc()) 2946 .setChain(DAG.getEntryNode()) 2947 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2948 getValue(GuardCheckFn), std::move(Args)); 2949 2950 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2951 DAG.setRoot(Result.second); 2952 return; 2953 } 2954 2955 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2956 // Otherwise, emit a volatile load to retrieve the stack guard value. 2957 SDValue Chain = DAG.getEntryNode(); 2958 if (TLI.useLoadStackGuardNode()) { 2959 Guard = getLoadStackGuard(DAG, dl, Chain); 2960 } else { 2961 const Value *IRGuard = TLI.getSDagStackGuard(M); 2962 SDValue GuardPtr = getValue(IRGuard); 2963 2964 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2965 MachinePointerInfo(IRGuard, 0), Align, 2966 MachineMemOperand::MOVolatile); 2967 } 2968 2969 // Perform the comparison via a getsetcc. 2970 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2971 *DAG.getContext(), 2972 Guard.getValueType()), 2973 Guard, GuardVal, ISD::SETNE); 2974 2975 // If the guard/stackslot do not equal, branch to failure MBB. 2976 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2977 MVT::Other, GuardVal.getOperand(0), 2978 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2979 // Otherwise branch to success MBB. 2980 SDValue Br = DAG.getNode(ISD::BR, dl, 2981 MVT::Other, BrCond, 2982 DAG.getBasicBlock(SPD.getSuccessMBB())); 2983 2984 DAG.setRoot(Br); 2985 } 2986 2987 /// Codegen the failure basic block for a stack protector check. 2988 /// 2989 /// A failure stack protector machine basic block consists simply of a call to 2990 /// __stack_chk_fail(). 2991 /// 2992 /// For a high level explanation of how this fits into the stack protector 2993 /// generation see the comment on the declaration of class 2994 /// StackProtectorDescriptor. 2995 void 2996 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2997 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2998 TargetLowering::MakeLibCallOptions CallOptions; 2999 CallOptions.setDiscardResult(true); 3000 SDValue Chain = 3001 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 3002 std::nullopt, CallOptions, getCurSDLoc()) 3003 .second; 3004 // On PS4/PS5, the "return address" must still be within the calling 3005 // function, even if it's at the very end, so emit an explicit TRAP here. 3006 // Passing 'true' for doesNotReturn above won't generate the trap for us. 3007 if (TM.getTargetTriple().isPS()) 3008 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3009 // WebAssembly needs an unreachable instruction after a non-returning call, 3010 // because the function return type can be different from __stack_chk_fail's 3011 // return type (void). 3012 if (TM.getTargetTriple().isWasm()) 3013 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3014 3015 DAG.setRoot(Chain); 3016 } 3017 3018 /// visitBitTestHeader - This function emits necessary code to produce value 3019 /// suitable for "bit tests" 3020 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 3021 MachineBasicBlock *SwitchBB) { 3022 SDLoc dl = getCurSDLoc(); 3023 3024 // Subtract the minimum value. 3025 SDValue SwitchOp = getValue(B.SValue); 3026 EVT VT = SwitchOp.getValueType(); 3027 SDValue RangeSub = 3028 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 3029 3030 // Determine the type of the test operands. 3031 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3032 bool UsePtrType = false; 3033 if (!TLI.isTypeLegal(VT)) { 3034 UsePtrType = true; 3035 } else { 3036 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 3037 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 3038 // Switch table case range are encoded into series of masks. 3039 // Just use pointer type, it's guaranteed to fit. 3040 UsePtrType = true; 3041 break; 3042 } 3043 } 3044 SDValue Sub = RangeSub; 3045 if (UsePtrType) { 3046 VT = TLI.getPointerTy(DAG.getDataLayout()); 3047 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 3048 } 3049 3050 B.RegVT = VT.getSimpleVT(); 3051 B.Reg = FuncInfo.CreateReg(B.RegVT); 3052 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 3053 3054 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 3055 3056 if (!B.FallthroughUnreachable) 3057 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 3058 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 3059 SwitchBB->normalizeSuccProbs(); 3060 3061 SDValue Root = CopyTo; 3062 if (!B.FallthroughUnreachable) { 3063 // Conditional branch to the default block. 3064 SDValue RangeCmp = DAG.getSetCC(dl, 3065 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3066 RangeSub.getValueType()), 3067 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 3068 ISD::SETUGT); 3069 3070 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 3071 DAG.getBasicBlock(B.Default)); 3072 } 3073 3074 // Avoid emitting unnecessary branches to the next block. 3075 if (MBB != NextBlock(SwitchBB)) 3076 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 3077 3078 DAG.setRoot(Root); 3079 } 3080 3081 /// visitBitTestCase - this function produces one "bit test" 3082 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 3083 MachineBasicBlock* NextMBB, 3084 BranchProbability BranchProbToNext, 3085 unsigned Reg, 3086 BitTestCase &B, 3087 MachineBasicBlock *SwitchBB) { 3088 SDLoc dl = getCurSDLoc(); 3089 MVT VT = BB.RegVT; 3090 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 3091 SDValue Cmp; 3092 unsigned PopCount = llvm::popcount(B.Mask); 3093 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3094 if (PopCount == 1) { 3095 // Testing for a single bit; just compare the shift count with what it 3096 // would need to be to shift a 1 bit in that position. 3097 Cmp = DAG.getSetCC( 3098 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3099 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 3100 ISD::SETEQ); 3101 } else if (PopCount == BB.Range) { 3102 // There is only one zero bit in the range, test for it directly. 3103 Cmp = DAG.getSetCC( 3104 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3105 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 3106 } else { 3107 // Make desired shift 3108 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 3109 DAG.getConstant(1, dl, VT), ShiftOp); 3110 3111 // Emit bit tests and jumps 3112 SDValue AndOp = DAG.getNode(ISD::AND, dl, 3113 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 3114 Cmp = DAG.getSetCC( 3115 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3116 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 3117 } 3118 3119 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 3120 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 3121 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 3122 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 3123 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 3124 // one as they are relative probabilities (and thus work more like weights), 3125 // and hence we need to normalize them to let the sum of them become one. 3126 SwitchBB->normalizeSuccProbs(); 3127 3128 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 3129 MVT::Other, getControlRoot(), 3130 Cmp, DAG.getBasicBlock(B.TargetBB)); 3131 3132 // Avoid emitting unnecessary branches to the next block. 3133 if (NextMBB != NextBlock(SwitchBB)) 3134 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 3135 DAG.getBasicBlock(NextMBB)); 3136 3137 DAG.setRoot(BrAnd); 3138 } 3139 3140 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3141 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3142 3143 // Retrieve successors. Look through artificial IR level blocks like 3144 // catchswitch for successors. 3145 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 3146 const BasicBlock *EHPadBB = I.getSuccessor(1); 3147 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 3148 3149 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3150 // have to do anything here to lower funclet bundles. 3151 assert(!I.hasOperandBundlesOtherThan( 3152 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3153 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3154 LLVMContext::OB_cfguardtarget, 3155 LLVMContext::OB_clang_arc_attachedcall}) && 3156 "Cannot lower invokes with arbitrary operand bundles yet!"); 3157 3158 const Value *Callee(I.getCalledOperand()); 3159 const Function *Fn = dyn_cast<Function>(Callee); 3160 if (isa<InlineAsm>(Callee)) 3161 visitInlineAsm(I, EHPadBB); 3162 else if (Fn && Fn->isIntrinsic()) { 3163 switch (Fn->getIntrinsicID()) { 3164 default: 3165 llvm_unreachable("Cannot invoke this intrinsic"); 3166 case Intrinsic::donothing: 3167 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3168 case Intrinsic::seh_try_begin: 3169 case Intrinsic::seh_scope_begin: 3170 case Intrinsic::seh_try_end: 3171 case Intrinsic::seh_scope_end: 3172 if (EHPadMBB) 3173 // a block referenced by EH table 3174 // so dtor-funclet not removed by opts 3175 EHPadMBB->setMachineBlockAddressTaken(); 3176 break; 3177 case Intrinsic::experimental_patchpoint_void: 3178 case Intrinsic::experimental_patchpoint_i64: 3179 visitPatchpoint(I, EHPadBB); 3180 break; 3181 case Intrinsic::experimental_gc_statepoint: 3182 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3183 break; 3184 case Intrinsic::wasm_rethrow: { 3185 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3186 // special because it can be invoked, so we manually lower it to a DAG 3187 // node here. 3188 SmallVector<SDValue, 8> Ops; 3189 Ops.push_back(getRoot()); // inchain 3190 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3191 Ops.push_back( 3192 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3193 TLI.getPointerTy(DAG.getDataLayout()))); 3194 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3195 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3196 break; 3197 } 3198 } 3199 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3200 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3201 // Eventually we will support lowering the @llvm.experimental.deoptimize 3202 // intrinsic, and right now there are no plans to support other intrinsics 3203 // with deopt state. 3204 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3205 } else { 3206 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3207 } 3208 3209 // If the value of the invoke is used outside of its defining block, make it 3210 // available as a virtual register. 3211 // We already took care of the exported value for the statepoint instruction 3212 // during call to the LowerStatepoint. 3213 if (!isa<GCStatepointInst>(I)) { 3214 CopyToExportRegsIfNeeded(&I); 3215 } 3216 3217 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3218 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3219 BranchProbability EHPadBBProb = 3220 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3221 : BranchProbability::getZero(); 3222 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3223 3224 // Update successor info. 3225 addSuccessorWithProb(InvokeMBB, Return); 3226 for (auto &UnwindDest : UnwindDests) { 3227 UnwindDest.first->setIsEHPad(); 3228 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3229 } 3230 InvokeMBB->normalizeSuccProbs(); 3231 3232 // Drop into normal successor. 3233 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3234 DAG.getBasicBlock(Return))); 3235 } 3236 3237 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3238 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3239 3240 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3241 // have to do anything here to lower funclet bundles. 3242 assert(!I.hasOperandBundlesOtherThan( 3243 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3244 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3245 3246 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3247 visitInlineAsm(I); 3248 CopyToExportRegsIfNeeded(&I); 3249 3250 // Retrieve successors. 3251 SmallPtrSet<BasicBlock *, 8> Dests; 3252 Dests.insert(I.getDefaultDest()); 3253 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3254 3255 // Update successor info. 3256 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3257 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3258 BasicBlock *Dest = I.getIndirectDest(i); 3259 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3260 Target->setIsInlineAsmBrIndirectTarget(); 3261 Target->setMachineBlockAddressTaken(); 3262 Target->setLabelMustBeEmitted(); 3263 // Don't add duplicate machine successors. 3264 if (Dests.insert(Dest).second) 3265 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3266 } 3267 CallBrMBB->normalizeSuccProbs(); 3268 3269 // Drop into default successor. 3270 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3271 MVT::Other, getControlRoot(), 3272 DAG.getBasicBlock(Return))); 3273 } 3274 3275 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3276 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3277 } 3278 3279 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3280 assert(FuncInfo.MBB->isEHPad() && 3281 "Call to landingpad not in landing pad!"); 3282 3283 // If there aren't registers to copy the values into (e.g., during SjLj 3284 // exceptions), then don't bother to create these DAG nodes. 3285 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3286 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3287 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3288 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3289 return; 3290 3291 // If landingpad's return type is token type, we don't create DAG nodes 3292 // for its exception pointer and selector value. The extraction of exception 3293 // pointer or selector value from token type landingpads is not currently 3294 // supported. 3295 if (LP.getType()->isTokenTy()) 3296 return; 3297 3298 SmallVector<EVT, 2> ValueVTs; 3299 SDLoc dl = getCurSDLoc(); 3300 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3301 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3302 3303 // Get the two live-in registers as SDValues. The physregs have already been 3304 // copied into virtual registers. 3305 SDValue Ops[2]; 3306 if (FuncInfo.ExceptionPointerVirtReg) { 3307 Ops[0] = DAG.getZExtOrTrunc( 3308 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3309 FuncInfo.ExceptionPointerVirtReg, 3310 TLI.getPointerTy(DAG.getDataLayout())), 3311 dl, ValueVTs[0]); 3312 } else { 3313 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3314 } 3315 Ops[1] = DAG.getZExtOrTrunc( 3316 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3317 FuncInfo.ExceptionSelectorVirtReg, 3318 TLI.getPointerTy(DAG.getDataLayout())), 3319 dl, ValueVTs[1]); 3320 3321 // Merge into one. 3322 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3323 DAG.getVTList(ValueVTs), Ops); 3324 setValue(&LP, Res); 3325 } 3326 3327 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3328 MachineBasicBlock *Last) { 3329 // Update JTCases. 3330 for (JumpTableBlock &JTB : SL->JTCases) 3331 if (JTB.first.HeaderBB == First) 3332 JTB.first.HeaderBB = Last; 3333 3334 // Update BitTestCases. 3335 for (BitTestBlock &BTB : SL->BitTestCases) 3336 if (BTB.Parent == First) 3337 BTB.Parent = Last; 3338 } 3339 3340 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3341 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3342 3343 // Update machine-CFG edges with unique successors. 3344 SmallSet<BasicBlock*, 32> Done; 3345 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3346 BasicBlock *BB = I.getSuccessor(i); 3347 bool Inserted = Done.insert(BB).second; 3348 if (!Inserted) 3349 continue; 3350 3351 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3352 addSuccessorWithProb(IndirectBrMBB, Succ); 3353 } 3354 IndirectBrMBB->normalizeSuccProbs(); 3355 3356 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3357 MVT::Other, getControlRoot(), 3358 getValue(I.getAddress()))); 3359 } 3360 3361 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3362 if (!DAG.getTarget().Options.TrapUnreachable) 3363 return; 3364 3365 // We may be able to ignore unreachable behind a noreturn call. 3366 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3367 if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) { 3368 if (Call->doesNotReturn()) 3369 return; 3370 } 3371 } 3372 3373 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3374 } 3375 3376 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3377 SDNodeFlags Flags; 3378 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3379 Flags.copyFMF(*FPOp); 3380 3381 SDValue Op = getValue(I.getOperand(0)); 3382 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3383 Op, Flags); 3384 setValue(&I, UnNodeValue); 3385 } 3386 3387 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3388 SDNodeFlags Flags; 3389 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3390 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3391 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3392 } 3393 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3394 Flags.setExact(ExactOp->isExact()); 3395 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I)) 3396 Flags.setDisjoint(DisjointOp->isDisjoint()); 3397 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3398 Flags.copyFMF(*FPOp); 3399 3400 SDValue Op1 = getValue(I.getOperand(0)); 3401 SDValue Op2 = getValue(I.getOperand(1)); 3402 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3403 Op1, Op2, Flags); 3404 setValue(&I, BinNodeValue); 3405 } 3406 3407 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3408 SDValue Op1 = getValue(I.getOperand(0)); 3409 SDValue Op2 = getValue(I.getOperand(1)); 3410 3411 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3412 Op1.getValueType(), DAG.getDataLayout()); 3413 3414 // Coerce the shift amount to the right type if we can. This exposes the 3415 // truncate or zext to optimization early. 3416 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3417 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3418 "Unexpected shift type"); 3419 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3420 } 3421 3422 bool nuw = false; 3423 bool nsw = false; 3424 bool exact = false; 3425 3426 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3427 3428 if (const OverflowingBinaryOperator *OFBinOp = 3429 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3430 nuw = OFBinOp->hasNoUnsignedWrap(); 3431 nsw = OFBinOp->hasNoSignedWrap(); 3432 } 3433 if (const PossiblyExactOperator *ExactOp = 3434 dyn_cast<const PossiblyExactOperator>(&I)) 3435 exact = ExactOp->isExact(); 3436 } 3437 SDNodeFlags Flags; 3438 Flags.setExact(exact); 3439 Flags.setNoSignedWrap(nsw); 3440 Flags.setNoUnsignedWrap(nuw); 3441 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3442 Flags); 3443 setValue(&I, Res); 3444 } 3445 3446 void SelectionDAGBuilder::visitSDiv(const User &I) { 3447 SDValue Op1 = getValue(I.getOperand(0)); 3448 SDValue Op2 = getValue(I.getOperand(1)); 3449 3450 SDNodeFlags Flags; 3451 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3452 cast<PossiblyExactOperator>(&I)->isExact()); 3453 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3454 Op2, Flags)); 3455 } 3456 3457 void SelectionDAGBuilder::visitICmp(const User &I) { 3458 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3459 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3460 predicate = IC->getPredicate(); 3461 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3462 predicate = ICmpInst::Predicate(IC->getPredicate()); 3463 SDValue Op1 = getValue(I.getOperand(0)); 3464 SDValue Op2 = getValue(I.getOperand(1)); 3465 ISD::CondCode Opcode = getICmpCondCode(predicate); 3466 3467 auto &TLI = DAG.getTargetLoweringInfo(); 3468 EVT MemVT = 3469 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3470 3471 // If a pointer's DAG type is larger than its memory type then the DAG values 3472 // are zero-extended. This breaks signed comparisons so truncate back to the 3473 // underlying type before doing the compare. 3474 if (Op1.getValueType() != MemVT) { 3475 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3476 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3477 } 3478 3479 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3480 I.getType()); 3481 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3482 } 3483 3484 void SelectionDAGBuilder::visitFCmp(const User &I) { 3485 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3486 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3487 predicate = FC->getPredicate(); 3488 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3489 predicate = FCmpInst::Predicate(FC->getPredicate()); 3490 SDValue Op1 = getValue(I.getOperand(0)); 3491 SDValue Op2 = getValue(I.getOperand(1)); 3492 3493 ISD::CondCode Condition = getFCmpCondCode(predicate); 3494 auto *FPMO = cast<FPMathOperator>(&I); 3495 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3496 Condition = getFCmpCodeWithoutNaN(Condition); 3497 3498 SDNodeFlags Flags; 3499 Flags.copyFMF(*FPMO); 3500 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3501 3502 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3503 I.getType()); 3504 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3505 } 3506 3507 // Check if the condition of the select has one use or two users that are both 3508 // selects with the same condition. 3509 static bool hasOnlySelectUsers(const Value *Cond) { 3510 return llvm::all_of(Cond->users(), [](const Value *V) { 3511 return isa<SelectInst>(V); 3512 }); 3513 } 3514 3515 void SelectionDAGBuilder::visitSelect(const User &I) { 3516 SmallVector<EVT, 4> ValueVTs; 3517 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3518 ValueVTs); 3519 unsigned NumValues = ValueVTs.size(); 3520 if (NumValues == 0) return; 3521 3522 SmallVector<SDValue, 4> Values(NumValues); 3523 SDValue Cond = getValue(I.getOperand(0)); 3524 SDValue LHSVal = getValue(I.getOperand(1)); 3525 SDValue RHSVal = getValue(I.getOperand(2)); 3526 SmallVector<SDValue, 1> BaseOps(1, Cond); 3527 ISD::NodeType OpCode = 3528 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3529 3530 bool IsUnaryAbs = false; 3531 bool Negate = false; 3532 3533 SDNodeFlags Flags; 3534 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3535 Flags.copyFMF(*FPOp); 3536 3537 Flags.setUnpredictable( 3538 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3539 3540 // Min/max matching is only viable if all output VTs are the same. 3541 if (all_equal(ValueVTs)) { 3542 EVT VT = ValueVTs[0]; 3543 LLVMContext &Ctx = *DAG.getContext(); 3544 auto &TLI = DAG.getTargetLoweringInfo(); 3545 3546 // We care about the legality of the operation after it has been type 3547 // legalized. 3548 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3549 VT = TLI.getTypeToTransformTo(Ctx, VT); 3550 3551 // If the vselect is legal, assume we want to leave this as a vector setcc + 3552 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3553 // min/max is legal on the scalar type. 3554 bool UseScalarMinMax = VT.isVector() && 3555 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3556 3557 // ValueTracking's select pattern matching does not account for -0.0, 3558 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3559 // -0.0 is less than +0.0. 3560 Value *LHS, *RHS; 3561 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3562 ISD::NodeType Opc = ISD::DELETED_NODE; 3563 switch (SPR.Flavor) { 3564 case SPF_UMAX: Opc = ISD::UMAX; break; 3565 case SPF_UMIN: Opc = ISD::UMIN; break; 3566 case SPF_SMAX: Opc = ISD::SMAX; break; 3567 case SPF_SMIN: Opc = ISD::SMIN; break; 3568 case SPF_FMINNUM: 3569 switch (SPR.NaNBehavior) { 3570 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3571 case SPNB_RETURNS_NAN: break; 3572 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3573 case SPNB_RETURNS_ANY: 3574 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3575 (UseScalarMinMax && 3576 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3577 Opc = ISD::FMINNUM; 3578 break; 3579 } 3580 break; 3581 case SPF_FMAXNUM: 3582 switch (SPR.NaNBehavior) { 3583 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3584 case SPNB_RETURNS_NAN: break; 3585 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3586 case SPNB_RETURNS_ANY: 3587 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3588 (UseScalarMinMax && 3589 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3590 Opc = ISD::FMAXNUM; 3591 break; 3592 } 3593 break; 3594 case SPF_NABS: 3595 Negate = true; 3596 [[fallthrough]]; 3597 case SPF_ABS: 3598 IsUnaryAbs = true; 3599 Opc = ISD::ABS; 3600 break; 3601 default: break; 3602 } 3603 3604 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3605 (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) || 3606 (UseScalarMinMax && 3607 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3608 // If the underlying comparison instruction is used by any other 3609 // instruction, the consumed instructions won't be destroyed, so it is 3610 // not profitable to convert to a min/max. 3611 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3612 OpCode = Opc; 3613 LHSVal = getValue(LHS); 3614 RHSVal = getValue(RHS); 3615 BaseOps.clear(); 3616 } 3617 3618 if (IsUnaryAbs) { 3619 OpCode = Opc; 3620 LHSVal = getValue(LHS); 3621 BaseOps.clear(); 3622 } 3623 } 3624 3625 if (IsUnaryAbs) { 3626 for (unsigned i = 0; i != NumValues; ++i) { 3627 SDLoc dl = getCurSDLoc(); 3628 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3629 Values[i] = 3630 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3631 if (Negate) 3632 Values[i] = DAG.getNegative(Values[i], dl, VT); 3633 } 3634 } else { 3635 for (unsigned i = 0; i != NumValues; ++i) { 3636 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3637 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3638 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3639 Values[i] = DAG.getNode( 3640 OpCode, getCurSDLoc(), 3641 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3642 } 3643 } 3644 3645 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3646 DAG.getVTList(ValueVTs), Values)); 3647 } 3648 3649 void SelectionDAGBuilder::visitTrunc(const User &I) { 3650 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3651 SDValue N = getValue(I.getOperand(0)); 3652 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3653 I.getType()); 3654 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3655 } 3656 3657 void SelectionDAGBuilder::visitZExt(const User &I) { 3658 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3659 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3660 SDValue N = getValue(I.getOperand(0)); 3661 auto &TLI = DAG.getTargetLoweringInfo(); 3662 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3663 3664 SDNodeFlags Flags; 3665 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3666 Flags.setNonNeg(PNI->hasNonNeg()); 3667 3668 // Eagerly use nonneg information to canonicalize towards sign_extend if 3669 // that is the target's preference. 3670 // TODO: Let the target do this later. 3671 if (Flags.hasNonNeg() && 3672 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3673 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3674 return; 3675 } 3676 3677 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3678 } 3679 3680 void SelectionDAGBuilder::visitSExt(const User &I) { 3681 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3682 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3683 SDValue N = getValue(I.getOperand(0)); 3684 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3685 I.getType()); 3686 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3687 } 3688 3689 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3690 // FPTrunc is never a no-op cast, no need to check 3691 SDValue N = getValue(I.getOperand(0)); 3692 SDLoc dl = getCurSDLoc(); 3693 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3694 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3695 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3696 DAG.getTargetConstant( 3697 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3698 } 3699 3700 void SelectionDAGBuilder::visitFPExt(const User &I) { 3701 // FPExt is never a no-op cast, no need to check 3702 SDValue N = getValue(I.getOperand(0)); 3703 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3704 I.getType()); 3705 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3706 } 3707 3708 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3709 // FPToUI is never a no-op cast, no need to check 3710 SDValue N = getValue(I.getOperand(0)); 3711 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3712 I.getType()); 3713 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3714 } 3715 3716 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3717 // FPToSI is never a no-op cast, no need to check 3718 SDValue N = getValue(I.getOperand(0)); 3719 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3720 I.getType()); 3721 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3722 } 3723 3724 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3725 // UIToFP is never a no-op cast, no need to check 3726 SDValue N = getValue(I.getOperand(0)); 3727 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3728 I.getType()); 3729 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3730 } 3731 3732 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3733 // SIToFP is never a no-op cast, no need to check 3734 SDValue N = getValue(I.getOperand(0)); 3735 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3736 I.getType()); 3737 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3738 } 3739 3740 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3741 // What to do depends on the size of the integer and the size of the pointer. 3742 // We can either truncate, zero extend, or no-op, accordingly. 3743 SDValue N = getValue(I.getOperand(0)); 3744 auto &TLI = DAG.getTargetLoweringInfo(); 3745 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3746 I.getType()); 3747 EVT PtrMemVT = 3748 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3749 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3750 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3751 setValue(&I, N); 3752 } 3753 3754 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3755 // What to do depends on the size of the integer and the size of the pointer. 3756 // We can either truncate, zero extend, or no-op, accordingly. 3757 SDValue N = getValue(I.getOperand(0)); 3758 auto &TLI = DAG.getTargetLoweringInfo(); 3759 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3760 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3761 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3762 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3763 setValue(&I, N); 3764 } 3765 3766 void SelectionDAGBuilder::visitBitCast(const User &I) { 3767 SDValue N = getValue(I.getOperand(0)); 3768 SDLoc dl = getCurSDLoc(); 3769 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3770 I.getType()); 3771 3772 // BitCast assures us that source and destination are the same size so this is 3773 // either a BITCAST or a no-op. 3774 if (DestVT != N.getValueType()) 3775 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3776 DestVT, N)); // convert types. 3777 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3778 // might fold any kind of constant expression to an integer constant and that 3779 // is not what we are looking for. Only recognize a bitcast of a genuine 3780 // constant integer as an opaque constant. 3781 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3782 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3783 /*isOpaque*/true)); 3784 else 3785 setValue(&I, N); // noop cast. 3786 } 3787 3788 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3789 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3790 const Value *SV = I.getOperand(0); 3791 SDValue N = getValue(SV); 3792 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3793 3794 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3795 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3796 3797 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3798 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3799 3800 setValue(&I, N); 3801 } 3802 3803 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3804 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3805 SDValue InVec = getValue(I.getOperand(0)); 3806 SDValue InVal = getValue(I.getOperand(1)); 3807 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3808 TLI.getVectorIdxTy(DAG.getDataLayout())); 3809 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3810 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3811 InVec, InVal, InIdx)); 3812 } 3813 3814 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3815 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3816 SDValue InVec = getValue(I.getOperand(0)); 3817 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3818 TLI.getVectorIdxTy(DAG.getDataLayout())); 3819 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3820 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3821 InVec, InIdx)); 3822 } 3823 3824 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3825 SDValue Src1 = getValue(I.getOperand(0)); 3826 SDValue Src2 = getValue(I.getOperand(1)); 3827 ArrayRef<int> Mask; 3828 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3829 Mask = SVI->getShuffleMask(); 3830 else 3831 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3832 SDLoc DL = getCurSDLoc(); 3833 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3834 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3835 EVT SrcVT = Src1.getValueType(); 3836 3837 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3838 VT.isScalableVector()) { 3839 // Canonical splat form of first element of first input vector. 3840 SDValue FirstElt = 3841 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3842 DAG.getVectorIdxConstant(0, DL)); 3843 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3844 return; 3845 } 3846 3847 // For now, we only handle splats for scalable vectors. 3848 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3849 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3850 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3851 3852 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3853 unsigned MaskNumElts = Mask.size(); 3854 3855 if (SrcNumElts == MaskNumElts) { 3856 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3857 return; 3858 } 3859 3860 // Normalize the shuffle vector since mask and vector length don't match. 3861 if (SrcNumElts < MaskNumElts) { 3862 // Mask is longer than the source vectors. We can use concatenate vector to 3863 // make the mask and vectors lengths match. 3864 3865 if (MaskNumElts % SrcNumElts == 0) { 3866 // Mask length is a multiple of the source vector length. 3867 // Check if the shuffle is some kind of concatenation of the input 3868 // vectors. 3869 unsigned NumConcat = MaskNumElts / SrcNumElts; 3870 bool IsConcat = true; 3871 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3872 for (unsigned i = 0; i != MaskNumElts; ++i) { 3873 int Idx = Mask[i]; 3874 if (Idx < 0) 3875 continue; 3876 // Ensure the indices in each SrcVT sized piece are sequential and that 3877 // the same source is used for the whole piece. 3878 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3879 (ConcatSrcs[i / SrcNumElts] >= 0 && 3880 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3881 IsConcat = false; 3882 break; 3883 } 3884 // Remember which source this index came from. 3885 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3886 } 3887 3888 // The shuffle is concatenating multiple vectors together. Just emit 3889 // a CONCAT_VECTORS operation. 3890 if (IsConcat) { 3891 SmallVector<SDValue, 8> ConcatOps; 3892 for (auto Src : ConcatSrcs) { 3893 if (Src < 0) 3894 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3895 else if (Src == 0) 3896 ConcatOps.push_back(Src1); 3897 else 3898 ConcatOps.push_back(Src2); 3899 } 3900 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3901 return; 3902 } 3903 } 3904 3905 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3906 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3907 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3908 PaddedMaskNumElts); 3909 3910 // Pad both vectors with undefs to make them the same length as the mask. 3911 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3912 3913 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3914 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3915 MOps1[0] = Src1; 3916 MOps2[0] = Src2; 3917 3918 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3919 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3920 3921 // Readjust mask for new input vector length. 3922 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3923 for (unsigned i = 0; i != MaskNumElts; ++i) { 3924 int Idx = Mask[i]; 3925 if (Idx >= (int)SrcNumElts) 3926 Idx -= SrcNumElts - PaddedMaskNumElts; 3927 MappedOps[i] = Idx; 3928 } 3929 3930 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3931 3932 // If the concatenated vector was padded, extract a subvector with the 3933 // correct number of elements. 3934 if (MaskNumElts != PaddedMaskNumElts) 3935 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3936 DAG.getVectorIdxConstant(0, DL)); 3937 3938 setValue(&I, Result); 3939 return; 3940 } 3941 3942 if (SrcNumElts > MaskNumElts) { 3943 // Analyze the access pattern of the vector to see if we can extract 3944 // two subvectors and do the shuffle. 3945 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3946 bool CanExtract = true; 3947 for (int Idx : Mask) { 3948 unsigned Input = 0; 3949 if (Idx < 0) 3950 continue; 3951 3952 if (Idx >= (int)SrcNumElts) { 3953 Input = 1; 3954 Idx -= SrcNumElts; 3955 } 3956 3957 // If all the indices come from the same MaskNumElts sized portion of 3958 // the sources we can use extract. Also make sure the extract wouldn't 3959 // extract past the end of the source. 3960 int NewStartIdx = alignDown(Idx, MaskNumElts); 3961 if (NewStartIdx + MaskNumElts > SrcNumElts || 3962 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3963 CanExtract = false; 3964 // Make sure we always update StartIdx as we use it to track if all 3965 // elements are undef. 3966 StartIdx[Input] = NewStartIdx; 3967 } 3968 3969 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3970 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3971 return; 3972 } 3973 if (CanExtract) { 3974 // Extract appropriate subvector and generate a vector shuffle 3975 for (unsigned Input = 0; Input < 2; ++Input) { 3976 SDValue &Src = Input == 0 ? Src1 : Src2; 3977 if (StartIdx[Input] < 0) 3978 Src = DAG.getUNDEF(VT); 3979 else { 3980 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3981 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3982 } 3983 } 3984 3985 // Calculate new mask. 3986 SmallVector<int, 8> MappedOps(Mask); 3987 for (int &Idx : MappedOps) { 3988 if (Idx >= (int)SrcNumElts) 3989 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3990 else if (Idx >= 0) 3991 Idx -= StartIdx[0]; 3992 } 3993 3994 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3995 return; 3996 } 3997 } 3998 3999 // We can't use either concat vectors or extract subvectors so fall back to 4000 // replacing the shuffle with extract and build vector. 4001 // to insert and build vector. 4002 EVT EltVT = VT.getVectorElementType(); 4003 SmallVector<SDValue,8> Ops; 4004 for (int Idx : Mask) { 4005 SDValue Res; 4006 4007 if (Idx < 0) { 4008 Res = DAG.getUNDEF(EltVT); 4009 } else { 4010 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 4011 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 4012 4013 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 4014 DAG.getVectorIdxConstant(Idx, DL)); 4015 } 4016 4017 Ops.push_back(Res); 4018 } 4019 4020 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 4021 } 4022 4023 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 4024 ArrayRef<unsigned> Indices = I.getIndices(); 4025 const Value *Op0 = I.getOperand(0); 4026 const Value *Op1 = I.getOperand(1); 4027 Type *AggTy = I.getType(); 4028 Type *ValTy = Op1->getType(); 4029 bool IntoUndef = isa<UndefValue>(Op0); 4030 bool FromUndef = isa<UndefValue>(Op1); 4031 4032 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4033 4034 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4035 SmallVector<EVT, 4> AggValueVTs; 4036 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 4037 SmallVector<EVT, 4> ValValueVTs; 4038 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4039 4040 unsigned NumAggValues = AggValueVTs.size(); 4041 unsigned NumValValues = ValValueVTs.size(); 4042 SmallVector<SDValue, 4> Values(NumAggValues); 4043 4044 // Ignore an insertvalue that produces an empty object 4045 if (!NumAggValues) { 4046 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4047 return; 4048 } 4049 4050 SDValue Agg = getValue(Op0); 4051 unsigned i = 0; 4052 // Copy the beginning value(s) from the original aggregate. 4053 for (; i != LinearIndex; ++i) 4054 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4055 SDValue(Agg.getNode(), Agg.getResNo() + i); 4056 // Copy values from the inserted value(s). 4057 if (NumValValues) { 4058 SDValue Val = getValue(Op1); 4059 for (; i != LinearIndex + NumValValues; ++i) 4060 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4061 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 4062 } 4063 // Copy remaining value(s) from the original aggregate. 4064 for (; i != NumAggValues; ++i) 4065 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4066 SDValue(Agg.getNode(), Agg.getResNo() + i); 4067 4068 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4069 DAG.getVTList(AggValueVTs), Values)); 4070 } 4071 4072 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 4073 ArrayRef<unsigned> Indices = I.getIndices(); 4074 const Value *Op0 = I.getOperand(0); 4075 Type *AggTy = Op0->getType(); 4076 Type *ValTy = I.getType(); 4077 bool OutOfUndef = isa<UndefValue>(Op0); 4078 4079 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4080 4081 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4082 SmallVector<EVT, 4> ValValueVTs; 4083 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4084 4085 unsigned NumValValues = ValValueVTs.size(); 4086 4087 // Ignore a extractvalue that produces an empty object 4088 if (!NumValValues) { 4089 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4090 return; 4091 } 4092 4093 SmallVector<SDValue, 4> Values(NumValValues); 4094 4095 SDValue Agg = getValue(Op0); 4096 // Copy out the selected value(s). 4097 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 4098 Values[i - LinearIndex] = 4099 OutOfUndef ? 4100 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 4101 SDValue(Agg.getNode(), Agg.getResNo() + i); 4102 4103 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4104 DAG.getVTList(ValValueVTs), Values)); 4105 } 4106 4107 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 4108 Value *Op0 = I.getOperand(0); 4109 // Note that the pointer operand may be a vector of pointers. Take the scalar 4110 // element which holds a pointer. 4111 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 4112 SDValue N = getValue(Op0); 4113 SDLoc dl = getCurSDLoc(); 4114 auto &TLI = DAG.getTargetLoweringInfo(); 4115 4116 // Normalize Vector GEP - all scalar operands should be converted to the 4117 // splat vector. 4118 bool IsVectorGEP = I.getType()->isVectorTy(); 4119 ElementCount VectorElementCount = 4120 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 4121 : ElementCount::getFixed(0); 4122 4123 if (IsVectorGEP && !N.getValueType().isVector()) { 4124 LLVMContext &Context = *DAG.getContext(); 4125 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 4126 N = DAG.getSplat(VT, dl, N); 4127 } 4128 4129 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 4130 GTI != E; ++GTI) { 4131 const Value *Idx = GTI.getOperand(); 4132 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4133 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4134 if (Field) { 4135 // N = N + Offset 4136 uint64_t Offset = 4137 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4138 4139 // In an inbounds GEP with an offset that is nonnegative even when 4140 // interpreted as signed, assume there is no unsigned overflow. 4141 SDNodeFlags Flags; 4142 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 4143 Flags.setNoUnsignedWrap(true); 4144 4145 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4146 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4147 } 4148 } else { 4149 // IdxSize is the width of the arithmetic according to IR semantics. 4150 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4151 // (and fix up the result later). 4152 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4153 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4154 TypeSize ElementSize = 4155 GTI.getSequentialElementStride(DAG.getDataLayout()); 4156 // We intentionally mask away the high bits here; ElementSize may not 4157 // fit in IdxTy. 4158 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4159 bool ElementScalable = ElementSize.isScalable(); 4160 4161 // If this is a scalar constant or a splat vector of constants, 4162 // handle it quickly. 4163 const auto *C = dyn_cast<Constant>(Idx); 4164 if (C && isa<VectorType>(C->getType())) 4165 C = C->getSplatValue(); 4166 4167 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4168 if (CI && CI->isZero()) 4169 continue; 4170 if (CI && !ElementScalable) { 4171 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4172 LLVMContext &Context = *DAG.getContext(); 4173 SDValue OffsVal; 4174 if (IsVectorGEP) 4175 OffsVal = DAG.getConstant( 4176 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4177 else 4178 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4179 4180 // In an inbounds GEP with an offset that is nonnegative even when 4181 // interpreted as signed, assume there is no unsigned overflow. 4182 SDNodeFlags Flags; 4183 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4184 Flags.setNoUnsignedWrap(true); 4185 4186 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4187 4188 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4189 continue; 4190 } 4191 4192 // N = N + Idx * ElementMul; 4193 SDValue IdxN = getValue(Idx); 4194 4195 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4196 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4197 VectorElementCount); 4198 IdxN = DAG.getSplat(VT, dl, IdxN); 4199 } 4200 4201 // If the index is smaller or larger than intptr_t, truncate or extend 4202 // it. 4203 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4204 4205 if (ElementScalable) { 4206 EVT VScaleTy = N.getValueType().getScalarType(); 4207 SDValue VScale = DAG.getNode( 4208 ISD::VSCALE, dl, VScaleTy, 4209 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4210 if (IsVectorGEP) 4211 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4212 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4213 } else { 4214 // If this is a multiply by a power of two, turn it into a shl 4215 // immediately. This is a very common case. 4216 if (ElementMul != 1) { 4217 if (ElementMul.isPowerOf2()) { 4218 unsigned Amt = ElementMul.logBase2(); 4219 IdxN = DAG.getNode(ISD::SHL, dl, 4220 N.getValueType(), IdxN, 4221 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4222 } else { 4223 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4224 IdxN.getValueType()); 4225 IdxN = DAG.getNode(ISD::MUL, dl, 4226 N.getValueType(), IdxN, Scale); 4227 } 4228 } 4229 } 4230 4231 N = DAG.getNode(ISD::ADD, dl, 4232 N.getValueType(), N, IdxN); 4233 } 4234 } 4235 4236 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4237 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4238 if (IsVectorGEP) { 4239 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4240 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4241 } 4242 4243 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4244 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4245 4246 setValue(&I, N); 4247 } 4248 4249 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4250 // If this is a fixed sized alloca in the entry block of the function, 4251 // allocate it statically on the stack. 4252 if (FuncInfo.StaticAllocaMap.count(&I)) 4253 return; // getValue will auto-populate this. 4254 4255 SDLoc dl = getCurSDLoc(); 4256 Type *Ty = I.getAllocatedType(); 4257 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4258 auto &DL = DAG.getDataLayout(); 4259 TypeSize TySize = DL.getTypeAllocSize(Ty); 4260 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4261 4262 SDValue AllocSize = getValue(I.getArraySize()); 4263 4264 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace()); 4265 if (AllocSize.getValueType() != IntPtr) 4266 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4267 4268 if (TySize.isScalable()) 4269 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4270 DAG.getVScale(dl, IntPtr, 4271 APInt(IntPtr.getScalarSizeInBits(), 4272 TySize.getKnownMinValue()))); 4273 else { 4274 SDValue TySizeValue = 4275 DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64)); 4276 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4277 DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr)); 4278 } 4279 4280 // Handle alignment. If the requested alignment is less than or equal to 4281 // the stack alignment, ignore it. If the size is greater than or equal to 4282 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4283 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4284 if (*Alignment <= StackAlign) 4285 Alignment = std::nullopt; 4286 4287 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4288 // Round the size of the allocation up to the stack alignment size 4289 // by add SA-1 to the size. This doesn't overflow because we're computing 4290 // an address inside an alloca. 4291 SDNodeFlags Flags; 4292 Flags.setNoUnsignedWrap(true); 4293 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4294 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4295 4296 // Mask out the low bits for alignment purposes. 4297 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4298 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4299 4300 SDValue Ops[] = { 4301 getRoot(), AllocSize, 4302 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4303 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4304 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4305 setValue(&I, DSA); 4306 DAG.setRoot(DSA.getValue(1)); 4307 4308 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4309 } 4310 4311 static const MDNode *getRangeMetadata(const Instruction &I) { 4312 // If !noundef is not present, then !range violation results in a poison 4313 // value rather than immediate undefined behavior. In theory, transferring 4314 // these annotations to SDAG is fine, but in practice there are key SDAG 4315 // transforms that are known not to be poison-safe, such as folding logical 4316 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4317 // also present. 4318 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4319 return nullptr; 4320 return I.getMetadata(LLVMContext::MD_range); 4321 } 4322 4323 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4324 if (I.isAtomic()) 4325 return visitAtomicLoad(I); 4326 4327 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4328 const Value *SV = I.getOperand(0); 4329 if (TLI.supportSwiftError()) { 4330 // Swifterror values can come from either a function parameter with 4331 // swifterror attribute or an alloca with swifterror attribute. 4332 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4333 if (Arg->hasSwiftErrorAttr()) 4334 return visitLoadFromSwiftError(I); 4335 } 4336 4337 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4338 if (Alloca->isSwiftError()) 4339 return visitLoadFromSwiftError(I); 4340 } 4341 } 4342 4343 SDValue Ptr = getValue(SV); 4344 4345 Type *Ty = I.getType(); 4346 SmallVector<EVT, 4> ValueVTs, MemVTs; 4347 SmallVector<TypeSize, 4> Offsets; 4348 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4349 unsigned NumValues = ValueVTs.size(); 4350 if (NumValues == 0) 4351 return; 4352 4353 Align Alignment = I.getAlign(); 4354 AAMDNodes AAInfo = I.getAAMetadata(); 4355 const MDNode *Ranges = getRangeMetadata(I); 4356 bool isVolatile = I.isVolatile(); 4357 MachineMemOperand::Flags MMOFlags = 4358 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4359 4360 SDValue Root; 4361 bool ConstantMemory = false; 4362 if (isVolatile) 4363 // Serialize volatile loads with other side effects. 4364 Root = getRoot(); 4365 else if (NumValues > MaxParallelChains) 4366 Root = getMemoryRoot(); 4367 else if (AA && 4368 AA->pointsToConstantMemory(MemoryLocation( 4369 SV, 4370 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4371 AAInfo))) { 4372 // Do not serialize (non-volatile) loads of constant memory with anything. 4373 Root = DAG.getEntryNode(); 4374 ConstantMemory = true; 4375 MMOFlags |= MachineMemOperand::MOInvariant; 4376 } else { 4377 // Do not serialize non-volatile loads against each other. 4378 Root = DAG.getRoot(); 4379 } 4380 4381 SDLoc dl = getCurSDLoc(); 4382 4383 if (isVolatile) 4384 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4385 4386 SmallVector<SDValue, 4> Values(NumValues); 4387 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4388 4389 unsigned ChainI = 0; 4390 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4391 // Serializing loads here may result in excessive register pressure, and 4392 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4393 // could recover a bit by hoisting nodes upward in the chain by recognizing 4394 // they are side-effect free or do not alias. The optimizer should really 4395 // avoid this case by converting large object/array copies to llvm.memcpy 4396 // (MaxParallelChains should always remain as failsafe). 4397 if (ChainI == MaxParallelChains) { 4398 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4399 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4400 ArrayRef(Chains.data(), ChainI)); 4401 Root = Chain; 4402 ChainI = 0; 4403 } 4404 4405 // TODO: MachinePointerInfo only supports a fixed length offset. 4406 MachinePointerInfo PtrInfo = 4407 !Offsets[i].isScalable() || Offsets[i].isZero() 4408 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4409 : MachinePointerInfo(); 4410 4411 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4412 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4413 MMOFlags, AAInfo, Ranges); 4414 Chains[ChainI] = L.getValue(1); 4415 4416 if (MemVTs[i] != ValueVTs[i]) 4417 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4418 4419 Values[i] = L; 4420 } 4421 4422 if (!ConstantMemory) { 4423 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4424 ArrayRef(Chains.data(), ChainI)); 4425 if (isVolatile) 4426 DAG.setRoot(Chain); 4427 else 4428 PendingLoads.push_back(Chain); 4429 } 4430 4431 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4432 DAG.getVTList(ValueVTs), Values)); 4433 } 4434 4435 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4436 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4437 "call visitStoreToSwiftError when backend supports swifterror"); 4438 4439 SmallVector<EVT, 4> ValueVTs; 4440 SmallVector<uint64_t, 4> Offsets; 4441 const Value *SrcV = I.getOperand(0); 4442 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4443 SrcV->getType(), ValueVTs, &Offsets, 0); 4444 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4445 "expect a single EVT for swifterror"); 4446 4447 SDValue Src = getValue(SrcV); 4448 // Create a virtual register, then update the virtual register. 4449 Register VReg = 4450 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4451 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4452 // Chain can be getRoot or getControlRoot. 4453 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4454 SDValue(Src.getNode(), Src.getResNo())); 4455 DAG.setRoot(CopyNode); 4456 } 4457 4458 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4459 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4460 "call visitLoadFromSwiftError when backend supports swifterror"); 4461 4462 assert(!I.isVolatile() && 4463 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4464 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4465 "Support volatile, non temporal, invariant for load_from_swift_error"); 4466 4467 const Value *SV = I.getOperand(0); 4468 Type *Ty = I.getType(); 4469 assert( 4470 (!AA || 4471 !AA->pointsToConstantMemory(MemoryLocation( 4472 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4473 I.getAAMetadata()))) && 4474 "load_from_swift_error should not be constant memory"); 4475 4476 SmallVector<EVT, 4> ValueVTs; 4477 SmallVector<uint64_t, 4> Offsets; 4478 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4479 ValueVTs, &Offsets, 0); 4480 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4481 "expect a single EVT for swifterror"); 4482 4483 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4484 SDValue L = DAG.getCopyFromReg( 4485 getRoot(), getCurSDLoc(), 4486 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4487 4488 setValue(&I, L); 4489 } 4490 4491 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4492 if (I.isAtomic()) 4493 return visitAtomicStore(I); 4494 4495 const Value *SrcV = I.getOperand(0); 4496 const Value *PtrV = I.getOperand(1); 4497 4498 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4499 if (TLI.supportSwiftError()) { 4500 // Swifterror values can come from either a function parameter with 4501 // swifterror attribute or an alloca with swifterror attribute. 4502 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4503 if (Arg->hasSwiftErrorAttr()) 4504 return visitStoreToSwiftError(I); 4505 } 4506 4507 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4508 if (Alloca->isSwiftError()) 4509 return visitStoreToSwiftError(I); 4510 } 4511 } 4512 4513 SmallVector<EVT, 4> ValueVTs, MemVTs; 4514 SmallVector<TypeSize, 4> Offsets; 4515 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4516 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4517 unsigned NumValues = ValueVTs.size(); 4518 if (NumValues == 0) 4519 return; 4520 4521 // Get the lowered operands. Note that we do this after 4522 // checking if NumResults is zero, because with zero results 4523 // the operands won't have values in the map. 4524 SDValue Src = getValue(SrcV); 4525 SDValue Ptr = getValue(PtrV); 4526 4527 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4528 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4529 SDLoc dl = getCurSDLoc(); 4530 Align Alignment = I.getAlign(); 4531 AAMDNodes AAInfo = I.getAAMetadata(); 4532 4533 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4534 4535 unsigned ChainI = 0; 4536 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4537 // See visitLoad comments. 4538 if (ChainI == MaxParallelChains) { 4539 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4540 ArrayRef(Chains.data(), ChainI)); 4541 Root = Chain; 4542 ChainI = 0; 4543 } 4544 4545 // TODO: MachinePointerInfo only supports a fixed length offset. 4546 MachinePointerInfo PtrInfo = 4547 !Offsets[i].isScalable() || Offsets[i].isZero() 4548 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4549 : MachinePointerInfo(); 4550 4551 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4552 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4553 if (MemVTs[i] != ValueVTs[i]) 4554 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4555 SDValue St = 4556 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4557 Chains[ChainI] = St; 4558 } 4559 4560 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4561 ArrayRef(Chains.data(), ChainI)); 4562 setValue(&I, StoreNode); 4563 DAG.setRoot(StoreNode); 4564 } 4565 4566 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4567 bool IsCompressing) { 4568 SDLoc sdl = getCurSDLoc(); 4569 4570 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4571 MaybeAlign &Alignment) { 4572 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4573 Src0 = I.getArgOperand(0); 4574 Ptr = I.getArgOperand(1); 4575 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4576 Mask = I.getArgOperand(3); 4577 }; 4578 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4579 MaybeAlign &Alignment) { 4580 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4581 Src0 = I.getArgOperand(0); 4582 Ptr = I.getArgOperand(1); 4583 Mask = I.getArgOperand(2); 4584 Alignment = std::nullopt; 4585 }; 4586 4587 Value *PtrOperand, *MaskOperand, *Src0Operand; 4588 MaybeAlign Alignment; 4589 if (IsCompressing) 4590 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4591 else 4592 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4593 4594 SDValue Ptr = getValue(PtrOperand); 4595 SDValue Src0 = getValue(Src0Operand); 4596 SDValue Mask = getValue(MaskOperand); 4597 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4598 4599 EVT VT = Src0.getValueType(); 4600 if (!Alignment) 4601 Alignment = DAG.getEVTAlign(VT); 4602 4603 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4604 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4605 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4606 SDValue StoreNode = 4607 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4608 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4609 DAG.setRoot(StoreNode); 4610 setValue(&I, StoreNode); 4611 } 4612 4613 // Get a uniform base for the Gather/Scatter intrinsic. 4614 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4615 // We try to represent it as a base pointer + vector of indices. 4616 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4617 // The first operand of the GEP may be a single pointer or a vector of pointers 4618 // Example: 4619 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4620 // or 4621 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4622 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4623 // 4624 // When the first GEP operand is a single pointer - it is the uniform base we 4625 // are looking for. If first operand of the GEP is a splat vector - we 4626 // extract the splat value and use it as a uniform base. 4627 // In all other cases the function returns 'false'. 4628 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4629 ISD::MemIndexType &IndexType, SDValue &Scale, 4630 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4631 uint64_t ElemSize) { 4632 SelectionDAG& DAG = SDB->DAG; 4633 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4634 const DataLayout &DL = DAG.getDataLayout(); 4635 4636 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4637 4638 // Handle splat constant pointer. 4639 if (auto *C = dyn_cast<Constant>(Ptr)) { 4640 C = C->getSplatValue(); 4641 if (!C) 4642 return false; 4643 4644 Base = SDB->getValue(C); 4645 4646 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4647 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4648 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4649 IndexType = ISD::SIGNED_SCALED; 4650 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4651 return true; 4652 } 4653 4654 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4655 if (!GEP || GEP->getParent() != CurBB) 4656 return false; 4657 4658 if (GEP->getNumOperands() != 2) 4659 return false; 4660 4661 const Value *BasePtr = GEP->getPointerOperand(); 4662 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4663 4664 // Make sure the base is scalar and the index is a vector. 4665 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4666 return false; 4667 4668 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4669 if (ScaleVal.isScalable()) 4670 return false; 4671 4672 // Target may not support the required addressing mode. 4673 if (ScaleVal != 1 && 4674 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4675 return false; 4676 4677 Base = SDB->getValue(BasePtr); 4678 Index = SDB->getValue(IndexVal); 4679 IndexType = ISD::SIGNED_SCALED; 4680 4681 Scale = 4682 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4683 return true; 4684 } 4685 4686 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4687 SDLoc sdl = getCurSDLoc(); 4688 4689 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4690 const Value *Ptr = I.getArgOperand(1); 4691 SDValue Src0 = getValue(I.getArgOperand(0)); 4692 SDValue Mask = getValue(I.getArgOperand(3)); 4693 EVT VT = Src0.getValueType(); 4694 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4695 ->getMaybeAlignValue() 4696 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4697 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4698 4699 SDValue Base; 4700 SDValue Index; 4701 ISD::MemIndexType IndexType; 4702 SDValue Scale; 4703 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4704 I.getParent(), VT.getScalarStoreSize()); 4705 4706 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4707 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4708 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4709 // TODO: Make MachineMemOperands aware of scalable 4710 // vectors. 4711 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4712 if (!UniformBase) { 4713 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4714 Index = getValue(Ptr); 4715 IndexType = ISD::SIGNED_SCALED; 4716 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4717 } 4718 4719 EVT IdxVT = Index.getValueType(); 4720 EVT EltTy = IdxVT.getVectorElementType(); 4721 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4722 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4723 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4724 } 4725 4726 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4727 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4728 Ops, MMO, IndexType, false); 4729 DAG.setRoot(Scatter); 4730 setValue(&I, Scatter); 4731 } 4732 4733 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4734 SDLoc sdl = getCurSDLoc(); 4735 4736 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4737 MaybeAlign &Alignment) { 4738 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4739 Ptr = I.getArgOperand(0); 4740 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4741 Mask = I.getArgOperand(2); 4742 Src0 = I.getArgOperand(3); 4743 }; 4744 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4745 MaybeAlign &Alignment) { 4746 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4747 Ptr = I.getArgOperand(0); 4748 Alignment = std::nullopt; 4749 Mask = I.getArgOperand(1); 4750 Src0 = I.getArgOperand(2); 4751 }; 4752 4753 Value *PtrOperand, *MaskOperand, *Src0Operand; 4754 MaybeAlign Alignment; 4755 if (IsExpanding) 4756 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4757 else 4758 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4759 4760 SDValue Ptr = getValue(PtrOperand); 4761 SDValue Src0 = getValue(Src0Operand); 4762 SDValue Mask = getValue(MaskOperand); 4763 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4764 4765 EVT VT = Src0.getValueType(); 4766 if (!Alignment) 4767 Alignment = DAG.getEVTAlign(VT); 4768 4769 AAMDNodes AAInfo = I.getAAMetadata(); 4770 const MDNode *Ranges = getRangeMetadata(I); 4771 4772 // Do not serialize masked loads of constant memory with anything. 4773 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4774 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4775 4776 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4777 4778 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4779 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4780 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4781 4782 SDValue Load = 4783 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4784 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4785 if (AddToChain) 4786 PendingLoads.push_back(Load.getValue(1)); 4787 setValue(&I, Load); 4788 } 4789 4790 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4791 SDLoc sdl = getCurSDLoc(); 4792 4793 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4794 const Value *Ptr = I.getArgOperand(0); 4795 SDValue Src0 = getValue(I.getArgOperand(3)); 4796 SDValue Mask = getValue(I.getArgOperand(2)); 4797 4798 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4799 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4800 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4801 ->getMaybeAlignValue() 4802 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4803 4804 const MDNode *Ranges = getRangeMetadata(I); 4805 4806 SDValue Root = DAG.getRoot(); 4807 SDValue Base; 4808 SDValue Index; 4809 ISD::MemIndexType IndexType; 4810 SDValue Scale; 4811 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4812 I.getParent(), VT.getScalarStoreSize()); 4813 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4814 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4815 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4816 // TODO: Make MachineMemOperands aware of scalable 4817 // vectors. 4818 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4819 4820 if (!UniformBase) { 4821 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4822 Index = getValue(Ptr); 4823 IndexType = ISD::SIGNED_SCALED; 4824 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4825 } 4826 4827 EVT IdxVT = Index.getValueType(); 4828 EVT EltTy = IdxVT.getVectorElementType(); 4829 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4830 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4831 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4832 } 4833 4834 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4835 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4836 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4837 4838 PendingLoads.push_back(Gather.getValue(1)); 4839 setValue(&I, Gather); 4840 } 4841 4842 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4843 SDLoc dl = getCurSDLoc(); 4844 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4845 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4846 SyncScope::ID SSID = I.getSyncScopeID(); 4847 4848 SDValue InChain = getRoot(); 4849 4850 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4851 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4852 4853 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4854 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4855 4856 MachineFunction &MF = DAG.getMachineFunction(); 4857 MachineMemOperand *MMO = MF.getMachineMemOperand( 4858 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4859 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4860 FailureOrdering); 4861 4862 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4863 dl, MemVT, VTs, InChain, 4864 getValue(I.getPointerOperand()), 4865 getValue(I.getCompareOperand()), 4866 getValue(I.getNewValOperand()), MMO); 4867 4868 SDValue OutChain = L.getValue(2); 4869 4870 setValue(&I, L); 4871 DAG.setRoot(OutChain); 4872 } 4873 4874 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4875 SDLoc dl = getCurSDLoc(); 4876 ISD::NodeType NT; 4877 switch (I.getOperation()) { 4878 default: llvm_unreachable("Unknown atomicrmw operation"); 4879 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4880 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4881 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4882 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4883 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4884 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4885 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4886 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4887 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4888 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4889 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4890 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4891 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4892 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4893 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4894 case AtomicRMWInst::UIncWrap: 4895 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4896 break; 4897 case AtomicRMWInst::UDecWrap: 4898 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4899 break; 4900 } 4901 AtomicOrdering Ordering = I.getOrdering(); 4902 SyncScope::ID SSID = I.getSyncScopeID(); 4903 4904 SDValue InChain = getRoot(); 4905 4906 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4907 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4908 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4909 4910 MachineFunction &MF = DAG.getMachineFunction(); 4911 MachineMemOperand *MMO = MF.getMachineMemOperand( 4912 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4913 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4914 4915 SDValue L = 4916 DAG.getAtomic(NT, dl, MemVT, InChain, 4917 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4918 MMO); 4919 4920 SDValue OutChain = L.getValue(1); 4921 4922 setValue(&I, L); 4923 DAG.setRoot(OutChain); 4924 } 4925 4926 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4927 SDLoc dl = getCurSDLoc(); 4928 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4929 SDValue Ops[3]; 4930 Ops[0] = getRoot(); 4931 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4932 TLI.getFenceOperandTy(DAG.getDataLayout())); 4933 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4934 TLI.getFenceOperandTy(DAG.getDataLayout())); 4935 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4936 setValue(&I, N); 4937 DAG.setRoot(N); 4938 } 4939 4940 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4941 SDLoc dl = getCurSDLoc(); 4942 AtomicOrdering Order = I.getOrdering(); 4943 SyncScope::ID SSID = I.getSyncScopeID(); 4944 4945 SDValue InChain = getRoot(); 4946 4947 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4948 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4949 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4950 4951 if (!TLI.supportsUnalignedAtomics() && 4952 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4953 report_fatal_error("Cannot generate unaligned atomic load"); 4954 4955 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4956 4957 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4958 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4959 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4960 4961 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4962 4963 SDValue Ptr = getValue(I.getPointerOperand()); 4964 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4965 Ptr, MMO); 4966 4967 SDValue OutChain = L.getValue(1); 4968 if (MemVT != VT) 4969 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4970 4971 setValue(&I, L); 4972 DAG.setRoot(OutChain); 4973 } 4974 4975 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4976 SDLoc dl = getCurSDLoc(); 4977 4978 AtomicOrdering Ordering = I.getOrdering(); 4979 SyncScope::ID SSID = I.getSyncScopeID(); 4980 4981 SDValue InChain = getRoot(); 4982 4983 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4984 EVT MemVT = 4985 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4986 4987 if (!TLI.supportsUnalignedAtomics() && 4988 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4989 report_fatal_error("Cannot generate unaligned atomic store"); 4990 4991 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4992 4993 MachineFunction &MF = DAG.getMachineFunction(); 4994 MachineMemOperand *MMO = MF.getMachineMemOperand( 4995 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4996 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4997 4998 SDValue Val = getValue(I.getValueOperand()); 4999 if (Val.getValueType() != MemVT) 5000 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 5001 SDValue Ptr = getValue(I.getPointerOperand()); 5002 5003 SDValue OutChain = 5004 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 5005 5006 setValue(&I, OutChain); 5007 DAG.setRoot(OutChain); 5008 } 5009 5010 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 5011 /// node. 5012 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 5013 unsigned Intrinsic) { 5014 // Ignore the callsite's attributes. A specific call site may be marked with 5015 // readnone, but the lowering code will expect the chain based on the 5016 // definition. 5017 const Function *F = I.getCalledFunction(); 5018 bool HasChain = !F->doesNotAccessMemory(); 5019 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 5020 5021 // Build the operand list. 5022 SmallVector<SDValue, 8> Ops; 5023 if (HasChain) { // If this intrinsic has side-effects, chainify it. 5024 if (OnlyLoad) { 5025 // We don't need to serialize loads against other loads. 5026 Ops.push_back(DAG.getRoot()); 5027 } else { 5028 Ops.push_back(getRoot()); 5029 } 5030 } 5031 5032 // Info is set by getTgtMemIntrinsic 5033 TargetLowering::IntrinsicInfo Info; 5034 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5035 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 5036 DAG.getMachineFunction(), 5037 Intrinsic); 5038 5039 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 5040 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 5041 Info.opc == ISD::INTRINSIC_W_CHAIN) 5042 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 5043 TLI.getPointerTy(DAG.getDataLayout()))); 5044 5045 // Add all operands of the call to the operand list. 5046 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 5047 const Value *Arg = I.getArgOperand(i); 5048 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 5049 Ops.push_back(getValue(Arg)); 5050 continue; 5051 } 5052 5053 // Use TargetConstant instead of a regular constant for immarg. 5054 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 5055 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 5056 assert(CI->getBitWidth() <= 64 && 5057 "large intrinsic immediates not handled"); 5058 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 5059 } else { 5060 Ops.push_back( 5061 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 5062 } 5063 } 5064 5065 SmallVector<EVT, 4> ValueVTs; 5066 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 5067 5068 if (HasChain) 5069 ValueVTs.push_back(MVT::Other); 5070 5071 SDVTList VTs = DAG.getVTList(ValueVTs); 5072 5073 // Propagate fast-math-flags from IR to node(s). 5074 SDNodeFlags Flags; 5075 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 5076 Flags.copyFMF(*FPMO); 5077 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 5078 5079 // Create the node. 5080 SDValue Result; 5081 5082 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) { 5083 auto *Token = Bundle->Inputs[0].get(); 5084 SDValue ConvControlToken = getValue(Token); 5085 assert(Ops.back().getValueType() != MVT::Glue && 5086 "Did not expected another glue node here."); 5087 ConvControlToken = 5088 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken); 5089 Ops.push_back(ConvControlToken); 5090 } 5091 5092 // In some cases, custom collection of operands from CallInst I may be needed. 5093 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 5094 if (IsTgtIntrinsic) { 5095 // This is target intrinsic that touches memory 5096 // 5097 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 5098 // didn't yield anything useful. 5099 MachinePointerInfo MPI; 5100 if (Info.ptrVal) 5101 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 5102 else if (Info.fallbackAddressSpace) 5103 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 5104 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 5105 Info.memVT, MPI, Info.align, Info.flags, 5106 Info.size, I.getAAMetadata()); 5107 } else if (!HasChain) { 5108 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 5109 } else if (!I.getType()->isVoidTy()) { 5110 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 5111 } else { 5112 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 5113 } 5114 5115 if (HasChain) { 5116 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 5117 if (OnlyLoad) 5118 PendingLoads.push_back(Chain); 5119 else 5120 DAG.setRoot(Chain); 5121 } 5122 5123 if (!I.getType()->isVoidTy()) { 5124 if (!isa<VectorType>(I.getType())) 5125 Result = lowerRangeToAssertZExt(DAG, I, Result); 5126 5127 MaybeAlign Alignment = I.getRetAlign(); 5128 5129 // Insert `assertalign` node if there's an alignment. 5130 if (InsertAssertAlign && Alignment) { 5131 Result = 5132 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5133 } 5134 5135 setValue(&I, Result); 5136 } 5137 } 5138 5139 /// GetSignificand - Get the significand and build it into a floating-point 5140 /// number with exponent of 1: 5141 /// 5142 /// Op = (Op & 0x007fffff) | 0x3f800000; 5143 /// 5144 /// where Op is the hexadecimal representation of floating point value. 5145 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5146 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5147 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5148 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5149 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5150 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5151 } 5152 5153 /// GetExponent - Get the exponent: 5154 /// 5155 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5156 /// 5157 /// where Op is the hexadecimal representation of floating point value. 5158 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5159 const TargetLowering &TLI, const SDLoc &dl) { 5160 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5161 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5162 SDValue t1 = DAG.getNode( 5163 ISD::SRL, dl, MVT::i32, t0, 5164 DAG.getConstant(23, dl, 5165 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5166 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5167 DAG.getConstant(127, dl, MVT::i32)); 5168 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5169 } 5170 5171 /// getF32Constant - Get 32-bit floating point constant. 5172 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5173 const SDLoc &dl) { 5174 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5175 MVT::f32); 5176 } 5177 5178 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5179 SelectionDAG &DAG) { 5180 // TODO: What fast-math-flags should be set on the floating-point nodes? 5181 5182 // IntegerPartOfX = ((int32_t)(t0); 5183 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5184 5185 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5186 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5187 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5188 5189 // IntegerPartOfX <<= 23; 5190 IntegerPartOfX = 5191 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5192 DAG.getConstant(23, dl, 5193 DAG.getTargetLoweringInfo().getShiftAmountTy( 5194 MVT::i32, DAG.getDataLayout()))); 5195 5196 SDValue TwoToFractionalPartOfX; 5197 if (LimitFloatPrecision <= 6) { 5198 // For floating-point precision of 6: 5199 // 5200 // TwoToFractionalPartOfX = 5201 // 0.997535578f + 5202 // (0.735607626f + 0.252464424f * x) * x; 5203 // 5204 // error 0.0144103317, which is 6 bits 5205 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5206 getF32Constant(DAG, 0x3e814304, dl)); 5207 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5208 getF32Constant(DAG, 0x3f3c50c8, dl)); 5209 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5210 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5211 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5212 } else if (LimitFloatPrecision <= 12) { 5213 // For floating-point precision of 12: 5214 // 5215 // TwoToFractionalPartOfX = 5216 // 0.999892986f + 5217 // (0.696457318f + 5218 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5219 // 5220 // error 0.000107046256, which is 13 to 14 bits 5221 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5222 getF32Constant(DAG, 0x3da235e3, dl)); 5223 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5224 getF32Constant(DAG, 0x3e65b8f3, dl)); 5225 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5226 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5227 getF32Constant(DAG, 0x3f324b07, dl)); 5228 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5229 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5230 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5231 } else { // LimitFloatPrecision <= 18 5232 // For floating-point precision of 18: 5233 // 5234 // TwoToFractionalPartOfX = 5235 // 0.999999982f + 5236 // (0.693148872f + 5237 // (0.240227044f + 5238 // (0.554906021e-1f + 5239 // (0.961591928e-2f + 5240 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5241 // error 2.47208000*10^(-7), which is better than 18 bits 5242 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5243 getF32Constant(DAG, 0x3924b03e, dl)); 5244 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5245 getF32Constant(DAG, 0x3ab24b87, dl)); 5246 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5247 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5248 getF32Constant(DAG, 0x3c1d8c17, dl)); 5249 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5250 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5251 getF32Constant(DAG, 0x3d634a1d, dl)); 5252 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5253 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5254 getF32Constant(DAG, 0x3e75fe14, dl)); 5255 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5256 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5257 getF32Constant(DAG, 0x3f317234, dl)); 5258 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5259 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5260 getF32Constant(DAG, 0x3f800000, dl)); 5261 } 5262 5263 // Add the exponent into the result in integer domain. 5264 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5265 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5266 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5267 } 5268 5269 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5270 /// limited-precision mode. 5271 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5272 const TargetLowering &TLI, SDNodeFlags Flags) { 5273 if (Op.getValueType() == MVT::f32 && 5274 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5275 5276 // Put the exponent in the right bit position for later addition to the 5277 // final result: 5278 // 5279 // t0 = Op * log2(e) 5280 5281 // TODO: What fast-math-flags should be set here? 5282 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5283 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5284 return getLimitedPrecisionExp2(t0, dl, DAG); 5285 } 5286 5287 // No special expansion. 5288 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5289 } 5290 5291 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5292 /// limited-precision mode. 5293 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5294 const TargetLowering &TLI, SDNodeFlags Flags) { 5295 // TODO: What fast-math-flags should be set on the floating-point nodes? 5296 5297 if (Op.getValueType() == MVT::f32 && 5298 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5299 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5300 5301 // Scale the exponent by log(2). 5302 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5303 SDValue LogOfExponent = 5304 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5305 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5306 5307 // Get the significand and build it into a floating-point number with 5308 // exponent of 1. 5309 SDValue X = GetSignificand(DAG, Op1, dl); 5310 5311 SDValue LogOfMantissa; 5312 if (LimitFloatPrecision <= 6) { 5313 // For floating-point precision of 6: 5314 // 5315 // LogofMantissa = 5316 // -1.1609546f + 5317 // (1.4034025f - 0.23903021f * x) * x; 5318 // 5319 // error 0.0034276066, which is better than 8 bits 5320 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5321 getF32Constant(DAG, 0xbe74c456, dl)); 5322 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5323 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5324 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5325 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5326 getF32Constant(DAG, 0x3f949a29, dl)); 5327 } else if (LimitFloatPrecision <= 12) { 5328 // For floating-point precision of 12: 5329 // 5330 // LogOfMantissa = 5331 // -1.7417939f + 5332 // (2.8212026f + 5333 // (-1.4699568f + 5334 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5335 // 5336 // error 0.000061011436, which is 14 bits 5337 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5338 getF32Constant(DAG, 0xbd67b6d6, dl)); 5339 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5340 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5341 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5342 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5343 getF32Constant(DAG, 0x3fbc278b, dl)); 5344 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5345 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5346 getF32Constant(DAG, 0x40348e95, dl)); 5347 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5348 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5349 getF32Constant(DAG, 0x3fdef31a, dl)); 5350 } else { // LimitFloatPrecision <= 18 5351 // For floating-point precision of 18: 5352 // 5353 // LogOfMantissa = 5354 // -2.1072184f + 5355 // (4.2372794f + 5356 // (-3.7029485f + 5357 // (2.2781945f + 5358 // (-0.87823314f + 5359 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5360 // 5361 // error 0.0000023660568, which is better than 18 bits 5362 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5363 getF32Constant(DAG, 0xbc91e5ac, dl)); 5364 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5365 getF32Constant(DAG, 0x3e4350aa, dl)); 5366 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5367 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5368 getF32Constant(DAG, 0x3f60d3e3, dl)); 5369 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5370 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5371 getF32Constant(DAG, 0x4011cdf0, dl)); 5372 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5373 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5374 getF32Constant(DAG, 0x406cfd1c, dl)); 5375 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5376 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5377 getF32Constant(DAG, 0x408797cb, dl)); 5378 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5379 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5380 getF32Constant(DAG, 0x4006dcab, dl)); 5381 } 5382 5383 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5384 } 5385 5386 // No special expansion. 5387 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5388 } 5389 5390 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5391 /// limited-precision mode. 5392 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5393 const TargetLowering &TLI, SDNodeFlags Flags) { 5394 // TODO: What fast-math-flags should be set on the floating-point nodes? 5395 5396 if (Op.getValueType() == MVT::f32 && 5397 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5398 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5399 5400 // Get the exponent. 5401 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5402 5403 // Get the significand and build it into a floating-point number with 5404 // exponent of 1. 5405 SDValue X = GetSignificand(DAG, Op1, dl); 5406 5407 // Different possible minimax approximations of significand in 5408 // floating-point for various degrees of accuracy over [1,2]. 5409 SDValue Log2ofMantissa; 5410 if (LimitFloatPrecision <= 6) { 5411 // For floating-point precision of 6: 5412 // 5413 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5414 // 5415 // error 0.0049451742, which is more than 7 bits 5416 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5417 getF32Constant(DAG, 0xbeb08fe0, dl)); 5418 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5419 getF32Constant(DAG, 0x40019463, dl)); 5420 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5421 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5422 getF32Constant(DAG, 0x3fd6633d, dl)); 5423 } else if (LimitFloatPrecision <= 12) { 5424 // For floating-point precision of 12: 5425 // 5426 // Log2ofMantissa = 5427 // -2.51285454f + 5428 // (4.07009056f + 5429 // (-2.12067489f + 5430 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5431 // 5432 // error 0.0000876136000, which is better than 13 bits 5433 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5434 getF32Constant(DAG, 0xbda7262e, dl)); 5435 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5436 getF32Constant(DAG, 0x3f25280b, dl)); 5437 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5438 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5439 getF32Constant(DAG, 0x4007b923, dl)); 5440 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5441 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5442 getF32Constant(DAG, 0x40823e2f, dl)); 5443 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5444 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5445 getF32Constant(DAG, 0x4020d29c, dl)); 5446 } else { // LimitFloatPrecision <= 18 5447 // For floating-point precision of 18: 5448 // 5449 // Log2ofMantissa = 5450 // -3.0400495f + 5451 // (6.1129976f + 5452 // (-5.3420409f + 5453 // (3.2865683f + 5454 // (-1.2669343f + 5455 // (0.27515199f - 5456 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5457 // 5458 // error 0.0000018516, which is better than 18 bits 5459 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5460 getF32Constant(DAG, 0xbcd2769e, dl)); 5461 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5462 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5463 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5464 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5465 getF32Constant(DAG, 0x3fa22ae7, dl)); 5466 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5467 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5468 getF32Constant(DAG, 0x40525723, dl)); 5469 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5470 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5471 getF32Constant(DAG, 0x40aaf200, dl)); 5472 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5473 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5474 getF32Constant(DAG, 0x40c39dad, dl)); 5475 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5476 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5477 getF32Constant(DAG, 0x4042902c, dl)); 5478 } 5479 5480 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5481 } 5482 5483 // No special expansion. 5484 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5485 } 5486 5487 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5488 /// limited-precision mode. 5489 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5490 const TargetLowering &TLI, SDNodeFlags Flags) { 5491 // TODO: What fast-math-flags should be set on the floating-point nodes? 5492 5493 if (Op.getValueType() == MVT::f32 && 5494 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5495 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5496 5497 // Scale the exponent by log10(2) [0.30102999f]. 5498 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5499 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5500 getF32Constant(DAG, 0x3e9a209a, dl)); 5501 5502 // Get the significand and build it into a floating-point number with 5503 // exponent of 1. 5504 SDValue X = GetSignificand(DAG, Op1, dl); 5505 5506 SDValue Log10ofMantissa; 5507 if (LimitFloatPrecision <= 6) { 5508 // For floating-point precision of 6: 5509 // 5510 // Log10ofMantissa = 5511 // -0.50419619f + 5512 // (0.60948995f - 0.10380950f * x) * x; 5513 // 5514 // error 0.0014886165, which is 6 bits 5515 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5516 getF32Constant(DAG, 0xbdd49a13, dl)); 5517 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5518 getF32Constant(DAG, 0x3f1c0789, dl)); 5519 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5520 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5521 getF32Constant(DAG, 0x3f011300, dl)); 5522 } else if (LimitFloatPrecision <= 12) { 5523 // For floating-point precision of 12: 5524 // 5525 // Log10ofMantissa = 5526 // -0.64831180f + 5527 // (0.91751397f + 5528 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5529 // 5530 // error 0.00019228036, which is better than 12 bits 5531 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5532 getF32Constant(DAG, 0x3d431f31, dl)); 5533 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5534 getF32Constant(DAG, 0x3ea21fb2, dl)); 5535 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5536 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5537 getF32Constant(DAG, 0x3f6ae232, dl)); 5538 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5539 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5540 getF32Constant(DAG, 0x3f25f7c3, dl)); 5541 } else { // LimitFloatPrecision <= 18 5542 // For floating-point precision of 18: 5543 // 5544 // Log10ofMantissa = 5545 // -0.84299375f + 5546 // (1.5327582f + 5547 // (-1.0688956f + 5548 // (0.49102474f + 5549 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5550 // 5551 // error 0.0000037995730, which is better than 18 bits 5552 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5553 getF32Constant(DAG, 0x3c5d51ce, dl)); 5554 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5555 getF32Constant(DAG, 0x3e00685a, dl)); 5556 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5557 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5558 getF32Constant(DAG, 0x3efb6798, dl)); 5559 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5560 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5561 getF32Constant(DAG, 0x3f88d192, dl)); 5562 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5563 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5564 getF32Constant(DAG, 0x3fc4316c, dl)); 5565 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5566 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5567 getF32Constant(DAG, 0x3f57ce70, dl)); 5568 } 5569 5570 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5571 } 5572 5573 // No special expansion. 5574 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5575 } 5576 5577 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5578 /// limited-precision mode. 5579 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5580 const TargetLowering &TLI, SDNodeFlags Flags) { 5581 if (Op.getValueType() == MVT::f32 && 5582 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5583 return getLimitedPrecisionExp2(Op, dl, DAG); 5584 5585 // No special expansion. 5586 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5587 } 5588 5589 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5590 /// limited-precision mode with x == 10.0f. 5591 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5592 SelectionDAG &DAG, const TargetLowering &TLI, 5593 SDNodeFlags Flags) { 5594 bool IsExp10 = false; 5595 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5596 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5597 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5598 APFloat Ten(10.0f); 5599 IsExp10 = LHSC->isExactlyValue(Ten); 5600 } 5601 } 5602 5603 // TODO: What fast-math-flags should be set on the FMUL node? 5604 if (IsExp10) { 5605 // Put the exponent in the right bit position for later addition to the 5606 // final result: 5607 // 5608 // #define LOG2OF10 3.3219281f 5609 // t0 = Op * LOG2OF10; 5610 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5611 getF32Constant(DAG, 0x40549a78, dl)); 5612 return getLimitedPrecisionExp2(t0, dl, DAG); 5613 } 5614 5615 // No special expansion. 5616 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5617 } 5618 5619 /// ExpandPowI - Expand a llvm.powi intrinsic. 5620 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5621 SelectionDAG &DAG) { 5622 // If RHS is a constant, we can expand this out to a multiplication tree if 5623 // it's beneficial on the target, otherwise we end up lowering to a call to 5624 // __powidf2 (for example). 5625 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5626 unsigned Val = RHSC->getSExtValue(); 5627 5628 // powi(x, 0) -> 1.0 5629 if (Val == 0) 5630 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5631 5632 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5633 Val, DAG.shouldOptForSize())) { 5634 // Get the exponent as a positive value. 5635 if ((int)Val < 0) 5636 Val = -Val; 5637 // We use the simple binary decomposition method to generate the multiply 5638 // sequence. There are more optimal ways to do this (for example, 5639 // powi(x,15) generates one more multiply than it should), but this has 5640 // the benefit of being both really simple and much better than a libcall. 5641 SDValue Res; // Logically starts equal to 1.0 5642 SDValue CurSquare = LHS; 5643 // TODO: Intrinsics should have fast-math-flags that propagate to these 5644 // nodes. 5645 while (Val) { 5646 if (Val & 1) { 5647 if (Res.getNode()) 5648 Res = 5649 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5650 else 5651 Res = CurSquare; // 1.0*CurSquare. 5652 } 5653 5654 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5655 CurSquare, CurSquare); 5656 Val >>= 1; 5657 } 5658 5659 // If the original was negative, invert the result, producing 1/(x*x*x). 5660 if (RHSC->getSExtValue() < 0) 5661 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5662 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5663 return Res; 5664 } 5665 } 5666 5667 // Otherwise, expand to a libcall. 5668 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5669 } 5670 5671 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5672 SDValue LHS, SDValue RHS, SDValue Scale, 5673 SelectionDAG &DAG, const TargetLowering &TLI) { 5674 EVT VT = LHS.getValueType(); 5675 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5676 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5677 LLVMContext &Ctx = *DAG.getContext(); 5678 5679 // If the type is legal but the operation isn't, this node might survive all 5680 // the way to operation legalization. If we end up there and we do not have 5681 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5682 // node. 5683 5684 // Coax the legalizer into expanding the node during type legalization instead 5685 // by bumping the size by one bit. This will force it to Promote, enabling the 5686 // early expansion and avoiding the need to expand later. 5687 5688 // We don't have to do this if Scale is 0; that can always be expanded, unless 5689 // it's a saturating signed operation. Those can experience true integer 5690 // division overflow, a case which we must avoid. 5691 5692 // FIXME: We wouldn't have to do this (or any of the early 5693 // expansion/promotion) if it was possible to expand a libcall of an 5694 // illegal type during operation legalization. But it's not, so things 5695 // get a bit hacky. 5696 unsigned ScaleInt = Scale->getAsZExtVal(); 5697 if ((ScaleInt > 0 || (Saturating && Signed)) && 5698 (TLI.isTypeLegal(VT) || 5699 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5700 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5701 Opcode, VT, ScaleInt); 5702 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5703 EVT PromVT; 5704 if (VT.isScalarInteger()) 5705 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5706 else if (VT.isVector()) { 5707 PromVT = VT.getVectorElementType(); 5708 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5709 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5710 } else 5711 llvm_unreachable("Wrong VT for DIVFIX?"); 5712 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5713 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5714 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5715 // For saturating operations, we need to shift up the LHS to get the 5716 // proper saturation width, and then shift down again afterwards. 5717 if (Saturating) 5718 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5719 DAG.getConstant(1, DL, ShiftTy)); 5720 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5721 if (Saturating) 5722 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5723 DAG.getConstant(1, DL, ShiftTy)); 5724 return DAG.getZExtOrTrunc(Res, DL, VT); 5725 } 5726 } 5727 5728 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5729 } 5730 5731 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5732 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5733 static void 5734 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5735 const SDValue &N) { 5736 switch (N.getOpcode()) { 5737 case ISD::CopyFromReg: { 5738 SDValue Op = N.getOperand(1); 5739 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5740 Op.getValueType().getSizeInBits()); 5741 return; 5742 } 5743 case ISD::BITCAST: 5744 case ISD::AssertZext: 5745 case ISD::AssertSext: 5746 case ISD::TRUNCATE: 5747 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5748 return; 5749 case ISD::BUILD_PAIR: 5750 case ISD::BUILD_VECTOR: 5751 case ISD::CONCAT_VECTORS: 5752 for (SDValue Op : N->op_values()) 5753 getUnderlyingArgRegs(Regs, Op); 5754 return; 5755 default: 5756 return; 5757 } 5758 } 5759 5760 /// If the DbgValueInst is a dbg_value of a function argument, create the 5761 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5762 /// instruction selection, they will be inserted to the entry BB. 5763 /// We don't currently support this for variadic dbg_values, as they shouldn't 5764 /// appear for function arguments or in the prologue. 5765 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5766 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5767 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5768 const Argument *Arg = dyn_cast<Argument>(V); 5769 if (!Arg) 5770 return false; 5771 5772 MachineFunction &MF = DAG.getMachineFunction(); 5773 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5774 5775 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5776 // we've been asked to pursue. 5777 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5778 bool Indirect) { 5779 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5780 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5781 // pointing at the VReg, which will be patched up later. 5782 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5783 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5784 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5785 /* isKill */ false, /* isDead */ false, 5786 /* isUndef */ false, /* isEarlyClobber */ false, 5787 /* SubReg */ 0, /* isDebug */ true)}); 5788 5789 auto *NewDIExpr = FragExpr; 5790 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5791 // the DIExpression. 5792 if (Indirect) 5793 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5794 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5795 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5796 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5797 } else { 5798 // Create a completely standard DBG_VALUE. 5799 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5800 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5801 } 5802 }; 5803 5804 if (Kind == FuncArgumentDbgValueKind::Value) { 5805 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5806 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5807 // the entry block. 5808 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5809 if (!IsInEntryBlock) 5810 return false; 5811 5812 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5813 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5814 // variable that also is a param. 5815 // 5816 // Although, if we are at the top of the entry block already, we can still 5817 // emit using ArgDbgValue. This might catch some situations when the 5818 // dbg.value refers to an argument that isn't used in the entry block, so 5819 // any CopyToReg node would be optimized out and the only way to express 5820 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5821 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5822 // we should only emit as ArgDbgValue if the Variable is an argument to the 5823 // current function, and the dbg.value intrinsic is found in the entry 5824 // block. 5825 bool VariableIsFunctionInputArg = Variable->isParameter() && 5826 !DL->getInlinedAt(); 5827 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5828 if (!IsInPrologue && !VariableIsFunctionInputArg) 5829 return false; 5830 5831 // Here we assume that a function argument on IR level only can be used to 5832 // describe one input parameter on source level. If we for example have 5833 // source code like this 5834 // 5835 // struct A { long x, y; }; 5836 // void foo(struct A a, long b) { 5837 // ... 5838 // b = a.x; 5839 // ... 5840 // } 5841 // 5842 // and IR like this 5843 // 5844 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5845 // entry: 5846 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5847 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5848 // call void @llvm.dbg.value(metadata i32 %b, "b", 5849 // ... 5850 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5851 // ... 5852 // 5853 // then the last dbg.value is describing a parameter "b" using a value that 5854 // is an argument. But since we already has used %a1 to describe a parameter 5855 // we should not handle that last dbg.value here (that would result in an 5856 // incorrect hoisting of the DBG_VALUE to the function entry). 5857 // Notice that we allow one dbg.value per IR level argument, to accommodate 5858 // for the situation with fragments above. 5859 if (VariableIsFunctionInputArg) { 5860 unsigned ArgNo = Arg->getArgNo(); 5861 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5862 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5863 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5864 return false; 5865 FuncInfo.DescribedArgs.set(ArgNo); 5866 } 5867 } 5868 5869 bool IsIndirect = false; 5870 std::optional<MachineOperand> Op; 5871 // Some arguments' frame index is recorded during argument lowering. 5872 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5873 if (FI != std::numeric_limits<int>::max()) 5874 Op = MachineOperand::CreateFI(FI); 5875 5876 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5877 if (!Op && N.getNode()) { 5878 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5879 Register Reg; 5880 if (ArgRegsAndSizes.size() == 1) 5881 Reg = ArgRegsAndSizes.front().first; 5882 5883 if (Reg && Reg.isVirtual()) { 5884 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5885 Register PR = RegInfo.getLiveInPhysReg(Reg); 5886 if (PR) 5887 Reg = PR; 5888 } 5889 if (Reg) { 5890 Op = MachineOperand::CreateReg(Reg, false); 5891 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5892 } 5893 } 5894 5895 if (!Op && N.getNode()) { 5896 // Check if frame index is available. 5897 SDValue LCandidate = peekThroughBitcasts(N); 5898 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5899 if (FrameIndexSDNode *FINode = 5900 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5901 Op = MachineOperand::CreateFI(FINode->getIndex()); 5902 } 5903 5904 if (!Op) { 5905 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5906 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5907 SplitRegs) { 5908 unsigned Offset = 0; 5909 for (const auto &RegAndSize : SplitRegs) { 5910 // If the expression is already a fragment, the current register 5911 // offset+size might extend beyond the fragment. In this case, only 5912 // the register bits that are inside the fragment are relevant. 5913 int RegFragmentSizeInBits = RegAndSize.second; 5914 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5915 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5916 // The register is entirely outside the expression fragment, 5917 // so is irrelevant for debug info. 5918 if (Offset >= ExprFragmentSizeInBits) 5919 break; 5920 // The register is partially outside the expression fragment, only 5921 // the low bits within the fragment are relevant for debug info. 5922 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5923 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5924 } 5925 } 5926 5927 auto FragmentExpr = DIExpression::createFragmentExpression( 5928 Expr, Offset, RegFragmentSizeInBits); 5929 Offset += RegAndSize.second; 5930 // If a valid fragment expression cannot be created, the variable's 5931 // correct value cannot be determined and so it is set as Undef. 5932 if (!FragmentExpr) { 5933 SDDbgValue *SDV = DAG.getConstantDbgValue( 5934 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5935 DAG.AddDbgValue(SDV, false); 5936 continue; 5937 } 5938 MachineInstr *NewMI = 5939 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5940 Kind != FuncArgumentDbgValueKind::Value); 5941 FuncInfo.ArgDbgValues.push_back(NewMI); 5942 } 5943 }; 5944 5945 // Check if ValueMap has reg number. 5946 DenseMap<const Value *, Register>::const_iterator 5947 VMI = FuncInfo.ValueMap.find(V); 5948 if (VMI != FuncInfo.ValueMap.end()) { 5949 const auto &TLI = DAG.getTargetLoweringInfo(); 5950 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5951 V->getType(), std::nullopt); 5952 if (RFV.occupiesMultipleRegs()) { 5953 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5954 return true; 5955 } 5956 5957 Op = MachineOperand::CreateReg(VMI->second, false); 5958 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5959 } else if (ArgRegsAndSizes.size() > 1) { 5960 // This was split due to the calling convention, and no virtual register 5961 // mapping exists for the value. 5962 splitMultiRegDbgValue(ArgRegsAndSizes); 5963 return true; 5964 } 5965 } 5966 5967 if (!Op) 5968 return false; 5969 5970 assert(Variable->isValidLocationForIntrinsic(DL) && 5971 "Expected inlined-at fields to agree"); 5972 MachineInstr *NewMI = nullptr; 5973 5974 if (Op->isReg()) 5975 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5976 else 5977 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5978 Variable, Expr); 5979 5980 // Otherwise, use ArgDbgValues. 5981 FuncInfo.ArgDbgValues.push_back(NewMI); 5982 return true; 5983 } 5984 5985 /// Return the appropriate SDDbgValue based on N. 5986 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5987 DILocalVariable *Variable, 5988 DIExpression *Expr, 5989 const DebugLoc &dl, 5990 unsigned DbgSDNodeOrder) { 5991 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5992 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5993 // stack slot locations. 5994 // 5995 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5996 // debug values here after optimization: 5997 // 5998 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5999 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 6000 // 6001 // Both describe the direct values of their associated variables. 6002 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 6003 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6004 } 6005 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 6006 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6007 } 6008 6009 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 6010 switch (Intrinsic) { 6011 case Intrinsic::smul_fix: 6012 return ISD::SMULFIX; 6013 case Intrinsic::umul_fix: 6014 return ISD::UMULFIX; 6015 case Intrinsic::smul_fix_sat: 6016 return ISD::SMULFIXSAT; 6017 case Intrinsic::umul_fix_sat: 6018 return ISD::UMULFIXSAT; 6019 case Intrinsic::sdiv_fix: 6020 return ISD::SDIVFIX; 6021 case Intrinsic::udiv_fix: 6022 return ISD::UDIVFIX; 6023 case Intrinsic::sdiv_fix_sat: 6024 return ISD::SDIVFIXSAT; 6025 case Intrinsic::udiv_fix_sat: 6026 return ISD::UDIVFIXSAT; 6027 default: 6028 llvm_unreachable("Unhandled fixed point intrinsic"); 6029 } 6030 } 6031 6032 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 6033 const char *FunctionName) { 6034 assert(FunctionName && "FunctionName must not be nullptr"); 6035 SDValue Callee = DAG.getExternalSymbol( 6036 FunctionName, 6037 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6038 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 6039 } 6040 6041 /// Given a @llvm.call.preallocated.setup, return the corresponding 6042 /// preallocated call. 6043 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 6044 assert(cast<CallBase>(PreallocatedSetup) 6045 ->getCalledFunction() 6046 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 6047 "expected call_preallocated_setup Value"); 6048 for (const auto *U : PreallocatedSetup->users()) { 6049 auto *UseCall = cast<CallBase>(U); 6050 const Function *Fn = UseCall->getCalledFunction(); 6051 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 6052 return UseCall; 6053 } 6054 } 6055 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 6056 } 6057 6058 /// If DI is a debug value with an EntryValue expression, lower it using the 6059 /// corresponding physical register of the associated Argument value 6060 /// (guaranteed to exist by the verifier). 6061 bool SelectionDAGBuilder::visitEntryValueDbgValue( 6062 ArrayRef<const Value *> Values, DILocalVariable *Variable, 6063 DIExpression *Expr, DebugLoc DbgLoc) { 6064 if (!Expr->isEntryValue() || !hasSingleElement(Values)) 6065 return false; 6066 6067 // These properties are guaranteed by the verifier. 6068 const Argument *Arg = cast<Argument>(Values[0]); 6069 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 6070 6071 auto ArgIt = FuncInfo.ValueMap.find(Arg); 6072 if (ArgIt == FuncInfo.ValueMap.end()) { 6073 LLVM_DEBUG( 6074 dbgs() << "Dropping dbg.value: expression is entry_value but " 6075 "couldn't find an associated register for the Argument\n"); 6076 return true; 6077 } 6078 Register ArgVReg = ArgIt->getSecond(); 6079 6080 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 6081 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 6082 SDDbgValue *SDV = DAG.getVRegDbgValue( 6083 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder); 6084 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 6085 return true; 6086 } 6087 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 6088 "couldn't find a physical register\n"); 6089 return true; 6090 } 6091 6092 /// Lower the call to the specified intrinsic function. 6093 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I, 6094 unsigned Intrinsic) { 6095 SDLoc sdl = getCurSDLoc(); 6096 switch (Intrinsic) { 6097 case Intrinsic::experimental_convergence_anchor: 6098 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped)); 6099 break; 6100 case Intrinsic::experimental_convergence_entry: 6101 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped)); 6102 break; 6103 case Intrinsic::experimental_convergence_loop: { 6104 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl); 6105 auto *Token = Bundle->Inputs[0].get(); 6106 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped, 6107 getValue(Token))); 6108 break; 6109 } 6110 } 6111 } 6112 6113 /// Lower the call to the specified intrinsic function. 6114 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 6115 unsigned Intrinsic) { 6116 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6117 SDLoc sdl = getCurSDLoc(); 6118 DebugLoc dl = getCurDebugLoc(); 6119 SDValue Res; 6120 6121 SDNodeFlags Flags; 6122 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 6123 Flags.copyFMF(*FPOp); 6124 6125 switch (Intrinsic) { 6126 default: 6127 // By default, turn this into a target intrinsic node. 6128 visitTargetIntrinsic(I, Intrinsic); 6129 return; 6130 case Intrinsic::vscale: { 6131 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6132 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 6133 return; 6134 } 6135 case Intrinsic::vastart: visitVAStart(I); return; 6136 case Intrinsic::vaend: visitVAEnd(I); return; 6137 case Intrinsic::vacopy: visitVACopy(I); return; 6138 case Intrinsic::returnaddress: 6139 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 6140 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6141 getValue(I.getArgOperand(0)))); 6142 return; 6143 case Intrinsic::addressofreturnaddress: 6144 setValue(&I, 6145 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6146 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6147 return; 6148 case Intrinsic::sponentry: 6149 setValue(&I, 6150 DAG.getNode(ISD::SPONENTRY, sdl, 6151 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6152 return; 6153 case Intrinsic::frameaddress: 6154 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6155 TLI.getFrameIndexTy(DAG.getDataLayout()), 6156 getValue(I.getArgOperand(0)))); 6157 return; 6158 case Intrinsic::read_volatile_register: 6159 case Intrinsic::read_register: { 6160 Value *Reg = I.getArgOperand(0); 6161 SDValue Chain = getRoot(); 6162 SDValue RegName = 6163 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6164 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6165 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6166 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6167 setValue(&I, Res); 6168 DAG.setRoot(Res.getValue(1)); 6169 return; 6170 } 6171 case Intrinsic::write_register: { 6172 Value *Reg = I.getArgOperand(0); 6173 Value *RegValue = I.getArgOperand(1); 6174 SDValue Chain = getRoot(); 6175 SDValue RegName = 6176 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6177 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6178 RegName, getValue(RegValue))); 6179 return; 6180 } 6181 case Intrinsic::memcpy: { 6182 const auto &MCI = cast<MemCpyInst>(I); 6183 SDValue Op1 = getValue(I.getArgOperand(0)); 6184 SDValue Op2 = getValue(I.getArgOperand(1)); 6185 SDValue Op3 = getValue(I.getArgOperand(2)); 6186 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6187 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6188 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6189 Align Alignment = std::min(DstAlign, SrcAlign); 6190 bool isVol = MCI.isVolatile(); 6191 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6192 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6193 // node. 6194 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6195 SDValue MC = DAG.getMemcpy( 6196 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6197 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6198 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6199 updateDAGForMaybeTailCall(MC); 6200 return; 6201 } 6202 case Intrinsic::memcpy_inline: { 6203 const auto &MCI = cast<MemCpyInlineInst>(I); 6204 SDValue Dst = getValue(I.getArgOperand(0)); 6205 SDValue Src = getValue(I.getArgOperand(1)); 6206 SDValue Size = getValue(I.getArgOperand(2)); 6207 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6208 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6209 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6210 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6211 Align Alignment = std::min(DstAlign, SrcAlign); 6212 bool isVol = MCI.isVolatile(); 6213 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6214 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6215 // node. 6216 SDValue MC = DAG.getMemcpy( 6217 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6218 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6219 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6220 updateDAGForMaybeTailCall(MC); 6221 return; 6222 } 6223 case Intrinsic::memset: { 6224 const auto &MSI = cast<MemSetInst>(I); 6225 SDValue Op1 = getValue(I.getArgOperand(0)); 6226 SDValue Op2 = getValue(I.getArgOperand(1)); 6227 SDValue Op3 = getValue(I.getArgOperand(2)); 6228 // @llvm.memset defines 0 and 1 to both mean no alignment. 6229 Align Alignment = MSI.getDestAlign().valueOrOne(); 6230 bool isVol = MSI.isVolatile(); 6231 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6232 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6233 SDValue MS = DAG.getMemset( 6234 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6235 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6236 updateDAGForMaybeTailCall(MS); 6237 return; 6238 } 6239 case Intrinsic::memset_inline: { 6240 const auto &MSII = cast<MemSetInlineInst>(I); 6241 SDValue Dst = getValue(I.getArgOperand(0)); 6242 SDValue Value = getValue(I.getArgOperand(1)); 6243 SDValue Size = getValue(I.getArgOperand(2)); 6244 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6245 // @llvm.memset defines 0 and 1 to both mean no alignment. 6246 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6247 bool isVol = MSII.isVolatile(); 6248 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6249 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6250 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6251 /* AlwaysInline */ true, isTC, 6252 MachinePointerInfo(I.getArgOperand(0)), 6253 I.getAAMetadata()); 6254 updateDAGForMaybeTailCall(MC); 6255 return; 6256 } 6257 case Intrinsic::memmove: { 6258 const auto &MMI = cast<MemMoveInst>(I); 6259 SDValue Op1 = getValue(I.getArgOperand(0)); 6260 SDValue Op2 = getValue(I.getArgOperand(1)); 6261 SDValue Op3 = getValue(I.getArgOperand(2)); 6262 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6263 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6264 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6265 Align Alignment = std::min(DstAlign, SrcAlign); 6266 bool isVol = MMI.isVolatile(); 6267 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6268 // FIXME: Support passing different dest/src alignments to the memmove DAG 6269 // node. 6270 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6271 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6272 isTC, MachinePointerInfo(I.getArgOperand(0)), 6273 MachinePointerInfo(I.getArgOperand(1)), 6274 I.getAAMetadata(), AA); 6275 updateDAGForMaybeTailCall(MM); 6276 return; 6277 } 6278 case Intrinsic::memcpy_element_unordered_atomic: { 6279 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6280 SDValue Dst = getValue(MI.getRawDest()); 6281 SDValue Src = getValue(MI.getRawSource()); 6282 SDValue Length = getValue(MI.getLength()); 6283 6284 Type *LengthTy = MI.getLength()->getType(); 6285 unsigned ElemSz = MI.getElementSizeInBytes(); 6286 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6287 SDValue MC = 6288 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6289 isTC, MachinePointerInfo(MI.getRawDest()), 6290 MachinePointerInfo(MI.getRawSource())); 6291 updateDAGForMaybeTailCall(MC); 6292 return; 6293 } 6294 case Intrinsic::memmove_element_unordered_atomic: { 6295 auto &MI = cast<AtomicMemMoveInst>(I); 6296 SDValue Dst = getValue(MI.getRawDest()); 6297 SDValue Src = getValue(MI.getRawSource()); 6298 SDValue Length = getValue(MI.getLength()); 6299 6300 Type *LengthTy = MI.getLength()->getType(); 6301 unsigned ElemSz = MI.getElementSizeInBytes(); 6302 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6303 SDValue MC = 6304 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6305 isTC, MachinePointerInfo(MI.getRawDest()), 6306 MachinePointerInfo(MI.getRawSource())); 6307 updateDAGForMaybeTailCall(MC); 6308 return; 6309 } 6310 case Intrinsic::memset_element_unordered_atomic: { 6311 auto &MI = cast<AtomicMemSetInst>(I); 6312 SDValue Dst = getValue(MI.getRawDest()); 6313 SDValue Val = getValue(MI.getValue()); 6314 SDValue Length = getValue(MI.getLength()); 6315 6316 Type *LengthTy = MI.getLength()->getType(); 6317 unsigned ElemSz = MI.getElementSizeInBytes(); 6318 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6319 SDValue MC = 6320 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6321 isTC, MachinePointerInfo(MI.getRawDest())); 6322 updateDAGForMaybeTailCall(MC); 6323 return; 6324 } 6325 case Intrinsic::call_preallocated_setup: { 6326 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6327 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6328 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6329 getRoot(), SrcValue); 6330 setValue(&I, Res); 6331 DAG.setRoot(Res); 6332 return; 6333 } 6334 case Intrinsic::call_preallocated_arg: { 6335 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6336 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6337 SDValue Ops[3]; 6338 Ops[0] = getRoot(); 6339 Ops[1] = SrcValue; 6340 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6341 MVT::i32); // arg index 6342 SDValue Res = DAG.getNode( 6343 ISD::PREALLOCATED_ARG, sdl, 6344 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6345 setValue(&I, Res); 6346 DAG.setRoot(Res.getValue(1)); 6347 return; 6348 } 6349 case Intrinsic::dbg_declare: { 6350 const auto &DI = cast<DbgDeclareInst>(I); 6351 // Debug intrinsics are handled separately in assignment tracking mode. 6352 // Some intrinsics are handled right after Argument lowering. 6353 if (AssignmentTrackingEnabled || 6354 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6355 return; 6356 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n"); 6357 DILocalVariable *Variable = DI.getVariable(); 6358 DIExpression *Expression = DI.getExpression(); 6359 dropDanglingDebugInfo(Variable, Expression); 6360 // Assume dbg.declare can not currently use DIArgList, i.e. 6361 // it is non-variadic. 6362 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6363 handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression, 6364 DI.getDebugLoc()); 6365 return; 6366 } 6367 case Intrinsic::dbg_label: { 6368 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6369 DILabel *Label = DI.getLabel(); 6370 assert(Label && "Missing label"); 6371 6372 SDDbgLabel *SDV; 6373 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6374 DAG.AddDbgLabel(SDV); 6375 return; 6376 } 6377 case Intrinsic::dbg_assign: { 6378 // Debug intrinsics are handled seperately in assignment tracking mode. 6379 if (AssignmentTrackingEnabled) 6380 return; 6381 // If assignment tracking hasn't been enabled then fall through and treat 6382 // the dbg.assign as a dbg.value. 6383 [[fallthrough]]; 6384 } 6385 case Intrinsic::dbg_value: { 6386 // Debug intrinsics are handled seperately in assignment tracking mode. 6387 if (AssignmentTrackingEnabled) 6388 return; 6389 const DbgValueInst &DI = cast<DbgValueInst>(I); 6390 assert(DI.getVariable() && "Missing variable"); 6391 6392 DILocalVariable *Variable = DI.getVariable(); 6393 DIExpression *Expression = DI.getExpression(); 6394 dropDanglingDebugInfo(Variable, Expression); 6395 6396 if (DI.isKillLocation()) { 6397 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6398 return; 6399 } 6400 6401 SmallVector<Value *, 4> Values(DI.getValues()); 6402 if (Values.empty()) 6403 return; 6404 6405 bool IsVariadic = DI.hasArgList(); 6406 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6407 SDNodeOrder, IsVariadic)) 6408 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 6409 DI.getDebugLoc(), SDNodeOrder); 6410 return; 6411 } 6412 6413 case Intrinsic::eh_typeid_for: { 6414 // Find the type id for the given typeinfo. 6415 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6416 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6417 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6418 setValue(&I, Res); 6419 return; 6420 } 6421 6422 case Intrinsic::eh_return_i32: 6423 case Intrinsic::eh_return_i64: 6424 DAG.getMachineFunction().setCallsEHReturn(true); 6425 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6426 MVT::Other, 6427 getControlRoot(), 6428 getValue(I.getArgOperand(0)), 6429 getValue(I.getArgOperand(1)))); 6430 return; 6431 case Intrinsic::eh_unwind_init: 6432 DAG.getMachineFunction().setCallsUnwindInit(true); 6433 return; 6434 case Intrinsic::eh_dwarf_cfa: 6435 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6436 TLI.getPointerTy(DAG.getDataLayout()), 6437 getValue(I.getArgOperand(0)))); 6438 return; 6439 case Intrinsic::eh_sjlj_callsite: { 6440 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6441 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6442 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6443 6444 MMI.setCurrentCallSite(CI->getZExtValue()); 6445 return; 6446 } 6447 case Intrinsic::eh_sjlj_functioncontext: { 6448 // Get and store the index of the function context. 6449 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6450 AllocaInst *FnCtx = 6451 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6452 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6453 MFI.setFunctionContextIndex(FI); 6454 return; 6455 } 6456 case Intrinsic::eh_sjlj_setjmp: { 6457 SDValue Ops[2]; 6458 Ops[0] = getRoot(); 6459 Ops[1] = getValue(I.getArgOperand(0)); 6460 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6461 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6462 setValue(&I, Op.getValue(0)); 6463 DAG.setRoot(Op.getValue(1)); 6464 return; 6465 } 6466 case Intrinsic::eh_sjlj_longjmp: 6467 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6468 getRoot(), getValue(I.getArgOperand(0)))); 6469 return; 6470 case Intrinsic::eh_sjlj_setup_dispatch: 6471 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6472 getRoot())); 6473 return; 6474 case Intrinsic::masked_gather: 6475 visitMaskedGather(I); 6476 return; 6477 case Intrinsic::masked_load: 6478 visitMaskedLoad(I); 6479 return; 6480 case Intrinsic::masked_scatter: 6481 visitMaskedScatter(I); 6482 return; 6483 case Intrinsic::masked_store: 6484 visitMaskedStore(I); 6485 return; 6486 case Intrinsic::masked_expandload: 6487 visitMaskedLoad(I, true /* IsExpanding */); 6488 return; 6489 case Intrinsic::masked_compressstore: 6490 visitMaskedStore(I, true /* IsCompressing */); 6491 return; 6492 case Intrinsic::powi: 6493 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6494 getValue(I.getArgOperand(1)), DAG)); 6495 return; 6496 case Intrinsic::log: 6497 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6498 return; 6499 case Intrinsic::log2: 6500 setValue(&I, 6501 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6502 return; 6503 case Intrinsic::log10: 6504 setValue(&I, 6505 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6506 return; 6507 case Intrinsic::exp: 6508 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6509 return; 6510 case Intrinsic::exp2: 6511 setValue(&I, 6512 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6513 return; 6514 case Intrinsic::pow: 6515 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6516 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6517 return; 6518 case Intrinsic::sqrt: 6519 case Intrinsic::fabs: 6520 case Intrinsic::sin: 6521 case Intrinsic::cos: 6522 case Intrinsic::exp10: 6523 case Intrinsic::floor: 6524 case Intrinsic::ceil: 6525 case Intrinsic::trunc: 6526 case Intrinsic::rint: 6527 case Intrinsic::nearbyint: 6528 case Intrinsic::round: 6529 case Intrinsic::roundeven: 6530 case Intrinsic::canonicalize: { 6531 unsigned Opcode; 6532 switch (Intrinsic) { 6533 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6534 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6535 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6536 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6537 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6538 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6539 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6540 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6541 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6542 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6543 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6544 case Intrinsic::round: Opcode = ISD::FROUND; break; 6545 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6546 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6547 } 6548 6549 setValue(&I, DAG.getNode(Opcode, sdl, 6550 getValue(I.getArgOperand(0)).getValueType(), 6551 getValue(I.getArgOperand(0)), Flags)); 6552 return; 6553 } 6554 case Intrinsic::lround: 6555 case Intrinsic::llround: 6556 case Intrinsic::lrint: 6557 case Intrinsic::llrint: { 6558 unsigned Opcode; 6559 switch (Intrinsic) { 6560 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6561 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6562 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6563 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6564 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6565 } 6566 6567 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6568 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6569 getValue(I.getArgOperand(0)))); 6570 return; 6571 } 6572 case Intrinsic::minnum: 6573 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6574 getValue(I.getArgOperand(0)).getValueType(), 6575 getValue(I.getArgOperand(0)), 6576 getValue(I.getArgOperand(1)), Flags)); 6577 return; 6578 case Intrinsic::maxnum: 6579 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6580 getValue(I.getArgOperand(0)).getValueType(), 6581 getValue(I.getArgOperand(0)), 6582 getValue(I.getArgOperand(1)), Flags)); 6583 return; 6584 case Intrinsic::minimum: 6585 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6586 getValue(I.getArgOperand(0)).getValueType(), 6587 getValue(I.getArgOperand(0)), 6588 getValue(I.getArgOperand(1)), Flags)); 6589 return; 6590 case Intrinsic::maximum: 6591 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6592 getValue(I.getArgOperand(0)).getValueType(), 6593 getValue(I.getArgOperand(0)), 6594 getValue(I.getArgOperand(1)), Flags)); 6595 return; 6596 case Intrinsic::copysign: 6597 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6598 getValue(I.getArgOperand(0)).getValueType(), 6599 getValue(I.getArgOperand(0)), 6600 getValue(I.getArgOperand(1)), Flags)); 6601 return; 6602 case Intrinsic::ldexp: 6603 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6604 getValue(I.getArgOperand(0)).getValueType(), 6605 getValue(I.getArgOperand(0)), 6606 getValue(I.getArgOperand(1)), Flags)); 6607 return; 6608 case Intrinsic::frexp: { 6609 SmallVector<EVT, 2> ValueVTs; 6610 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6611 SDVTList VTs = DAG.getVTList(ValueVTs); 6612 setValue(&I, 6613 DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0)))); 6614 return; 6615 } 6616 case Intrinsic::arithmetic_fence: { 6617 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6618 getValue(I.getArgOperand(0)).getValueType(), 6619 getValue(I.getArgOperand(0)), Flags)); 6620 return; 6621 } 6622 case Intrinsic::fma: 6623 setValue(&I, DAG.getNode( 6624 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6625 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6626 getValue(I.getArgOperand(2)), Flags)); 6627 return; 6628 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6629 case Intrinsic::INTRINSIC: 6630 #include "llvm/IR/ConstrainedOps.def" 6631 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6632 return; 6633 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6634 #include "llvm/IR/VPIntrinsics.def" 6635 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6636 return; 6637 case Intrinsic::fptrunc_round: { 6638 // Get the last argument, the metadata and convert it to an integer in the 6639 // call 6640 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6641 std::optional<RoundingMode> RoundMode = 6642 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6643 6644 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6645 6646 // Propagate fast-math-flags from IR to node(s). 6647 SDNodeFlags Flags; 6648 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6649 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6650 6651 SDValue Result; 6652 Result = DAG.getNode( 6653 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6654 DAG.getTargetConstant((int)*RoundMode, sdl, 6655 TLI.getPointerTy(DAG.getDataLayout()))); 6656 setValue(&I, Result); 6657 6658 return; 6659 } 6660 case Intrinsic::fmuladd: { 6661 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6662 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6663 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6664 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6665 getValue(I.getArgOperand(0)).getValueType(), 6666 getValue(I.getArgOperand(0)), 6667 getValue(I.getArgOperand(1)), 6668 getValue(I.getArgOperand(2)), Flags)); 6669 } else { 6670 // TODO: Intrinsic calls should have fast-math-flags. 6671 SDValue Mul = DAG.getNode( 6672 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6673 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6674 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6675 getValue(I.getArgOperand(0)).getValueType(), 6676 Mul, getValue(I.getArgOperand(2)), Flags); 6677 setValue(&I, Add); 6678 } 6679 return; 6680 } 6681 case Intrinsic::convert_to_fp16: 6682 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6683 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6684 getValue(I.getArgOperand(0)), 6685 DAG.getTargetConstant(0, sdl, 6686 MVT::i32)))); 6687 return; 6688 case Intrinsic::convert_from_fp16: 6689 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6690 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6691 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6692 getValue(I.getArgOperand(0))))); 6693 return; 6694 case Intrinsic::fptosi_sat: { 6695 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6696 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6697 getValue(I.getArgOperand(0)), 6698 DAG.getValueType(VT.getScalarType()))); 6699 return; 6700 } 6701 case Intrinsic::fptoui_sat: { 6702 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6703 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6704 getValue(I.getArgOperand(0)), 6705 DAG.getValueType(VT.getScalarType()))); 6706 return; 6707 } 6708 case Intrinsic::set_rounding: 6709 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6710 {getRoot(), getValue(I.getArgOperand(0))}); 6711 setValue(&I, Res); 6712 DAG.setRoot(Res.getValue(0)); 6713 return; 6714 case Intrinsic::is_fpclass: { 6715 const DataLayout DLayout = DAG.getDataLayout(); 6716 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6717 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6718 FPClassTest Test = static_cast<FPClassTest>( 6719 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6720 MachineFunction &MF = DAG.getMachineFunction(); 6721 const Function &F = MF.getFunction(); 6722 SDValue Op = getValue(I.getArgOperand(0)); 6723 SDNodeFlags Flags; 6724 Flags.setNoFPExcept( 6725 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6726 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6727 // expansion can use illegal types. Making expansion early allows 6728 // legalizing these types prior to selection. 6729 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6730 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6731 setValue(&I, Result); 6732 return; 6733 } 6734 6735 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6736 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6737 setValue(&I, V); 6738 return; 6739 } 6740 case Intrinsic::get_fpenv: { 6741 const DataLayout DLayout = DAG.getDataLayout(); 6742 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 6743 Align TempAlign = DAG.getEVTAlign(EnvVT); 6744 SDValue Chain = getRoot(); 6745 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 6746 // and temporary storage in stack. 6747 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 6748 Res = DAG.getNode( 6749 ISD::GET_FPENV, sdl, 6750 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6751 MVT::Other), 6752 Chain); 6753 } else { 6754 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6755 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6756 auto MPI = 6757 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6758 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6759 MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize, 6760 TempAlign); 6761 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6762 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 6763 } 6764 setValue(&I, Res); 6765 DAG.setRoot(Res.getValue(1)); 6766 return; 6767 } 6768 case Intrinsic::set_fpenv: { 6769 const DataLayout DLayout = DAG.getDataLayout(); 6770 SDValue Env = getValue(I.getArgOperand(0)); 6771 EVT EnvVT = Env.getValueType(); 6772 Align TempAlign = DAG.getEVTAlign(EnvVT); 6773 SDValue Chain = getRoot(); 6774 // If SET_FPENV is custom or legal, use it. Otherwise use loading 6775 // environment from memory. 6776 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 6777 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 6778 } else { 6779 // Allocate space in stack, copy environment bits into it and use this 6780 // memory in SET_FPENV_MEM. 6781 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6782 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6783 auto MPI = 6784 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6785 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 6786 MachineMemOperand::MOStore); 6787 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6788 MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize, 6789 TempAlign); 6790 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6791 } 6792 DAG.setRoot(Chain); 6793 return; 6794 } 6795 case Intrinsic::reset_fpenv: 6796 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 6797 return; 6798 case Intrinsic::get_fpmode: 6799 Res = DAG.getNode( 6800 ISD::GET_FPMODE, sdl, 6801 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6802 MVT::Other), 6803 DAG.getRoot()); 6804 setValue(&I, Res); 6805 DAG.setRoot(Res.getValue(1)); 6806 return; 6807 case Intrinsic::set_fpmode: 6808 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 6809 getValue(I.getArgOperand(0))); 6810 DAG.setRoot(Res); 6811 return; 6812 case Intrinsic::reset_fpmode: { 6813 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 6814 DAG.setRoot(Res); 6815 return; 6816 } 6817 case Intrinsic::pcmarker: { 6818 SDValue Tmp = getValue(I.getArgOperand(0)); 6819 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6820 return; 6821 } 6822 case Intrinsic::readcyclecounter: { 6823 SDValue Op = getRoot(); 6824 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6825 DAG.getVTList(MVT::i64, MVT::Other), Op); 6826 setValue(&I, Res); 6827 DAG.setRoot(Res.getValue(1)); 6828 return; 6829 } 6830 case Intrinsic::readsteadycounter: { 6831 SDValue Op = getRoot(); 6832 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl, 6833 DAG.getVTList(MVT::i64, MVT::Other), Op); 6834 setValue(&I, Res); 6835 DAG.setRoot(Res.getValue(1)); 6836 return; 6837 } 6838 case Intrinsic::bitreverse: 6839 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6840 getValue(I.getArgOperand(0)).getValueType(), 6841 getValue(I.getArgOperand(0)))); 6842 return; 6843 case Intrinsic::bswap: 6844 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6845 getValue(I.getArgOperand(0)).getValueType(), 6846 getValue(I.getArgOperand(0)))); 6847 return; 6848 case Intrinsic::cttz: { 6849 SDValue Arg = getValue(I.getArgOperand(0)); 6850 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6851 EVT Ty = Arg.getValueType(); 6852 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6853 sdl, Ty, Arg)); 6854 return; 6855 } 6856 case Intrinsic::ctlz: { 6857 SDValue Arg = getValue(I.getArgOperand(0)); 6858 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6859 EVT Ty = Arg.getValueType(); 6860 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6861 sdl, Ty, Arg)); 6862 return; 6863 } 6864 case Intrinsic::ctpop: { 6865 SDValue Arg = getValue(I.getArgOperand(0)); 6866 EVT Ty = Arg.getValueType(); 6867 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6868 return; 6869 } 6870 case Intrinsic::fshl: 6871 case Intrinsic::fshr: { 6872 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6873 SDValue X = getValue(I.getArgOperand(0)); 6874 SDValue Y = getValue(I.getArgOperand(1)); 6875 SDValue Z = getValue(I.getArgOperand(2)); 6876 EVT VT = X.getValueType(); 6877 6878 if (X == Y) { 6879 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6880 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6881 } else { 6882 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6883 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6884 } 6885 return; 6886 } 6887 case Intrinsic::sadd_sat: { 6888 SDValue Op1 = getValue(I.getArgOperand(0)); 6889 SDValue Op2 = getValue(I.getArgOperand(1)); 6890 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6891 return; 6892 } 6893 case Intrinsic::uadd_sat: { 6894 SDValue Op1 = getValue(I.getArgOperand(0)); 6895 SDValue Op2 = getValue(I.getArgOperand(1)); 6896 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6897 return; 6898 } 6899 case Intrinsic::ssub_sat: { 6900 SDValue Op1 = getValue(I.getArgOperand(0)); 6901 SDValue Op2 = getValue(I.getArgOperand(1)); 6902 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6903 return; 6904 } 6905 case Intrinsic::usub_sat: { 6906 SDValue Op1 = getValue(I.getArgOperand(0)); 6907 SDValue Op2 = getValue(I.getArgOperand(1)); 6908 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6909 return; 6910 } 6911 case Intrinsic::sshl_sat: { 6912 SDValue Op1 = getValue(I.getArgOperand(0)); 6913 SDValue Op2 = getValue(I.getArgOperand(1)); 6914 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6915 return; 6916 } 6917 case Intrinsic::ushl_sat: { 6918 SDValue Op1 = getValue(I.getArgOperand(0)); 6919 SDValue Op2 = getValue(I.getArgOperand(1)); 6920 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6921 return; 6922 } 6923 case Intrinsic::smul_fix: 6924 case Intrinsic::umul_fix: 6925 case Intrinsic::smul_fix_sat: 6926 case Intrinsic::umul_fix_sat: { 6927 SDValue Op1 = getValue(I.getArgOperand(0)); 6928 SDValue Op2 = getValue(I.getArgOperand(1)); 6929 SDValue Op3 = getValue(I.getArgOperand(2)); 6930 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6931 Op1.getValueType(), Op1, Op2, Op3)); 6932 return; 6933 } 6934 case Intrinsic::sdiv_fix: 6935 case Intrinsic::udiv_fix: 6936 case Intrinsic::sdiv_fix_sat: 6937 case Intrinsic::udiv_fix_sat: { 6938 SDValue Op1 = getValue(I.getArgOperand(0)); 6939 SDValue Op2 = getValue(I.getArgOperand(1)); 6940 SDValue Op3 = getValue(I.getArgOperand(2)); 6941 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6942 Op1, Op2, Op3, DAG, TLI)); 6943 return; 6944 } 6945 case Intrinsic::smax: { 6946 SDValue Op1 = getValue(I.getArgOperand(0)); 6947 SDValue Op2 = getValue(I.getArgOperand(1)); 6948 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6949 return; 6950 } 6951 case Intrinsic::smin: { 6952 SDValue Op1 = getValue(I.getArgOperand(0)); 6953 SDValue Op2 = getValue(I.getArgOperand(1)); 6954 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6955 return; 6956 } 6957 case Intrinsic::umax: { 6958 SDValue Op1 = getValue(I.getArgOperand(0)); 6959 SDValue Op2 = getValue(I.getArgOperand(1)); 6960 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6961 return; 6962 } 6963 case Intrinsic::umin: { 6964 SDValue Op1 = getValue(I.getArgOperand(0)); 6965 SDValue Op2 = getValue(I.getArgOperand(1)); 6966 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6967 return; 6968 } 6969 case Intrinsic::abs: { 6970 // TODO: Preserve "int min is poison" arg in SDAG? 6971 SDValue Op1 = getValue(I.getArgOperand(0)); 6972 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6973 return; 6974 } 6975 case Intrinsic::stacksave: { 6976 SDValue Op = getRoot(); 6977 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6978 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6979 setValue(&I, Res); 6980 DAG.setRoot(Res.getValue(1)); 6981 return; 6982 } 6983 case Intrinsic::stackrestore: 6984 Res = getValue(I.getArgOperand(0)); 6985 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6986 return; 6987 case Intrinsic::get_dynamic_area_offset: { 6988 SDValue Op = getRoot(); 6989 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6990 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6991 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6992 // target. 6993 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6994 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6995 " intrinsic!"); 6996 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6997 Op); 6998 DAG.setRoot(Op); 6999 setValue(&I, Res); 7000 return; 7001 } 7002 case Intrinsic::stackguard: { 7003 MachineFunction &MF = DAG.getMachineFunction(); 7004 const Module &M = *MF.getFunction().getParent(); 7005 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7006 SDValue Chain = getRoot(); 7007 if (TLI.useLoadStackGuardNode()) { 7008 Res = getLoadStackGuard(DAG, sdl, Chain); 7009 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy); 7010 } else { 7011 const Value *Global = TLI.getSDagStackGuard(M); 7012 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 7013 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 7014 MachinePointerInfo(Global, 0), Align, 7015 MachineMemOperand::MOVolatile); 7016 } 7017 if (TLI.useStackGuardXorFP()) 7018 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 7019 DAG.setRoot(Chain); 7020 setValue(&I, Res); 7021 return; 7022 } 7023 case Intrinsic::stackprotector: { 7024 // Emit code into the DAG to store the stack guard onto the stack. 7025 MachineFunction &MF = DAG.getMachineFunction(); 7026 MachineFrameInfo &MFI = MF.getFrameInfo(); 7027 SDValue Src, Chain = getRoot(); 7028 7029 if (TLI.useLoadStackGuardNode()) 7030 Src = getLoadStackGuard(DAG, sdl, Chain); 7031 else 7032 Src = getValue(I.getArgOperand(0)); // The guard's value. 7033 7034 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 7035 7036 int FI = FuncInfo.StaticAllocaMap[Slot]; 7037 MFI.setStackProtectorIndex(FI); 7038 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7039 7040 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 7041 7042 // Store the stack protector onto the stack. 7043 Res = DAG.getStore( 7044 Chain, sdl, Src, FIN, 7045 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 7046 MaybeAlign(), MachineMemOperand::MOVolatile); 7047 setValue(&I, Res); 7048 DAG.setRoot(Res); 7049 return; 7050 } 7051 case Intrinsic::objectsize: 7052 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 7053 7054 case Intrinsic::is_constant: 7055 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 7056 7057 case Intrinsic::annotation: 7058 case Intrinsic::ptr_annotation: 7059 case Intrinsic::launder_invariant_group: 7060 case Intrinsic::strip_invariant_group: 7061 // Drop the intrinsic, but forward the value 7062 setValue(&I, getValue(I.getOperand(0))); 7063 return; 7064 7065 case Intrinsic::assume: 7066 case Intrinsic::experimental_noalias_scope_decl: 7067 case Intrinsic::var_annotation: 7068 case Intrinsic::sideeffect: 7069 // Discard annotate attributes, noalias scope declarations, assumptions, and 7070 // artificial side-effects. 7071 return; 7072 7073 case Intrinsic::codeview_annotation: { 7074 // Emit a label associated with this metadata. 7075 MachineFunction &MF = DAG.getMachineFunction(); 7076 MCSymbol *Label = 7077 MF.getMMI().getContext().createTempSymbol("annotation", true); 7078 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 7079 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 7080 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 7081 DAG.setRoot(Res); 7082 return; 7083 } 7084 7085 case Intrinsic::init_trampoline: { 7086 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 7087 7088 SDValue Ops[6]; 7089 Ops[0] = getRoot(); 7090 Ops[1] = getValue(I.getArgOperand(0)); 7091 Ops[2] = getValue(I.getArgOperand(1)); 7092 Ops[3] = getValue(I.getArgOperand(2)); 7093 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 7094 Ops[5] = DAG.getSrcValue(F); 7095 7096 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 7097 7098 DAG.setRoot(Res); 7099 return; 7100 } 7101 case Intrinsic::adjust_trampoline: 7102 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7103 TLI.getPointerTy(DAG.getDataLayout()), 7104 getValue(I.getArgOperand(0)))); 7105 return; 7106 case Intrinsic::gcroot: { 7107 assert(DAG.getMachineFunction().getFunction().hasGC() && 7108 "only valid in functions with gc specified, enforced by Verifier"); 7109 assert(GFI && "implied by previous"); 7110 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7111 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7112 7113 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7114 GFI->addStackRoot(FI->getIndex(), TypeMap); 7115 return; 7116 } 7117 case Intrinsic::gcread: 7118 case Intrinsic::gcwrite: 7119 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7120 case Intrinsic::get_rounding: 7121 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7122 setValue(&I, Res); 7123 DAG.setRoot(Res.getValue(1)); 7124 return; 7125 7126 case Intrinsic::expect: 7127 // Just replace __builtin_expect(exp, c) with EXP. 7128 setValue(&I, getValue(I.getArgOperand(0))); 7129 return; 7130 7131 case Intrinsic::ubsantrap: 7132 case Intrinsic::debugtrap: 7133 case Intrinsic::trap: { 7134 StringRef TrapFuncName = 7135 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7136 if (TrapFuncName.empty()) { 7137 switch (Intrinsic) { 7138 case Intrinsic::trap: 7139 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7140 break; 7141 case Intrinsic::debugtrap: 7142 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7143 break; 7144 case Intrinsic::ubsantrap: 7145 DAG.setRoot(DAG.getNode( 7146 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7147 DAG.getTargetConstant( 7148 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7149 MVT::i32))); 7150 break; 7151 default: llvm_unreachable("unknown trap intrinsic"); 7152 } 7153 return; 7154 } 7155 TargetLowering::ArgListTy Args; 7156 if (Intrinsic == Intrinsic::ubsantrap) { 7157 Args.push_back(TargetLoweringBase::ArgListEntry()); 7158 Args[0].Val = I.getArgOperand(0); 7159 Args[0].Node = getValue(Args[0].Val); 7160 Args[0].Ty = Args[0].Val->getType(); 7161 } 7162 7163 TargetLowering::CallLoweringInfo CLI(DAG); 7164 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7165 CallingConv::C, I.getType(), 7166 DAG.getExternalSymbol(TrapFuncName.data(), 7167 TLI.getPointerTy(DAG.getDataLayout())), 7168 std::move(Args)); 7169 7170 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7171 DAG.setRoot(Result.second); 7172 return; 7173 } 7174 7175 case Intrinsic::uadd_with_overflow: 7176 case Intrinsic::sadd_with_overflow: 7177 case Intrinsic::usub_with_overflow: 7178 case Intrinsic::ssub_with_overflow: 7179 case Intrinsic::umul_with_overflow: 7180 case Intrinsic::smul_with_overflow: { 7181 ISD::NodeType Op; 7182 switch (Intrinsic) { 7183 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7184 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7185 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7186 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7187 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7188 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7189 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7190 } 7191 SDValue Op1 = getValue(I.getArgOperand(0)); 7192 SDValue Op2 = getValue(I.getArgOperand(1)); 7193 7194 EVT ResultVT = Op1.getValueType(); 7195 EVT OverflowVT = MVT::i1; 7196 if (ResultVT.isVector()) 7197 OverflowVT = EVT::getVectorVT( 7198 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7199 7200 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7201 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7202 return; 7203 } 7204 case Intrinsic::prefetch: { 7205 SDValue Ops[5]; 7206 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7207 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7208 Ops[0] = DAG.getRoot(); 7209 Ops[1] = getValue(I.getArgOperand(0)); 7210 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7211 MVT::i32); 7212 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7213 MVT::i32); 7214 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7215 MVT::i32); 7216 SDValue Result = DAG.getMemIntrinsicNode( 7217 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7218 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7219 /* align */ std::nullopt, Flags); 7220 7221 // Chain the prefetch in parallel with any pending loads, to stay out of 7222 // the way of later optimizations. 7223 PendingLoads.push_back(Result); 7224 Result = getRoot(); 7225 DAG.setRoot(Result); 7226 return; 7227 } 7228 case Intrinsic::lifetime_start: 7229 case Intrinsic::lifetime_end: { 7230 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7231 // Stack coloring is not enabled in O0, discard region information. 7232 if (TM.getOptLevel() == CodeGenOptLevel::None) 7233 return; 7234 7235 const int64_t ObjectSize = 7236 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7237 Value *const ObjectPtr = I.getArgOperand(1); 7238 SmallVector<const Value *, 4> Allocas; 7239 getUnderlyingObjects(ObjectPtr, Allocas); 7240 7241 for (const Value *Alloca : Allocas) { 7242 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7243 7244 // Could not find an Alloca. 7245 if (!LifetimeObject) 7246 continue; 7247 7248 // First check that the Alloca is static, otherwise it won't have a 7249 // valid frame index. 7250 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7251 if (SI == FuncInfo.StaticAllocaMap.end()) 7252 return; 7253 7254 const int FrameIndex = SI->second; 7255 int64_t Offset; 7256 if (GetPointerBaseWithConstantOffset( 7257 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7258 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7259 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7260 Offset); 7261 DAG.setRoot(Res); 7262 } 7263 return; 7264 } 7265 case Intrinsic::pseudoprobe: { 7266 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7267 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7268 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7269 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7270 DAG.setRoot(Res); 7271 return; 7272 } 7273 case Intrinsic::invariant_start: 7274 // Discard region information. 7275 setValue(&I, 7276 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7277 return; 7278 case Intrinsic::invariant_end: 7279 // Discard region information. 7280 return; 7281 case Intrinsic::clear_cache: 7282 /// FunctionName may be null. 7283 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7284 lowerCallToExternalSymbol(I, FunctionName); 7285 return; 7286 case Intrinsic::donothing: 7287 case Intrinsic::seh_try_begin: 7288 case Intrinsic::seh_scope_begin: 7289 case Intrinsic::seh_try_end: 7290 case Intrinsic::seh_scope_end: 7291 // ignore 7292 return; 7293 case Intrinsic::experimental_stackmap: 7294 visitStackmap(I); 7295 return; 7296 case Intrinsic::experimental_patchpoint_void: 7297 case Intrinsic::experimental_patchpoint_i64: 7298 visitPatchpoint(I); 7299 return; 7300 case Intrinsic::experimental_gc_statepoint: 7301 LowerStatepoint(cast<GCStatepointInst>(I)); 7302 return; 7303 case Intrinsic::experimental_gc_result: 7304 visitGCResult(cast<GCResultInst>(I)); 7305 return; 7306 case Intrinsic::experimental_gc_relocate: 7307 visitGCRelocate(cast<GCRelocateInst>(I)); 7308 return; 7309 case Intrinsic::instrprof_cover: 7310 llvm_unreachable("instrprof failed to lower a cover"); 7311 case Intrinsic::instrprof_increment: 7312 llvm_unreachable("instrprof failed to lower an increment"); 7313 case Intrinsic::instrprof_timestamp: 7314 llvm_unreachable("instrprof failed to lower a timestamp"); 7315 case Intrinsic::instrprof_value_profile: 7316 llvm_unreachable("instrprof failed to lower a value profiling call"); 7317 case Intrinsic::instrprof_mcdc_parameters: 7318 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7319 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7320 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7321 case Intrinsic::instrprof_mcdc_condbitmap_update: 7322 llvm_unreachable("instrprof failed to lower an mcdc condbitmap update"); 7323 case Intrinsic::localescape: { 7324 MachineFunction &MF = DAG.getMachineFunction(); 7325 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7326 7327 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7328 // is the same on all targets. 7329 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7330 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7331 if (isa<ConstantPointerNull>(Arg)) 7332 continue; // Skip null pointers. They represent a hole in index space. 7333 AllocaInst *Slot = cast<AllocaInst>(Arg); 7334 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7335 "can only escape static allocas"); 7336 int FI = FuncInfo.StaticAllocaMap[Slot]; 7337 MCSymbol *FrameAllocSym = 7338 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7339 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7340 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7341 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7342 .addSym(FrameAllocSym) 7343 .addFrameIndex(FI); 7344 } 7345 7346 return; 7347 } 7348 7349 case Intrinsic::localrecover: { 7350 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7351 MachineFunction &MF = DAG.getMachineFunction(); 7352 7353 // Get the symbol that defines the frame offset. 7354 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7355 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7356 unsigned IdxVal = 7357 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7358 MCSymbol *FrameAllocSym = 7359 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7360 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7361 7362 Value *FP = I.getArgOperand(1); 7363 SDValue FPVal = getValue(FP); 7364 EVT PtrVT = FPVal.getValueType(); 7365 7366 // Create a MCSymbol for the label to avoid any target lowering 7367 // that would make this PC relative. 7368 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7369 SDValue OffsetVal = 7370 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7371 7372 // Add the offset to the FP. 7373 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7374 setValue(&I, Add); 7375 7376 return; 7377 } 7378 7379 case Intrinsic::eh_exceptionpointer: 7380 case Intrinsic::eh_exceptioncode: { 7381 // Get the exception pointer vreg, copy from it, and resize it to fit. 7382 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7383 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7384 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7385 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7386 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7387 if (Intrinsic == Intrinsic::eh_exceptioncode) 7388 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7389 setValue(&I, N); 7390 return; 7391 } 7392 case Intrinsic::xray_customevent: { 7393 // Here we want to make sure that the intrinsic behaves as if it has a 7394 // specific calling convention. 7395 const auto &Triple = DAG.getTarget().getTargetTriple(); 7396 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7397 return; 7398 7399 SmallVector<SDValue, 8> Ops; 7400 7401 // We want to say that we always want the arguments in registers. 7402 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7403 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7404 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7405 SDValue Chain = getRoot(); 7406 Ops.push_back(LogEntryVal); 7407 Ops.push_back(StrSizeVal); 7408 Ops.push_back(Chain); 7409 7410 // We need to enforce the calling convention for the callsite, so that 7411 // argument ordering is enforced correctly, and that register allocation can 7412 // see that some registers may be assumed clobbered and have to preserve 7413 // them across calls to the intrinsic. 7414 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7415 sdl, NodeTys, Ops); 7416 SDValue patchableNode = SDValue(MN, 0); 7417 DAG.setRoot(patchableNode); 7418 setValue(&I, patchableNode); 7419 return; 7420 } 7421 case Intrinsic::xray_typedevent: { 7422 // Here we want to make sure that the intrinsic behaves as if it has a 7423 // specific calling convention. 7424 const auto &Triple = DAG.getTarget().getTargetTriple(); 7425 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7426 return; 7427 7428 SmallVector<SDValue, 8> Ops; 7429 7430 // We want to say that we always want the arguments in registers. 7431 // It's unclear to me how manipulating the selection DAG here forces callers 7432 // to provide arguments in registers instead of on the stack. 7433 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7434 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7435 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7436 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7437 SDValue Chain = getRoot(); 7438 Ops.push_back(LogTypeId); 7439 Ops.push_back(LogEntryVal); 7440 Ops.push_back(StrSizeVal); 7441 Ops.push_back(Chain); 7442 7443 // We need to enforce the calling convention for the callsite, so that 7444 // argument ordering is enforced correctly, and that register allocation can 7445 // see that some registers may be assumed clobbered and have to preserve 7446 // them across calls to the intrinsic. 7447 MachineSDNode *MN = DAG.getMachineNode( 7448 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7449 SDValue patchableNode = SDValue(MN, 0); 7450 DAG.setRoot(patchableNode); 7451 setValue(&I, patchableNode); 7452 return; 7453 } 7454 case Intrinsic::experimental_deoptimize: 7455 LowerDeoptimizeCall(&I); 7456 return; 7457 case Intrinsic::experimental_stepvector: 7458 visitStepVector(I); 7459 return; 7460 case Intrinsic::vector_reduce_fadd: 7461 case Intrinsic::vector_reduce_fmul: 7462 case Intrinsic::vector_reduce_add: 7463 case Intrinsic::vector_reduce_mul: 7464 case Intrinsic::vector_reduce_and: 7465 case Intrinsic::vector_reduce_or: 7466 case Intrinsic::vector_reduce_xor: 7467 case Intrinsic::vector_reduce_smax: 7468 case Intrinsic::vector_reduce_smin: 7469 case Intrinsic::vector_reduce_umax: 7470 case Intrinsic::vector_reduce_umin: 7471 case Intrinsic::vector_reduce_fmax: 7472 case Intrinsic::vector_reduce_fmin: 7473 case Intrinsic::vector_reduce_fmaximum: 7474 case Intrinsic::vector_reduce_fminimum: 7475 visitVectorReduce(I, Intrinsic); 7476 return; 7477 7478 case Intrinsic::icall_branch_funnel: { 7479 SmallVector<SDValue, 16> Ops; 7480 Ops.push_back(getValue(I.getArgOperand(0))); 7481 7482 int64_t Offset; 7483 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7484 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7485 if (!Base) 7486 report_fatal_error( 7487 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7488 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7489 7490 struct BranchFunnelTarget { 7491 int64_t Offset; 7492 SDValue Target; 7493 }; 7494 SmallVector<BranchFunnelTarget, 8> Targets; 7495 7496 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7497 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7498 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7499 if (ElemBase != Base) 7500 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7501 "to the same GlobalValue"); 7502 7503 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7504 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7505 if (!GA) 7506 report_fatal_error( 7507 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7508 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7509 GA->getGlobal(), sdl, Val.getValueType(), 7510 GA->getOffset())}); 7511 } 7512 llvm::sort(Targets, 7513 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7514 return T1.Offset < T2.Offset; 7515 }); 7516 7517 for (auto &T : Targets) { 7518 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7519 Ops.push_back(T.Target); 7520 } 7521 7522 Ops.push_back(DAG.getRoot()); // Chain 7523 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7524 MVT::Other, Ops), 7525 0); 7526 DAG.setRoot(N); 7527 setValue(&I, N); 7528 HasTailCall = true; 7529 return; 7530 } 7531 7532 case Intrinsic::wasm_landingpad_index: 7533 // Information this intrinsic contained has been transferred to 7534 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7535 // delete it now. 7536 return; 7537 7538 case Intrinsic::aarch64_settag: 7539 case Intrinsic::aarch64_settag_zero: { 7540 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7541 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7542 SDValue Val = TSI.EmitTargetCodeForSetTag( 7543 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7544 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7545 ZeroMemory); 7546 DAG.setRoot(Val); 7547 setValue(&I, Val); 7548 return; 7549 } 7550 case Intrinsic::amdgcn_cs_chain: { 7551 assert(I.arg_size() == 5 && "Additional args not supported yet"); 7552 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 7553 "Non-zero flags not supported yet"); 7554 7555 // At this point we don't care if it's amdgpu_cs_chain or 7556 // amdgpu_cs_chain_preserve. 7557 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 7558 7559 Type *RetTy = I.getType(); 7560 assert(RetTy->isVoidTy() && "Should not return"); 7561 7562 SDValue Callee = getValue(I.getOperand(0)); 7563 7564 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 7565 // We'll also tack the value of the EXEC mask at the end. 7566 TargetLowering::ArgListTy Args; 7567 Args.reserve(3); 7568 7569 for (unsigned Idx : {2, 3, 1}) { 7570 TargetLowering::ArgListEntry Arg; 7571 Arg.Node = getValue(I.getOperand(Idx)); 7572 Arg.Ty = I.getOperand(Idx)->getType(); 7573 Arg.setAttributes(&I, Idx); 7574 Args.push_back(Arg); 7575 } 7576 7577 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 7578 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 7579 Args[2].IsInReg = true; // EXEC should be inreg 7580 7581 TargetLowering::CallLoweringInfo CLI(DAG); 7582 CLI.setDebugLoc(getCurSDLoc()) 7583 .setChain(getRoot()) 7584 .setCallee(CC, RetTy, Callee, std::move(Args)) 7585 .setNoReturn(true) 7586 .setTailCall(true) 7587 .setConvergent(I.isConvergent()); 7588 CLI.CB = &I; 7589 std::pair<SDValue, SDValue> Result = 7590 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 7591 (void)Result; 7592 assert(!Result.first.getNode() && !Result.second.getNode() && 7593 "Should've lowered as tail call"); 7594 7595 HasTailCall = true; 7596 return; 7597 } 7598 case Intrinsic::ptrmask: { 7599 SDValue Ptr = getValue(I.getOperand(0)); 7600 SDValue Mask = getValue(I.getOperand(1)); 7601 7602 EVT PtrVT = Ptr.getValueType(); 7603 assert(PtrVT == Mask.getValueType() && 7604 "Pointers with different index type are not supported by SDAG"); 7605 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 7606 return; 7607 } 7608 case Intrinsic::threadlocal_address: { 7609 setValue(&I, getValue(I.getOperand(0))); 7610 return; 7611 } 7612 case Intrinsic::get_active_lane_mask: { 7613 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7614 SDValue Index = getValue(I.getOperand(0)); 7615 EVT ElementVT = Index.getValueType(); 7616 7617 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7618 visitTargetIntrinsic(I, Intrinsic); 7619 return; 7620 } 7621 7622 SDValue TripCount = getValue(I.getOperand(1)); 7623 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 7624 CCVT.getVectorElementCount()); 7625 7626 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7627 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7628 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7629 SDValue VectorInduction = DAG.getNode( 7630 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7631 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7632 VectorTripCount, ISD::CondCode::SETULT); 7633 setValue(&I, SetCC); 7634 return; 7635 } 7636 case Intrinsic::experimental_get_vector_length: { 7637 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7638 "Expected positive VF"); 7639 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7640 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7641 7642 SDValue Count = getValue(I.getOperand(0)); 7643 EVT CountVT = Count.getValueType(); 7644 7645 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7646 visitTargetIntrinsic(I, Intrinsic); 7647 return; 7648 } 7649 7650 // Expand to a umin between the trip count and the maximum elements the type 7651 // can hold. 7652 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7653 7654 // Extend the trip count to at least the result VT. 7655 if (CountVT.bitsLT(VT)) { 7656 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7657 CountVT = VT; 7658 } 7659 7660 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7661 ElementCount::get(VF, IsScalable)); 7662 7663 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7664 // Clip to the result type if needed. 7665 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7666 7667 setValue(&I, Trunc); 7668 return; 7669 } 7670 case Intrinsic::experimental_cttz_elts: { 7671 auto DL = getCurSDLoc(); 7672 SDValue Op = getValue(I.getOperand(0)); 7673 EVT OpVT = Op.getValueType(); 7674 7675 if (!TLI.shouldExpandCttzElements(OpVT)) { 7676 visitTargetIntrinsic(I, Intrinsic); 7677 return; 7678 } 7679 7680 if (OpVT.getScalarType() != MVT::i1) { 7681 // Compare the input vector elements to zero & use to count trailing zeros 7682 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 7683 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 7684 OpVT.getVectorElementCount()); 7685 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 7686 } 7687 7688 // Find the smallest "sensible" element type to use for the expansion. 7689 ConstantRange CR( 7690 APInt(64, OpVT.getVectorElementCount().getKnownMinValue())); 7691 if (OpVT.isScalableVT()) 7692 CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64)); 7693 7694 // If the zero-is-poison flag is set, we can assume the upper limit 7695 // of the result is VF-1. 7696 if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero()) 7697 CR = CR.subtract(APInt(64, 1)); 7698 7699 unsigned EltWidth = I.getType()->getScalarSizeInBits(); 7700 EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits()); 7701 EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8); 7702 7703 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 7704 7705 // Create the new vector type & get the vector length 7706 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 7707 OpVT.getVectorElementCount()); 7708 7709 SDValue VL = 7710 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 7711 7712 SDValue StepVec = DAG.getStepVector(DL, NewVT); 7713 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 7714 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 7715 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 7716 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 7717 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 7718 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 7719 7720 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7721 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 7722 7723 setValue(&I, Ret); 7724 return; 7725 } 7726 case Intrinsic::vector_insert: { 7727 SDValue Vec = getValue(I.getOperand(0)); 7728 SDValue SubVec = getValue(I.getOperand(1)); 7729 SDValue Index = getValue(I.getOperand(2)); 7730 7731 // The intrinsic's index type is i64, but the SDNode requires an index type 7732 // suitable for the target. Convert the index as required. 7733 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7734 if (Index.getValueType() != VectorIdxTy) 7735 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7736 7737 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7738 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7739 Index)); 7740 return; 7741 } 7742 case Intrinsic::vector_extract: { 7743 SDValue Vec = getValue(I.getOperand(0)); 7744 SDValue Index = getValue(I.getOperand(1)); 7745 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7746 7747 // The intrinsic's index type is i64, but the SDNode requires an index type 7748 // suitable for the target. Convert the index as required. 7749 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7750 if (Index.getValueType() != VectorIdxTy) 7751 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7752 7753 setValue(&I, 7754 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7755 return; 7756 } 7757 case Intrinsic::experimental_vector_reverse: 7758 visitVectorReverse(I); 7759 return; 7760 case Intrinsic::experimental_vector_splice: 7761 visitVectorSplice(I); 7762 return; 7763 case Intrinsic::callbr_landingpad: 7764 visitCallBrLandingPad(I); 7765 return; 7766 case Intrinsic::experimental_vector_interleave2: 7767 visitVectorInterleave(I); 7768 return; 7769 case Intrinsic::experimental_vector_deinterleave2: 7770 visitVectorDeinterleave(I); 7771 return; 7772 case Intrinsic::experimental_convergence_anchor: 7773 case Intrinsic::experimental_convergence_entry: 7774 case Intrinsic::experimental_convergence_loop: 7775 visitConvergenceControl(I, Intrinsic); 7776 } 7777 } 7778 7779 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7780 const ConstrainedFPIntrinsic &FPI) { 7781 SDLoc sdl = getCurSDLoc(); 7782 7783 // We do not need to serialize constrained FP intrinsics against 7784 // each other or against (nonvolatile) loads, so they can be 7785 // chained like loads. 7786 SDValue Chain = DAG.getRoot(); 7787 SmallVector<SDValue, 4> Opers; 7788 Opers.push_back(Chain); 7789 if (FPI.isUnaryOp()) { 7790 Opers.push_back(getValue(FPI.getArgOperand(0))); 7791 } else if (FPI.isTernaryOp()) { 7792 Opers.push_back(getValue(FPI.getArgOperand(0))); 7793 Opers.push_back(getValue(FPI.getArgOperand(1))); 7794 Opers.push_back(getValue(FPI.getArgOperand(2))); 7795 } else { 7796 Opers.push_back(getValue(FPI.getArgOperand(0))); 7797 Opers.push_back(getValue(FPI.getArgOperand(1))); 7798 } 7799 7800 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7801 assert(Result.getNode()->getNumValues() == 2); 7802 7803 // Push node to the appropriate list so that future instructions can be 7804 // chained up correctly. 7805 SDValue OutChain = Result.getValue(1); 7806 switch (EB) { 7807 case fp::ExceptionBehavior::ebIgnore: 7808 // The only reason why ebIgnore nodes still need to be chained is that 7809 // they might depend on the current rounding mode, and therefore must 7810 // not be moved across instruction that may change that mode. 7811 [[fallthrough]]; 7812 case fp::ExceptionBehavior::ebMayTrap: 7813 // These must not be moved across calls or instructions that may change 7814 // floating-point exception masks. 7815 PendingConstrainedFP.push_back(OutChain); 7816 break; 7817 case fp::ExceptionBehavior::ebStrict: 7818 // These must not be moved across calls or instructions that may change 7819 // floating-point exception masks or read floating-point exception flags. 7820 // In addition, they cannot be optimized out even if unused. 7821 PendingConstrainedFPStrict.push_back(OutChain); 7822 break; 7823 } 7824 }; 7825 7826 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7827 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7828 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7829 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7830 7831 SDNodeFlags Flags; 7832 if (EB == fp::ExceptionBehavior::ebIgnore) 7833 Flags.setNoFPExcept(true); 7834 7835 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7836 Flags.copyFMF(*FPOp); 7837 7838 unsigned Opcode; 7839 switch (FPI.getIntrinsicID()) { 7840 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7841 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7842 case Intrinsic::INTRINSIC: \ 7843 Opcode = ISD::STRICT_##DAGN; \ 7844 break; 7845 #include "llvm/IR/ConstrainedOps.def" 7846 case Intrinsic::experimental_constrained_fmuladd: { 7847 Opcode = ISD::STRICT_FMA; 7848 // Break fmuladd into fmul and fadd. 7849 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7850 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7851 Opers.pop_back(); 7852 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7853 pushOutChain(Mul, EB); 7854 Opcode = ISD::STRICT_FADD; 7855 Opers.clear(); 7856 Opers.push_back(Mul.getValue(1)); 7857 Opers.push_back(Mul.getValue(0)); 7858 Opers.push_back(getValue(FPI.getArgOperand(2))); 7859 } 7860 break; 7861 } 7862 } 7863 7864 // A few strict DAG nodes carry additional operands that are not 7865 // set up by the default code above. 7866 switch (Opcode) { 7867 default: break; 7868 case ISD::STRICT_FP_ROUND: 7869 Opers.push_back( 7870 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7871 break; 7872 case ISD::STRICT_FSETCC: 7873 case ISD::STRICT_FSETCCS: { 7874 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7875 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7876 if (TM.Options.NoNaNsFPMath) 7877 Condition = getFCmpCodeWithoutNaN(Condition); 7878 Opers.push_back(DAG.getCondCode(Condition)); 7879 break; 7880 } 7881 } 7882 7883 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7884 pushOutChain(Result, EB); 7885 7886 SDValue FPResult = Result.getValue(0); 7887 setValue(&FPI, FPResult); 7888 } 7889 7890 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7891 std::optional<unsigned> ResOPC; 7892 switch (VPIntrin.getIntrinsicID()) { 7893 case Intrinsic::vp_ctlz: { 7894 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7895 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7896 break; 7897 } 7898 case Intrinsic::vp_cttz: { 7899 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7900 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7901 break; 7902 } 7903 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7904 case Intrinsic::VPID: \ 7905 ResOPC = ISD::VPSD; \ 7906 break; 7907 #include "llvm/IR/VPIntrinsics.def" 7908 } 7909 7910 if (!ResOPC) 7911 llvm_unreachable( 7912 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7913 7914 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7915 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7916 if (VPIntrin.getFastMathFlags().allowReassoc()) 7917 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7918 : ISD::VP_REDUCE_FMUL; 7919 } 7920 7921 return *ResOPC; 7922 } 7923 7924 void SelectionDAGBuilder::visitVPLoad( 7925 const VPIntrinsic &VPIntrin, EVT VT, 7926 const SmallVectorImpl<SDValue> &OpValues) { 7927 SDLoc DL = getCurSDLoc(); 7928 Value *PtrOperand = VPIntrin.getArgOperand(0); 7929 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7930 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7931 const MDNode *Ranges = getRangeMetadata(VPIntrin); 7932 SDValue LD; 7933 // Do not serialize variable-length loads of constant memory with 7934 // anything. 7935 if (!Alignment) 7936 Alignment = DAG.getEVTAlign(VT); 7937 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7938 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7939 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7940 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7941 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7942 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7943 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7944 MMO, false /*IsExpanding */); 7945 if (AddToChain) 7946 PendingLoads.push_back(LD.getValue(1)); 7947 setValue(&VPIntrin, LD); 7948 } 7949 7950 void SelectionDAGBuilder::visitVPGather( 7951 const VPIntrinsic &VPIntrin, EVT VT, 7952 const SmallVectorImpl<SDValue> &OpValues) { 7953 SDLoc DL = getCurSDLoc(); 7954 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7955 Value *PtrOperand = VPIntrin.getArgOperand(0); 7956 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7957 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7958 const MDNode *Ranges = getRangeMetadata(VPIntrin); 7959 SDValue LD; 7960 if (!Alignment) 7961 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7962 unsigned AS = 7963 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7964 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7965 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7966 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7967 SDValue Base, Index, Scale; 7968 ISD::MemIndexType IndexType; 7969 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7970 this, VPIntrin.getParent(), 7971 VT.getScalarStoreSize()); 7972 if (!UniformBase) { 7973 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7974 Index = getValue(PtrOperand); 7975 IndexType = ISD::SIGNED_SCALED; 7976 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7977 } 7978 EVT IdxVT = Index.getValueType(); 7979 EVT EltTy = IdxVT.getVectorElementType(); 7980 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7981 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7982 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7983 } 7984 LD = DAG.getGatherVP( 7985 DAG.getVTList(VT, MVT::Other), VT, DL, 7986 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7987 IndexType); 7988 PendingLoads.push_back(LD.getValue(1)); 7989 setValue(&VPIntrin, LD); 7990 } 7991 7992 void SelectionDAGBuilder::visitVPStore( 7993 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7994 SDLoc DL = getCurSDLoc(); 7995 Value *PtrOperand = VPIntrin.getArgOperand(1); 7996 EVT VT = OpValues[0].getValueType(); 7997 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7998 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7999 SDValue ST; 8000 if (!Alignment) 8001 Alignment = DAG.getEVTAlign(VT); 8002 SDValue Ptr = OpValues[1]; 8003 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 8004 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8005 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 8006 MemoryLocation::UnknownSize, *Alignment, AAInfo); 8007 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 8008 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 8009 /* IsTruncating */ false, /*IsCompressing*/ false); 8010 DAG.setRoot(ST); 8011 setValue(&VPIntrin, ST); 8012 } 8013 8014 void SelectionDAGBuilder::visitVPScatter( 8015 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8016 SDLoc DL = getCurSDLoc(); 8017 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8018 Value *PtrOperand = VPIntrin.getArgOperand(1); 8019 EVT VT = OpValues[0].getValueType(); 8020 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8021 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8022 SDValue ST; 8023 if (!Alignment) 8024 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8025 unsigned AS = 8026 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8027 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8028 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8029 MemoryLocation::UnknownSize, *Alignment, AAInfo); 8030 SDValue Base, Index, Scale; 8031 ISD::MemIndexType IndexType; 8032 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8033 this, VPIntrin.getParent(), 8034 VT.getScalarStoreSize()); 8035 if (!UniformBase) { 8036 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8037 Index = getValue(PtrOperand); 8038 IndexType = ISD::SIGNED_SCALED; 8039 Scale = 8040 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8041 } 8042 EVT IdxVT = Index.getValueType(); 8043 EVT EltTy = IdxVT.getVectorElementType(); 8044 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8045 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8046 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8047 } 8048 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 8049 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 8050 OpValues[2], OpValues[3]}, 8051 MMO, IndexType); 8052 DAG.setRoot(ST); 8053 setValue(&VPIntrin, ST); 8054 } 8055 8056 void SelectionDAGBuilder::visitVPStridedLoad( 8057 const VPIntrinsic &VPIntrin, EVT VT, 8058 const SmallVectorImpl<SDValue> &OpValues) { 8059 SDLoc DL = getCurSDLoc(); 8060 Value *PtrOperand = VPIntrin.getArgOperand(0); 8061 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8062 if (!Alignment) 8063 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8064 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8065 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8066 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8067 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8068 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8069 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8070 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8071 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8072 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 8073 8074 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 8075 OpValues[2], OpValues[3], MMO, 8076 false /*IsExpanding*/); 8077 8078 if (AddToChain) 8079 PendingLoads.push_back(LD.getValue(1)); 8080 setValue(&VPIntrin, LD); 8081 } 8082 8083 void SelectionDAGBuilder::visitVPStridedStore( 8084 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8085 SDLoc DL = getCurSDLoc(); 8086 Value *PtrOperand = VPIntrin.getArgOperand(1); 8087 EVT VT = OpValues[0].getValueType(); 8088 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8089 if (!Alignment) 8090 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8091 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8092 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8093 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8094 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8095 MemoryLocation::UnknownSize, *Alignment, AAInfo); 8096 8097 SDValue ST = DAG.getStridedStoreVP( 8098 getMemoryRoot(), DL, OpValues[0], OpValues[1], 8099 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 8100 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 8101 /*IsCompressing*/ false); 8102 8103 DAG.setRoot(ST); 8104 setValue(&VPIntrin, ST); 8105 } 8106 8107 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8108 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8109 SDLoc DL = getCurSDLoc(); 8110 8111 ISD::CondCode Condition; 8112 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8113 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8114 if (IsFP) { 8115 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8116 // flags, but calls that don't return floating-point types can't be 8117 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8118 Condition = getFCmpCondCode(CondCode); 8119 if (TM.Options.NoNaNsFPMath) 8120 Condition = getFCmpCodeWithoutNaN(Condition); 8121 } else { 8122 Condition = getICmpCondCode(CondCode); 8123 } 8124 8125 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8126 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8127 // #2 is the condition code 8128 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8129 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8130 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8131 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8132 "Unexpected target EVL type"); 8133 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8134 8135 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8136 VPIntrin.getType()); 8137 setValue(&VPIntrin, 8138 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8139 } 8140 8141 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8142 const VPIntrinsic &VPIntrin) { 8143 SDLoc DL = getCurSDLoc(); 8144 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8145 8146 auto IID = VPIntrin.getIntrinsicID(); 8147 8148 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8149 return visitVPCmp(*CmpI); 8150 8151 SmallVector<EVT, 4> ValueVTs; 8152 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8153 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8154 SDVTList VTs = DAG.getVTList(ValueVTs); 8155 8156 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8157 8158 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8159 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8160 "Unexpected target EVL type"); 8161 8162 // Request operands. 8163 SmallVector<SDValue, 7> OpValues; 8164 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8165 auto Op = getValue(VPIntrin.getArgOperand(I)); 8166 if (I == EVLParamPos) 8167 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8168 OpValues.push_back(Op); 8169 } 8170 8171 switch (Opcode) { 8172 default: { 8173 SDNodeFlags SDFlags; 8174 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8175 SDFlags.copyFMF(*FPMO); 8176 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8177 setValue(&VPIntrin, Result); 8178 break; 8179 } 8180 case ISD::VP_LOAD: 8181 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8182 break; 8183 case ISD::VP_GATHER: 8184 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8185 break; 8186 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8187 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8188 break; 8189 case ISD::VP_STORE: 8190 visitVPStore(VPIntrin, OpValues); 8191 break; 8192 case ISD::VP_SCATTER: 8193 visitVPScatter(VPIntrin, OpValues); 8194 break; 8195 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8196 visitVPStridedStore(VPIntrin, OpValues); 8197 break; 8198 case ISD::VP_FMULADD: { 8199 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8200 SDNodeFlags SDFlags; 8201 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8202 SDFlags.copyFMF(*FPMO); 8203 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8204 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8205 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8206 } else { 8207 SDValue Mul = DAG.getNode( 8208 ISD::VP_FMUL, DL, VTs, 8209 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8210 SDValue Add = 8211 DAG.getNode(ISD::VP_FADD, DL, VTs, 8212 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8213 setValue(&VPIntrin, Add); 8214 } 8215 break; 8216 } 8217 case ISD::VP_IS_FPCLASS: { 8218 const DataLayout DLayout = DAG.getDataLayout(); 8219 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8220 auto Constant = OpValues[1]->getAsZExtVal(); 8221 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8222 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8223 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8224 setValue(&VPIntrin, V); 8225 return; 8226 } 8227 case ISD::VP_INTTOPTR: { 8228 SDValue N = OpValues[0]; 8229 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8230 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8231 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8232 OpValues[2]); 8233 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8234 OpValues[2]); 8235 setValue(&VPIntrin, N); 8236 break; 8237 } 8238 case ISD::VP_PTRTOINT: { 8239 SDValue N = OpValues[0]; 8240 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8241 VPIntrin.getType()); 8242 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8243 VPIntrin.getOperand(0)->getType()); 8244 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8245 OpValues[2]); 8246 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8247 OpValues[2]); 8248 setValue(&VPIntrin, N); 8249 break; 8250 } 8251 case ISD::VP_ABS: 8252 case ISD::VP_CTLZ: 8253 case ISD::VP_CTLZ_ZERO_UNDEF: 8254 case ISD::VP_CTTZ: 8255 case ISD::VP_CTTZ_ZERO_UNDEF: { 8256 SDValue Result = 8257 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8258 setValue(&VPIntrin, Result); 8259 break; 8260 } 8261 } 8262 } 8263 8264 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8265 const BasicBlock *EHPadBB, 8266 MCSymbol *&BeginLabel) { 8267 MachineFunction &MF = DAG.getMachineFunction(); 8268 MachineModuleInfo &MMI = MF.getMMI(); 8269 8270 // Insert a label before the invoke call to mark the try range. This can be 8271 // used to detect deletion of the invoke via the MachineModuleInfo. 8272 BeginLabel = MMI.getContext().createTempSymbol(); 8273 8274 // For SjLj, keep track of which landing pads go with which invokes 8275 // so as to maintain the ordering of pads in the LSDA. 8276 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 8277 if (CallSiteIndex) { 8278 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8279 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 8280 8281 // Now that the call site is handled, stop tracking it. 8282 MMI.setCurrentCallSite(0); 8283 } 8284 8285 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8286 } 8287 8288 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8289 const BasicBlock *EHPadBB, 8290 MCSymbol *BeginLabel) { 8291 assert(BeginLabel && "BeginLabel should've been set"); 8292 8293 MachineFunction &MF = DAG.getMachineFunction(); 8294 MachineModuleInfo &MMI = MF.getMMI(); 8295 8296 // Insert a label at the end of the invoke call to mark the try range. This 8297 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8298 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 8299 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8300 8301 // Inform MachineModuleInfo of range. 8302 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8303 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8304 // actually use outlined funclets and their LSDA info style. 8305 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8306 assert(II && "II should've been set"); 8307 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8308 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8309 } else if (!isScopedEHPersonality(Pers)) { 8310 assert(EHPadBB); 8311 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 8312 } 8313 8314 return Chain; 8315 } 8316 8317 std::pair<SDValue, SDValue> 8318 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8319 const BasicBlock *EHPadBB) { 8320 MCSymbol *BeginLabel = nullptr; 8321 8322 if (EHPadBB) { 8323 // Both PendingLoads and PendingExports must be flushed here; 8324 // this call might not return. 8325 (void)getRoot(); 8326 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8327 CLI.setChain(getRoot()); 8328 } 8329 8330 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8331 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8332 8333 assert((CLI.IsTailCall || Result.second.getNode()) && 8334 "Non-null chain expected with non-tail call!"); 8335 assert((Result.second.getNode() || !Result.first.getNode()) && 8336 "Null value expected with tail call!"); 8337 8338 if (!Result.second.getNode()) { 8339 // As a special case, a null chain means that a tail call has been emitted 8340 // and the DAG root is already updated. 8341 HasTailCall = true; 8342 8343 // Since there's no actual continuation from this block, nothing can be 8344 // relying on us setting vregs for them. 8345 PendingExports.clear(); 8346 } else { 8347 DAG.setRoot(Result.second); 8348 } 8349 8350 if (EHPadBB) { 8351 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8352 BeginLabel)); 8353 } 8354 8355 return Result; 8356 } 8357 8358 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8359 bool isTailCall, 8360 bool isMustTailCall, 8361 const BasicBlock *EHPadBB) { 8362 auto &DL = DAG.getDataLayout(); 8363 FunctionType *FTy = CB.getFunctionType(); 8364 Type *RetTy = CB.getType(); 8365 8366 TargetLowering::ArgListTy Args; 8367 Args.reserve(CB.arg_size()); 8368 8369 const Value *SwiftErrorVal = nullptr; 8370 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8371 8372 if (isTailCall) { 8373 // Avoid emitting tail calls in functions with the disable-tail-calls 8374 // attribute. 8375 auto *Caller = CB.getParent()->getParent(); 8376 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8377 "true" && !isMustTailCall) 8378 isTailCall = false; 8379 8380 // We can't tail call inside a function with a swifterror argument. Lowering 8381 // does not support this yet. It would have to move into the swifterror 8382 // register before the call. 8383 if (TLI.supportSwiftError() && 8384 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8385 isTailCall = false; 8386 } 8387 8388 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8389 TargetLowering::ArgListEntry Entry; 8390 const Value *V = *I; 8391 8392 // Skip empty types 8393 if (V->getType()->isEmptyTy()) 8394 continue; 8395 8396 SDValue ArgNode = getValue(V); 8397 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8398 8399 Entry.setAttributes(&CB, I - CB.arg_begin()); 8400 8401 // Use swifterror virtual register as input to the call. 8402 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8403 SwiftErrorVal = V; 8404 // We find the virtual register for the actual swifterror argument. 8405 // Instead of using the Value, we use the virtual register instead. 8406 Entry.Node = 8407 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8408 EVT(TLI.getPointerTy(DL))); 8409 } 8410 8411 Args.push_back(Entry); 8412 8413 // If we have an explicit sret argument that is an Instruction, (i.e., it 8414 // might point to function-local memory), we can't meaningfully tail-call. 8415 if (Entry.IsSRet && isa<Instruction>(V)) 8416 isTailCall = false; 8417 } 8418 8419 // If call site has a cfguardtarget operand bundle, create and add an 8420 // additional ArgListEntry. 8421 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8422 TargetLowering::ArgListEntry Entry; 8423 Value *V = Bundle->Inputs[0]; 8424 SDValue ArgNode = getValue(V); 8425 Entry.Node = ArgNode; 8426 Entry.Ty = V->getType(); 8427 Entry.IsCFGuardTarget = true; 8428 Args.push_back(Entry); 8429 } 8430 8431 // Check if target-independent constraints permit a tail call here. 8432 // Target-dependent constraints are checked within TLI->LowerCallTo. 8433 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8434 isTailCall = false; 8435 8436 // Disable tail calls if there is an swifterror argument. Targets have not 8437 // been updated to support tail calls. 8438 if (TLI.supportSwiftError() && SwiftErrorVal) 8439 isTailCall = false; 8440 8441 ConstantInt *CFIType = nullptr; 8442 if (CB.isIndirectCall()) { 8443 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8444 if (!TLI.supportKCFIBundles()) 8445 report_fatal_error( 8446 "Target doesn't support calls with kcfi operand bundles."); 8447 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8448 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8449 } 8450 } 8451 8452 SDValue ConvControlToken; 8453 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) { 8454 auto *Token = Bundle->Inputs[0].get(); 8455 ConvControlToken = getValue(Token); 8456 } else { 8457 ConvControlToken = DAG.getUNDEF(MVT::Untyped); 8458 } 8459 8460 TargetLowering::CallLoweringInfo CLI(DAG); 8461 CLI.setDebugLoc(getCurSDLoc()) 8462 .setChain(getRoot()) 8463 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8464 .setTailCall(isTailCall) 8465 .setConvergent(CB.isConvergent()) 8466 .setIsPreallocated( 8467 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8468 .setCFIType(CFIType) 8469 .setConvergenceControlToken(ConvControlToken); 8470 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8471 8472 if (Result.first.getNode()) { 8473 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8474 setValue(&CB, Result.first); 8475 } 8476 8477 // The last element of CLI.InVals has the SDValue for swifterror return. 8478 // Here we copy it to a virtual register and update SwiftErrorMap for 8479 // book-keeping. 8480 if (SwiftErrorVal && TLI.supportSwiftError()) { 8481 // Get the last element of InVals. 8482 SDValue Src = CLI.InVals.back(); 8483 Register VReg = 8484 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8485 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8486 DAG.setRoot(CopyNode); 8487 } 8488 } 8489 8490 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8491 SelectionDAGBuilder &Builder) { 8492 // Check to see if this load can be trivially constant folded, e.g. if the 8493 // input is from a string literal. 8494 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8495 // Cast pointer to the type we really want to load. 8496 Type *LoadTy = 8497 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8498 if (LoadVT.isVector()) 8499 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8500 8501 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8502 PointerType::getUnqual(LoadTy)); 8503 8504 if (const Constant *LoadCst = 8505 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8506 LoadTy, Builder.DAG.getDataLayout())) 8507 return Builder.getValue(LoadCst); 8508 } 8509 8510 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8511 // still constant memory, the input chain can be the entry node. 8512 SDValue Root; 8513 bool ConstantMemory = false; 8514 8515 // Do not serialize (non-volatile) loads of constant memory with anything. 8516 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8517 Root = Builder.DAG.getEntryNode(); 8518 ConstantMemory = true; 8519 } else { 8520 // Do not serialize non-volatile loads against each other. 8521 Root = Builder.DAG.getRoot(); 8522 } 8523 8524 SDValue Ptr = Builder.getValue(PtrVal); 8525 SDValue LoadVal = 8526 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8527 MachinePointerInfo(PtrVal), Align(1)); 8528 8529 if (!ConstantMemory) 8530 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8531 return LoadVal; 8532 } 8533 8534 /// Record the value for an instruction that produces an integer result, 8535 /// converting the type where necessary. 8536 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8537 SDValue Value, 8538 bool IsSigned) { 8539 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8540 I.getType(), true); 8541 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8542 setValue(&I, Value); 8543 } 8544 8545 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8546 /// true and lower it. Otherwise return false, and it will be lowered like a 8547 /// normal call. 8548 /// The caller already checked that \p I calls the appropriate LibFunc with a 8549 /// correct prototype. 8550 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8551 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8552 const Value *Size = I.getArgOperand(2); 8553 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8554 if (CSize && CSize->getZExtValue() == 0) { 8555 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8556 I.getType(), true); 8557 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8558 return true; 8559 } 8560 8561 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8562 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8563 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8564 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8565 if (Res.first.getNode()) { 8566 processIntegerCallValue(I, Res.first, true); 8567 PendingLoads.push_back(Res.second); 8568 return true; 8569 } 8570 8571 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8572 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8573 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8574 return false; 8575 8576 // If the target has a fast compare for the given size, it will return a 8577 // preferred load type for that size. Require that the load VT is legal and 8578 // that the target supports unaligned loads of that type. Otherwise, return 8579 // INVALID. 8580 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8581 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8582 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8583 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8584 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8585 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8586 // TODO: Check alignment of src and dest ptrs. 8587 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8588 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8589 if (!TLI.isTypeLegal(LVT) || 8590 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8591 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8592 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8593 } 8594 8595 return LVT; 8596 }; 8597 8598 // This turns into unaligned loads. We only do this if the target natively 8599 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8600 // we'll only produce a small number of byte loads. 8601 MVT LoadVT; 8602 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8603 switch (NumBitsToCompare) { 8604 default: 8605 return false; 8606 case 16: 8607 LoadVT = MVT::i16; 8608 break; 8609 case 32: 8610 LoadVT = MVT::i32; 8611 break; 8612 case 64: 8613 case 128: 8614 case 256: 8615 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8616 break; 8617 } 8618 8619 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8620 return false; 8621 8622 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8623 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8624 8625 // Bitcast to a wide integer type if the loads are vectors. 8626 if (LoadVT.isVector()) { 8627 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8628 LoadL = DAG.getBitcast(CmpVT, LoadL); 8629 LoadR = DAG.getBitcast(CmpVT, LoadR); 8630 } 8631 8632 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8633 processIntegerCallValue(I, Cmp, false); 8634 return true; 8635 } 8636 8637 /// See if we can lower a memchr call into an optimized form. If so, return 8638 /// true and lower it. Otherwise return false, and it will be lowered like a 8639 /// normal call. 8640 /// The caller already checked that \p I calls the appropriate LibFunc with a 8641 /// correct prototype. 8642 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8643 const Value *Src = I.getArgOperand(0); 8644 const Value *Char = I.getArgOperand(1); 8645 const Value *Length = I.getArgOperand(2); 8646 8647 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8648 std::pair<SDValue, SDValue> Res = 8649 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8650 getValue(Src), getValue(Char), getValue(Length), 8651 MachinePointerInfo(Src)); 8652 if (Res.first.getNode()) { 8653 setValue(&I, Res.first); 8654 PendingLoads.push_back(Res.second); 8655 return true; 8656 } 8657 8658 return false; 8659 } 8660 8661 /// See if we can lower a mempcpy call into an optimized form. If so, return 8662 /// true and lower it. Otherwise return false, and it will be lowered like a 8663 /// normal call. 8664 /// The caller already checked that \p I calls the appropriate LibFunc with a 8665 /// correct prototype. 8666 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8667 SDValue Dst = getValue(I.getArgOperand(0)); 8668 SDValue Src = getValue(I.getArgOperand(1)); 8669 SDValue Size = getValue(I.getArgOperand(2)); 8670 8671 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8672 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8673 // DAG::getMemcpy needs Alignment to be defined. 8674 Align Alignment = std::min(DstAlign, SrcAlign); 8675 8676 SDLoc sdl = getCurSDLoc(); 8677 8678 // In the mempcpy context we need to pass in a false value for isTailCall 8679 // because the return pointer needs to be adjusted by the size of 8680 // the copied memory. 8681 SDValue Root = getMemoryRoot(); 8682 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8683 /*isTailCall=*/false, 8684 MachinePointerInfo(I.getArgOperand(0)), 8685 MachinePointerInfo(I.getArgOperand(1)), 8686 I.getAAMetadata()); 8687 assert(MC.getNode() != nullptr && 8688 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8689 DAG.setRoot(MC); 8690 8691 // Check if Size needs to be truncated or extended. 8692 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8693 8694 // Adjust return pointer to point just past the last dst byte. 8695 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8696 Dst, Size); 8697 setValue(&I, DstPlusSize); 8698 return true; 8699 } 8700 8701 /// See if we can lower a strcpy call into an optimized form. If so, return 8702 /// true and lower it, otherwise return false and it will be lowered like a 8703 /// normal call. 8704 /// The caller already checked that \p I calls the appropriate LibFunc with a 8705 /// correct prototype. 8706 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8707 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8708 8709 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8710 std::pair<SDValue, SDValue> Res = 8711 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8712 getValue(Arg0), getValue(Arg1), 8713 MachinePointerInfo(Arg0), 8714 MachinePointerInfo(Arg1), isStpcpy); 8715 if (Res.first.getNode()) { 8716 setValue(&I, Res.first); 8717 DAG.setRoot(Res.second); 8718 return true; 8719 } 8720 8721 return false; 8722 } 8723 8724 /// See if we can lower a strcmp call into an optimized form. If so, return 8725 /// true and lower it, otherwise return false and it will be lowered like a 8726 /// normal call. 8727 /// The caller already checked that \p I calls the appropriate LibFunc with a 8728 /// correct prototype. 8729 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8730 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8731 8732 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8733 std::pair<SDValue, SDValue> Res = 8734 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8735 getValue(Arg0), getValue(Arg1), 8736 MachinePointerInfo(Arg0), 8737 MachinePointerInfo(Arg1)); 8738 if (Res.first.getNode()) { 8739 processIntegerCallValue(I, Res.first, true); 8740 PendingLoads.push_back(Res.second); 8741 return true; 8742 } 8743 8744 return false; 8745 } 8746 8747 /// See if we can lower a strlen call into an optimized form. If so, return 8748 /// true and lower it, otherwise return false and it will be lowered like a 8749 /// normal call. 8750 /// The caller already checked that \p I calls the appropriate LibFunc with a 8751 /// correct prototype. 8752 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8753 const Value *Arg0 = I.getArgOperand(0); 8754 8755 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8756 std::pair<SDValue, SDValue> Res = 8757 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8758 getValue(Arg0), MachinePointerInfo(Arg0)); 8759 if (Res.first.getNode()) { 8760 processIntegerCallValue(I, Res.first, false); 8761 PendingLoads.push_back(Res.second); 8762 return true; 8763 } 8764 8765 return false; 8766 } 8767 8768 /// See if we can lower a strnlen call into an optimized form. If so, return 8769 /// true and lower it, otherwise return false and it will be lowered like a 8770 /// normal call. 8771 /// The caller already checked that \p I calls the appropriate LibFunc with a 8772 /// correct prototype. 8773 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8774 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8775 8776 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8777 std::pair<SDValue, SDValue> Res = 8778 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8779 getValue(Arg0), getValue(Arg1), 8780 MachinePointerInfo(Arg0)); 8781 if (Res.first.getNode()) { 8782 processIntegerCallValue(I, Res.first, false); 8783 PendingLoads.push_back(Res.second); 8784 return true; 8785 } 8786 8787 return false; 8788 } 8789 8790 /// See if we can lower a unary floating-point operation into an SDNode with 8791 /// the specified Opcode. If so, return true and lower it, otherwise return 8792 /// false and it will be lowered like a normal call. 8793 /// The caller already checked that \p I calls the appropriate LibFunc with a 8794 /// correct prototype. 8795 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8796 unsigned Opcode) { 8797 // We already checked this call's prototype; verify it doesn't modify errno. 8798 if (!I.onlyReadsMemory()) 8799 return false; 8800 8801 SDNodeFlags Flags; 8802 Flags.copyFMF(cast<FPMathOperator>(I)); 8803 8804 SDValue Tmp = getValue(I.getArgOperand(0)); 8805 setValue(&I, 8806 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8807 return true; 8808 } 8809 8810 /// See if we can lower a binary floating-point operation into an SDNode with 8811 /// the specified Opcode. If so, return true and lower it. Otherwise return 8812 /// false, and it will be lowered like a normal call. 8813 /// The caller already checked that \p I calls the appropriate LibFunc with a 8814 /// correct prototype. 8815 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8816 unsigned Opcode) { 8817 // We already checked this call's prototype; verify it doesn't modify errno. 8818 if (!I.onlyReadsMemory()) 8819 return false; 8820 8821 SDNodeFlags Flags; 8822 Flags.copyFMF(cast<FPMathOperator>(I)); 8823 8824 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8825 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8826 EVT VT = Tmp0.getValueType(); 8827 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8828 return true; 8829 } 8830 8831 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8832 // Handle inline assembly differently. 8833 if (I.isInlineAsm()) { 8834 visitInlineAsm(I); 8835 return; 8836 } 8837 8838 diagnoseDontCall(I); 8839 8840 if (Function *F = I.getCalledFunction()) { 8841 if (F->isDeclaration()) { 8842 // Is this an LLVM intrinsic or a target-specific intrinsic? 8843 unsigned IID = F->getIntrinsicID(); 8844 if (!IID) 8845 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8846 IID = II->getIntrinsicID(F); 8847 8848 if (IID) { 8849 visitIntrinsicCall(I, IID); 8850 return; 8851 } 8852 } 8853 8854 // Check for well-known libc/libm calls. If the function is internal, it 8855 // can't be a library call. Don't do the check if marked as nobuiltin for 8856 // some reason or the call site requires strict floating point semantics. 8857 LibFunc Func; 8858 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8859 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8860 LibInfo->hasOptimizedCodeGen(Func)) { 8861 switch (Func) { 8862 default: break; 8863 case LibFunc_bcmp: 8864 if (visitMemCmpBCmpCall(I)) 8865 return; 8866 break; 8867 case LibFunc_copysign: 8868 case LibFunc_copysignf: 8869 case LibFunc_copysignl: 8870 // We already checked this call's prototype; verify it doesn't modify 8871 // errno. 8872 if (I.onlyReadsMemory()) { 8873 SDValue LHS = getValue(I.getArgOperand(0)); 8874 SDValue RHS = getValue(I.getArgOperand(1)); 8875 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8876 LHS.getValueType(), LHS, RHS)); 8877 return; 8878 } 8879 break; 8880 case LibFunc_fabs: 8881 case LibFunc_fabsf: 8882 case LibFunc_fabsl: 8883 if (visitUnaryFloatCall(I, ISD::FABS)) 8884 return; 8885 break; 8886 case LibFunc_fmin: 8887 case LibFunc_fminf: 8888 case LibFunc_fminl: 8889 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8890 return; 8891 break; 8892 case LibFunc_fmax: 8893 case LibFunc_fmaxf: 8894 case LibFunc_fmaxl: 8895 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8896 return; 8897 break; 8898 case LibFunc_sin: 8899 case LibFunc_sinf: 8900 case LibFunc_sinl: 8901 if (visitUnaryFloatCall(I, ISD::FSIN)) 8902 return; 8903 break; 8904 case LibFunc_cos: 8905 case LibFunc_cosf: 8906 case LibFunc_cosl: 8907 if (visitUnaryFloatCall(I, ISD::FCOS)) 8908 return; 8909 break; 8910 case LibFunc_sqrt: 8911 case LibFunc_sqrtf: 8912 case LibFunc_sqrtl: 8913 case LibFunc_sqrt_finite: 8914 case LibFunc_sqrtf_finite: 8915 case LibFunc_sqrtl_finite: 8916 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8917 return; 8918 break; 8919 case LibFunc_floor: 8920 case LibFunc_floorf: 8921 case LibFunc_floorl: 8922 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8923 return; 8924 break; 8925 case LibFunc_nearbyint: 8926 case LibFunc_nearbyintf: 8927 case LibFunc_nearbyintl: 8928 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8929 return; 8930 break; 8931 case LibFunc_ceil: 8932 case LibFunc_ceilf: 8933 case LibFunc_ceill: 8934 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8935 return; 8936 break; 8937 case LibFunc_rint: 8938 case LibFunc_rintf: 8939 case LibFunc_rintl: 8940 if (visitUnaryFloatCall(I, ISD::FRINT)) 8941 return; 8942 break; 8943 case LibFunc_round: 8944 case LibFunc_roundf: 8945 case LibFunc_roundl: 8946 if (visitUnaryFloatCall(I, ISD::FROUND)) 8947 return; 8948 break; 8949 case LibFunc_trunc: 8950 case LibFunc_truncf: 8951 case LibFunc_truncl: 8952 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8953 return; 8954 break; 8955 case LibFunc_log2: 8956 case LibFunc_log2f: 8957 case LibFunc_log2l: 8958 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8959 return; 8960 break; 8961 case LibFunc_exp2: 8962 case LibFunc_exp2f: 8963 case LibFunc_exp2l: 8964 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8965 return; 8966 break; 8967 case LibFunc_exp10: 8968 case LibFunc_exp10f: 8969 case LibFunc_exp10l: 8970 if (visitUnaryFloatCall(I, ISD::FEXP10)) 8971 return; 8972 break; 8973 case LibFunc_ldexp: 8974 case LibFunc_ldexpf: 8975 case LibFunc_ldexpl: 8976 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 8977 return; 8978 break; 8979 case LibFunc_memcmp: 8980 if (visitMemCmpBCmpCall(I)) 8981 return; 8982 break; 8983 case LibFunc_mempcpy: 8984 if (visitMemPCpyCall(I)) 8985 return; 8986 break; 8987 case LibFunc_memchr: 8988 if (visitMemChrCall(I)) 8989 return; 8990 break; 8991 case LibFunc_strcpy: 8992 if (visitStrCpyCall(I, false)) 8993 return; 8994 break; 8995 case LibFunc_stpcpy: 8996 if (visitStrCpyCall(I, true)) 8997 return; 8998 break; 8999 case LibFunc_strcmp: 9000 if (visitStrCmpCall(I)) 9001 return; 9002 break; 9003 case LibFunc_strlen: 9004 if (visitStrLenCall(I)) 9005 return; 9006 break; 9007 case LibFunc_strnlen: 9008 if (visitStrNLenCall(I)) 9009 return; 9010 break; 9011 } 9012 } 9013 } 9014 9015 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 9016 // have to do anything here to lower funclet bundles. 9017 // CFGuardTarget bundles are lowered in LowerCallTo. 9018 assert(!I.hasOperandBundlesOtherThan( 9019 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 9020 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 9021 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi, 9022 LLVMContext::OB_convergencectrl}) && 9023 "Cannot lower calls with arbitrary operand bundles!"); 9024 9025 SDValue Callee = getValue(I.getCalledOperand()); 9026 9027 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 9028 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 9029 else 9030 // Check if we can potentially perform a tail call. More detailed checking 9031 // is be done within LowerCallTo, after more information about the call is 9032 // known. 9033 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 9034 } 9035 9036 namespace { 9037 9038 /// AsmOperandInfo - This contains information for each constraint that we are 9039 /// lowering. 9040 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 9041 public: 9042 /// CallOperand - If this is the result output operand or a clobber 9043 /// this is null, otherwise it is the incoming operand to the CallInst. 9044 /// This gets modified as the asm is processed. 9045 SDValue CallOperand; 9046 9047 /// AssignedRegs - If this is a register or register class operand, this 9048 /// contains the set of register corresponding to the operand. 9049 RegsForValue AssignedRegs; 9050 9051 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 9052 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 9053 } 9054 9055 /// Whether or not this operand accesses memory 9056 bool hasMemory(const TargetLowering &TLI) const { 9057 // Indirect operand accesses access memory. 9058 if (isIndirect) 9059 return true; 9060 9061 for (const auto &Code : Codes) 9062 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 9063 return true; 9064 9065 return false; 9066 } 9067 }; 9068 9069 9070 } // end anonymous namespace 9071 9072 /// Make sure that the output operand \p OpInfo and its corresponding input 9073 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 9074 /// out). 9075 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 9076 SDISelAsmOperandInfo &MatchingOpInfo, 9077 SelectionDAG &DAG) { 9078 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 9079 return; 9080 9081 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 9082 const auto &TLI = DAG.getTargetLoweringInfo(); 9083 9084 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 9085 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 9086 OpInfo.ConstraintVT); 9087 std::pair<unsigned, const TargetRegisterClass *> InputRC = 9088 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 9089 MatchingOpInfo.ConstraintVT); 9090 if ((OpInfo.ConstraintVT.isInteger() != 9091 MatchingOpInfo.ConstraintVT.isInteger()) || 9092 (MatchRC.second != InputRC.second)) { 9093 // FIXME: error out in a more elegant fashion 9094 report_fatal_error("Unsupported asm: input constraint" 9095 " with a matching output constraint of" 9096 " incompatible type!"); 9097 } 9098 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 9099 } 9100 9101 /// Get a direct memory input to behave well as an indirect operand. 9102 /// This may introduce stores, hence the need for a \p Chain. 9103 /// \return The (possibly updated) chain. 9104 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 9105 SDISelAsmOperandInfo &OpInfo, 9106 SelectionDAG &DAG) { 9107 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9108 9109 // If we don't have an indirect input, put it in the constpool if we can, 9110 // otherwise spill it to a stack slot. 9111 // TODO: This isn't quite right. We need to handle these according to 9112 // the addressing mode that the constraint wants. Also, this may take 9113 // an additional register for the computation and we don't want that 9114 // either. 9115 9116 // If the operand is a float, integer, or vector constant, spill to a 9117 // constant pool entry to get its address. 9118 const Value *OpVal = OpInfo.CallOperandVal; 9119 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9120 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9121 OpInfo.CallOperand = DAG.getConstantPool( 9122 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9123 return Chain; 9124 } 9125 9126 // Otherwise, create a stack slot and emit a store to it before the asm. 9127 Type *Ty = OpVal->getType(); 9128 auto &DL = DAG.getDataLayout(); 9129 uint64_t TySize = DL.getTypeAllocSize(Ty); 9130 MachineFunction &MF = DAG.getMachineFunction(); 9131 int SSFI = MF.getFrameInfo().CreateStackObject( 9132 TySize, DL.getPrefTypeAlign(Ty), false); 9133 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9134 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9135 MachinePointerInfo::getFixedStack(MF, SSFI), 9136 TLI.getMemValueType(DL, Ty)); 9137 OpInfo.CallOperand = StackSlot; 9138 9139 return Chain; 9140 } 9141 9142 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9143 /// specified operand. We prefer to assign virtual registers, to allow the 9144 /// register allocator to handle the assignment process. However, if the asm 9145 /// uses features that we can't model on machineinstrs, we have SDISel do the 9146 /// allocation. This produces generally horrible, but correct, code. 9147 /// 9148 /// OpInfo describes the operand 9149 /// RefOpInfo describes the matching operand if any, the operand otherwise 9150 static std::optional<unsigned> 9151 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9152 SDISelAsmOperandInfo &OpInfo, 9153 SDISelAsmOperandInfo &RefOpInfo) { 9154 LLVMContext &Context = *DAG.getContext(); 9155 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9156 9157 MachineFunction &MF = DAG.getMachineFunction(); 9158 SmallVector<unsigned, 4> Regs; 9159 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9160 9161 // No work to do for memory/address operands. 9162 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9163 OpInfo.ConstraintType == TargetLowering::C_Address) 9164 return std::nullopt; 9165 9166 // If this is a constraint for a single physreg, or a constraint for a 9167 // register class, find it. 9168 unsigned AssignedReg; 9169 const TargetRegisterClass *RC; 9170 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9171 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9172 // RC is unset only on failure. Return immediately. 9173 if (!RC) 9174 return std::nullopt; 9175 9176 // Get the actual register value type. This is important, because the user 9177 // may have asked for (e.g.) the AX register in i32 type. We need to 9178 // remember that AX is actually i16 to get the right extension. 9179 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9180 9181 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9182 // If this is an FP operand in an integer register (or visa versa), or more 9183 // generally if the operand value disagrees with the register class we plan 9184 // to stick it in, fix the operand type. 9185 // 9186 // If this is an input value, the bitcast to the new type is done now. 9187 // Bitcast for output value is done at the end of visitInlineAsm(). 9188 if ((OpInfo.Type == InlineAsm::isOutput || 9189 OpInfo.Type == InlineAsm::isInput) && 9190 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9191 // Try to convert to the first EVT that the reg class contains. If the 9192 // types are identical size, use a bitcast to convert (e.g. two differing 9193 // vector types). Note: output bitcast is done at the end of 9194 // visitInlineAsm(). 9195 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9196 // Exclude indirect inputs while they are unsupported because the code 9197 // to perform the load is missing and thus OpInfo.CallOperand still 9198 // refers to the input address rather than the pointed-to value. 9199 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9200 OpInfo.CallOperand = 9201 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9202 OpInfo.ConstraintVT = RegVT; 9203 // If the operand is an FP value and we want it in integer registers, 9204 // use the corresponding integer type. This turns an f64 value into 9205 // i64, which can be passed with two i32 values on a 32-bit machine. 9206 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9207 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9208 if (OpInfo.Type == InlineAsm::isInput) 9209 OpInfo.CallOperand = 9210 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9211 OpInfo.ConstraintVT = VT; 9212 } 9213 } 9214 } 9215 9216 // No need to allocate a matching input constraint since the constraint it's 9217 // matching to has already been allocated. 9218 if (OpInfo.isMatchingInputConstraint()) 9219 return std::nullopt; 9220 9221 EVT ValueVT = OpInfo.ConstraintVT; 9222 if (OpInfo.ConstraintVT == MVT::Other) 9223 ValueVT = RegVT; 9224 9225 // Initialize NumRegs. 9226 unsigned NumRegs = 1; 9227 if (OpInfo.ConstraintVT != MVT::Other) 9228 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9229 9230 // If this is a constraint for a specific physical register, like {r17}, 9231 // assign it now. 9232 9233 // If this associated to a specific register, initialize iterator to correct 9234 // place. If virtual, make sure we have enough registers 9235 9236 // Initialize iterator if necessary 9237 TargetRegisterClass::iterator I = RC->begin(); 9238 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9239 9240 // Do not check for single registers. 9241 if (AssignedReg) { 9242 I = std::find(I, RC->end(), AssignedReg); 9243 if (I == RC->end()) { 9244 // RC does not contain the selected register, which indicates a 9245 // mismatch between the register and the required type/bitwidth. 9246 return {AssignedReg}; 9247 } 9248 } 9249 9250 for (; NumRegs; --NumRegs, ++I) { 9251 assert(I != RC->end() && "Ran out of registers to allocate!"); 9252 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9253 Regs.push_back(R); 9254 } 9255 9256 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9257 return std::nullopt; 9258 } 9259 9260 static unsigned 9261 findMatchingInlineAsmOperand(unsigned OperandNo, 9262 const std::vector<SDValue> &AsmNodeOperands) { 9263 // Scan until we find the definition we already emitted of this operand. 9264 unsigned CurOp = InlineAsm::Op_FirstOperand; 9265 for (; OperandNo; --OperandNo) { 9266 // Advance to the next operand. 9267 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal(); 9268 const InlineAsm::Flag F(OpFlag); 9269 assert( 9270 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9271 "Skipped past definitions?"); 9272 CurOp += F.getNumOperandRegisters() + 1; 9273 } 9274 return CurOp; 9275 } 9276 9277 namespace { 9278 9279 class ExtraFlags { 9280 unsigned Flags = 0; 9281 9282 public: 9283 explicit ExtraFlags(const CallBase &Call) { 9284 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9285 if (IA->hasSideEffects()) 9286 Flags |= InlineAsm::Extra_HasSideEffects; 9287 if (IA->isAlignStack()) 9288 Flags |= InlineAsm::Extra_IsAlignStack; 9289 if (Call.isConvergent()) 9290 Flags |= InlineAsm::Extra_IsConvergent; 9291 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9292 } 9293 9294 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9295 // Ideally, we would only check against memory constraints. However, the 9296 // meaning of an Other constraint can be target-specific and we can't easily 9297 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9298 // for Other constraints as well. 9299 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9300 OpInfo.ConstraintType == TargetLowering::C_Other) { 9301 if (OpInfo.Type == InlineAsm::isInput) 9302 Flags |= InlineAsm::Extra_MayLoad; 9303 else if (OpInfo.Type == InlineAsm::isOutput) 9304 Flags |= InlineAsm::Extra_MayStore; 9305 else if (OpInfo.Type == InlineAsm::isClobber) 9306 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9307 } 9308 } 9309 9310 unsigned get() const { return Flags; } 9311 }; 9312 9313 } // end anonymous namespace 9314 9315 static bool isFunction(SDValue Op) { 9316 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9317 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9318 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9319 9320 // In normal "call dllimport func" instruction (non-inlineasm) it force 9321 // indirect access by specifing call opcode. And usually specially print 9322 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9323 // not do in this way now. (In fact, this is similar with "Data Access" 9324 // action). So here we ignore dllimport function. 9325 if (Fn && !Fn->hasDLLImportStorageClass()) 9326 return true; 9327 } 9328 } 9329 return false; 9330 } 9331 9332 /// visitInlineAsm - Handle a call to an InlineAsm object. 9333 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9334 const BasicBlock *EHPadBB) { 9335 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9336 9337 /// ConstraintOperands - Information about all of the constraints. 9338 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9339 9340 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9341 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9342 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9343 9344 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9345 // AsmDialect, MayLoad, MayStore). 9346 bool HasSideEffect = IA->hasSideEffects(); 9347 ExtraFlags ExtraInfo(Call); 9348 9349 for (auto &T : TargetConstraints) { 9350 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9351 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9352 9353 if (OpInfo.CallOperandVal) 9354 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9355 9356 if (!HasSideEffect) 9357 HasSideEffect = OpInfo.hasMemory(TLI); 9358 9359 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9360 // FIXME: Could we compute this on OpInfo rather than T? 9361 9362 // Compute the constraint code and ConstraintType to use. 9363 TLI.ComputeConstraintToUse(T, SDValue()); 9364 9365 if (T.ConstraintType == TargetLowering::C_Immediate && 9366 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9367 // We've delayed emitting a diagnostic like the "n" constraint because 9368 // inlining could cause an integer showing up. 9369 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9370 "' expects an integer constant " 9371 "expression"); 9372 9373 ExtraInfo.update(T); 9374 } 9375 9376 // We won't need to flush pending loads if this asm doesn't touch 9377 // memory and is nonvolatile. 9378 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9379 9380 bool EmitEHLabels = isa<InvokeInst>(Call); 9381 if (EmitEHLabels) { 9382 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9383 } 9384 bool IsCallBr = isa<CallBrInst>(Call); 9385 9386 if (IsCallBr || EmitEHLabels) { 9387 // If this is a callbr or invoke we need to flush pending exports since 9388 // inlineasm_br and invoke are terminators. 9389 // We need to do this before nodes are glued to the inlineasm_br node. 9390 Chain = getControlRoot(); 9391 } 9392 9393 MCSymbol *BeginLabel = nullptr; 9394 if (EmitEHLabels) { 9395 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9396 } 9397 9398 int OpNo = -1; 9399 SmallVector<StringRef> AsmStrs; 9400 IA->collectAsmStrs(AsmStrs); 9401 9402 // Second pass over the constraints: compute which constraint option to use. 9403 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9404 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9405 OpNo++; 9406 9407 // If this is an output operand with a matching input operand, look up the 9408 // matching input. If their types mismatch, e.g. one is an integer, the 9409 // other is floating point, or their sizes are different, flag it as an 9410 // error. 9411 if (OpInfo.hasMatchingInput()) { 9412 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9413 patchMatchingInput(OpInfo, Input, DAG); 9414 } 9415 9416 // Compute the constraint code and ConstraintType to use. 9417 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9418 9419 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9420 OpInfo.Type == InlineAsm::isClobber) || 9421 OpInfo.ConstraintType == TargetLowering::C_Address) 9422 continue; 9423 9424 // In Linux PIC model, there are 4 cases about value/label addressing: 9425 // 9426 // 1: Function call or Label jmp inside the module. 9427 // 2: Data access (such as global variable, static variable) inside module. 9428 // 3: Function call or Label jmp outside the module. 9429 // 4: Data access (such as global variable) outside the module. 9430 // 9431 // Due to current llvm inline asm architecture designed to not "recognize" 9432 // the asm code, there are quite troubles for us to treat mem addressing 9433 // differently for same value/adress used in different instuctions. 9434 // For example, in pic model, call a func may in plt way or direclty 9435 // pc-related, but lea/mov a function adress may use got. 9436 // 9437 // Here we try to "recognize" function call for the case 1 and case 3 in 9438 // inline asm. And try to adjust the constraint for them. 9439 // 9440 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9441 // label, so here we don't handle jmp function label now, but we need to 9442 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9443 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9444 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9445 TM.getCodeModel() != CodeModel::Large) { 9446 OpInfo.isIndirect = false; 9447 OpInfo.ConstraintType = TargetLowering::C_Address; 9448 } 9449 9450 // If this is a memory input, and if the operand is not indirect, do what we 9451 // need to provide an address for the memory input. 9452 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9453 !OpInfo.isIndirect) { 9454 assert((OpInfo.isMultipleAlternative || 9455 (OpInfo.Type == InlineAsm::isInput)) && 9456 "Can only indirectify direct input operands!"); 9457 9458 // Memory operands really want the address of the value. 9459 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9460 9461 // There is no longer a Value* corresponding to this operand. 9462 OpInfo.CallOperandVal = nullptr; 9463 9464 // It is now an indirect operand. 9465 OpInfo.isIndirect = true; 9466 } 9467 9468 } 9469 9470 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9471 std::vector<SDValue> AsmNodeOperands; 9472 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9473 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9474 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9475 9476 // If we have a !srcloc metadata node associated with it, we want to attach 9477 // this to the ultimately generated inline asm machineinstr. To do this, we 9478 // pass in the third operand as this (potentially null) inline asm MDNode. 9479 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9480 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9481 9482 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9483 // bits as operand 3. 9484 AsmNodeOperands.push_back(DAG.getTargetConstant( 9485 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9486 9487 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9488 // this, assign virtual and physical registers for inputs and otput. 9489 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9490 // Assign Registers. 9491 SDISelAsmOperandInfo &RefOpInfo = 9492 OpInfo.isMatchingInputConstraint() 9493 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9494 : OpInfo; 9495 const auto RegError = 9496 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9497 if (RegError) { 9498 const MachineFunction &MF = DAG.getMachineFunction(); 9499 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9500 const char *RegName = TRI.getName(*RegError); 9501 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9502 "' allocated for constraint '" + 9503 Twine(OpInfo.ConstraintCode) + 9504 "' does not match required type"); 9505 return; 9506 } 9507 9508 auto DetectWriteToReservedRegister = [&]() { 9509 const MachineFunction &MF = DAG.getMachineFunction(); 9510 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9511 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9512 if (Register::isPhysicalRegister(Reg) && 9513 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9514 const char *RegName = TRI.getName(Reg); 9515 emitInlineAsmError(Call, "write to reserved register '" + 9516 Twine(RegName) + "'"); 9517 return true; 9518 } 9519 } 9520 return false; 9521 }; 9522 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9523 (OpInfo.Type == InlineAsm::isInput && 9524 !OpInfo.isMatchingInputConstraint())) && 9525 "Only address as input operand is allowed."); 9526 9527 switch (OpInfo.Type) { 9528 case InlineAsm::isOutput: 9529 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9530 const InlineAsm::ConstraintCode ConstraintID = 9531 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9532 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9533 "Failed to convert memory constraint code to constraint id."); 9534 9535 // Add information to the INLINEASM node to know about this output. 9536 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 9537 OpFlags.setMemConstraint(ConstraintID); 9538 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9539 MVT::i32)); 9540 AsmNodeOperands.push_back(OpInfo.CallOperand); 9541 } else { 9542 // Otherwise, this outputs to a register (directly for C_Register / 9543 // C_RegisterClass, and a target-defined fashion for 9544 // C_Immediate/C_Other). Find a register that we can use. 9545 if (OpInfo.AssignedRegs.Regs.empty()) { 9546 emitInlineAsmError( 9547 Call, "couldn't allocate output register for constraint '" + 9548 Twine(OpInfo.ConstraintCode) + "'"); 9549 return; 9550 } 9551 9552 if (DetectWriteToReservedRegister()) 9553 return; 9554 9555 // Add information to the INLINEASM node to know that this register is 9556 // set. 9557 OpInfo.AssignedRegs.AddInlineAsmOperands( 9558 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 9559 : InlineAsm::Kind::RegDef, 9560 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9561 } 9562 break; 9563 9564 case InlineAsm::isInput: 9565 case InlineAsm::isLabel: { 9566 SDValue InOperandVal = OpInfo.CallOperand; 9567 9568 if (OpInfo.isMatchingInputConstraint()) { 9569 // If this is required to match an output register we have already set, 9570 // just use its register. 9571 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9572 AsmNodeOperands); 9573 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal()); 9574 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 9575 if (OpInfo.isIndirect) { 9576 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9577 emitInlineAsmError(Call, "inline asm not supported yet: " 9578 "don't know how to handle tied " 9579 "indirect register inputs"); 9580 return; 9581 } 9582 9583 SmallVector<unsigned, 4> Regs; 9584 MachineFunction &MF = DAG.getMachineFunction(); 9585 MachineRegisterInfo &MRI = MF.getRegInfo(); 9586 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9587 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9588 Register TiedReg = R->getReg(); 9589 MVT RegVT = R->getSimpleValueType(0); 9590 const TargetRegisterClass *RC = 9591 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9592 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9593 : TRI.getMinimalPhysRegClass(TiedReg); 9594 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 9595 Regs.push_back(MRI.createVirtualRegister(RC)); 9596 9597 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9598 9599 SDLoc dl = getCurSDLoc(); 9600 // Use the produced MatchedRegs object to 9601 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9602 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 9603 OpInfo.getMatchedOperand(), dl, DAG, 9604 AsmNodeOperands); 9605 break; 9606 } 9607 9608 assert(Flag.isMemKind() && "Unknown matching constraint!"); 9609 assert(Flag.getNumOperandRegisters() == 1 && 9610 "Unexpected number of operands"); 9611 // Add information to the INLINEASM node to know about this input. 9612 // See InlineAsm.h isUseOperandTiedToDef. 9613 Flag.clearMemConstraint(); 9614 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 9615 AsmNodeOperands.push_back(DAG.getTargetConstant( 9616 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9617 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9618 break; 9619 } 9620 9621 // Treat indirect 'X' constraint as memory. 9622 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9623 OpInfo.isIndirect) 9624 OpInfo.ConstraintType = TargetLowering::C_Memory; 9625 9626 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9627 OpInfo.ConstraintType == TargetLowering::C_Other) { 9628 std::vector<SDValue> Ops; 9629 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9630 Ops, DAG); 9631 if (Ops.empty()) { 9632 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9633 if (isa<ConstantSDNode>(InOperandVal)) { 9634 emitInlineAsmError(Call, "value out of range for constraint '" + 9635 Twine(OpInfo.ConstraintCode) + "'"); 9636 return; 9637 } 9638 9639 emitInlineAsmError(Call, 9640 "invalid operand for inline asm constraint '" + 9641 Twine(OpInfo.ConstraintCode) + "'"); 9642 return; 9643 } 9644 9645 // Add information to the INLINEASM node to know about this input. 9646 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 9647 AsmNodeOperands.push_back(DAG.getTargetConstant( 9648 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9649 llvm::append_range(AsmNodeOperands, Ops); 9650 break; 9651 } 9652 9653 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9654 assert((OpInfo.isIndirect || 9655 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9656 "Operand must be indirect to be a mem!"); 9657 assert(InOperandVal.getValueType() == 9658 TLI.getPointerTy(DAG.getDataLayout()) && 9659 "Memory operands expect pointer values"); 9660 9661 const InlineAsm::ConstraintCode ConstraintID = 9662 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9663 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9664 "Failed to convert memory constraint code to constraint id."); 9665 9666 // Add information to the INLINEASM node to know about this input. 9667 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9668 ResOpType.setMemConstraint(ConstraintID); 9669 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9670 getCurSDLoc(), 9671 MVT::i32)); 9672 AsmNodeOperands.push_back(InOperandVal); 9673 break; 9674 } 9675 9676 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9677 const InlineAsm::ConstraintCode ConstraintID = 9678 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9679 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9680 "Failed to convert memory constraint code to constraint id."); 9681 9682 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9683 9684 SDValue AsmOp = InOperandVal; 9685 if (isFunction(InOperandVal)) { 9686 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9687 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 9688 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9689 InOperandVal.getValueType(), 9690 GA->getOffset()); 9691 } 9692 9693 // Add information to the INLINEASM node to know about this input. 9694 ResOpType.setMemConstraint(ConstraintID); 9695 9696 AsmNodeOperands.push_back( 9697 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9698 9699 AsmNodeOperands.push_back(AsmOp); 9700 break; 9701 } 9702 9703 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9704 OpInfo.ConstraintType == TargetLowering::C_Register) && 9705 "Unknown constraint type!"); 9706 9707 // TODO: Support this. 9708 if (OpInfo.isIndirect) { 9709 emitInlineAsmError( 9710 Call, "Don't know how to handle indirect register inputs yet " 9711 "for constraint '" + 9712 Twine(OpInfo.ConstraintCode) + "'"); 9713 return; 9714 } 9715 9716 // Copy the input into the appropriate registers. 9717 if (OpInfo.AssignedRegs.Regs.empty()) { 9718 emitInlineAsmError(Call, 9719 "couldn't allocate input reg for constraint '" + 9720 Twine(OpInfo.ConstraintCode) + "'"); 9721 return; 9722 } 9723 9724 if (DetectWriteToReservedRegister()) 9725 return; 9726 9727 SDLoc dl = getCurSDLoc(); 9728 9729 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9730 &Call); 9731 9732 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 9733 0, dl, DAG, AsmNodeOperands); 9734 break; 9735 } 9736 case InlineAsm::isClobber: 9737 // Add the clobbered value to the operand list, so that the register 9738 // allocator is aware that the physreg got clobbered. 9739 if (!OpInfo.AssignedRegs.Regs.empty()) 9740 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 9741 false, 0, getCurSDLoc(), DAG, 9742 AsmNodeOperands); 9743 break; 9744 } 9745 } 9746 9747 // Finish up input operands. Set the input chain and add the flag last. 9748 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9749 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9750 9751 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9752 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9753 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9754 Glue = Chain.getValue(1); 9755 9756 // Do additional work to generate outputs. 9757 9758 SmallVector<EVT, 1> ResultVTs; 9759 SmallVector<SDValue, 1> ResultValues; 9760 SmallVector<SDValue, 8> OutChains; 9761 9762 llvm::Type *CallResultType = Call.getType(); 9763 ArrayRef<Type *> ResultTypes; 9764 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9765 ResultTypes = StructResult->elements(); 9766 else if (!CallResultType->isVoidTy()) 9767 ResultTypes = ArrayRef(CallResultType); 9768 9769 auto CurResultType = ResultTypes.begin(); 9770 auto handleRegAssign = [&](SDValue V) { 9771 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9772 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9773 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9774 ++CurResultType; 9775 // If the type of the inline asm call site return value is different but has 9776 // same size as the type of the asm output bitcast it. One example of this 9777 // is for vectors with different width / number of elements. This can 9778 // happen for register classes that can contain multiple different value 9779 // types. The preg or vreg allocated may not have the same VT as was 9780 // expected. 9781 // 9782 // This can also happen for a return value that disagrees with the register 9783 // class it is put in, eg. a double in a general-purpose register on a 9784 // 32-bit machine. 9785 if (ResultVT != V.getValueType() && 9786 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9787 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9788 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9789 V.getValueType().isInteger()) { 9790 // If a result value was tied to an input value, the computed result 9791 // may have a wider width than the expected result. Extract the 9792 // relevant portion. 9793 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9794 } 9795 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9796 ResultVTs.push_back(ResultVT); 9797 ResultValues.push_back(V); 9798 }; 9799 9800 // Deal with output operands. 9801 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9802 if (OpInfo.Type == InlineAsm::isOutput) { 9803 SDValue Val; 9804 // Skip trivial output operands. 9805 if (OpInfo.AssignedRegs.Regs.empty()) 9806 continue; 9807 9808 switch (OpInfo.ConstraintType) { 9809 case TargetLowering::C_Register: 9810 case TargetLowering::C_RegisterClass: 9811 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9812 Chain, &Glue, &Call); 9813 break; 9814 case TargetLowering::C_Immediate: 9815 case TargetLowering::C_Other: 9816 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9817 OpInfo, DAG); 9818 break; 9819 case TargetLowering::C_Memory: 9820 break; // Already handled. 9821 case TargetLowering::C_Address: 9822 break; // Silence warning. 9823 case TargetLowering::C_Unknown: 9824 assert(false && "Unexpected unknown constraint"); 9825 } 9826 9827 // Indirect output manifest as stores. Record output chains. 9828 if (OpInfo.isIndirect) { 9829 const Value *Ptr = OpInfo.CallOperandVal; 9830 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9831 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9832 MachinePointerInfo(Ptr)); 9833 OutChains.push_back(Store); 9834 } else { 9835 // generate CopyFromRegs to associated registers. 9836 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9837 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9838 for (const SDValue &V : Val->op_values()) 9839 handleRegAssign(V); 9840 } else 9841 handleRegAssign(Val); 9842 } 9843 } 9844 } 9845 9846 // Set results. 9847 if (!ResultValues.empty()) { 9848 assert(CurResultType == ResultTypes.end() && 9849 "Mismatch in number of ResultTypes"); 9850 assert(ResultValues.size() == ResultTypes.size() && 9851 "Mismatch in number of output operands in asm result"); 9852 9853 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9854 DAG.getVTList(ResultVTs), ResultValues); 9855 setValue(&Call, V); 9856 } 9857 9858 // Collect store chains. 9859 if (!OutChains.empty()) 9860 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9861 9862 if (EmitEHLabels) { 9863 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9864 } 9865 9866 // Only Update Root if inline assembly has a memory effect. 9867 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9868 EmitEHLabels) 9869 DAG.setRoot(Chain); 9870 } 9871 9872 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9873 const Twine &Message) { 9874 LLVMContext &Ctx = *DAG.getContext(); 9875 Ctx.emitError(&Call, Message); 9876 9877 // Make sure we leave the DAG in a valid state 9878 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9879 SmallVector<EVT, 1> ValueVTs; 9880 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9881 9882 if (ValueVTs.empty()) 9883 return; 9884 9885 SmallVector<SDValue, 1> Ops; 9886 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9887 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9888 9889 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9890 } 9891 9892 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9893 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9894 MVT::Other, getRoot(), 9895 getValue(I.getArgOperand(0)), 9896 DAG.getSrcValue(I.getArgOperand(0)))); 9897 } 9898 9899 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9900 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9901 const DataLayout &DL = DAG.getDataLayout(); 9902 SDValue V = DAG.getVAArg( 9903 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9904 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9905 DL.getABITypeAlign(I.getType()).value()); 9906 DAG.setRoot(V.getValue(1)); 9907 9908 if (I.getType()->isPointerTy()) 9909 V = DAG.getPtrExtOrTrunc( 9910 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9911 setValue(&I, V); 9912 } 9913 9914 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9915 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9916 MVT::Other, getRoot(), 9917 getValue(I.getArgOperand(0)), 9918 DAG.getSrcValue(I.getArgOperand(0)))); 9919 } 9920 9921 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9922 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9923 MVT::Other, getRoot(), 9924 getValue(I.getArgOperand(0)), 9925 getValue(I.getArgOperand(1)), 9926 DAG.getSrcValue(I.getArgOperand(0)), 9927 DAG.getSrcValue(I.getArgOperand(1)))); 9928 } 9929 9930 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9931 const Instruction &I, 9932 SDValue Op) { 9933 const MDNode *Range = getRangeMetadata(I); 9934 if (!Range) 9935 return Op; 9936 9937 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9938 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9939 return Op; 9940 9941 APInt Lo = CR.getUnsignedMin(); 9942 if (!Lo.isMinValue()) 9943 return Op; 9944 9945 APInt Hi = CR.getUnsignedMax(); 9946 unsigned Bits = std::max(Hi.getActiveBits(), 9947 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9948 9949 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9950 9951 SDLoc SL = getCurSDLoc(); 9952 9953 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9954 DAG.getValueType(SmallVT)); 9955 unsigned NumVals = Op.getNode()->getNumValues(); 9956 if (NumVals == 1) 9957 return ZExt; 9958 9959 SmallVector<SDValue, 4> Ops; 9960 9961 Ops.push_back(ZExt); 9962 for (unsigned I = 1; I != NumVals; ++I) 9963 Ops.push_back(Op.getValue(I)); 9964 9965 return DAG.getMergeValues(Ops, SL); 9966 } 9967 9968 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9969 /// the call being lowered. 9970 /// 9971 /// This is a helper for lowering intrinsics that follow a target calling 9972 /// convention or require stack pointer adjustment. Only a subset of the 9973 /// intrinsic's operands need to participate in the calling convention. 9974 void SelectionDAGBuilder::populateCallLoweringInfo( 9975 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9976 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9977 AttributeSet RetAttrs, bool IsPatchPoint) { 9978 TargetLowering::ArgListTy Args; 9979 Args.reserve(NumArgs); 9980 9981 // Populate the argument list. 9982 // Attributes for args start at offset 1, after the return attribute. 9983 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9984 ArgI != ArgE; ++ArgI) { 9985 const Value *V = Call->getOperand(ArgI); 9986 9987 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9988 9989 TargetLowering::ArgListEntry Entry; 9990 Entry.Node = getValue(V); 9991 Entry.Ty = V->getType(); 9992 Entry.setAttributes(Call, ArgI); 9993 Args.push_back(Entry); 9994 } 9995 9996 CLI.setDebugLoc(getCurSDLoc()) 9997 .setChain(getRoot()) 9998 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 9999 RetAttrs) 10000 .setDiscardResult(Call->use_empty()) 10001 .setIsPatchPoint(IsPatchPoint) 10002 .setIsPreallocated( 10003 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 10004 } 10005 10006 /// Add a stack map intrinsic call's live variable operands to a stackmap 10007 /// or patchpoint target node's operand list. 10008 /// 10009 /// Constants are converted to TargetConstants purely as an optimization to 10010 /// avoid constant materialization and register allocation. 10011 /// 10012 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 10013 /// generate addess computation nodes, and so FinalizeISel can convert the 10014 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 10015 /// address materialization and register allocation, but may also be required 10016 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 10017 /// alloca in the entry block, then the runtime may assume that the alloca's 10018 /// StackMap location can be read immediately after compilation and that the 10019 /// location is valid at any point during execution (this is similar to the 10020 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 10021 /// only available in a register, then the runtime would need to trap when 10022 /// execution reaches the StackMap in order to read the alloca's location. 10023 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 10024 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 10025 SelectionDAGBuilder &Builder) { 10026 SelectionDAG &DAG = Builder.DAG; 10027 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 10028 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 10029 10030 // Things on the stack are pointer-typed, meaning that they are already 10031 // legal and can be emitted directly to target nodes. 10032 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 10033 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 10034 } else { 10035 // Otherwise emit a target independent node to be legalised. 10036 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 10037 } 10038 } 10039 } 10040 10041 /// Lower llvm.experimental.stackmap. 10042 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 10043 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 10044 // [live variables...]) 10045 10046 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 10047 10048 SDValue Chain, InGlue, Callee; 10049 SmallVector<SDValue, 32> Ops; 10050 10051 SDLoc DL = getCurSDLoc(); 10052 Callee = getValue(CI.getCalledOperand()); 10053 10054 // The stackmap intrinsic only records the live variables (the arguments 10055 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 10056 // intrinsic, this won't be lowered to a function call. This means we don't 10057 // have to worry about calling conventions and target specific lowering code. 10058 // Instead we perform the call lowering right here. 10059 // 10060 // chain, flag = CALLSEQ_START(chain, 0, 0) 10061 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 10062 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 10063 // 10064 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 10065 InGlue = Chain.getValue(1); 10066 10067 // Add the STACKMAP operands, starting with DAG house-keeping. 10068 Ops.push_back(Chain); 10069 Ops.push_back(InGlue); 10070 10071 // Add the <id>, <numShadowBytes> operands. 10072 // 10073 // These do not require legalisation, and can be emitted directly to target 10074 // constant nodes. 10075 SDValue ID = getValue(CI.getArgOperand(0)); 10076 assert(ID.getValueType() == MVT::i64); 10077 SDValue IDConst = 10078 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType()); 10079 Ops.push_back(IDConst); 10080 10081 SDValue Shad = getValue(CI.getArgOperand(1)); 10082 assert(Shad.getValueType() == MVT::i32); 10083 SDValue ShadConst = 10084 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType()); 10085 Ops.push_back(ShadConst); 10086 10087 // Add the live variables. 10088 addStackMapLiveVars(CI, 2, DL, Ops, *this); 10089 10090 // Create the STACKMAP node. 10091 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10092 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 10093 InGlue = Chain.getValue(1); 10094 10095 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 10096 10097 // Stackmaps don't generate values, so nothing goes into the NodeMap. 10098 10099 // Set the root to the target-lowered call chain. 10100 DAG.setRoot(Chain); 10101 10102 // Inform the Frame Information that we have a stackmap in this function. 10103 FuncInfo.MF->getFrameInfo().setHasStackMap(); 10104 } 10105 10106 /// Lower llvm.experimental.patchpoint directly to its target opcode. 10107 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 10108 const BasicBlock *EHPadBB) { 10109 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 10110 // i32 <numBytes>, 10111 // i8* <target>, 10112 // i32 <numArgs>, 10113 // [Args...], 10114 // [live variables...]) 10115 10116 CallingConv::ID CC = CB.getCallingConv(); 10117 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10118 bool HasDef = !CB.getType()->isVoidTy(); 10119 SDLoc dl = getCurSDLoc(); 10120 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10121 10122 // Handle immediate and symbolic callees. 10123 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10124 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10125 /*isTarget=*/true); 10126 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10127 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10128 SDLoc(SymbolicCallee), 10129 SymbolicCallee->getValueType(0)); 10130 10131 // Get the real number of arguments participating in the call <numArgs> 10132 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10133 unsigned NumArgs = NArgVal->getAsZExtVal(); 10134 10135 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10136 // Intrinsics include all meta-operands up to but not including CC. 10137 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10138 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10139 "Not enough arguments provided to the patchpoint intrinsic"); 10140 10141 // For AnyRegCC the arguments are lowered later on manually. 10142 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10143 Type *ReturnTy = 10144 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10145 10146 TargetLowering::CallLoweringInfo CLI(DAG); 10147 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10148 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10149 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10150 10151 SDNode *CallEnd = Result.second.getNode(); 10152 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10153 CallEnd = CallEnd->getOperand(0).getNode(); 10154 10155 /// Get a call instruction from the call sequence chain. 10156 /// Tail calls are not allowed. 10157 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10158 "Expected a callseq node."); 10159 SDNode *Call = CallEnd->getOperand(0).getNode(); 10160 bool HasGlue = Call->getGluedNode(); 10161 10162 // Replace the target specific call node with the patchable intrinsic. 10163 SmallVector<SDValue, 8> Ops; 10164 10165 // Push the chain. 10166 Ops.push_back(*(Call->op_begin())); 10167 10168 // Optionally, push the glue (if any). 10169 if (HasGlue) 10170 Ops.push_back(*(Call->op_end() - 1)); 10171 10172 // Push the register mask info. 10173 if (HasGlue) 10174 Ops.push_back(*(Call->op_end() - 2)); 10175 else 10176 Ops.push_back(*(Call->op_end() - 1)); 10177 10178 // Add the <id> and <numBytes> constants. 10179 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10180 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64)); 10181 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10182 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32)); 10183 10184 // Add the callee. 10185 Ops.push_back(Callee); 10186 10187 // Adjust <numArgs> to account for any arguments that have been passed on the 10188 // stack instead. 10189 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10190 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10191 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10192 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10193 10194 // Add the calling convention 10195 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10196 10197 // Add the arguments we omitted previously. The register allocator should 10198 // place these in any free register. 10199 if (IsAnyRegCC) 10200 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10201 Ops.push_back(getValue(CB.getArgOperand(i))); 10202 10203 // Push the arguments from the call instruction. 10204 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10205 Ops.append(Call->op_begin() + 2, e); 10206 10207 // Push live variables for the stack map. 10208 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10209 10210 SDVTList NodeTys; 10211 if (IsAnyRegCC && HasDef) { 10212 // Create the return types based on the intrinsic definition 10213 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10214 SmallVector<EVT, 3> ValueVTs; 10215 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10216 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10217 10218 // There is always a chain and a glue type at the end 10219 ValueVTs.push_back(MVT::Other); 10220 ValueVTs.push_back(MVT::Glue); 10221 NodeTys = DAG.getVTList(ValueVTs); 10222 } else 10223 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10224 10225 // Replace the target specific call node with a PATCHPOINT node. 10226 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10227 10228 // Update the NodeMap. 10229 if (HasDef) { 10230 if (IsAnyRegCC) 10231 setValue(&CB, SDValue(PPV.getNode(), 0)); 10232 else 10233 setValue(&CB, Result.first); 10234 } 10235 10236 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10237 // call sequence. Furthermore the location of the chain and glue can change 10238 // when the AnyReg calling convention is used and the intrinsic returns a 10239 // value. 10240 if (IsAnyRegCC && HasDef) { 10241 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10242 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10243 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10244 } else 10245 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10246 DAG.DeleteNode(Call); 10247 10248 // Inform the Frame Information that we have a patchpoint in this function. 10249 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10250 } 10251 10252 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10253 unsigned Intrinsic) { 10254 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10255 SDValue Op1 = getValue(I.getArgOperand(0)); 10256 SDValue Op2; 10257 if (I.arg_size() > 1) 10258 Op2 = getValue(I.getArgOperand(1)); 10259 SDLoc dl = getCurSDLoc(); 10260 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10261 SDValue Res; 10262 SDNodeFlags SDFlags; 10263 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10264 SDFlags.copyFMF(*FPMO); 10265 10266 switch (Intrinsic) { 10267 case Intrinsic::vector_reduce_fadd: 10268 if (SDFlags.hasAllowReassociation()) 10269 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10270 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10271 SDFlags); 10272 else 10273 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10274 break; 10275 case Intrinsic::vector_reduce_fmul: 10276 if (SDFlags.hasAllowReassociation()) 10277 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10278 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10279 SDFlags); 10280 else 10281 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10282 break; 10283 case Intrinsic::vector_reduce_add: 10284 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10285 break; 10286 case Intrinsic::vector_reduce_mul: 10287 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10288 break; 10289 case Intrinsic::vector_reduce_and: 10290 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10291 break; 10292 case Intrinsic::vector_reduce_or: 10293 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10294 break; 10295 case Intrinsic::vector_reduce_xor: 10296 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10297 break; 10298 case Intrinsic::vector_reduce_smax: 10299 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10300 break; 10301 case Intrinsic::vector_reduce_smin: 10302 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10303 break; 10304 case Intrinsic::vector_reduce_umax: 10305 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10306 break; 10307 case Intrinsic::vector_reduce_umin: 10308 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10309 break; 10310 case Intrinsic::vector_reduce_fmax: 10311 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10312 break; 10313 case Intrinsic::vector_reduce_fmin: 10314 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10315 break; 10316 case Intrinsic::vector_reduce_fmaximum: 10317 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10318 break; 10319 case Intrinsic::vector_reduce_fminimum: 10320 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10321 break; 10322 default: 10323 llvm_unreachable("Unhandled vector reduce intrinsic"); 10324 } 10325 setValue(&I, Res); 10326 } 10327 10328 /// Returns an AttributeList representing the attributes applied to the return 10329 /// value of the given call. 10330 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10331 SmallVector<Attribute::AttrKind, 2> Attrs; 10332 if (CLI.RetSExt) 10333 Attrs.push_back(Attribute::SExt); 10334 if (CLI.RetZExt) 10335 Attrs.push_back(Attribute::ZExt); 10336 if (CLI.IsInReg) 10337 Attrs.push_back(Attribute::InReg); 10338 10339 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10340 Attrs); 10341 } 10342 10343 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10344 /// implementation, which just calls LowerCall. 10345 /// FIXME: When all targets are 10346 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10347 std::pair<SDValue, SDValue> 10348 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10349 // Handle the incoming return values from the call. 10350 CLI.Ins.clear(); 10351 Type *OrigRetTy = CLI.RetTy; 10352 SmallVector<EVT, 4> RetTys; 10353 SmallVector<uint64_t, 4> Offsets; 10354 auto &DL = CLI.DAG.getDataLayout(); 10355 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0); 10356 10357 if (CLI.IsPostTypeLegalization) { 10358 // If we are lowering a libcall after legalization, split the return type. 10359 SmallVector<EVT, 4> OldRetTys; 10360 SmallVector<uint64_t, 4> OldOffsets; 10361 RetTys.swap(OldRetTys); 10362 Offsets.swap(OldOffsets); 10363 10364 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10365 EVT RetVT = OldRetTys[i]; 10366 uint64_t Offset = OldOffsets[i]; 10367 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10368 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10369 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10370 RetTys.append(NumRegs, RegisterVT); 10371 for (unsigned j = 0; j != NumRegs; ++j) 10372 Offsets.push_back(Offset + j * RegisterVTByteSZ); 10373 } 10374 } 10375 10376 SmallVector<ISD::OutputArg, 4> Outs; 10377 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10378 10379 bool CanLowerReturn = 10380 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10381 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10382 10383 SDValue DemoteStackSlot; 10384 int DemoteStackIdx = -100; 10385 if (!CanLowerReturn) { 10386 // FIXME: equivalent assert? 10387 // assert(!CS.hasInAllocaArgument() && 10388 // "sret demotion is incompatible with inalloca"); 10389 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10390 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10391 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10392 DemoteStackIdx = 10393 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10394 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10395 DL.getAllocaAddrSpace()); 10396 10397 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10398 ArgListEntry Entry; 10399 Entry.Node = DemoteStackSlot; 10400 Entry.Ty = StackSlotPtrType; 10401 Entry.IsSExt = false; 10402 Entry.IsZExt = false; 10403 Entry.IsInReg = false; 10404 Entry.IsSRet = true; 10405 Entry.IsNest = false; 10406 Entry.IsByVal = false; 10407 Entry.IsByRef = false; 10408 Entry.IsReturned = false; 10409 Entry.IsSwiftSelf = false; 10410 Entry.IsSwiftAsync = false; 10411 Entry.IsSwiftError = false; 10412 Entry.IsCFGuardTarget = false; 10413 Entry.Alignment = Alignment; 10414 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10415 CLI.NumFixedArgs += 1; 10416 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10417 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10418 10419 // sret demotion isn't compatible with tail-calls, since the sret argument 10420 // points into the callers stack frame. 10421 CLI.IsTailCall = false; 10422 } else { 10423 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10424 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10425 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10426 ISD::ArgFlagsTy Flags; 10427 if (NeedsRegBlock) { 10428 Flags.setInConsecutiveRegs(); 10429 if (I == RetTys.size() - 1) 10430 Flags.setInConsecutiveRegsLast(); 10431 } 10432 EVT VT = RetTys[I]; 10433 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10434 CLI.CallConv, VT); 10435 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10436 CLI.CallConv, VT); 10437 for (unsigned i = 0; i != NumRegs; ++i) { 10438 ISD::InputArg MyFlags; 10439 MyFlags.Flags = Flags; 10440 MyFlags.VT = RegisterVT; 10441 MyFlags.ArgVT = VT; 10442 MyFlags.Used = CLI.IsReturnValueUsed; 10443 if (CLI.RetTy->isPointerTy()) { 10444 MyFlags.Flags.setPointer(); 10445 MyFlags.Flags.setPointerAddrSpace( 10446 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10447 } 10448 if (CLI.RetSExt) 10449 MyFlags.Flags.setSExt(); 10450 if (CLI.RetZExt) 10451 MyFlags.Flags.setZExt(); 10452 if (CLI.IsInReg) 10453 MyFlags.Flags.setInReg(); 10454 CLI.Ins.push_back(MyFlags); 10455 } 10456 } 10457 } 10458 10459 // We push in swifterror return as the last element of CLI.Ins. 10460 ArgListTy &Args = CLI.getArgs(); 10461 if (supportSwiftError()) { 10462 for (const ArgListEntry &Arg : Args) { 10463 if (Arg.IsSwiftError) { 10464 ISD::InputArg MyFlags; 10465 MyFlags.VT = getPointerTy(DL); 10466 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10467 MyFlags.Flags.setSwiftError(); 10468 CLI.Ins.push_back(MyFlags); 10469 } 10470 } 10471 } 10472 10473 // Handle all of the outgoing arguments. 10474 CLI.Outs.clear(); 10475 CLI.OutVals.clear(); 10476 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10477 SmallVector<EVT, 4> ValueVTs; 10478 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10479 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10480 Type *FinalType = Args[i].Ty; 10481 if (Args[i].IsByVal) 10482 FinalType = Args[i].IndirectType; 10483 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10484 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10485 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10486 ++Value) { 10487 EVT VT = ValueVTs[Value]; 10488 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10489 SDValue Op = SDValue(Args[i].Node.getNode(), 10490 Args[i].Node.getResNo() + Value); 10491 ISD::ArgFlagsTy Flags; 10492 10493 // Certain targets (such as MIPS), may have a different ABI alignment 10494 // for a type depending on the context. Give the target a chance to 10495 // specify the alignment it wants. 10496 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10497 Flags.setOrigAlign(OriginalAlignment); 10498 10499 if (Args[i].Ty->isPointerTy()) { 10500 Flags.setPointer(); 10501 Flags.setPointerAddrSpace( 10502 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10503 } 10504 if (Args[i].IsZExt) 10505 Flags.setZExt(); 10506 if (Args[i].IsSExt) 10507 Flags.setSExt(); 10508 if (Args[i].IsInReg) { 10509 // If we are using vectorcall calling convention, a structure that is 10510 // passed InReg - is surely an HVA 10511 if (CLI.CallConv == CallingConv::X86_VectorCall && 10512 isa<StructType>(FinalType)) { 10513 // The first value of a structure is marked 10514 if (0 == Value) 10515 Flags.setHvaStart(); 10516 Flags.setHva(); 10517 } 10518 // Set InReg Flag 10519 Flags.setInReg(); 10520 } 10521 if (Args[i].IsSRet) 10522 Flags.setSRet(); 10523 if (Args[i].IsSwiftSelf) 10524 Flags.setSwiftSelf(); 10525 if (Args[i].IsSwiftAsync) 10526 Flags.setSwiftAsync(); 10527 if (Args[i].IsSwiftError) 10528 Flags.setSwiftError(); 10529 if (Args[i].IsCFGuardTarget) 10530 Flags.setCFGuardTarget(); 10531 if (Args[i].IsByVal) 10532 Flags.setByVal(); 10533 if (Args[i].IsByRef) 10534 Flags.setByRef(); 10535 if (Args[i].IsPreallocated) { 10536 Flags.setPreallocated(); 10537 // Set the byval flag for CCAssignFn callbacks that don't know about 10538 // preallocated. This way we can know how many bytes we should've 10539 // allocated and how many bytes a callee cleanup function will pop. If 10540 // we port preallocated to more targets, we'll have to add custom 10541 // preallocated handling in the various CC lowering callbacks. 10542 Flags.setByVal(); 10543 } 10544 if (Args[i].IsInAlloca) { 10545 Flags.setInAlloca(); 10546 // Set the byval flag for CCAssignFn callbacks that don't know about 10547 // inalloca. This way we can know how many bytes we should've allocated 10548 // and how many bytes a callee cleanup function will pop. If we port 10549 // inalloca to more targets, we'll have to add custom inalloca handling 10550 // in the various CC lowering callbacks. 10551 Flags.setByVal(); 10552 } 10553 Align MemAlign; 10554 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10555 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10556 Flags.setByValSize(FrameSize); 10557 10558 // info is not there but there are cases it cannot get right. 10559 if (auto MA = Args[i].Alignment) 10560 MemAlign = *MA; 10561 else 10562 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10563 } else if (auto MA = Args[i].Alignment) { 10564 MemAlign = *MA; 10565 } else { 10566 MemAlign = OriginalAlignment; 10567 } 10568 Flags.setMemAlign(MemAlign); 10569 if (Args[i].IsNest) 10570 Flags.setNest(); 10571 if (NeedsRegBlock) 10572 Flags.setInConsecutiveRegs(); 10573 10574 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10575 CLI.CallConv, VT); 10576 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10577 CLI.CallConv, VT); 10578 SmallVector<SDValue, 4> Parts(NumParts); 10579 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10580 10581 if (Args[i].IsSExt) 10582 ExtendKind = ISD::SIGN_EXTEND; 10583 else if (Args[i].IsZExt) 10584 ExtendKind = ISD::ZERO_EXTEND; 10585 10586 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10587 // for now. 10588 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10589 CanLowerReturn) { 10590 assert((CLI.RetTy == Args[i].Ty || 10591 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10592 CLI.RetTy->getPointerAddressSpace() == 10593 Args[i].Ty->getPointerAddressSpace())) && 10594 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10595 // Before passing 'returned' to the target lowering code, ensure that 10596 // either the register MVT and the actual EVT are the same size or that 10597 // the return value and argument are extended in the same way; in these 10598 // cases it's safe to pass the argument register value unchanged as the 10599 // return register value (although it's at the target's option whether 10600 // to do so) 10601 // TODO: allow code generation to take advantage of partially preserved 10602 // registers rather than clobbering the entire register when the 10603 // parameter extension method is not compatible with the return 10604 // extension method 10605 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10606 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10607 CLI.RetZExt == Args[i].IsZExt)) 10608 Flags.setReturned(); 10609 } 10610 10611 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10612 CLI.CallConv, ExtendKind); 10613 10614 for (unsigned j = 0; j != NumParts; ++j) { 10615 // if it isn't first piece, alignment must be 1 10616 // For scalable vectors the scalable part is currently handled 10617 // by individual targets, so we just use the known minimum size here. 10618 ISD::OutputArg MyFlags( 10619 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10620 i < CLI.NumFixedArgs, i, 10621 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10622 if (NumParts > 1 && j == 0) 10623 MyFlags.Flags.setSplit(); 10624 else if (j != 0) { 10625 MyFlags.Flags.setOrigAlign(Align(1)); 10626 if (j == NumParts - 1) 10627 MyFlags.Flags.setSplitEnd(); 10628 } 10629 10630 CLI.Outs.push_back(MyFlags); 10631 CLI.OutVals.push_back(Parts[j]); 10632 } 10633 10634 if (NeedsRegBlock && Value == NumValues - 1) 10635 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10636 } 10637 } 10638 10639 SmallVector<SDValue, 4> InVals; 10640 CLI.Chain = LowerCall(CLI, InVals); 10641 10642 // Update CLI.InVals to use outside of this function. 10643 CLI.InVals = InVals; 10644 10645 // Verify that the target's LowerCall behaved as expected. 10646 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10647 "LowerCall didn't return a valid chain!"); 10648 assert((!CLI.IsTailCall || InVals.empty()) && 10649 "LowerCall emitted a return value for a tail call!"); 10650 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10651 "LowerCall didn't emit the correct number of values!"); 10652 10653 // For a tail call, the return value is merely live-out and there aren't 10654 // any nodes in the DAG representing it. Return a special value to 10655 // indicate that a tail call has been emitted and no more Instructions 10656 // should be processed in the current block. 10657 if (CLI.IsTailCall) { 10658 CLI.DAG.setRoot(CLI.Chain); 10659 return std::make_pair(SDValue(), SDValue()); 10660 } 10661 10662 #ifndef NDEBUG 10663 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10664 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10665 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10666 "LowerCall emitted a value with the wrong type!"); 10667 } 10668 #endif 10669 10670 SmallVector<SDValue, 4> ReturnValues; 10671 if (!CanLowerReturn) { 10672 // The instruction result is the result of loading from the 10673 // hidden sret parameter. 10674 SmallVector<EVT, 1> PVTs; 10675 Type *PtrRetTy = 10676 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 10677 10678 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10679 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10680 EVT PtrVT = PVTs[0]; 10681 10682 unsigned NumValues = RetTys.size(); 10683 ReturnValues.resize(NumValues); 10684 SmallVector<SDValue, 4> Chains(NumValues); 10685 10686 // An aggregate return value cannot wrap around the address space, so 10687 // offsets to its parts don't wrap either. 10688 SDNodeFlags Flags; 10689 Flags.setNoUnsignedWrap(true); 10690 10691 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10692 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10693 for (unsigned i = 0; i < NumValues; ++i) { 10694 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10695 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10696 PtrVT), Flags); 10697 SDValue L = CLI.DAG.getLoad( 10698 RetTys[i], CLI.DL, CLI.Chain, Add, 10699 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10700 DemoteStackIdx, Offsets[i]), 10701 HiddenSRetAlign); 10702 ReturnValues[i] = L; 10703 Chains[i] = L.getValue(1); 10704 } 10705 10706 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10707 } else { 10708 // Collect the legal value parts into potentially illegal values 10709 // that correspond to the original function's return values. 10710 std::optional<ISD::NodeType> AssertOp; 10711 if (CLI.RetSExt) 10712 AssertOp = ISD::AssertSext; 10713 else if (CLI.RetZExt) 10714 AssertOp = ISD::AssertZext; 10715 unsigned CurReg = 0; 10716 for (EVT VT : RetTys) { 10717 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10718 CLI.CallConv, VT); 10719 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10720 CLI.CallConv, VT); 10721 10722 ReturnValues.push_back(getCopyFromParts( 10723 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr, 10724 CLI.Chain, CLI.CallConv, AssertOp)); 10725 CurReg += NumRegs; 10726 } 10727 10728 // For a function returning void, there is no return value. We can't create 10729 // such a node, so we just return a null return value in that case. In 10730 // that case, nothing will actually look at the value. 10731 if (ReturnValues.empty()) 10732 return std::make_pair(SDValue(), CLI.Chain); 10733 } 10734 10735 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10736 CLI.DAG.getVTList(RetTys), ReturnValues); 10737 return std::make_pair(Res, CLI.Chain); 10738 } 10739 10740 /// Places new result values for the node in Results (their number 10741 /// and types must exactly match those of the original return values of 10742 /// the node), or leaves Results empty, which indicates that the node is not 10743 /// to be custom lowered after all. 10744 void TargetLowering::LowerOperationWrapper(SDNode *N, 10745 SmallVectorImpl<SDValue> &Results, 10746 SelectionDAG &DAG) const { 10747 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10748 10749 if (!Res.getNode()) 10750 return; 10751 10752 // If the original node has one result, take the return value from 10753 // LowerOperation as is. It might not be result number 0. 10754 if (N->getNumValues() == 1) { 10755 Results.push_back(Res); 10756 return; 10757 } 10758 10759 // If the original node has multiple results, then the return node should 10760 // have the same number of results. 10761 assert((N->getNumValues() == Res->getNumValues()) && 10762 "Lowering returned the wrong number of results!"); 10763 10764 // Places new result values base on N result number. 10765 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10766 Results.push_back(Res.getValue(I)); 10767 } 10768 10769 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10770 llvm_unreachable("LowerOperation not implemented for this target!"); 10771 } 10772 10773 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10774 unsigned Reg, 10775 ISD::NodeType ExtendType) { 10776 SDValue Op = getNonRegisterValue(V); 10777 assert((Op.getOpcode() != ISD::CopyFromReg || 10778 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10779 "Copy from a reg to the same reg!"); 10780 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10781 10782 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10783 // If this is an InlineAsm we have to match the registers required, not the 10784 // notional registers required by the type. 10785 10786 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10787 std::nullopt); // This is not an ABI copy. 10788 SDValue Chain = DAG.getEntryNode(); 10789 10790 if (ExtendType == ISD::ANY_EXTEND) { 10791 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10792 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10793 ExtendType = PreferredExtendIt->second; 10794 } 10795 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10796 PendingExports.push_back(Chain); 10797 } 10798 10799 #include "llvm/CodeGen/SelectionDAGISel.h" 10800 10801 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10802 /// entry block, return true. This includes arguments used by switches, since 10803 /// the switch may expand into multiple basic blocks. 10804 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10805 // With FastISel active, we may be splitting blocks, so force creation 10806 // of virtual registers for all non-dead arguments. 10807 if (FastISel) 10808 return A->use_empty(); 10809 10810 const BasicBlock &Entry = A->getParent()->front(); 10811 for (const User *U : A->users()) 10812 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10813 return false; // Use not in entry block. 10814 10815 return true; 10816 } 10817 10818 using ArgCopyElisionMapTy = 10819 DenseMap<const Argument *, 10820 std::pair<const AllocaInst *, const StoreInst *>>; 10821 10822 /// Scan the entry block of the function in FuncInfo for arguments that look 10823 /// like copies into a local alloca. Record any copied arguments in 10824 /// ArgCopyElisionCandidates. 10825 static void 10826 findArgumentCopyElisionCandidates(const DataLayout &DL, 10827 FunctionLoweringInfo *FuncInfo, 10828 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10829 // Record the state of every static alloca used in the entry block. Argument 10830 // allocas are all used in the entry block, so we need approximately as many 10831 // entries as we have arguments. 10832 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10833 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10834 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10835 StaticAllocas.reserve(NumArgs * 2); 10836 10837 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10838 if (!V) 10839 return nullptr; 10840 V = V->stripPointerCasts(); 10841 const auto *AI = dyn_cast<AllocaInst>(V); 10842 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10843 return nullptr; 10844 auto Iter = StaticAllocas.insert({AI, Unknown}); 10845 return &Iter.first->second; 10846 }; 10847 10848 // Look for stores of arguments to static allocas. Look through bitcasts and 10849 // GEPs to handle type coercions, as long as the alloca is fully initialized 10850 // by the store. Any non-store use of an alloca escapes it and any subsequent 10851 // unanalyzed store might write it. 10852 // FIXME: Handle structs initialized with multiple stores. 10853 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10854 // Look for stores, and handle non-store uses conservatively. 10855 const auto *SI = dyn_cast<StoreInst>(&I); 10856 if (!SI) { 10857 // We will look through cast uses, so ignore them completely. 10858 if (I.isCast()) 10859 continue; 10860 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10861 // to allocas. 10862 if (I.isDebugOrPseudoInst()) 10863 continue; 10864 // This is an unknown instruction. Assume it escapes or writes to all 10865 // static alloca operands. 10866 for (const Use &U : I.operands()) { 10867 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10868 *Info = StaticAllocaInfo::Clobbered; 10869 } 10870 continue; 10871 } 10872 10873 // If the stored value is a static alloca, mark it as escaped. 10874 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10875 *Info = StaticAllocaInfo::Clobbered; 10876 10877 // Check if the destination is a static alloca. 10878 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10879 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10880 if (!Info) 10881 continue; 10882 const AllocaInst *AI = cast<AllocaInst>(Dst); 10883 10884 // Skip allocas that have been initialized or clobbered. 10885 if (*Info != StaticAllocaInfo::Unknown) 10886 continue; 10887 10888 // Check if the stored value is an argument, and that this store fully 10889 // initializes the alloca. 10890 // If the argument type has padding bits we can't directly forward a pointer 10891 // as the upper bits may contain garbage. 10892 // Don't elide copies from the same argument twice. 10893 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10894 const auto *Arg = dyn_cast<Argument>(Val); 10895 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10896 Arg->getType()->isEmptyTy() || 10897 DL.getTypeStoreSize(Arg->getType()) != 10898 DL.getTypeAllocSize(AI->getAllocatedType()) || 10899 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10900 ArgCopyElisionCandidates.count(Arg)) { 10901 *Info = StaticAllocaInfo::Clobbered; 10902 continue; 10903 } 10904 10905 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10906 << '\n'); 10907 10908 // Mark this alloca and store for argument copy elision. 10909 *Info = StaticAllocaInfo::Elidable; 10910 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10911 10912 // Stop scanning if we've seen all arguments. This will happen early in -O0 10913 // builds, which is useful, because -O0 builds have large entry blocks and 10914 // many allocas. 10915 if (ArgCopyElisionCandidates.size() == NumArgs) 10916 break; 10917 } 10918 } 10919 10920 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10921 /// ArgVal is a load from a suitable fixed stack object. 10922 static void tryToElideArgumentCopy( 10923 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10924 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10925 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10926 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10927 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 10928 // Check if this is a load from a fixed stack object. 10929 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 10930 if (!LNode) 10931 return; 10932 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10933 if (!FINode) 10934 return; 10935 10936 // Check that the fixed stack object is the right size and alignment. 10937 // Look at the alignment that the user wrote on the alloca instead of looking 10938 // at the stack object. 10939 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10940 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10941 const AllocaInst *AI = ArgCopyIter->second.first; 10942 int FixedIndex = FINode->getIndex(); 10943 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10944 int OldIndex = AllocaIndex; 10945 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10946 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10947 LLVM_DEBUG( 10948 dbgs() << " argument copy elision failed due to bad fixed stack " 10949 "object size\n"); 10950 return; 10951 } 10952 Align RequiredAlignment = AI->getAlign(); 10953 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10954 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10955 "greater than stack argument alignment (" 10956 << DebugStr(RequiredAlignment) << " vs " 10957 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10958 return; 10959 } 10960 10961 // Perform the elision. Delete the old stack object and replace its only use 10962 // in the variable info map. Mark the stack object as mutable. 10963 LLVM_DEBUG({ 10964 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10965 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10966 << '\n'; 10967 }); 10968 MFI.RemoveStackObject(OldIndex); 10969 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10970 AllocaIndex = FixedIndex; 10971 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10972 for (SDValue ArgVal : ArgVals) 10973 Chains.push_back(ArgVal.getValue(1)); 10974 10975 // Avoid emitting code for the store implementing the copy. 10976 const StoreInst *SI = ArgCopyIter->second.second; 10977 ElidedArgCopyInstrs.insert(SI); 10978 10979 // Check for uses of the argument again so that we can avoid exporting ArgVal 10980 // if it is't used by anything other than the store. 10981 for (const Value *U : Arg.users()) { 10982 if (U != SI) { 10983 ArgHasUses = true; 10984 break; 10985 } 10986 } 10987 } 10988 10989 void SelectionDAGISel::LowerArguments(const Function &F) { 10990 SelectionDAG &DAG = SDB->DAG; 10991 SDLoc dl = SDB->getCurSDLoc(); 10992 const DataLayout &DL = DAG.getDataLayout(); 10993 SmallVector<ISD::InputArg, 16> Ins; 10994 10995 // In Naked functions we aren't going to save any registers. 10996 if (F.hasFnAttribute(Attribute::Naked)) 10997 return; 10998 10999 if (!FuncInfo->CanLowerReturn) { 11000 // Put in an sret pointer parameter before all the other parameters. 11001 SmallVector<EVT, 1> ValueVTs; 11002 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11003 PointerType::get(F.getContext(), 11004 DAG.getDataLayout().getAllocaAddrSpace()), 11005 ValueVTs); 11006 11007 // NOTE: Assuming that a pointer will never break down to more than one VT 11008 // or one register. 11009 ISD::ArgFlagsTy Flags; 11010 Flags.setSRet(); 11011 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 11012 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 11013 ISD::InputArg::NoArgIndex, 0); 11014 Ins.push_back(RetArg); 11015 } 11016 11017 // Look for stores of arguments to static allocas. Mark such arguments with a 11018 // flag to ask the target to give us the memory location of that argument if 11019 // available. 11020 ArgCopyElisionMapTy ArgCopyElisionCandidates; 11021 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 11022 ArgCopyElisionCandidates); 11023 11024 // Set up the incoming argument description vector. 11025 for (const Argument &Arg : F.args()) { 11026 unsigned ArgNo = Arg.getArgNo(); 11027 SmallVector<EVT, 4> ValueVTs; 11028 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11029 bool isArgValueUsed = !Arg.use_empty(); 11030 unsigned PartBase = 0; 11031 Type *FinalType = Arg.getType(); 11032 if (Arg.hasAttribute(Attribute::ByVal)) 11033 FinalType = Arg.getParamByValType(); 11034 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 11035 FinalType, F.getCallingConv(), F.isVarArg(), DL); 11036 for (unsigned Value = 0, NumValues = ValueVTs.size(); 11037 Value != NumValues; ++Value) { 11038 EVT VT = ValueVTs[Value]; 11039 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 11040 ISD::ArgFlagsTy Flags; 11041 11042 11043 if (Arg.getType()->isPointerTy()) { 11044 Flags.setPointer(); 11045 Flags.setPointerAddrSpace( 11046 cast<PointerType>(Arg.getType())->getAddressSpace()); 11047 } 11048 if (Arg.hasAttribute(Attribute::ZExt)) 11049 Flags.setZExt(); 11050 if (Arg.hasAttribute(Attribute::SExt)) 11051 Flags.setSExt(); 11052 if (Arg.hasAttribute(Attribute::InReg)) { 11053 // If we are using vectorcall calling convention, a structure that is 11054 // passed InReg - is surely an HVA 11055 if (F.getCallingConv() == CallingConv::X86_VectorCall && 11056 isa<StructType>(Arg.getType())) { 11057 // The first value of a structure is marked 11058 if (0 == Value) 11059 Flags.setHvaStart(); 11060 Flags.setHva(); 11061 } 11062 // Set InReg Flag 11063 Flags.setInReg(); 11064 } 11065 if (Arg.hasAttribute(Attribute::StructRet)) 11066 Flags.setSRet(); 11067 if (Arg.hasAttribute(Attribute::SwiftSelf)) 11068 Flags.setSwiftSelf(); 11069 if (Arg.hasAttribute(Attribute::SwiftAsync)) 11070 Flags.setSwiftAsync(); 11071 if (Arg.hasAttribute(Attribute::SwiftError)) 11072 Flags.setSwiftError(); 11073 if (Arg.hasAttribute(Attribute::ByVal)) 11074 Flags.setByVal(); 11075 if (Arg.hasAttribute(Attribute::ByRef)) 11076 Flags.setByRef(); 11077 if (Arg.hasAttribute(Attribute::InAlloca)) { 11078 Flags.setInAlloca(); 11079 // Set the byval flag for CCAssignFn callbacks that don't know about 11080 // inalloca. This way we can know how many bytes we should've allocated 11081 // and how many bytes a callee cleanup function will pop. If we port 11082 // inalloca to more targets, we'll have to add custom inalloca handling 11083 // in the various CC lowering callbacks. 11084 Flags.setByVal(); 11085 } 11086 if (Arg.hasAttribute(Attribute::Preallocated)) { 11087 Flags.setPreallocated(); 11088 // Set the byval flag for CCAssignFn callbacks that don't know about 11089 // preallocated. This way we can know how many bytes we should've 11090 // allocated and how many bytes a callee cleanup function will pop. If 11091 // we port preallocated to more targets, we'll have to add custom 11092 // preallocated handling in the various CC lowering callbacks. 11093 Flags.setByVal(); 11094 } 11095 11096 // Certain targets (such as MIPS), may have a different ABI alignment 11097 // for a type depending on the context. Give the target a chance to 11098 // specify the alignment it wants. 11099 const Align OriginalAlignment( 11100 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 11101 Flags.setOrigAlign(OriginalAlignment); 11102 11103 Align MemAlign; 11104 Type *ArgMemTy = nullptr; 11105 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 11106 Flags.isByRef()) { 11107 if (!ArgMemTy) 11108 ArgMemTy = Arg.getPointeeInMemoryValueType(); 11109 11110 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11111 11112 // For in-memory arguments, size and alignment should be passed from FE. 11113 // BE will guess if this info is not there but there are cases it cannot 11114 // get right. 11115 if (auto ParamAlign = Arg.getParamStackAlign()) 11116 MemAlign = *ParamAlign; 11117 else if ((ParamAlign = Arg.getParamAlign())) 11118 MemAlign = *ParamAlign; 11119 else 11120 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11121 if (Flags.isByRef()) 11122 Flags.setByRefSize(MemSize); 11123 else 11124 Flags.setByValSize(MemSize); 11125 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11126 MemAlign = *ParamAlign; 11127 } else { 11128 MemAlign = OriginalAlignment; 11129 } 11130 Flags.setMemAlign(MemAlign); 11131 11132 if (Arg.hasAttribute(Attribute::Nest)) 11133 Flags.setNest(); 11134 if (NeedsRegBlock) 11135 Flags.setInConsecutiveRegs(); 11136 if (ArgCopyElisionCandidates.count(&Arg)) 11137 Flags.setCopyElisionCandidate(); 11138 if (Arg.hasAttribute(Attribute::Returned)) 11139 Flags.setReturned(); 11140 11141 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11142 *CurDAG->getContext(), F.getCallingConv(), VT); 11143 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11144 *CurDAG->getContext(), F.getCallingConv(), VT); 11145 for (unsigned i = 0; i != NumRegs; ++i) { 11146 // For scalable vectors, use the minimum size; individual targets 11147 // are responsible for handling scalable vector arguments and 11148 // return values. 11149 ISD::InputArg MyFlags( 11150 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11151 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11152 if (NumRegs > 1 && i == 0) 11153 MyFlags.Flags.setSplit(); 11154 // if it isn't first piece, alignment must be 1 11155 else if (i > 0) { 11156 MyFlags.Flags.setOrigAlign(Align(1)); 11157 if (i == NumRegs - 1) 11158 MyFlags.Flags.setSplitEnd(); 11159 } 11160 Ins.push_back(MyFlags); 11161 } 11162 if (NeedsRegBlock && Value == NumValues - 1) 11163 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11164 PartBase += VT.getStoreSize().getKnownMinValue(); 11165 } 11166 } 11167 11168 // Call the target to set up the argument values. 11169 SmallVector<SDValue, 8> InVals; 11170 SDValue NewRoot = TLI->LowerFormalArguments( 11171 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11172 11173 // Verify that the target's LowerFormalArguments behaved as expected. 11174 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11175 "LowerFormalArguments didn't return a valid chain!"); 11176 assert(InVals.size() == Ins.size() && 11177 "LowerFormalArguments didn't emit the correct number of values!"); 11178 LLVM_DEBUG({ 11179 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11180 assert(InVals[i].getNode() && 11181 "LowerFormalArguments emitted a null value!"); 11182 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11183 "LowerFormalArguments emitted a value with the wrong type!"); 11184 } 11185 }); 11186 11187 // Update the DAG with the new chain value resulting from argument lowering. 11188 DAG.setRoot(NewRoot); 11189 11190 // Set up the argument values. 11191 unsigned i = 0; 11192 if (!FuncInfo->CanLowerReturn) { 11193 // Create a virtual register for the sret pointer, and put in a copy 11194 // from the sret argument into it. 11195 SmallVector<EVT, 1> ValueVTs; 11196 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11197 PointerType::get(F.getContext(), 11198 DAG.getDataLayout().getAllocaAddrSpace()), 11199 ValueVTs); 11200 MVT VT = ValueVTs[0].getSimpleVT(); 11201 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11202 std::optional<ISD::NodeType> AssertOp; 11203 SDValue ArgValue = 11204 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot, 11205 F.getCallingConv(), AssertOp); 11206 11207 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11208 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11209 Register SRetReg = 11210 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11211 FuncInfo->DemoteRegister = SRetReg; 11212 NewRoot = 11213 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11214 DAG.setRoot(NewRoot); 11215 11216 // i indexes lowered arguments. Bump it past the hidden sret argument. 11217 ++i; 11218 } 11219 11220 SmallVector<SDValue, 4> Chains; 11221 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11222 for (const Argument &Arg : F.args()) { 11223 SmallVector<SDValue, 4> ArgValues; 11224 SmallVector<EVT, 4> ValueVTs; 11225 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11226 unsigned NumValues = ValueVTs.size(); 11227 if (NumValues == 0) 11228 continue; 11229 11230 bool ArgHasUses = !Arg.use_empty(); 11231 11232 // Elide the copying store if the target loaded this argument from a 11233 // suitable fixed stack object. 11234 if (Ins[i].Flags.isCopyElisionCandidate()) { 11235 unsigned NumParts = 0; 11236 for (EVT VT : ValueVTs) 11237 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11238 F.getCallingConv(), VT); 11239 11240 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11241 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11242 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11243 } 11244 11245 // If this argument is unused then remember its value. It is used to generate 11246 // debugging information. 11247 bool isSwiftErrorArg = 11248 TLI->supportSwiftError() && 11249 Arg.hasAttribute(Attribute::SwiftError); 11250 if (!ArgHasUses && !isSwiftErrorArg) { 11251 SDB->setUnusedArgValue(&Arg, InVals[i]); 11252 11253 // Also remember any frame index for use in FastISel. 11254 if (FrameIndexSDNode *FI = 11255 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11256 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11257 } 11258 11259 for (unsigned Val = 0; Val != NumValues; ++Val) { 11260 EVT VT = ValueVTs[Val]; 11261 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11262 F.getCallingConv(), VT); 11263 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11264 *CurDAG->getContext(), F.getCallingConv(), VT); 11265 11266 // Even an apparent 'unused' swifterror argument needs to be returned. So 11267 // we do generate a copy for it that can be used on return from the 11268 // function. 11269 if (ArgHasUses || isSwiftErrorArg) { 11270 std::optional<ISD::NodeType> AssertOp; 11271 if (Arg.hasAttribute(Attribute::SExt)) 11272 AssertOp = ISD::AssertSext; 11273 else if (Arg.hasAttribute(Attribute::ZExt)) 11274 AssertOp = ISD::AssertZext; 11275 11276 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11277 PartVT, VT, nullptr, NewRoot, 11278 F.getCallingConv(), AssertOp)); 11279 } 11280 11281 i += NumParts; 11282 } 11283 11284 // We don't need to do anything else for unused arguments. 11285 if (ArgValues.empty()) 11286 continue; 11287 11288 // Note down frame index. 11289 if (FrameIndexSDNode *FI = 11290 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11291 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11292 11293 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11294 SDB->getCurSDLoc()); 11295 11296 SDB->setValue(&Arg, Res); 11297 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11298 // We want to associate the argument with the frame index, among 11299 // involved operands, that correspond to the lowest address. The 11300 // getCopyFromParts function, called earlier, is swapping the order of 11301 // the operands to BUILD_PAIR depending on endianness. The result of 11302 // that swapping is that the least significant bits of the argument will 11303 // be in the first operand of the BUILD_PAIR node, and the most 11304 // significant bits will be in the second operand. 11305 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11306 if (LoadSDNode *LNode = 11307 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11308 if (FrameIndexSDNode *FI = 11309 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11310 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11311 } 11312 11313 // Analyses past this point are naive and don't expect an assertion. 11314 if (Res.getOpcode() == ISD::AssertZext) 11315 Res = Res.getOperand(0); 11316 11317 // Update the SwiftErrorVRegDefMap. 11318 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11319 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11320 if (Register::isVirtualRegister(Reg)) 11321 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11322 Reg); 11323 } 11324 11325 // If this argument is live outside of the entry block, insert a copy from 11326 // wherever we got it to the vreg that other BB's will reference it as. 11327 if (Res.getOpcode() == ISD::CopyFromReg) { 11328 // If we can, though, try to skip creating an unnecessary vreg. 11329 // FIXME: This isn't very clean... it would be nice to make this more 11330 // general. 11331 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11332 if (Register::isVirtualRegister(Reg)) { 11333 FuncInfo->ValueMap[&Arg] = Reg; 11334 continue; 11335 } 11336 } 11337 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11338 FuncInfo->InitializeRegForValue(&Arg); 11339 SDB->CopyToExportRegsIfNeeded(&Arg); 11340 } 11341 } 11342 11343 if (!Chains.empty()) { 11344 Chains.push_back(NewRoot); 11345 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11346 } 11347 11348 DAG.setRoot(NewRoot); 11349 11350 assert(i == InVals.size() && "Argument register count mismatch!"); 11351 11352 // If any argument copy elisions occurred and we have debug info, update the 11353 // stale frame indices used in the dbg.declare variable info table. 11354 if (!ArgCopyElisionFrameIndexMap.empty()) { 11355 for (MachineFunction::VariableDbgInfo &VI : 11356 MF->getInStackSlotVariableDbgInfo()) { 11357 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11358 if (I != ArgCopyElisionFrameIndexMap.end()) 11359 VI.updateStackSlot(I->second); 11360 } 11361 } 11362 11363 // Finally, if the target has anything special to do, allow it to do so. 11364 emitFunctionEntryCode(); 11365 } 11366 11367 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11368 /// ensure constants are generated when needed. Remember the virtual registers 11369 /// that need to be added to the Machine PHI nodes as input. We cannot just 11370 /// directly add them, because expansion might result in multiple MBB's for one 11371 /// BB. As such, the start of the BB might correspond to a different MBB than 11372 /// the end. 11373 void 11374 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11375 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11376 11377 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11378 11379 // Check PHI nodes in successors that expect a value to be available from this 11380 // block. 11381 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11382 if (!isa<PHINode>(SuccBB->begin())) continue; 11383 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 11384 11385 // If this terminator has multiple identical successors (common for 11386 // switches), only handle each succ once. 11387 if (!SuccsHandled.insert(SuccMBB).second) 11388 continue; 11389 11390 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11391 11392 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11393 // nodes and Machine PHI nodes, but the incoming operands have not been 11394 // emitted yet. 11395 for (const PHINode &PN : SuccBB->phis()) { 11396 // Ignore dead phi's. 11397 if (PN.use_empty()) 11398 continue; 11399 11400 // Skip empty types 11401 if (PN.getType()->isEmptyTy()) 11402 continue; 11403 11404 unsigned Reg; 11405 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11406 11407 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11408 unsigned &RegOut = ConstantsOut[C]; 11409 if (RegOut == 0) { 11410 RegOut = FuncInfo.CreateRegs(C); 11411 // We need to zero/sign extend ConstantInt phi operands to match 11412 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11413 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11414 if (auto *CI = dyn_cast<ConstantInt>(C)) 11415 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11416 : ISD::ZERO_EXTEND; 11417 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11418 } 11419 Reg = RegOut; 11420 } else { 11421 DenseMap<const Value *, Register>::iterator I = 11422 FuncInfo.ValueMap.find(PHIOp); 11423 if (I != FuncInfo.ValueMap.end()) 11424 Reg = I->second; 11425 else { 11426 assert(isa<AllocaInst>(PHIOp) && 11427 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11428 "Didn't codegen value into a register!??"); 11429 Reg = FuncInfo.CreateRegs(PHIOp); 11430 CopyValueToVirtualRegister(PHIOp, Reg); 11431 } 11432 } 11433 11434 // Remember that this register needs to added to the machine PHI node as 11435 // the input for this MBB. 11436 SmallVector<EVT, 4> ValueVTs; 11437 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11438 for (EVT VT : ValueVTs) { 11439 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11440 for (unsigned i = 0; i != NumRegisters; ++i) 11441 FuncInfo.PHINodesToUpdate.push_back( 11442 std::make_pair(&*MBBI++, Reg + i)); 11443 Reg += NumRegisters; 11444 } 11445 } 11446 } 11447 11448 ConstantsOut.clear(); 11449 } 11450 11451 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11452 MachineFunction::iterator I(MBB); 11453 if (++I == FuncInfo.MF->end()) 11454 return nullptr; 11455 return &*I; 11456 } 11457 11458 /// During lowering new call nodes can be created (such as memset, etc.). 11459 /// Those will become new roots of the current DAG, but complications arise 11460 /// when they are tail calls. In such cases, the call lowering will update 11461 /// the root, but the builder still needs to know that a tail call has been 11462 /// lowered in order to avoid generating an additional return. 11463 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11464 // If the node is null, we do have a tail call. 11465 if (MaybeTC.getNode() != nullptr) 11466 DAG.setRoot(MaybeTC); 11467 else 11468 HasTailCall = true; 11469 } 11470 11471 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11472 MachineBasicBlock *SwitchMBB, 11473 MachineBasicBlock *DefaultMBB) { 11474 MachineFunction *CurMF = FuncInfo.MF; 11475 MachineBasicBlock *NextMBB = nullptr; 11476 MachineFunction::iterator BBI(W.MBB); 11477 if (++BBI != FuncInfo.MF->end()) 11478 NextMBB = &*BBI; 11479 11480 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11481 11482 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11483 11484 if (Size == 2 && W.MBB == SwitchMBB) { 11485 // If any two of the cases has the same destination, and if one value 11486 // is the same as the other, but has one bit unset that the other has set, 11487 // use bit manipulation to do two compares at once. For example: 11488 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11489 // TODO: This could be extended to merge any 2 cases in switches with 3 11490 // cases. 11491 // TODO: Handle cases where W.CaseBB != SwitchBB. 11492 CaseCluster &Small = *W.FirstCluster; 11493 CaseCluster &Big = *W.LastCluster; 11494 11495 if (Small.Low == Small.High && Big.Low == Big.High && 11496 Small.MBB == Big.MBB) { 11497 const APInt &SmallValue = Small.Low->getValue(); 11498 const APInt &BigValue = Big.Low->getValue(); 11499 11500 // Check that there is only one bit different. 11501 APInt CommonBit = BigValue ^ SmallValue; 11502 if (CommonBit.isPowerOf2()) { 11503 SDValue CondLHS = getValue(Cond); 11504 EVT VT = CondLHS.getValueType(); 11505 SDLoc DL = getCurSDLoc(); 11506 11507 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11508 DAG.getConstant(CommonBit, DL, VT)); 11509 SDValue Cond = DAG.getSetCC( 11510 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11511 ISD::SETEQ); 11512 11513 // Update successor info. 11514 // Both Small and Big will jump to Small.BB, so we sum up the 11515 // probabilities. 11516 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11517 if (BPI) 11518 addSuccessorWithProb( 11519 SwitchMBB, DefaultMBB, 11520 // The default destination is the first successor in IR. 11521 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11522 else 11523 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11524 11525 // Insert the true branch. 11526 SDValue BrCond = 11527 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11528 DAG.getBasicBlock(Small.MBB)); 11529 // Insert the false branch. 11530 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11531 DAG.getBasicBlock(DefaultMBB)); 11532 11533 DAG.setRoot(BrCond); 11534 return; 11535 } 11536 } 11537 } 11538 11539 if (TM.getOptLevel() != CodeGenOptLevel::None) { 11540 // Here, we order cases by probability so the most likely case will be 11541 // checked first. However, two clusters can have the same probability in 11542 // which case their relative ordering is non-deterministic. So we use Low 11543 // as a tie-breaker as clusters are guaranteed to never overlap. 11544 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11545 [](const CaseCluster &a, const CaseCluster &b) { 11546 return a.Prob != b.Prob ? 11547 a.Prob > b.Prob : 11548 a.Low->getValue().slt(b.Low->getValue()); 11549 }); 11550 11551 // Rearrange the case blocks so that the last one falls through if possible 11552 // without changing the order of probabilities. 11553 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11554 --I; 11555 if (I->Prob > W.LastCluster->Prob) 11556 break; 11557 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11558 std::swap(*I, *W.LastCluster); 11559 break; 11560 } 11561 } 11562 } 11563 11564 // Compute total probability. 11565 BranchProbability DefaultProb = W.DefaultProb; 11566 BranchProbability UnhandledProbs = DefaultProb; 11567 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11568 UnhandledProbs += I->Prob; 11569 11570 MachineBasicBlock *CurMBB = W.MBB; 11571 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11572 bool FallthroughUnreachable = false; 11573 MachineBasicBlock *Fallthrough; 11574 if (I == W.LastCluster) { 11575 // For the last cluster, fall through to the default destination. 11576 Fallthrough = DefaultMBB; 11577 FallthroughUnreachable = isa<UnreachableInst>( 11578 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11579 } else { 11580 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11581 CurMF->insert(BBI, Fallthrough); 11582 // Put Cond in a virtual register to make it available from the new blocks. 11583 ExportFromCurrentBlock(Cond); 11584 } 11585 UnhandledProbs -= I->Prob; 11586 11587 switch (I->Kind) { 11588 case CC_JumpTable: { 11589 // FIXME: Optimize away range check based on pivot comparisons. 11590 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11591 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11592 11593 // The jump block hasn't been inserted yet; insert it here. 11594 MachineBasicBlock *JumpMBB = JT->MBB; 11595 CurMF->insert(BBI, JumpMBB); 11596 11597 auto JumpProb = I->Prob; 11598 auto FallthroughProb = UnhandledProbs; 11599 11600 // If the default statement is a target of the jump table, we evenly 11601 // distribute the default probability to successors of CurMBB. Also 11602 // update the probability on the edge from JumpMBB to Fallthrough. 11603 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11604 SE = JumpMBB->succ_end(); 11605 SI != SE; ++SI) { 11606 if (*SI == DefaultMBB) { 11607 JumpProb += DefaultProb / 2; 11608 FallthroughProb -= DefaultProb / 2; 11609 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11610 JumpMBB->normalizeSuccProbs(); 11611 break; 11612 } 11613 } 11614 11615 // If the default clause is unreachable, propagate that knowledge into 11616 // JTH->FallthroughUnreachable which will use it to suppress the range 11617 // check. 11618 // 11619 // However, don't do this if we're doing branch target enforcement, 11620 // because a table branch _without_ a range check can be a tempting JOP 11621 // gadget - out-of-bounds inputs that are impossible in correct 11622 // execution become possible again if an attacker can influence the 11623 // control flow. So if an attacker doesn't already have a BTI bypass 11624 // available, we don't want them to be able to get one out of this 11625 // table branch. 11626 if (FallthroughUnreachable) { 11627 Function &CurFunc = CurMF->getFunction(); 11628 bool HasBranchTargetEnforcement = false; 11629 if (CurFunc.hasFnAttribute("branch-target-enforcement")) { 11630 HasBranchTargetEnforcement = 11631 CurFunc.getFnAttribute("branch-target-enforcement") 11632 .getValueAsBool(); 11633 } else { 11634 HasBranchTargetEnforcement = 11635 CurMF->getMMI().getModule()->getModuleFlag( 11636 "branch-target-enforcement"); 11637 } 11638 if (!HasBranchTargetEnforcement) 11639 JTH->FallthroughUnreachable = true; 11640 } 11641 11642 if (!JTH->FallthroughUnreachable) 11643 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11644 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11645 CurMBB->normalizeSuccProbs(); 11646 11647 // The jump table header will be inserted in our current block, do the 11648 // range check, and fall through to our fallthrough block. 11649 JTH->HeaderBB = CurMBB; 11650 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11651 11652 // If we're in the right place, emit the jump table header right now. 11653 if (CurMBB == SwitchMBB) { 11654 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11655 JTH->Emitted = true; 11656 } 11657 break; 11658 } 11659 case CC_BitTests: { 11660 // FIXME: Optimize away range check based on pivot comparisons. 11661 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11662 11663 // The bit test blocks haven't been inserted yet; insert them here. 11664 for (BitTestCase &BTC : BTB->Cases) 11665 CurMF->insert(BBI, BTC.ThisBB); 11666 11667 // Fill in fields of the BitTestBlock. 11668 BTB->Parent = CurMBB; 11669 BTB->Default = Fallthrough; 11670 11671 BTB->DefaultProb = UnhandledProbs; 11672 // If the cases in bit test don't form a contiguous range, we evenly 11673 // distribute the probability on the edge to Fallthrough to two 11674 // successors of CurMBB. 11675 if (!BTB->ContiguousRange) { 11676 BTB->Prob += DefaultProb / 2; 11677 BTB->DefaultProb -= DefaultProb / 2; 11678 } 11679 11680 if (FallthroughUnreachable) 11681 BTB->FallthroughUnreachable = true; 11682 11683 // If we're in the right place, emit the bit test header right now. 11684 if (CurMBB == SwitchMBB) { 11685 visitBitTestHeader(*BTB, SwitchMBB); 11686 BTB->Emitted = true; 11687 } 11688 break; 11689 } 11690 case CC_Range: { 11691 const Value *RHS, *LHS, *MHS; 11692 ISD::CondCode CC; 11693 if (I->Low == I->High) { 11694 // Check Cond == I->Low. 11695 CC = ISD::SETEQ; 11696 LHS = Cond; 11697 RHS=I->Low; 11698 MHS = nullptr; 11699 } else { 11700 // Check I->Low <= Cond <= I->High. 11701 CC = ISD::SETLE; 11702 LHS = I->Low; 11703 MHS = Cond; 11704 RHS = I->High; 11705 } 11706 11707 // If Fallthrough is unreachable, fold away the comparison. 11708 if (FallthroughUnreachable) 11709 CC = ISD::SETTRUE; 11710 11711 // The false probability is the sum of all unhandled cases. 11712 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11713 getCurSDLoc(), I->Prob, UnhandledProbs); 11714 11715 if (CurMBB == SwitchMBB) 11716 visitSwitchCase(CB, SwitchMBB); 11717 else 11718 SL->SwitchCases.push_back(CB); 11719 11720 break; 11721 } 11722 } 11723 CurMBB = Fallthrough; 11724 } 11725 } 11726 11727 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11728 const SwitchWorkListItem &W, 11729 Value *Cond, 11730 MachineBasicBlock *SwitchMBB) { 11731 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11732 "Clusters not sorted?"); 11733 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11734 11735 auto [LastLeft, FirstRight, LeftProb, RightProb] = 11736 SL->computeSplitWorkItemInfo(W); 11737 11738 // Use the first element on the right as pivot since we will make less-than 11739 // comparisons against it. 11740 CaseClusterIt PivotCluster = FirstRight; 11741 assert(PivotCluster > W.FirstCluster); 11742 assert(PivotCluster <= W.LastCluster); 11743 11744 CaseClusterIt FirstLeft = W.FirstCluster; 11745 CaseClusterIt LastRight = W.LastCluster; 11746 11747 const ConstantInt *Pivot = PivotCluster->Low; 11748 11749 // New blocks will be inserted immediately after the current one. 11750 MachineFunction::iterator BBI(W.MBB); 11751 ++BBI; 11752 11753 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11754 // we can branch to its destination directly if it's squeezed exactly in 11755 // between the known lower bound and Pivot - 1. 11756 MachineBasicBlock *LeftMBB; 11757 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11758 FirstLeft->Low == W.GE && 11759 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11760 LeftMBB = FirstLeft->MBB; 11761 } else { 11762 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11763 FuncInfo.MF->insert(BBI, LeftMBB); 11764 WorkList.push_back( 11765 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11766 // Put Cond in a virtual register to make it available from the new blocks. 11767 ExportFromCurrentBlock(Cond); 11768 } 11769 11770 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11771 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11772 // directly if RHS.High equals the current upper bound. 11773 MachineBasicBlock *RightMBB; 11774 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11775 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11776 RightMBB = FirstRight->MBB; 11777 } else { 11778 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11779 FuncInfo.MF->insert(BBI, RightMBB); 11780 WorkList.push_back( 11781 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11782 // Put Cond in a virtual register to make it available from the new blocks. 11783 ExportFromCurrentBlock(Cond); 11784 } 11785 11786 // Create the CaseBlock record that will be used to lower the branch. 11787 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11788 getCurSDLoc(), LeftProb, RightProb); 11789 11790 if (W.MBB == SwitchMBB) 11791 visitSwitchCase(CB, SwitchMBB); 11792 else 11793 SL->SwitchCases.push_back(CB); 11794 } 11795 11796 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11797 // from the swith statement. 11798 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11799 BranchProbability PeeledCaseProb) { 11800 if (PeeledCaseProb == BranchProbability::getOne()) 11801 return BranchProbability::getZero(); 11802 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11803 11804 uint32_t Numerator = CaseProb.getNumerator(); 11805 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11806 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11807 } 11808 11809 // Try to peel the top probability case if it exceeds the threshold. 11810 // Return current MachineBasicBlock for the switch statement if the peeling 11811 // does not occur. 11812 // If the peeling is performed, return the newly created MachineBasicBlock 11813 // for the peeled switch statement. Also update Clusters to remove the peeled 11814 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11815 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11816 const SwitchInst &SI, CaseClusterVector &Clusters, 11817 BranchProbability &PeeledCaseProb) { 11818 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11819 // Don't perform if there is only one cluster or optimizing for size. 11820 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11821 TM.getOptLevel() == CodeGenOptLevel::None || 11822 SwitchMBB->getParent()->getFunction().hasMinSize()) 11823 return SwitchMBB; 11824 11825 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11826 unsigned PeeledCaseIndex = 0; 11827 bool SwitchPeeled = false; 11828 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11829 CaseCluster &CC = Clusters[Index]; 11830 if (CC.Prob < TopCaseProb) 11831 continue; 11832 TopCaseProb = CC.Prob; 11833 PeeledCaseIndex = Index; 11834 SwitchPeeled = true; 11835 } 11836 if (!SwitchPeeled) 11837 return SwitchMBB; 11838 11839 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11840 << TopCaseProb << "\n"); 11841 11842 // Record the MBB for the peeled switch statement. 11843 MachineFunction::iterator BBI(SwitchMBB); 11844 ++BBI; 11845 MachineBasicBlock *PeeledSwitchMBB = 11846 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11847 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11848 11849 ExportFromCurrentBlock(SI.getCondition()); 11850 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11851 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11852 nullptr, nullptr, TopCaseProb.getCompl()}; 11853 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11854 11855 Clusters.erase(PeeledCaseIt); 11856 for (CaseCluster &CC : Clusters) { 11857 LLVM_DEBUG( 11858 dbgs() << "Scale the probablity for one cluster, before scaling: " 11859 << CC.Prob << "\n"); 11860 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11861 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11862 } 11863 PeeledCaseProb = TopCaseProb; 11864 return PeeledSwitchMBB; 11865 } 11866 11867 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11868 // Extract cases from the switch. 11869 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11870 CaseClusterVector Clusters; 11871 Clusters.reserve(SI.getNumCases()); 11872 for (auto I : SI.cases()) { 11873 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11874 const ConstantInt *CaseVal = I.getCaseValue(); 11875 BranchProbability Prob = 11876 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11877 : BranchProbability(1, SI.getNumCases() + 1); 11878 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11879 } 11880 11881 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11882 11883 // Cluster adjacent cases with the same destination. We do this at all 11884 // optimization levels because it's cheap to do and will make codegen faster 11885 // if there are many clusters. 11886 sortAndRangeify(Clusters); 11887 11888 // The branch probablity of the peeled case. 11889 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11890 MachineBasicBlock *PeeledSwitchMBB = 11891 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11892 11893 // If there is only the default destination, jump there directly. 11894 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11895 if (Clusters.empty()) { 11896 assert(PeeledSwitchMBB == SwitchMBB); 11897 SwitchMBB->addSuccessor(DefaultMBB); 11898 if (DefaultMBB != NextBlock(SwitchMBB)) { 11899 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11900 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11901 } 11902 return; 11903 } 11904 11905 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(), 11906 DAG.getBFI()); 11907 SL->findBitTestClusters(Clusters, &SI); 11908 11909 LLVM_DEBUG({ 11910 dbgs() << "Case clusters: "; 11911 for (const CaseCluster &C : Clusters) { 11912 if (C.Kind == CC_JumpTable) 11913 dbgs() << "JT:"; 11914 if (C.Kind == CC_BitTests) 11915 dbgs() << "BT:"; 11916 11917 C.Low->getValue().print(dbgs(), true); 11918 if (C.Low != C.High) { 11919 dbgs() << '-'; 11920 C.High->getValue().print(dbgs(), true); 11921 } 11922 dbgs() << ' '; 11923 } 11924 dbgs() << '\n'; 11925 }); 11926 11927 assert(!Clusters.empty()); 11928 SwitchWorkList WorkList; 11929 CaseClusterIt First = Clusters.begin(); 11930 CaseClusterIt Last = Clusters.end() - 1; 11931 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11932 // Scale the branchprobability for DefaultMBB if the peel occurs and 11933 // DefaultMBB is not replaced. 11934 if (PeeledCaseProb != BranchProbability::getZero() && 11935 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11936 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11937 WorkList.push_back( 11938 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11939 11940 while (!WorkList.empty()) { 11941 SwitchWorkListItem W = WorkList.pop_back_val(); 11942 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11943 11944 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 11945 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11946 // For optimized builds, lower large range as a balanced binary tree. 11947 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11948 continue; 11949 } 11950 11951 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11952 } 11953 } 11954 11955 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11956 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11957 auto DL = getCurSDLoc(); 11958 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11959 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11960 } 11961 11962 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11963 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11964 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11965 11966 SDLoc DL = getCurSDLoc(); 11967 SDValue V = getValue(I.getOperand(0)); 11968 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11969 11970 if (VT.isScalableVector()) { 11971 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11972 return; 11973 } 11974 11975 // Use VECTOR_SHUFFLE for the fixed-length vector 11976 // to maintain existing behavior. 11977 SmallVector<int, 8> Mask; 11978 unsigned NumElts = VT.getVectorMinNumElements(); 11979 for (unsigned i = 0; i != NumElts; ++i) 11980 Mask.push_back(NumElts - 1 - i); 11981 11982 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11983 } 11984 11985 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11986 auto DL = getCurSDLoc(); 11987 SDValue InVec = getValue(I.getOperand(0)); 11988 EVT OutVT = 11989 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11990 11991 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11992 11993 // ISD Node needs the input vectors split into two equal parts 11994 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11995 DAG.getVectorIdxConstant(0, DL)); 11996 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11997 DAG.getVectorIdxConstant(OutNumElts, DL)); 11998 11999 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12000 // legalisation and combines. 12001 if (OutVT.isFixedLengthVector()) { 12002 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12003 createStrideMask(0, 2, OutNumElts)); 12004 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12005 createStrideMask(1, 2, OutNumElts)); 12006 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 12007 setValue(&I, Res); 12008 return; 12009 } 12010 12011 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 12012 DAG.getVTList(OutVT, OutVT), Lo, Hi); 12013 setValue(&I, Res); 12014 } 12015 12016 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 12017 auto DL = getCurSDLoc(); 12018 EVT InVT = getValue(I.getOperand(0)).getValueType(); 12019 SDValue InVec0 = getValue(I.getOperand(0)); 12020 SDValue InVec1 = getValue(I.getOperand(1)); 12021 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12022 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12023 12024 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12025 // legalisation and combines. 12026 if (OutVT.isFixedLengthVector()) { 12027 unsigned NumElts = InVT.getVectorMinNumElements(); 12028 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 12029 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 12030 createInterleaveMask(NumElts, 2))); 12031 return; 12032 } 12033 12034 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 12035 DAG.getVTList(InVT, InVT), InVec0, InVec1); 12036 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 12037 Res.getValue(1)); 12038 setValue(&I, Res); 12039 } 12040 12041 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 12042 SmallVector<EVT, 4> ValueVTs; 12043 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 12044 ValueVTs); 12045 unsigned NumValues = ValueVTs.size(); 12046 if (NumValues == 0) return; 12047 12048 SmallVector<SDValue, 4> Values(NumValues); 12049 SDValue Op = getValue(I.getOperand(0)); 12050 12051 for (unsigned i = 0; i != NumValues; ++i) 12052 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 12053 SDValue(Op.getNode(), Op.getResNo() + i)); 12054 12055 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12056 DAG.getVTList(ValueVTs), Values)); 12057 } 12058 12059 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 12060 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12061 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12062 12063 SDLoc DL = getCurSDLoc(); 12064 SDValue V1 = getValue(I.getOperand(0)); 12065 SDValue V2 = getValue(I.getOperand(1)); 12066 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12067 12068 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12069 if (VT.isScalableVector()) { 12070 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 12071 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12072 DAG.getConstant(Imm, DL, IdxVT))); 12073 return; 12074 } 12075 12076 unsigned NumElts = VT.getVectorNumElements(); 12077 12078 uint64_t Idx = (NumElts + Imm) % NumElts; 12079 12080 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12081 SmallVector<int, 8> Mask; 12082 for (unsigned i = 0; i < NumElts; ++i) 12083 Mask.push_back(Idx + i); 12084 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12085 } 12086 12087 // Consider the following MIR after SelectionDAG, which produces output in 12088 // phyregs in the first case or virtregs in the second case. 12089 // 12090 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12091 // %5:gr32 = COPY $ebx 12092 // %6:gr32 = COPY $edx 12093 // %1:gr32 = COPY %6:gr32 12094 // %0:gr32 = COPY %5:gr32 12095 // 12096 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12097 // %1:gr32 = COPY %6:gr32 12098 // %0:gr32 = COPY %5:gr32 12099 // 12100 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12101 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12102 // 12103 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12104 // to a single virtreg (such as %0). The remaining outputs monotonically 12105 // increase in virtreg number from there. If a callbr has no outputs, then it 12106 // should not have a corresponding callbr landingpad; in fact, the callbr 12107 // landingpad would not even be able to refer to such a callbr. 12108 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12109 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12110 // There is definitely at least one copy. 12111 assert(MI->getOpcode() == TargetOpcode::COPY && 12112 "start of copy chain MUST be COPY"); 12113 Reg = MI->getOperand(1).getReg(); 12114 MI = MRI.def_begin(Reg)->getParent(); 12115 // There may be an optional second copy. 12116 if (MI->getOpcode() == TargetOpcode::COPY) { 12117 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12118 Reg = MI->getOperand(1).getReg(); 12119 assert(Reg.isPhysical() && "expected COPY of physical register"); 12120 MI = MRI.def_begin(Reg)->getParent(); 12121 } 12122 // The start of the chain must be an INLINEASM_BR. 12123 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12124 "end of copy chain MUST be INLINEASM_BR"); 12125 return Reg; 12126 } 12127 12128 // We must do this walk rather than the simpler 12129 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12130 // otherwise we will end up with copies of virtregs only valid along direct 12131 // edges. 12132 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12133 SmallVector<EVT, 8> ResultVTs; 12134 SmallVector<SDValue, 8> ResultValues; 12135 const auto *CBR = 12136 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12137 12138 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12139 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12140 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12141 12142 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12143 SDValue Chain = DAG.getRoot(); 12144 12145 // Re-parse the asm constraints string. 12146 TargetLowering::AsmOperandInfoVector TargetConstraints = 12147 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12148 for (auto &T : TargetConstraints) { 12149 SDISelAsmOperandInfo OpInfo(T); 12150 if (OpInfo.Type != InlineAsm::isOutput) 12151 continue; 12152 12153 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12154 // individual constraint. 12155 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12156 12157 switch (OpInfo.ConstraintType) { 12158 case TargetLowering::C_Register: 12159 case TargetLowering::C_RegisterClass: { 12160 // Fill in OpInfo.AssignedRegs.Regs. 12161 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12162 12163 // getRegistersForValue may produce 1 to many registers based on whether 12164 // the OpInfo.ConstraintVT is legal on the target or not. 12165 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 12166 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12167 if (Register::isPhysicalRegister(OriginalDef)) 12168 FuncInfo.MBB->addLiveIn(OriginalDef); 12169 // Update the assigned registers to use the original defs. 12170 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 12171 } 12172 12173 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12174 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12175 ResultValues.push_back(V); 12176 ResultVTs.push_back(OpInfo.ConstraintVT); 12177 break; 12178 } 12179 case TargetLowering::C_Other: { 12180 SDValue Flag; 12181 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12182 OpInfo, DAG); 12183 ++InitialDef; 12184 ResultValues.push_back(V); 12185 ResultVTs.push_back(OpInfo.ConstraintVT); 12186 break; 12187 } 12188 default: 12189 break; 12190 } 12191 } 12192 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12193 DAG.getVTList(ResultVTs), ResultValues); 12194 setValue(&I, V); 12195 } 12196