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/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/BranchProbabilityInfo.h" 28 #include "llvm/Analysis/ConstantFolding.h" 29 #include "llvm/Analysis/EHPersonalities.h" 30 #include "llvm/Analysis/Loads.h" 31 #include "llvm/Analysis/MemoryLocation.h" 32 #include "llvm/Analysis/TargetLibraryInfo.h" 33 #include "llvm/Analysis/ValueTracking.h" 34 #include "llvm/CodeGen/Analysis.h" 35 #include "llvm/CodeGen/CodeGenCommonISel.h" 36 #include "llvm/CodeGen/FunctionLoweringInfo.h" 37 #include "llvm/CodeGen/GCMetadata.h" 38 #include "llvm/CodeGen/MachineBasicBlock.h" 39 #include "llvm/CodeGen/MachineFrameInfo.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineInstrBuilder.h" 42 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 43 #include "llvm/CodeGen/MachineMemOperand.h" 44 #include "llvm/CodeGen/MachineModuleInfo.h" 45 #include "llvm/CodeGen/MachineOperand.h" 46 #include "llvm/CodeGen/MachineRegisterInfo.h" 47 #include "llvm/CodeGen/RuntimeLibcalls.h" 48 #include "llvm/CodeGen/SelectionDAG.h" 49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 50 #include "llvm/CodeGen/StackMaps.h" 51 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 52 #include "llvm/CodeGen/TargetFrameLowering.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetOpcodes.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/TargetSubtargetInfo.h" 57 #include "llvm/CodeGen/WinEHFuncInfo.h" 58 #include "llvm/IR/Argument.h" 59 #include "llvm/IR/Attributes.h" 60 #include "llvm/IR/BasicBlock.h" 61 #include "llvm/IR/CFG.h" 62 #include "llvm/IR/CallingConv.h" 63 #include "llvm/IR/Constant.h" 64 #include "llvm/IR/ConstantRange.h" 65 #include "llvm/IR/Constants.h" 66 #include "llvm/IR/DataLayout.h" 67 #include "llvm/IR/DebugInfoMetadata.h" 68 #include "llvm/IR/DerivedTypes.h" 69 #include "llvm/IR/DiagnosticInfo.h" 70 #include "llvm/IR/Function.h" 71 #include "llvm/IR/GetElementPtrTypeIterator.h" 72 #include "llvm/IR/InlineAsm.h" 73 #include "llvm/IR/InstrTypes.h" 74 #include "llvm/IR/Instructions.h" 75 #include "llvm/IR/IntrinsicInst.h" 76 #include "llvm/IR/Intrinsics.h" 77 #include "llvm/IR/IntrinsicsAArch64.h" 78 #include "llvm/IR/IntrinsicsWebAssembly.h" 79 #include "llvm/IR/LLVMContext.h" 80 #include "llvm/IR/Metadata.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/Operator.h" 83 #include "llvm/IR/PatternMatch.h" 84 #include "llvm/IR/Statepoint.h" 85 #include "llvm/IR/Type.h" 86 #include "llvm/IR/User.h" 87 #include "llvm/IR/Value.h" 88 #include "llvm/MC/MCContext.h" 89 #include "llvm/Support/AtomicOrdering.h" 90 #include "llvm/Support/Casting.h" 91 #include "llvm/Support/CommandLine.h" 92 #include "llvm/Support/Compiler.h" 93 #include "llvm/Support/Debug.h" 94 #include "llvm/Support/MathExtras.h" 95 #include "llvm/Support/raw_ostream.h" 96 #include "llvm/Target/TargetIntrinsicInfo.h" 97 #include "llvm/Target/TargetMachine.h" 98 #include "llvm/Target/TargetOptions.h" 99 #include "llvm/Transforms/Utils/Local.h" 100 #include <cstddef> 101 #include <iterator> 102 #include <limits> 103 #include <optional> 104 #include <tuple> 105 106 using namespace llvm; 107 using namespace PatternMatch; 108 using namespace SwitchCG; 109 110 #define DEBUG_TYPE "isel" 111 112 /// LimitFloatPrecision - Generate low-precision inline sequences for 113 /// some float libcalls (6, 8 or 12 bits). 114 static unsigned LimitFloatPrecision; 115 116 static cl::opt<bool> 117 InsertAssertAlign("insert-assert-align", cl::init(true), 118 cl::desc("Insert the experimental `assertalign` node."), 119 cl::ReallyHidden); 120 121 static cl::opt<unsigned, true> 122 LimitFPPrecision("limit-float-precision", 123 cl::desc("Generate low-precision inline sequences " 124 "for some float libcalls"), 125 cl::location(LimitFloatPrecision), cl::Hidden, 126 cl::init(0)); 127 128 static cl::opt<unsigned> SwitchPeelThreshold( 129 "switch-peel-threshold", cl::Hidden, cl::init(66), 130 cl::desc("Set the case probability threshold for peeling the case from a " 131 "switch statement. A value greater than 100 will void this " 132 "optimization")); 133 134 // Limit the width of DAG chains. This is important in general to prevent 135 // DAG-based analysis from blowing up. For example, alias analysis and 136 // load clustering may not complete in reasonable time. It is difficult to 137 // recognize and avoid this situation within each individual analysis, and 138 // future analyses are likely to have the same behavior. Limiting DAG width is 139 // the safe approach and will be especially important with global DAGs. 140 // 141 // MaxParallelChains default is arbitrarily high to avoid affecting 142 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 143 // sequence over this should have been converted to llvm.memcpy by the 144 // frontend. It is easy to induce this behavior with .ll code such as: 145 // %buffer = alloca [4096 x i8] 146 // %data = load [4096 x i8]* %argPtr 147 // store [4096 x i8] %data, [4096 x i8]* %buffer 148 static const unsigned MaxParallelChains = 64; 149 150 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 151 const SDValue *Parts, unsigned NumParts, 152 MVT PartVT, EVT ValueVT, const Value *V, 153 Optional<CallingConv::ID> CC); 154 155 /// getCopyFromParts - Create a value that contains the specified legal parts 156 /// combined into the value they represent. If the parts combine to a type 157 /// larger than ValueVT then AssertOp can be used to specify whether the extra 158 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 159 /// (ISD::AssertSext). 160 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 161 const SDValue *Parts, unsigned NumParts, 162 MVT PartVT, EVT ValueVT, const Value *V, 163 Optional<CallingConv::ID> CC = None, 164 Optional<ISD::NodeType> AssertOp = None) { 165 // Let the target assemble the parts if it wants to 166 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 167 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 168 PartVT, ValueVT, CC)) 169 return Val; 170 171 if (ValueVT.isVector()) 172 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 173 CC); 174 175 assert(NumParts > 0 && "No parts to assemble!"); 176 SDValue Val = Parts[0]; 177 178 if (NumParts > 1) { 179 // Assemble the value from multiple parts. 180 if (ValueVT.isInteger()) { 181 unsigned PartBits = PartVT.getSizeInBits(); 182 unsigned ValueBits = ValueVT.getSizeInBits(); 183 184 // Assemble the power of 2 part. 185 unsigned RoundParts = 186 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 187 unsigned RoundBits = PartBits * RoundParts; 188 EVT RoundVT = RoundBits == ValueBits ? 189 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 190 SDValue Lo, Hi; 191 192 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 193 194 if (RoundParts > 2) { 195 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 196 PartVT, HalfVT, V); 197 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 198 RoundParts / 2, PartVT, HalfVT, V); 199 } else { 200 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 201 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 202 } 203 204 if (DAG.getDataLayout().isBigEndian()) 205 std::swap(Lo, Hi); 206 207 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 208 209 if (RoundParts < NumParts) { 210 // Assemble the trailing non-power-of-2 part. 211 unsigned OddParts = NumParts - RoundParts; 212 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 213 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 214 OddVT, V, CC); 215 216 // Combine the round and odd parts. 217 Lo = Val; 218 if (DAG.getDataLayout().isBigEndian()) 219 std::swap(Lo, Hi); 220 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 221 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 222 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 223 DAG.getConstant(Lo.getValueSizeInBits(), DL, 224 TLI.getShiftAmountTy( 225 TotalVT, DAG.getDataLayout()))); 226 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 227 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 228 } 229 } else if (PartVT.isFloatingPoint()) { 230 // FP split into multiple FP parts (for ppcf128) 231 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 232 "Unexpected split"); 233 SDValue Lo, Hi; 234 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 235 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 236 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 237 std::swap(Lo, Hi); 238 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 239 } else { 240 // FP split into integer parts (soft fp) 241 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 242 !PartVT.isVector() && "Unexpected split"); 243 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 244 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 245 } 246 } 247 248 // There is now one part, held in Val. Correct it to match ValueVT. 249 // PartEVT is the type of the register class that holds the value. 250 // ValueVT is the type of the inline asm operation. 251 EVT PartEVT = Val.getValueType(); 252 253 if (PartEVT == ValueVT) 254 return Val; 255 256 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 257 ValueVT.bitsLT(PartEVT)) { 258 // For an FP value in an integer part, we need to truncate to the right 259 // width first. 260 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 261 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 262 } 263 264 // Handle types that have the same size. 265 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 266 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 267 268 // Handle types with different sizes. 269 if (PartEVT.isInteger() && ValueVT.isInteger()) { 270 if (ValueVT.bitsLT(PartEVT)) { 271 // For a truncate, see if we have any information to 272 // indicate whether the truncated bits will always be 273 // zero or sign-extension. 274 if (AssertOp) 275 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 276 DAG.getValueType(ValueVT)); 277 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 278 } 279 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 280 } 281 282 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 283 // FP_ROUND's are always exact here. 284 if (ValueVT.bitsLT(Val.getValueType())) 285 return DAG.getNode( 286 ISD::FP_ROUND, DL, ValueVT, Val, 287 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 288 289 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 290 } 291 292 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 293 // then truncating. 294 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 295 ValueVT.bitsLT(PartEVT)) { 296 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 297 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 298 } 299 300 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 301 } 302 303 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 304 const Twine &ErrMsg) { 305 const Instruction *I = dyn_cast_or_null<Instruction>(V); 306 if (!V) 307 return Ctx.emitError(ErrMsg); 308 309 const char *AsmError = ", possible invalid constraint for vector type"; 310 if (const CallInst *CI = dyn_cast<CallInst>(I)) 311 if (CI->isInlineAsm()) 312 return Ctx.emitError(I, ErrMsg + AsmError); 313 314 return Ctx.emitError(I, ErrMsg); 315 } 316 317 /// getCopyFromPartsVector - Create a value that contains the specified legal 318 /// parts combined into the value they represent. If the parts combine to a 319 /// type larger than ValueVT then AssertOp can be used to specify whether the 320 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 321 /// ValueVT (ISD::AssertSext). 322 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 323 const SDValue *Parts, unsigned NumParts, 324 MVT PartVT, EVT ValueVT, const Value *V, 325 Optional<CallingConv::ID> CallConv) { 326 assert(ValueVT.isVector() && "Not a vector value"); 327 assert(NumParts > 0 && "No parts to assemble!"); 328 const bool IsABIRegCopy = CallConv.has_value(); 329 330 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 331 SDValue Val = Parts[0]; 332 333 // Handle a multi-element vector. 334 if (NumParts > 1) { 335 EVT IntermediateVT; 336 MVT RegisterVT; 337 unsigned NumIntermediates; 338 unsigned NumRegs; 339 340 if (IsABIRegCopy) { 341 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 342 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 343 NumIntermediates, RegisterVT); 344 } else { 345 NumRegs = 346 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } 349 350 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 351 NumParts = NumRegs; // Silence a compiler warning. 352 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 353 assert(RegisterVT.getSizeInBits() == 354 Parts[0].getSimpleValueType().getSizeInBits() && 355 "Part type sizes don't match!"); 356 357 // Assemble the parts into intermediate operands. 358 SmallVector<SDValue, 8> Ops(NumIntermediates); 359 if (NumIntermediates == NumParts) { 360 // If the register was not expanded, truncate or copy the value, 361 // as appropriate. 362 for (unsigned i = 0; i != NumParts; ++i) 363 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 364 PartVT, IntermediateVT, V, CallConv); 365 } else if (NumParts > 0) { 366 // If the intermediate type was expanded, build the intermediate 367 // operands from the parts. 368 assert(NumParts % NumIntermediates == 0 && 369 "Must expand into a divisible number of parts!"); 370 unsigned Factor = NumParts / NumIntermediates; 371 for (unsigned i = 0; i != NumIntermediates; ++i) 372 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 373 PartVT, IntermediateVT, V, CallConv); 374 } 375 376 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 377 // intermediate operands. 378 EVT BuiltVectorTy = 379 IntermediateVT.isVector() 380 ? EVT::getVectorVT( 381 *DAG.getContext(), IntermediateVT.getScalarType(), 382 IntermediateVT.getVectorElementCount() * NumParts) 383 : EVT::getVectorVT(*DAG.getContext(), 384 IntermediateVT.getScalarType(), 385 NumIntermediates); 386 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 387 : ISD::BUILD_VECTOR, 388 DL, BuiltVectorTy, Ops); 389 } 390 391 // There is now one part, held in Val. Correct it to match ValueVT. 392 EVT PartEVT = Val.getValueType(); 393 394 if (PartEVT == ValueVT) 395 return Val; 396 397 if (PartEVT.isVector()) { 398 // Vector/Vector bitcast. 399 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 400 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 401 402 // If the parts vector has more elements than the value vector, then we 403 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 404 // Extract the elements we want. 405 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 406 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 407 ValueVT.getVectorElementCount().getKnownMinValue()) && 408 (PartEVT.getVectorElementCount().isScalable() == 409 ValueVT.getVectorElementCount().isScalable()) && 410 "Cannot narrow, it would be a lossy transformation"); 411 PartEVT = 412 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 413 ValueVT.getVectorElementCount()); 414 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 415 DAG.getVectorIdxConstant(0, DL)); 416 if (PartEVT == ValueVT) 417 return Val; 418 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 419 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 420 } 421 422 // Promoted vector extract 423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 424 } 425 426 // Trivial bitcast if the types are the same size and the destination 427 // vector type is legal. 428 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 429 TLI.isTypeLegal(ValueVT)) 430 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 431 432 if (ValueVT.getVectorNumElements() != 1) { 433 // Certain ABIs require that vectors are passed as integers. For vectors 434 // are the same size, this is an obvious bitcast. 435 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 436 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 437 } else if (ValueVT.bitsLT(PartEVT)) { 438 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 439 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 440 // Drop the extra bits. 441 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 442 return DAG.getBitcast(ValueVT, Val); 443 } 444 445 diagnosePossiblyInvalidConstraint( 446 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 447 return DAG.getUNDEF(ValueVT); 448 } 449 450 // Handle cases such as i8 -> <1 x i1> 451 EVT ValueSVT = ValueVT.getVectorElementType(); 452 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 453 unsigned ValueSize = ValueSVT.getSizeInBits(); 454 if (ValueSize == PartEVT.getSizeInBits()) { 455 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 456 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 457 // It's possible a scalar floating point type gets softened to integer and 458 // then promoted to a larger integer. If PartEVT is the larger integer 459 // we need to truncate it and then bitcast to the FP type. 460 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 461 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 462 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 463 Val = DAG.getBitcast(ValueSVT, Val); 464 } else { 465 Val = ValueVT.isFloatingPoint() 466 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 467 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 468 } 469 } 470 471 return DAG.getBuildVector(ValueVT, DL, Val); 472 } 473 474 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 475 SDValue Val, SDValue *Parts, unsigned NumParts, 476 MVT PartVT, const Value *V, 477 Optional<CallingConv::ID> CallConv); 478 479 /// getCopyToParts - Create a series of nodes that contain the specified value 480 /// split into legal parts. If the parts contain more bits than Val, then, for 481 /// integers, ExtendKind can be used to specify how to generate the extra bits. 482 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 483 SDValue *Parts, unsigned NumParts, MVT PartVT, 484 const Value *V, 485 Optional<CallingConv::ID> CallConv = None, 486 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 487 // Let the target split the parts if it wants to 488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 489 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 490 CallConv)) 491 return; 492 EVT ValueVT = Val.getValueType(); 493 494 // Handle the vector case separately. 495 if (ValueVT.isVector()) 496 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 497 CallConv); 498 499 unsigned PartBits = PartVT.getSizeInBits(); 500 unsigned OrigNumParts = NumParts; 501 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 502 "Copying to an illegal type!"); 503 504 if (NumParts == 0) 505 return; 506 507 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 508 EVT PartEVT = PartVT; 509 if (PartEVT == ValueVT) { 510 assert(NumParts == 1 && "No-op copy with multiple parts!"); 511 Parts[0] = Val; 512 return; 513 } 514 515 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 516 // If the parts cover more bits than the value has, promote the value. 517 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 518 assert(NumParts == 1 && "Do not know what to promote to!"); 519 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 520 } else { 521 if (ValueVT.isFloatingPoint()) { 522 // FP values need to be bitcast, then extended if they are being put 523 // into a larger container. 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 525 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 526 } 527 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 528 ValueVT.isInteger() && 529 "Unknown mismatch!"); 530 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 531 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 532 if (PartVT == MVT::x86mmx) 533 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 534 } 535 } else if (PartBits == ValueVT.getSizeInBits()) { 536 // Different types of the same size. 537 assert(NumParts == 1 && PartEVT != ValueVT); 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 540 // If the parts cover less bits than value has, truncate the value. 541 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 542 ValueVT.isInteger() && 543 "Unknown mismatch!"); 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 545 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 546 if (PartVT == MVT::x86mmx) 547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 548 } 549 550 // The value may have changed - recompute ValueVT. 551 ValueVT = Val.getValueType(); 552 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 553 "Failed to tile the value with PartVT!"); 554 555 if (NumParts == 1) { 556 if (PartEVT != ValueVT) { 557 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 558 "scalar-to-vector conversion failed"); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } 561 562 Parts[0] = Val; 563 return; 564 } 565 566 // Expand the value into multiple parts. 567 if (NumParts & (NumParts - 1)) { 568 // The number of parts is not a power of 2. Split off and copy the tail. 569 assert(PartVT.isInteger() && ValueVT.isInteger() && 570 "Do not know what to expand to!"); 571 unsigned RoundParts = 1 << Log2_32(NumParts); 572 unsigned RoundBits = RoundParts * PartBits; 573 unsigned OddParts = NumParts - RoundParts; 574 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 575 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 576 577 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 578 CallConv); 579 580 if (DAG.getDataLayout().isBigEndian()) 581 // The odd parts were reversed by getCopyToParts - unreverse them. 582 std::reverse(Parts + RoundParts, Parts + NumParts); 583 584 NumParts = RoundParts; 585 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 586 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 587 } 588 589 // The number of parts is a power of 2. Repeatedly bisect the value using 590 // EXTRACT_ELEMENT. 591 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 592 EVT::getIntegerVT(*DAG.getContext(), 593 ValueVT.getSizeInBits()), 594 Val); 595 596 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 597 for (unsigned i = 0; i < NumParts; i += StepSize) { 598 unsigned ThisBits = StepSize * PartBits / 2; 599 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 600 SDValue &Part0 = Parts[i]; 601 SDValue &Part1 = Parts[i+StepSize/2]; 602 603 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 604 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 605 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 606 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 607 608 if (ThisBits == PartBits && ThisVT != PartVT) { 609 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 610 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 611 } 612 } 613 } 614 615 if (DAG.getDataLayout().isBigEndian()) 616 std::reverse(Parts, Parts + OrigNumParts); 617 } 618 619 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 620 const SDLoc &DL, EVT PartVT) { 621 if (!PartVT.isVector()) 622 return SDValue(); 623 624 EVT ValueVT = Val.getValueType(); 625 ElementCount PartNumElts = PartVT.getVectorElementCount(); 626 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 627 628 // We only support widening vectors with equivalent element types and 629 // fixed/scalable properties. If a target needs to widen a fixed-length type 630 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 631 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 632 PartNumElts.isScalable() != ValueNumElts.isScalable() || 633 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 634 return SDValue(); 635 636 // Widening a scalable vector to another scalable vector is done by inserting 637 // the vector into a larger undef one. 638 if (PartNumElts.isScalable()) 639 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 640 Val, DAG.getVectorIdxConstant(0, DL)); 641 642 EVT ElementVT = PartVT.getVectorElementType(); 643 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 644 // undef elements. 645 SmallVector<SDValue, 16> Ops; 646 DAG.ExtractVectorElements(Val, Ops); 647 SDValue EltUndef = DAG.getUNDEF(ElementVT); 648 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 649 650 // FIXME: Use CONCAT for 2x -> 4x. 651 return DAG.getBuildVector(PartVT, DL, Ops); 652 } 653 654 /// getCopyToPartsVector - Create a series of nodes that contain the specified 655 /// value split into legal parts. 656 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 657 SDValue Val, SDValue *Parts, unsigned NumParts, 658 MVT PartVT, const Value *V, 659 Optional<CallingConv::ID> CallConv) { 660 EVT ValueVT = Val.getValueType(); 661 assert(ValueVT.isVector() && "Not a vector"); 662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 663 const bool IsABIRegCopy = CallConv.has_value(); 664 665 if (NumParts == 1) { 666 EVT PartEVT = PartVT; 667 if (PartEVT == ValueVT) { 668 // Nothing to do. 669 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 670 // Bitconvert vector->vector case. 671 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 672 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 673 Val = Widened; 674 } else if (PartVT.isVector() && 675 PartEVT.getVectorElementType().bitsGE( 676 ValueVT.getVectorElementType()) && 677 PartEVT.getVectorElementCount() == 678 ValueVT.getVectorElementCount()) { 679 680 // Promoted vector extract 681 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 682 } else if (PartEVT.isVector() && 683 PartEVT.getVectorElementType() != 684 ValueVT.getVectorElementType() && 685 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 686 TargetLowering::TypeWidenVector) { 687 // Combination of widening and promotion. 688 EVT WidenVT = 689 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 690 PartVT.getVectorElementCount()); 691 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 692 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 693 } else { 694 // Don't extract an integer from a float vector. This can happen if the 695 // FP type gets softened to integer and then promoted. The promotion 696 // prevents it from being picked up by the earlier bitcast case. 697 if (ValueVT.getVectorElementCount().isScalar() && 698 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 699 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 700 DAG.getVectorIdxConstant(0, DL)); 701 } else { 702 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 703 assert(PartVT.getFixedSizeInBits() > ValueSize && 704 "lossy conversion of vector to scalar type"); 705 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 706 Val = DAG.getBitcast(IntermediateType, Val); 707 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 708 } 709 } 710 711 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 712 Parts[0] = Val; 713 return; 714 } 715 716 // Handle a multi-element vector. 717 EVT IntermediateVT; 718 MVT RegisterVT; 719 unsigned NumIntermediates; 720 unsigned NumRegs; 721 if (IsABIRegCopy) { 722 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 723 *DAG.getContext(), CallConv.value(), ValueVT, IntermediateVT, 724 NumIntermediates, RegisterVT); 725 } else { 726 NumRegs = 727 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 728 NumIntermediates, RegisterVT); 729 } 730 731 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 732 NumParts = NumRegs; // Silence a compiler warning. 733 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 734 735 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 736 "Mixing scalable and fixed vectors when copying in parts"); 737 738 Optional<ElementCount> DestEltCnt; 739 740 if (IntermediateVT.isVector()) 741 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 742 else 743 DestEltCnt = ElementCount::getFixed(NumIntermediates); 744 745 EVT BuiltVectorTy = EVT::getVectorVT( 746 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 747 748 if (ValueVT == BuiltVectorTy) { 749 // Nothing to do. 750 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 751 // Bitconvert vector->vector case. 752 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 753 } else { 754 if (BuiltVectorTy.getVectorElementType().bitsGT( 755 ValueVT.getVectorElementType())) { 756 // Integer promotion. 757 ValueVT = EVT::getVectorVT(*DAG.getContext(), 758 BuiltVectorTy.getVectorElementType(), 759 ValueVT.getVectorElementCount()); 760 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 761 } 762 763 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 764 Val = Widened; 765 } 766 } 767 768 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 769 770 // Split the vector into intermediate operands. 771 SmallVector<SDValue, 8> Ops(NumIntermediates); 772 for (unsigned i = 0; i != NumIntermediates; ++i) { 773 if (IntermediateVT.isVector()) { 774 // This does something sensible for scalable vectors - see the 775 // definition of EXTRACT_SUBVECTOR for further details. 776 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 777 Ops[i] = 778 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 779 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 780 } else { 781 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 782 DAG.getVectorIdxConstant(i, DL)); 783 } 784 } 785 786 // Split the intermediate operands into legal parts. 787 if (NumParts == NumIntermediates) { 788 // If the register was not expanded, promote or copy the value, 789 // as appropriate. 790 for (unsigned i = 0; i != NumParts; ++i) 791 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 792 } else if (NumParts > 0) { 793 // If the intermediate type was expanded, split each the value into 794 // legal parts. 795 assert(NumIntermediates != 0 && "division by zero"); 796 assert(NumParts % NumIntermediates == 0 && 797 "Must expand into a divisible number of parts!"); 798 unsigned Factor = NumParts / NumIntermediates; 799 for (unsigned i = 0; i != NumIntermediates; ++i) 800 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 801 CallConv); 802 } 803 } 804 805 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 806 EVT valuevt, Optional<CallingConv::ID> CC) 807 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 808 RegCount(1, regs.size()), CallConv(CC) {} 809 810 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 811 const DataLayout &DL, unsigned Reg, Type *Ty, 812 Optional<CallingConv::ID> CC) { 813 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 814 815 CallConv = CC; 816 817 for (EVT ValueVT : ValueVTs) { 818 unsigned NumRegs = 819 isABIMangled() 820 ? TLI.getNumRegistersForCallingConv(Context, CC.value(), ValueVT) 821 : TLI.getNumRegisters(Context, ValueVT); 822 MVT RegisterVT = 823 isABIMangled() 824 ? TLI.getRegisterTypeForCallingConv(Context, CC.value(), ValueVT) 825 : TLI.getRegisterType(Context, ValueVT); 826 for (unsigned i = 0; i != NumRegs; ++i) 827 Regs.push_back(Reg + i); 828 RegVTs.push_back(RegisterVT); 829 RegCount.push_back(NumRegs); 830 Reg += NumRegs; 831 } 832 } 833 834 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 835 FunctionLoweringInfo &FuncInfo, 836 const SDLoc &dl, SDValue &Chain, 837 SDValue *Flag, const Value *V) const { 838 // A Value with type {} or [0 x %t] needs no registers. 839 if (ValueVTs.empty()) 840 return SDValue(); 841 842 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 843 844 // Assemble the legal parts into the final values. 845 SmallVector<SDValue, 4> Values(ValueVTs.size()); 846 SmallVector<SDValue, 8> Parts; 847 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 848 // Copy the legal parts from the registers. 849 EVT ValueVT = ValueVTs[Value]; 850 unsigned NumRegs = RegCount[Value]; 851 MVT RegisterVT = 852 isABIMangled() ? TLI.getRegisterTypeForCallingConv( 853 *DAG.getContext(), CallConv.value(), RegVTs[Value]) 854 : RegVTs[Value]; 855 856 Parts.resize(NumRegs); 857 for (unsigned i = 0; i != NumRegs; ++i) { 858 SDValue P; 859 if (!Flag) { 860 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 861 } else { 862 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 863 *Flag = P.getValue(2); 864 } 865 866 Chain = P.getValue(1); 867 Parts[i] = P; 868 869 // If the source register was virtual and if we know something about it, 870 // add an assert node. 871 if (!Register::isVirtualRegister(Regs[Part + i]) || 872 !RegisterVT.isInteger()) 873 continue; 874 875 const FunctionLoweringInfo::LiveOutInfo *LOI = 876 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 877 if (!LOI) 878 continue; 879 880 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 881 unsigned NumSignBits = LOI->NumSignBits; 882 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 883 884 if (NumZeroBits == RegSize) { 885 // The current value is a zero. 886 // Explicitly express that as it would be easier for 887 // optimizations to kick in. 888 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 889 continue; 890 } 891 892 // FIXME: We capture more information than the dag can represent. For 893 // now, just use the tightest assertzext/assertsext possible. 894 bool isSExt; 895 EVT FromVT(MVT::Other); 896 if (NumZeroBits) { 897 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 898 isSExt = false; 899 } else if (NumSignBits > 1) { 900 FromVT = 901 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 902 isSExt = true; 903 } else { 904 continue; 905 } 906 // Add an assertion node. 907 assert(FromVT != MVT::Other); 908 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 909 RegisterVT, P, DAG.getValueType(FromVT)); 910 } 911 912 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 913 RegisterVT, ValueVT, V, CallConv); 914 Part += NumRegs; 915 Parts.clear(); 916 } 917 918 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 919 } 920 921 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 922 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 923 const Value *V, 924 ISD::NodeType PreferredExtendType) const { 925 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 926 ISD::NodeType ExtendKind = PreferredExtendType; 927 928 // Get the list of the values's legal parts. 929 unsigned NumRegs = Regs.size(); 930 SmallVector<SDValue, 8> Parts(NumRegs); 931 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 932 unsigned NumParts = RegCount[Value]; 933 934 MVT RegisterVT = 935 isABIMangled() ? TLI.getRegisterTypeForCallingConv( 936 *DAG.getContext(), CallConv.value(), RegVTs[Value]) 937 : RegVTs[Value]; 938 939 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 940 ExtendKind = ISD::ZERO_EXTEND; 941 942 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 943 NumParts, RegisterVT, V, CallConv, ExtendKind); 944 Part += NumParts; 945 } 946 947 // Copy the parts into the registers. 948 SmallVector<SDValue, 8> Chains(NumRegs); 949 for (unsigned i = 0; i != NumRegs; ++i) { 950 SDValue Part; 951 if (!Flag) { 952 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 953 } else { 954 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 955 *Flag = Part.getValue(1); 956 } 957 958 Chains[i] = Part.getValue(0); 959 } 960 961 if (NumRegs == 1 || Flag) 962 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 963 // flagged to it. That is the CopyToReg nodes and the user are considered 964 // a single scheduling unit. If we create a TokenFactor and return it as 965 // chain, then the TokenFactor is both a predecessor (operand) of the 966 // user as well as a successor (the TF operands are flagged to the user). 967 // c1, f1 = CopyToReg 968 // c2, f2 = CopyToReg 969 // c3 = TokenFactor c1, c2 970 // ... 971 // = op c3, ..., f2 972 Chain = Chains[NumRegs-1]; 973 else 974 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 975 } 976 977 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 978 unsigned MatchingIdx, const SDLoc &dl, 979 SelectionDAG &DAG, 980 std::vector<SDValue> &Ops) const { 981 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 982 983 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 984 if (HasMatching) 985 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 986 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 987 // Put the register class of the virtual registers in the flag word. That 988 // way, later passes can recompute register class constraints for inline 989 // assembly as well as normal instructions. 990 // Don't do this for tied operands that can use the regclass information 991 // from the def. 992 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 993 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 994 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 995 } 996 997 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 998 Ops.push_back(Res); 999 1000 if (Code == InlineAsm::Kind_Clobber) { 1001 // Clobbers should always have a 1:1 mapping with registers, and may 1002 // reference registers that have illegal (e.g. vector) types. Hence, we 1003 // shouldn't try to apply any sort of splitting logic to them. 1004 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1005 "No 1:1 mapping from clobbers to regs?"); 1006 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1007 (void)SP; 1008 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1009 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1010 assert( 1011 (Regs[I] != SP || 1012 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1013 "If we clobbered the stack pointer, MFI should know about it."); 1014 } 1015 return; 1016 } 1017 1018 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1019 MVT RegisterVT = RegVTs[Value]; 1020 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1021 RegisterVT); 1022 for (unsigned i = 0; i != NumRegs; ++i) { 1023 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1024 unsigned TheReg = Regs[Reg++]; 1025 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1026 } 1027 } 1028 } 1029 1030 SmallVector<std::pair<unsigned, TypeSize>, 4> 1031 RegsForValue::getRegsAndSizes() const { 1032 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1033 unsigned I = 0; 1034 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1035 unsigned RegCount = std::get<0>(CountAndVT); 1036 MVT RegisterVT = std::get<1>(CountAndVT); 1037 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1038 for (unsigned E = I + RegCount; I != E; ++I) 1039 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1040 } 1041 return OutVec; 1042 } 1043 1044 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1045 AssumptionCache *ac, 1046 const TargetLibraryInfo *li) { 1047 AA = aa; 1048 AC = ac; 1049 GFI = gfi; 1050 LibInfo = li; 1051 Context = DAG.getContext(); 1052 LPadToCallSiteMap.clear(); 1053 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1054 } 1055 1056 void SelectionDAGBuilder::clear() { 1057 NodeMap.clear(); 1058 UnusedArgNodeMap.clear(); 1059 PendingLoads.clear(); 1060 PendingExports.clear(); 1061 PendingConstrainedFP.clear(); 1062 PendingConstrainedFPStrict.clear(); 1063 CurInst = nullptr; 1064 HasTailCall = false; 1065 SDNodeOrder = LowestSDNodeOrder; 1066 StatepointLowering.clear(); 1067 } 1068 1069 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1070 DanglingDebugInfoMap.clear(); 1071 } 1072 1073 // Update DAG root to include dependencies on Pending chains. 1074 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1075 SDValue Root = DAG.getRoot(); 1076 1077 if (Pending.empty()) 1078 return Root; 1079 1080 // Add current root to PendingChains, unless we already indirectly 1081 // depend on it. 1082 if (Root.getOpcode() != ISD::EntryToken) { 1083 unsigned i = 0, e = Pending.size(); 1084 for (; i != e; ++i) { 1085 assert(Pending[i].getNode()->getNumOperands() > 1); 1086 if (Pending[i].getNode()->getOperand(0) == Root) 1087 break; // Don't add the root if we already indirectly depend on it. 1088 } 1089 1090 if (i == e) 1091 Pending.push_back(Root); 1092 } 1093 1094 if (Pending.size() == 1) 1095 Root = Pending[0]; 1096 else 1097 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1098 1099 DAG.setRoot(Root); 1100 Pending.clear(); 1101 return Root; 1102 } 1103 1104 SDValue SelectionDAGBuilder::getMemoryRoot() { 1105 return updateRoot(PendingLoads); 1106 } 1107 1108 SDValue SelectionDAGBuilder::getRoot() { 1109 // Chain up all pending constrained intrinsics together with all 1110 // pending loads, by simply appending them to PendingLoads and 1111 // then calling getMemoryRoot(). 1112 PendingLoads.reserve(PendingLoads.size() + 1113 PendingConstrainedFP.size() + 1114 PendingConstrainedFPStrict.size()); 1115 PendingLoads.append(PendingConstrainedFP.begin(), 1116 PendingConstrainedFP.end()); 1117 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1118 PendingConstrainedFPStrict.end()); 1119 PendingConstrainedFP.clear(); 1120 PendingConstrainedFPStrict.clear(); 1121 return getMemoryRoot(); 1122 } 1123 1124 SDValue SelectionDAGBuilder::getControlRoot() { 1125 // We need to emit pending fpexcept.strict constrained intrinsics, 1126 // so append them to the PendingExports list. 1127 PendingExports.append(PendingConstrainedFPStrict.begin(), 1128 PendingConstrainedFPStrict.end()); 1129 PendingConstrainedFPStrict.clear(); 1130 return updateRoot(PendingExports); 1131 } 1132 1133 void SelectionDAGBuilder::visit(const Instruction &I) { 1134 // Set up outgoing PHI node register values before emitting the terminator. 1135 if (I.isTerminator()) { 1136 HandlePHINodesInSuccessorBlocks(I.getParent()); 1137 } 1138 1139 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1140 if (!isa<DbgInfoIntrinsic>(I)) 1141 ++SDNodeOrder; 1142 1143 CurInst = &I; 1144 1145 // Set inserted listener only if required. 1146 bool NodeInserted = false; 1147 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1148 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1149 if (PCSectionsMD) { 1150 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1151 DAG, [&](SDNode *) { NodeInserted = true; }); 1152 } 1153 1154 visit(I.getOpcode(), I); 1155 1156 if (!I.isTerminator() && !HasTailCall && 1157 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1158 CopyToExportRegsIfNeeded(&I); 1159 1160 // Handle metadata. 1161 if (PCSectionsMD) { 1162 auto It = NodeMap.find(&I); 1163 if (It != NodeMap.end()) { 1164 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1165 } else if (NodeInserted) { 1166 // This should not happen; if it does, don't let it go unnoticed so we can 1167 // fix it. Relevant visit*() function is probably missing a setValue(). 1168 errs() << "warning: loosing !pcsections metadata [" 1169 << I.getModule()->getName() << "]\n"; 1170 LLVM_DEBUG(I.dump()); 1171 assert(false); 1172 } 1173 } 1174 1175 CurInst = nullptr; 1176 } 1177 1178 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1179 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1180 } 1181 1182 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1183 // Note: this doesn't use InstVisitor, because it has to work with 1184 // ConstantExpr's in addition to instructions. 1185 switch (Opcode) { 1186 default: llvm_unreachable("Unknown instruction type encountered!"); 1187 // Build the switch statement using the Instruction.def file. 1188 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1189 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1190 #include "llvm/IR/Instruction.def" 1191 } 1192 } 1193 1194 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1195 unsigned Order) { 1196 // We treat variadic dbg_values differently at this stage. 1197 if (DI->hasArgList()) { 1198 // For variadic dbg_values we will now insert an undef. 1199 // FIXME: We can potentially recover these! 1200 SmallVector<SDDbgOperand, 2> Locs; 1201 for (const Value *V : DI->getValues()) { 1202 auto Undef = UndefValue::get(V->getType()); 1203 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1204 } 1205 SDDbgValue *SDV = DAG.getDbgValueList( 1206 DI->getVariable(), DI->getExpression(), Locs, {}, 1207 /*IsIndirect=*/false, DI->getDebugLoc(), Order, /*IsVariadic=*/true); 1208 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1209 } else { 1210 // TODO: Dangling debug info will eventually either be resolved or produce 1211 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1212 // between the original dbg.value location and its resolved DBG_VALUE, 1213 // which we should ideally fill with an extra Undef DBG_VALUE. 1214 assert(DI->getNumVariableLocationOps() == 1 && 1215 "DbgValueInst without an ArgList should have a single location " 1216 "operand."); 1217 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order); 1218 } 1219 } 1220 1221 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1222 const DIExpression *Expr) { 1223 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1224 DIVariable *DanglingVariable = DDI.getVariable(); 1225 DIExpression *DanglingExpr = DDI.getExpression(); 1226 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1227 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << DDI << "\n"); 1228 return true; 1229 } 1230 return false; 1231 }; 1232 1233 for (auto &DDIMI : DanglingDebugInfoMap) { 1234 DanglingDebugInfoVector &DDIV = DDIMI.second; 1235 1236 // If debug info is to be dropped, run it through final checks to see 1237 // whether it can be salvaged. 1238 for (auto &DDI : DDIV) 1239 if (isMatchingDbgValue(DDI)) 1240 salvageUnresolvedDbgValue(DDI); 1241 1242 erase_if(DDIV, isMatchingDbgValue); 1243 } 1244 } 1245 1246 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1247 // generate the debug data structures now that we've seen its definition. 1248 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1249 SDValue Val) { 1250 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1251 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1252 return; 1253 1254 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1255 for (auto &DDI : DDIV) { 1256 DebugLoc DL = DDI.getDebugLoc(); 1257 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1258 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1259 DILocalVariable *Variable = DDI.getVariable(); 1260 DIExpression *Expr = DDI.getExpression(); 1261 assert(Variable->isValidLocationForIntrinsic(DL) && 1262 "Expected inlined-at fields to agree"); 1263 SDDbgValue *SDV; 1264 if (Val.getNode()) { 1265 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1266 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1267 // we couldn't resolve it directly when examining the DbgValue intrinsic 1268 // in the first place we should not be more successful here). Unless we 1269 // have some test case that prove this to be correct we should avoid 1270 // calling EmitFuncArgumentDbgValue here. 1271 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1272 FuncArgumentDbgValueKind::Value, Val)) { 1273 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << DDI << "\n"); 1274 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1275 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1276 // inserted after the definition of Val when emitting the instructions 1277 // after ISel. An alternative could be to teach 1278 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1279 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1280 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1281 << ValSDNodeOrder << "\n"); 1282 SDV = getDbgValue(Val, Variable, Expr, DL, 1283 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1284 DAG.AddDbgValue(SDV, false); 1285 } else 1286 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << DDI 1287 << "in EmitFuncArgumentDbgValue\n"); 1288 } else { 1289 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DDI << "\n"); 1290 auto Undef = UndefValue::get(V->getType()); 1291 auto SDV = 1292 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1293 DAG.AddDbgValue(SDV, false); 1294 } 1295 } 1296 DDIV.clear(); 1297 } 1298 1299 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1300 // TODO: For the variadic implementation, instead of only checking the fail 1301 // state of `handleDebugValue`, we need know specifically which values were 1302 // invalid, so that we attempt to salvage only those values when processing 1303 // a DIArgList. 1304 Value *V = DDI.getVariableLocationOp(0); 1305 Value *OrigV = V; 1306 DILocalVariable *Var = DDI.getVariable(); 1307 DIExpression *Expr = DDI.getExpression(); 1308 DebugLoc DL = DDI.getDebugLoc(); 1309 unsigned SDOrder = DDI.getSDNodeOrder(); 1310 1311 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1312 // that DW_OP_stack_value is desired. 1313 bool StackValue = true; 1314 1315 // Can this Value can be encoded without any further work? 1316 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1317 return; 1318 1319 // Attempt to salvage back through as many instructions as possible. Bail if 1320 // a non-instruction is seen, such as a constant expression or global 1321 // variable. FIXME: Further work could recover those too. 1322 while (isa<Instruction>(V)) { 1323 Instruction &VAsInst = *cast<Instruction>(V); 1324 // Temporary "0", awaiting real implementation. 1325 SmallVector<uint64_t, 16> Ops; 1326 SmallVector<Value *, 4> AdditionalValues; 1327 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1328 AdditionalValues); 1329 // If we cannot salvage any further, and haven't yet found a suitable debug 1330 // expression, bail out. 1331 if (!V) 1332 break; 1333 1334 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1335 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1336 // here for variadic dbg_values, remove that condition. 1337 if (!AdditionalValues.empty()) 1338 break; 1339 1340 // New value and expr now represent this debuginfo. 1341 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1342 1343 // Some kind of simplification occurred: check whether the operand of the 1344 // salvaged debug expression can be encoded in this DAG. 1345 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1346 LLVM_DEBUG( 1347 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1348 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1349 return; 1350 } 1351 } 1352 1353 // This was the final opportunity to salvage this debug information, and it 1354 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1355 // any earlier variable location. 1356 assert(OrigV && "V shouldn't be null"); 1357 auto *Undef = UndefValue::get(OrigV->getType()); 1358 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1359 DAG.AddDbgValue(SDV, false); 1360 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI << "\n"); 1361 } 1362 1363 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1364 DILocalVariable *Var, 1365 DIExpression *Expr, DebugLoc DbgLoc, 1366 unsigned Order, bool IsVariadic) { 1367 if (Values.empty()) 1368 return true; 1369 SmallVector<SDDbgOperand> LocationOps; 1370 SmallVector<SDNode *> Dependencies; 1371 for (const Value *V : Values) { 1372 // Constant value. 1373 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1374 isa<ConstantPointerNull>(V)) { 1375 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1376 continue; 1377 } 1378 1379 // Look through IntToPtr constants. 1380 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1381 if (CE->getOpcode() == Instruction::IntToPtr) { 1382 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1383 continue; 1384 } 1385 1386 // If the Value is a frame index, we can create a FrameIndex debug value 1387 // without relying on the DAG at all. 1388 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1389 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1390 if (SI != FuncInfo.StaticAllocaMap.end()) { 1391 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1392 continue; 1393 } 1394 } 1395 1396 // Do not use getValue() in here; we don't want to generate code at 1397 // this point if it hasn't been done yet. 1398 SDValue N = NodeMap[V]; 1399 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1400 N = UnusedArgNodeMap[V]; 1401 if (N.getNode()) { 1402 // Only emit func arg dbg value for non-variadic dbg.values for now. 1403 if (!IsVariadic && 1404 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1405 FuncArgumentDbgValueKind::Value, N)) 1406 return true; 1407 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1408 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1409 // describe stack slot locations. 1410 // 1411 // Consider "int x = 0; int *px = &x;". There are two kinds of 1412 // interesting debug values here after optimization: 1413 // 1414 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1415 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1416 // 1417 // Both describe the direct values of their associated variables. 1418 Dependencies.push_back(N.getNode()); 1419 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1420 continue; 1421 } 1422 LocationOps.emplace_back( 1423 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1424 continue; 1425 } 1426 1427 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1428 // Special rules apply for the first dbg.values of parameter variables in a 1429 // function. Identify them by the fact they reference Argument Values, that 1430 // they're parameters, and they are parameters of the current function. We 1431 // need to let them dangle until they get an SDNode. 1432 bool IsParamOfFunc = 1433 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1434 if (IsParamOfFunc) 1435 return false; 1436 1437 // The value is not used in this block yet (or it would have an SDNode). 1438 // We still want the value to appear for the user if possible -- if it has 1439 // an associated VReg, we can refer to that instead. 1440 auto VMI = FuncInfo.ValueMap.find(V); 1441 if (VMI != FuncInfo.ValueMap.end()) { 1442 unsigned Reg = VMI->second; 1443 // If this is a PHI node, it may be split up into several MI PHI nodes 1444 // (in FunctionLoweringInfo::set). 1445 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1446 V->getType(), None); 1447 if (RFV.occupiesMultipleRegs()) { 1448 // FIXME: We could potentially support variadic dbg_values here. 1449 if (IsVariadic) 1450 return false; 1451 unsigned Offset = 0; 1452 unsigned BitsToDescribe = 0; 1453 if (auto VarSize = Var->getSizeInBits()) 1454 BitsToDescribe = *VarSize; 1455 if (auto Fragment = Expr->getFragmentInfo()) 1456 BitsToDescribe = Fragment->SizeInBits; 1457 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1458 // Bail out if all bits are described already. 1459 if (Offset >= BitsToDescribe) 1460 break; 1461 // TODO: handle scalable vectors. 1462 unsigned RegisterSize = RegAndSize.second; 1463 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1464 ? BitsToDescribe - Offset 1465 : RegisterSize; 1466 auto FragmentExpr = DIExpression::createFragmentExpression( 1467 Expr, Offset, FragmentSize); 1468 if (!FragmentExpr) 1469 continue; 1470 SDDbgValue *SDV = DAG.getVRegDbgValue( 1471 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1472 DAG.AddDbgValue(SDV, false); 1473 Offset += RegisterSize; 1474 } 1475 return true; 1476 } 1477 // We can use simple vreg locations for variadic dbg_values as well. 1478 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1479 continue; 1480 } 1481 // We failed to create a SDDbgOperand for V. 1482 return false; 1483 } 1484 1485 // We have created a SDDbgOperand for each Value in Values. 1486 // Should use Order instead of SDNodeOrder? 1487 assert(!LocationOps.empty()); 1488 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1489 /*IsIndirect=*/false, DbgLoc, 1490 SDNodeOrder, IsVariadic); 1491 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1492 return true; 1493 } 1494 1495 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1496 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1497 for (auto &Pair : DanglingDebugInfoMap) 1498 for (auto &DDI : Pair.second) 1499 salvageUnresolvedDbgValue(DDI); 1500 clearDanglingDebugInfo(); 1501 } 1502 1503 /// getCopyFromRegs - If there was virtual register allocated for the value V 1504 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1505 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1506 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1507 SDValue Result; 1508 1509 if (It != FuncInfo.ValueMap.end()) { 1510 Register InReg = It->second; 1511 1512 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1513 DAG.getDataLayout(), InReg, Ty, 1514 None); // This is not an ABI copy. 1515 SDValue Chain = DAG.getEntryNode(); 1516 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1517 V); 1518 resolveDanglingDebugInfo(V, Result); 1519 } 1520 1521 return Result; 1522 } 1523 1524 /// getValue - Return an SDValue for the given Value. 1525 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1526 // If we already have an SDValue for this value, use it. It's important 1527 // to do this first, so that we don't create a CopyFromReg if we already 1528 // have a regular SDValue. 1529 SDValue &N = NodeMap[V]; 1530 if (N.getNode()) return N; 1531 1532 // If there's a virtual register allocated and initialized for this 1533 // value, use it. 1534 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1535 return copyFromReg; 1536 1537 // Otherwise create a new SDValue and remember it. 1538 SDValue Val = getValueImpl(V); 1539 NodeMap[V] = Val; 1540 resolveDanglingDebugInfo(V, Val); 1541 return Val; 1542 } 1543 1544 /// getNonRegisterValue - Return an SDValue for the given Value, but 1545 /// don't look in FuncInfo.ValueMap for a virtual register. 1546 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1547 // If we already have an SDValue for this value, use it. 1548 SDValue &N = NodeMap[V]; 1549 if (N.getNode()) { 1550 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1551 // Remove the debug location from the node as the node is about to be used 1552 // in a location which may differ from the original debug location. This 1553 // is relevant to Constant and ConstantFP nodes because they can appear 1554 // as constant expressions inside PHI nodes. 1555 N->setDebugLoc(DebugLoc()); 1556 } 1557 return N; 1558 } 1559 1560 // Otherwise create a new SDValue and remember it. 1561 SDValue Val = getValueImpl(V); 1562 NodeMap[V] = Val; 1563 resolveDanglingDebugInfo(V, Val); 1564 return Val; 1565 } 1566 1567 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1568 /// Create an SDValue for the given value. 1569 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1570 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1571 1572 if (const Constant *C = dyn_cast<Constant>(V)) { 1573 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1574 1575 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1576 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1577 1578 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1579 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1580 1581 if (isa<ConstantPointerNull>(C)) { 1582 unsigned AS = V->getType()->getPointerAddressSpace(); 1583 return DAG.getConstant(0, getCurSDLoc(), 1584 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1585 } 1586 1587 if (match(C, m_VScale(DAG.getDataLayout()))) 1588 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1589 1590 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1591 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1592 1593 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1594 return DAG.getUNDEF(VT); 1595 1596 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1597 visit(CE->getOpcode(), *CE); 1598 SDValue N1 = NodeMap[V]; 1599 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1600 return N1; 1601 } 1602 1603 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1604 SmallVector<SDValue, 4> Constants; 1605 for (const Use &U : C->operands()) { 1606 SDNode *Val = getValue(U).getNode(); 1607 // If the operand is an empty aggregate, there are no values. 1608 if (!Val) continue; 1609 // Add each leaf value from the operand to the Constants list 1610 // to form a flattened list of all the values. 1611 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1612 Constants.push_back(SDValue(Val, i)); 1613 } 1614 1615 return DAG.getMergeValues(Constants, getCurSDLoc()); 1616 } 1617 1618 if (const ConstantDataSequential *CDS = 1619 dyn_cast<ConstantDataSequential>(C)) { 1620 SmallVector<SDValue, 4> Ops; 1621 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1622 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1623 // Add each leaf value from the operand to the Constants list 1624 // to form a flattened list of all the values. 1625 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1626 Ops.push_back(SDValue(Val, i)); 1627 } 1628 1629 if (isa<ArrayType>(CDS->getType())) 1630 return DAG.getMergeValues(Ops, getCurSDLoc()); 1631 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1632 } 1633 1634 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1635 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1636 "Unknown struct or array constant!"); 1637 1638 SmallVector<EVT, 4> ValueVTs; 1639 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1640 unsigned NumElts = ValueVTs.size(); 1641 if (NumElts == 0) 1642 return SDValue(); // empty struct 1643 SmallVector<SDValue, 4> Constants(NumElts); 1644 for (unsigned i = 0; i != NumElts; ++i) { 1645 EVT EltVT = ValueVTs[i]; 1646 if (isa<UndefValue>(C)) 1647 Constants[i] = DAG.getUNDEF(EltVT); 1648 else if (EltVT.isFloatingPoint()) 1649 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1650 else 1651 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1652 } 1653 1654 return DAG.getMergeValues(Constants, getCurSDLoc()); 1655 } 1656 1657 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1658 return DAG.getBlockAddress(BA, VT); 1659 1660 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1661 return getValue(Equiv->getGlobalValue()); 1662 1663 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1664 return getValue(NC->getGlobalValue()); 1665 1666 VectorType *VecTy = cast<VectorType>(V->getType()); 1667 1668 // Now that we know the number and type of the elements, get that number of 1669 // elements into the Ops array based on what kind of constant it is. 1670 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1671 SmallVector<SDValue, 16> Ops; 1672 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1673 for (unsigned i = 0; i != NumElements; ++i) 1674 Ops.push_back(getValue(CV->getOperand(i))); 1675 1676 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1677 } 1678 1679 if (isa<ConstantAggregateZero>(C)) { 1680 EVT EltVT = 1681 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1682 1683 SDValue Op; 1684 if (EltVT.isFloatingPoint()) 1685 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1686 else 1687 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1688 1689 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1690 } 1691 1692 llvm_unreachable("Unknown vector constant"); 1693 } 1694 1695 // If this is a static alloca, generate it as the frameindex instead of 1696 // computation. 1697 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1698 DenseMap<const AllocaInst*, int>::iterator SI = 1699 FuncInfo.StaticAllocaMap.find(AI); 1700 if (SI != FuncInfo.StaticAllocaMap.end()) 1701 return DAG.getFrameIndex(SI->second, 1702 TLI.getFrameIndexTy(DAG.getDataLayout())); 1703 } 1704 1705 // If this is an instruction which fast-isel has deferred, select it now. 1706 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1707 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1708 1709 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1710 Inst->getType(), None); 1711 SDValue Chain = DAG.getEntryNode(); 1712 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1713 } 1714 1715 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1716 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1717 1718 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1719 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1720 1721 llvm_unreachable("Can't get register for value!"); 1722 } 1723 1724 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1725 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1726 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1727 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1728 bool IsSEH = isAsynchronousEHPersonality(Pers); 1729 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1730 if (!IsSEH) 1731 CatchPadMBB->setIsEHScopeEntry(); 1732 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1733 if (IsMSVCCXX || IsCoreCLR) 1734 CatchPadMBB->setIsEHFuncletEntry(); 1735 } 1736 1737 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1738 // Update machine-CFG edge. 1739 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1740 FuncInfo.MBB->addSuccessor(TargetMBB); 1741 TargetMBB->setIsEHCatchretTarget(true); 1742 DAG.getMachineFunction().setHasEHCatchret(true); 1743 1744 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1745 bool IsSEH = isAsynchronousEHPersonality(Pers); 1746 if (IsSEH) { 1747 // If this is not a fall-through branch or optimizations are switched off, 1748 // emit the branch. 1749 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1750 TM.getOptLevel() == CodeGenOpt::None) 1751 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1752 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1753 return; 1754 } 1755 1756 // Figure out the funclet membership for the catchret's successor. 1757 // This will be used by the FuncletLayout pass to determine how to order the 1758 // BB's. 1759 // A 'catchret' returns to the outer scope's color. 1760 Value *ParentPad = I.getCatchSwitchParentPad(); 1761 const BasicBlock *SuccessorColor; 1762 if (isa<ConstantTokenNone>(ParentPad)) 1763 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1764 else 1765 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1766 assert(SuccessorColor && "No parent funclet for catchret!"); 1767 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1768 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1769 1770 // Create the terminator node. 1771 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1772 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1773 DAG.getBasicBlock(SuccessorColorMBB)); 1774 DAG.setRoot(Ret); 1775 } 1776 1777 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1778 // Don't emit any special code for the cleanuppad instruction. It just marks 1779 // the start of an EH scope/funclet. 1780 FuncInfo.MBB->setIsEHScopeEntry(); 1781 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1782 if (Pers != EHPersonality::Wasm_CXX) { 1783 FuncInfo.MBB->setIsEHFuncletEntry(); 1784 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1785 } 1786 } 1787 1788 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1789 // not match, it is OK to add only the first unwind destination catchpad to the 1790 // successors, because there will be at least one invoke instruction within the 1791 // catch scope that points to the next unwind destination, if one exists, so 1792 // CFGSort cannot mess up with BB sorting order. 1793 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1794 // call within them, and catchpads only consisting of 'catch (...)' have a 1795 // '__cxa_end_catch' call within them, both of which generate invokes in case 1796 // the next unwind destination exists, i.e., the next unwind destination is not 1797 // the caller.) 1798 // 1799 // Having at most one EH pad successor is also simpler and helps later 1800 // transformations. 1801 // 1802 // For example, 1803 // current: 1804 // invoke void @foo to ... unwind label %catch.dispatch 1805 // catch.dispatch: 1806 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1807 // catch.start: 1808 // ... 1809 // ... in this BB or some other child BB dominated by this BB there will be an 1810 // invoke that points to 'next' BB as an unwind destination 1811 // 1812 // next: ; We don't need to add this to 'current' BB's successor 1813 // ... 1814 static void findWasmUnwindDestinations( 1815 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1816 BranchProbability Prob, 1817 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1818 &UnwindDests) { 1819 while (EHPadBB) { 1820 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1821 if (isa<CleanupPadInst>(Pad)) { 1822 // Stop on cleanup pads. 1823 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1824 UnwindDests.back().first->setIsEHScopeEntry(); 1825 break; 1826 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1827 // Add the catchpad handlers to the possible destinations. We don't 1828 // continue to the unwind destination of the catchswitch for wasm. 1829 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1830 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1831 UnwindDests.back().first->setIsEHScopeEntry(); 1832 } 1833 break; 1834 } else { 1835 continue; 1836 } 1837 } 1838 } 1839 1840 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1841 /// many places it could ultimately go. In the IR, we have a single unwind 1842 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1843 /// This function skips over imaginary basic blocks that hold catchswitch 1844 /// instructions, and finds all the "real" machine 1845 /// basic block destinations. As those destinations may not be successors of 1846 /// EHPadBB, here we also calculate the edge probability to those destinations. 1847 /// The passed-in Prob is the edge probability to EHPadBB. 1848 static void findUnwindDestinations( 1849 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1850 BranchProbability Prob, 1851 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1852 &UnwindDests) { 1853 EHPersonality Personality = 1854 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1855 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1856 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1857 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1858 bool IsSEH = isAsynchronousEHPersonality(Personality); 1859 1860 if (IsWasmCXX) { 1861 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1862 assert(UnwindDests.size() <= 1 && 1863 "There should be at most one unwind destination for wasm"); 1864 return; 1865 } 1866 1867 while (EHPadBB) { 1868 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1869 BasicBlock *NewEHPadBB = nullptr; 1870 if (isa<LandingPadInst>(Pad)) { 1871 // Stop on landingpads. They are not funclets. 1872 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1873 break; 1874 } else if (isa<CleanupPadInst>(Pad)) { 1875 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1876 // personalities. 1877 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1878 UnwindDests.back().first->setIsEHScopeEntry(); 1879 UnwindDests.back().first->setIsEHFuncletEntry(); 1880 break; 1881 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1882 // Add the catchpad handlers to the possible destinations. 1883 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1884 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1885 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1886 if (IsMSVCCXX || IsCoreCLR) 1887 UnwindDests.back().first->setIsEHFuncletEntry(); 1888 if (!IsSEH) 1889 UnwindDests.back().first->setIsEHScopeEntry(); 1890 } 1891 NewEHPadBB = CatchSwitch->getUnwindDest(); 1892 } else { 1893 continue; 1894 } 1895 1896 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1897 if (BPI && NewEHPadBB) 1898 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1899 EHPadBB = NewEHPadBB; 1900 } 1901 } 1902 1903 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1904 // Update successor info. 1905 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1906 auto UnwindDest = I.getUnwindDest(); 1907 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1908 BranchProbability UnwindDestProb = 1909 (BPI && UnwindDest) 1910 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1911 : BranchProbability::getZero(); 1912 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1913 for (auto &UnwindDest : UnwindDests) { 1914 UnwindDest.first->setIsEHPad(); 1915 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1916 } 1917 FuncInfo.MBB->normalizeSuccProbs(); 1918 1919 // Create the terminator node. 1920 SDValue Ret = 1921 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1922 DAG.setRoot(Ret); 1923 } 1924 1925 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1926 report_fatal_error("visitCatchSwitch not yet implemented!"); 1927 } 1928 1929 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1930 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1931 auto &DL = DAG.getDataLayout(); 1932 SDValue Chain = getControlRoot(); 1933 SmallVector<ISD::OutputArg, 8> Outs; 1934 SmallVector<SDValue, 8> OutVals; 1935 1936 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1937 // lower 1938 // 1939 // %val = call <ty> @llvm.experimental.deoptimize() 1940 // ret <ty> %val 1941 // 1942 // differently. 1943 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1944 LowerDeoptimizingReturn(); 1945 return; 1946 } 1947 1948 if (!FuncInfo.CanLowerReturn) { 1949 unsigned DemoteReg = FuncInfo.DemoteRegister; 1950 const Function *F = I.getParent()->getParent(); 1951 1952 // Emit a store of the return value through the virtual register. 1953 // Leave Outs empty so that LowerReturn won't try to load return 1954 // registers the usual way. 1955 SmallVector<EVT, 1> PtrValueVTs; 1956 ComputeValueVTs(TLI, DL, 1957 F->getReturnType()->getPointerTo( 1958 DAG.getDataLayout().getAllocaAddrSpace()), 1959 PtrValueVTs); 1960 1961 SDValue RetPtr = 1962 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 1963 SDValue RetOp = getValue(I.getOperand(0)); 1964 1965 SmallVector<EVT, 4> ValueVTs, MemVTs; 1966 SmallVector<uint64_t, 4> Offsets; 1967 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1968 &Offsets); 1969 unsigned NumValues = ValueVTs.size(); 1970 1971 SmallVector<SDValue, 4> Chains(NumValues); 1972 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1973 for (unsigned i = 0; i != NumValues; ++i) { 1974 // An aggregate return value cannot wrap around the address space, so 1975 // offsets to its parts don't wrap either. 1976 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1977 TypeSize::Fixed(Offsets[i])); 1978 1979 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1980 if (MemVTs[i] != ValueVTs[i]) 1981 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1982 Chains[i] = DAG.getStore( 1983 Chain, getCurSDLoc(), Val, 1984 // FIXME: better loc info would be nice. 1985 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1986 commonAlignment(BaseAlign, Offsets[i])); 1987 } 1988 1989 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1990 MVT::Other, Chains); 1991 } else if (I.getNumOperands() != 0) { 1992 SmallVector<EVT, 4> ValueVTs; 1993 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1994 unsigned NumValues = ValueVTs.size(); 1995 if (NumValues) { 1996 SDValue RetOp = getValue(I.getOperand(0)); 1997 1998 const Function *F = I.getParent()->getParent(); 1999 2000 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2001 I.getOperand(0)->getType(), F->getCallingConv(), 2002 /*IsVarArg*/ false, DL); 2003 2004 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2005 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2006 ExtendKind = ISD::SIGN_EXTEND; 2007 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2008 ExtendKind = ISD::ZERO_EXTEND; 2009 2010 LLVMContext &Context = F->getContext(); 2011 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2012 2013 for (unsigned j = 0; j != NumValues; ++j) { 2014 EVT VT = ValueVTs[j]; 2015 2016 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2017 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2018 2019 CallingConv::ID CC = F->getCallingConv(); 2020 2021 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2022 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2023 SmallVector<SDValue, 4> Parts(NumParts); 2024 getCopyToParts(DAG, getCurSDLoc(), 2025 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2026 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2027 2028 // 'inreg' on function refers to return value 2029 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2030 if (RetInReg) 2031 Flags.setInReg(); 2032 2033 if (I.getOperand(0)->getType()->isPointerTy()) { 2034 Flags.setPointer(); 2035 Flags.setPointerAddrSpace( 2036 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2037 } 2038 2039 if (NeedsRegBlock) { 2040 Flags.setInConsecutiveRegs(); 2041 if (j == NumValues - 1) 2042 Flags.setInConsecutiveRegsLast(); 2043 } 2044 2045 // Propagate extension type if any 2046 if (ExtendKind == ISD::SIGN_EXTEND) 2047 Flags.setSExt(); 2048 else if (ExtendKind == ISD::ZERO_EXTEND) 2049 Flags.setZExt(); 2050 2051 for (unsigned i = 0; i < NumParts; ++i) { 2052 Outs.push_back(ISD::OutputArg(Flags, 2053 Parts[i].getValueType().getSimpleVT(), 2054 VT, /*isfixed=*/true, 0, 0)); 2055 OutVals.push_back(Parts[i]); 2056 } 2057 } 2058 } 2059 } 2060 2061 // Push in swifterror virtual register as the last element of Outs. This makes 2062 // sure swifterror virtual register will be returned in the swifterror 2063 // physical register. 2064 const Function *F = I.getParent()->getParent(); 2065 if (TLI.supportSwiftError() && 2066 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2067 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2068 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2069 Flags.setSwiftError(); 2070 Outs.push_back(ISD::OutputArg( 2071 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2072 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2073 // Create SDNode for the swifterror virtual register. 2074 OutVals.push_back( 2075 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2076 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2077 EVT(TLI.getPointerTy(DL)))); 2078 } 2079 2080 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2081 CallingConv::ID CallConv = 2082 DAG.getMachineFunction().getFunction().getCallingConv(); 2083 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2084 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2085 2086 // Verify that the target's LowerReturn behaved as expected. 2087 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2088 "LowerReturn didn't return a valid chain!"); 2089 2090 // Update the DAG with the new chain value resulting from return lowering. 2091 DAG.setRoot(Chain); 2092 } 2093 2094 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2095 /// created for it, emit nodes to copy the value into the virtual 2096 /// registers. 2097 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2098 // Skip empty types 2099 if (V->getType()->isEmptyTy()) 2100 return; 2101 2102 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2103 if (VMI != FuncInfo.ValueMap.end()) { 2104 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2105 CopyValueToVirtualRegister(V, VMI->second); 2106 } 2107 } 2108 2109 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2110 /// the current basic block, add it to ValueMap now so that we'll get a 2111 /// CopyTo/FromReg. 2112 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2113 // No need to export constants. 2114 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2115 2116 // Already exported? 2117 if (FuncInfo.isExportedInst(V)) return; 2118 2119 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2120 CopyValueToVirtualRegister(V, Reg); 2121 } 2122 2123 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2124 const BasicBlock *FromBB) { 2125 // The operands of the setcc have to be in this block. We don't know 2126 // how to export them from some other block. 2127 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2128 // Can export from current BB. 2129 if (VI->getParent() == FromBB) 2130 return true; 2131 2132 // Is already exported, noop. 2133 return FuncInfo.isExportedInst(V); 2134 } 2135 2136 // If this is an argument, we can export it if the BB is the entry block or 2137 // if it is already exported. 2138 if (isa<Argument>(V)) { 2139 if (FromBB->isEntryBlock()) 2140 return true; 2141 2142 // Otherwise, can only export this if it is already exported. 2143 return FuncInfo.isExportedInst(V); 2144 } 2145 2146 // Otherwise, constants can always be exported. 2147 return true; 2148 } 2149 2150 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2151 BranchProbability 2152 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2153 const MachineBasicBlock *Dst) const { 2154 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2155 const BasicBlock *SrcBB = Src->getBasicBlock(); 2156 const BasicBlock *DstBB = Dst->getBasicBlock(); 2157 if (!BPI) { 2158 // If BPI is not available, set the default probability as 1 / N, where N is 2159 // the number of successors. 2160 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2161 return BranchProbability(1, SuccSize); 2162 } 2163 return BPI->getEdgeProbability(SrcBB, DstBB); 2164 } 2165 2166 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2167 MachineBasicBlock *Dst, 2168 BranchProbability Prob) { 2169 if (!FuncInfo.BPI) 2170 Src->addSuccessorWithoutProb(Dst); 2171 else { 2172 if (Prob.isUnknown()) 2173 Prob = getEdgeProbability(Src, Dst); 2174 Src->addSuccessor(Dst, Prob); 2175 } 2176 } 2177 2178 static bool InBlock(const Value *V, const BasicBlock *BB) { 2179 if (const Instruction *I = dyn_cast<Instruction>(V)) 2180 return I->getParent() == BB; 2181 return true; 2182 } 2183 2184 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2185 /// This function emits a branch and is used at the leaves of an OR or an 2186 /// AND operator tree. 2187 void 2188 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2189 MachineBasicBlock *TBB, 2190 MachineBasicBlock *FBB, 2191 MachineBasicBlock *CurBB, 2192 MachineBasicBlock *SwitchBB, 2193 BranchProbability TProb, 2194 BranchProbability FProb, 2195 bool InvertCond) { 2196 const BasicBlock *BB = CurBB->getBasicBlock(); 2197 2198 // If the leaf of the tree is a comparison, merge the condition into 2199 // the caseblock. 2200 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2201 // The operands of the cmp have to be in this block. We don't know 2202 // how to export them from some other block. If this is the first block 2203 // of the sequence, no exporting is needed. 2204 if (CurBB == SwitchBB || 2205 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2206 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2207 ISD::CondCode Condition; 2208 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2209 ICmpInst::Predicate Pred = 2210 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2211 Condition = getICmpCondCode(Pred); 2212 } else { 2213 const FCmpInst *FC = cast<FCmpInst>(Cond); 2214 FCmpInst::Predicate Pred = 2215 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2216 Condition = getFCmpCondCode(Pred); 2217 if (TM.Options.NoNaNsFPMath) 2218 Condition = getFCmpCodeWithoutNaN(Condition); 2219 } 2220 2221 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2222 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2223 SL->SwitchCases.push_back(CB); 2224 return; 2225 } 2226 } 2227 2228 // Create a CaseBlock record representing this branch. 2229 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2230 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2231 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2232 SL->SwitchCases.push_back(CB); 2233 } 2234 2235 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2236 MachineBasicBlock *TBB, 2237 MachineBasicBlock *FBB, 2238 MachineBasicBlock *CurBB, 2239 MachineBasicBlock *SwitchBB, 2240 Instruction::BinaryOps Opc, 2241 BranchProbability TProb, 2242 BranchProbability FProb, 2243 bool InvertCond) { 2244 // Skip over not part of the tree and remember to invert op and operands at 2245 // next level. 2246 Value *NotCond; 2247 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2248 InBlock(NotCond, CurBB->getBasicBlock())) { 2249 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2250 !InvertCond); 2251 return; 2252 } 2253 2254 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2255 const Value *BOpOp0, *BOpOp1; 2256 // Compute the effective opcode for Cond, taking into account whether it needs 2257 // to be inverted, e.g. 2258 // and (not (or A, B)), C 2259 // gets lowered as 2260 // and (and (not A, not B), C) 2261 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2262 if (BOp) { 2263 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2264 ? Instruction::And 2265 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2266 ? Instruction::Or 2267 : (Instruction::BinaryOps)0); 2268 if (InvertCond) { 2269 if (BOpc == Instruction::And) 2270 BOpc = Instruction::Or; 2271 else if (BOpc == Instruction::Or) 2272 BOpc = Instruction::And; 2273 } 2274 } 2275 2276 // If this node is not part of the or/and tree, emit it as a branch. 2277 // Note that all nodes in the tree should have same opcode. 2278 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2279 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2280 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2281 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2282 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2283 TProb, FProb, InvertCond); 2284 return; 2285 } 2286 2287 // Create TmpBB after CurBB. 2288 MachineFunction::iterator BBI(CurBB); 2289 MachineFunction &MF = DAG.getMachineFunction(); 2290 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2291 CurBB->getParent()->insert(++BBI, TmpBB); 2292 2293 if (Opc == Instruction::Or) { 2294 // Codegen X | Y as: 2295 // BB1: 2296 // jmp_if_X TBB 2297 // jmp TmpBB 2298 // TmpBB: 2299 // jmp_if_Y TBB 2300 // jmp FBB 2301 // 2302 2303 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2304 // The requirement is that 2305 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2306 // = TrueProb for original BB. 2307 // Assuming the original probabilities are A and B, one choice is to set 2308 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2309 // A/(1+B) and 2B/(1+B). This choice assumes that 2310 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2311 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2312 // TmpBB, but the math is more complicated. 2313 2314 auto NewTrueProb = TProb / 2; 2315 auto NewFalseProb = TProb / 2 + FProb; 2316 // Emit the LHS condition. 2317 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2318 NewFalseProb, InvertCond); 2319 2320 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2321 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2322 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2323 // Emit the RHS condition into TmpBB. 2324 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2325 Probs[1], InvertCond); 2326 } else { 2327 assert(Opc == Instruction::And && "Unknown merge op!"); 2328 // Codegen X & Y as: 2329 // BB1: 2330 // jmp_if_X TmpBB 2331 // jmp FBB 2332 // TmpBB: 2333 // jmp_if_Y TBB 2334 // jmp FBB 2335 // 2336 // This requires creation of TmpBB after CurBB. 2337 2338 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2339 // The requirement is that 2340 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2341 // = FalseProb for original BB. 2342 // Assuming the original probabilities are A and B, one choice is to set 2343 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2344 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2345 // TrueProb for BB1 * FalseProb for TmpBB. 2346 2347 auto NewTrueProb = TProb + FProb / 2; 2348 auto NewFalseProb = FProb / 2; 2349 // Emit the LHS condition. 2350 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2351 NewFalseProb, InvertCond); 2352 2353 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2354 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2355 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2356 // Emit the RHS condition into TmpBB. 2357 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2358 Probs[1], InvertCond); 2359 } 2360 } 2361 2362 /// If the set of cases should be emitted as a series of branches, return true. 2363 /// If we should emit this as a bunch of and/or'd together conditions, return 2364 /// false. 2365 bool 2366 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2367 if (Cases.size() != 2) return true; 2368 2369 // If this is two comparisons of the same values or'd or and'd together, they 2370 // will get folded into a single comparison, so don't emit two blocks. 2371 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2372 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2373 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2374 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2375 return false; 2376 } 2377 2378 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2379 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2380 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2381 Cases[0].CC == Cases[1].CC && 2382 isa<Constant>(Cases[0].CmpRHS) && 2383 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2384 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2385 return false; 2386 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2387 return false; 2388 } 2389 2390 return true; 2391 } 2392 2393 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2394 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2395 2396 // Update machine-CFG edges. 2397 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2398 2399 if (I.isUnconditional()) { 2400 // Update machine-CFG edges. 2401 BrMBB->addSuccessor(Succ0MBB); 2402 2403 // If this is not a fall-through branch or optimizations are switched off, 2404 // emit the branch. 2405 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2406 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2407 MVT::Other, getControlRoot(), 2408 DAG.getBasicBlock(Succ0MBB))); 2409 2410 return; 2411 } 2412 2413 // If this condition is one of the special cases we handle, do special stuff 2414 // now. 2415 const Value *CondVal = I.getCondition(); 2416 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2417 2418 // If this is a series of conditions that are or'd or and'd together, emit 2419 // this as a sequence of branches instead of setcc's with and/or operations. 2420 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2421 // unpredictable branches, and vector extracts because those jumps are likely 2422 // expensive for any target), this should improve performance. 2423 // For example, instead of something like: 2424 // cmp A, B 2425 // C = seteq 2426 // cmp D, E 2427 // F = setle 2428 // or C, F 2429 // jnz foo 2430 // Emit: 2431 // cmp A, B 2432 // je foo 2433 // cmp D, E 2434 // jle foo 2435 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2436 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2437 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2438 Value *Vec; 2439 const Value *BOp0, *BOp1; 2440 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2441 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2442 Opcode = Instruction::And; 2443 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2444 Opcode = Instruction::Or; 2445 2446 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2447 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2448 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2449 getEdgeProbability(BrMBB, Succ0MBB), 2450 getEdgeProbability(BrMBB, Succ1MBB), 2451 /*InvertCond=*/false); 2452 // If the compares in later blocks need to use values not currently 2453 // exported from this block, export them now. This block should always 2454 // be the first entry. 2455 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2456 2457 // Allow some cases to be rejected. 2458 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2459 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2460 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2461 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2462 } 2463 2464 // Emit the branch for this block. 2465 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2466 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2467 return; 2468 } 2469 2470 // Okay, we decided not to do this, remove any inserted MBB's and clear 2471 // SwitchCases. 2472 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2473 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2474 2475 SL->SwitchCases.clear(); 2476 } 2477 } 2478 2479 // Create a CaseBlock record representing this branch. 2480 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2481 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2482 2483 // Use visitSwitchCase to actually insert the fast branch sequence for this 2484 // cond branch. 2485 visitSwitchCase(CB, BrMBB); 2486 } 2487 2488 /// visitSwitchCase - Emits the necessary code to represent a single node in 2489 /// the binary search tree resulting from lowering a switch instruction. 2490 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2491 MachineBasicBlock *SwitchBB) { 2492 SDValue Cond; 2493 SDValue CondLHS = getValue(CB.CmpLHS); 2494 SDLoc dl = CB.DL; 2495 2496 if (CB.CC == ISD::SETTRUE) { 2497 // Branch or fall through to TrueBB. 2498 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2499 SwitchBB->normalizeSuccProbs(); 2500 if (CB.TrueBB != NextBlock(SwitchBB)) { 2501 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2502 DAG.getBasicBlock(CB.TrueBB))); 2503 } 2504 return; 2505 } 2506 2507 auto &TLI = DAG.getTargetLoweringInfo(); 2508 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2509 2510 // Build the setcc now. 2511 if (!CB.CmpMHS) { 2512 // Fold "(X == true)" to X and "(X == false)" to !X to 2513 // handle common cases produced by branch lowering. 2514 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2515 CB.CC == ISD::SETEQ) 2516 Cond = CondLHS; 2517 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2518 CB.CC == ISD::SETEQ) { 2519 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2520 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2521 } else { 2522 SDValue CondRHS = getValue(CB.CmpRHS); 2523 2524 // If a pointer's DAG type is larger than its memory type then the DAG 2525 // values are zero-extended. This breaks signed comparisons so truncate 2526 // back to the underlying type before doing the compare. 2527 if (CondLHS.getValueType() != MemVT) { 2528 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2529 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2530 } 2531 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2532 } 2533 } else { 2534 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2535 2536 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2537 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2538 2539 SDValue CmpOp = getValue(CB.CmpMHS); 2540 EVT VT = CmpOp.getValueType(); 2541 2542 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2543 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2544 ISD::SETLE); 2545 } else { 2546 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2547 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2548 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2549 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2550 } 2551 } 2552 2553 // Update successor info 2554 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2555 // TrueBB and FalseBB are always different unless the incoming IR is 2556 // degenerate. This only happens when running llc on weird IR. 2557 if (CB.TrueBB != CB.FalseBB) 2558 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2559 SwitchBB->normalizeSuccProbs(); 2560 2561 // If the lhs block is the next block, invert the condition so that we can 2562 // fall through to the lhs instead of the rhs block. 2563 if (CB.TrueBB == NextBlock(SwitchBB)) { 2564 std::swap(CB.TrueBB, CB.FalseBB); 2565 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2566 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2567 } 2568 2569 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2570 MVT::Other, getControlRoot(), Cond, 2571 DAG.getBasicBlock(CB.TrueBB)); 2572 2573 setValue(CurInst, BrCond); 2574 2575 // Insert the false branch. Do this even if it's a fall through branch, 2576 // this makes it easier to do DAG optimizations which require inverting 2577 // the branch condition. 2578 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2579 DAG.getBasicBlock(CB.FalseBB)); 2580 2581 DAG.setRoot(BrCond); 2582 } 2583 2584 /// visitJumpTable - Emit JumpTable node in the current MBB 2585 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2586 // Emit the code for the jump table 2587 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2588 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2589 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2590 JT.Reg, PTy); 2591 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2592 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2593 MVT::Other, Index.getValue(1), 2594 Table, Index); 2595 DAG.setRoot(BrJumpTable); 2596 } 2597 2598 /// visitJumpTableHeader - This function emits necessary code to produce index 2599 /// in the JumpTable from switch case. 2600 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2601 JumpTableHeader &JTH, 2602 MachineBasicBlock *SwitchBB) { 2603 SDLoc dl = getCurSDLoc(); 2604 2605 // Subtract the lowest switch case value from the value being switched on. 2606 SDValue SwitchOp = getValue(JTH.SValue); 2607 EVT VT = SwitchOp.getValueType(); 2608 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2609 DAG.getConstant(JTH.First, dl, VT)); 2610 2611 // The SDNode we just created, which holds the value being switched on minus 2612 // the smallest case value, needs to be copied to a virtual register so it 2613 // can be used as an index into the jump table in a subsequent basic block. 2614 // This value may be smaller or larger than the target's pointer type, and 2615 // therefore require extension or truncating. 2616 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2617 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2618 2619 unsigned JumpTableReg = 2620 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2621 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2622 JumpTableReg, SwitchOp); 2623 JT.Reg = JumpTableReg; 2624 2625 if (!JTH.FallthroughUnreachable) { 2626 // Emit the range check for the jump table, and branch to the default block 2627 // for the switch statement if the value being switched on exceeds the 2628 // largest case in the switch. 2629 SDValue CMP = DAG.getSetCC( 2630 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2631 Sub.getValueType()), 2632 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2633 2634 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2635 MVT::Other, CopyTo, CMP, 2636 DAG.getBasicBlock(JT.Default)); 2637 2638 // Avoid emitting unnecessary branches to the next block. 2639 if (JT.MBB != NextBlock(SwitchBB)) 2640 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2641 DAG.getBasicBlock(JT.MBB)); 2642 2643 DAG.setRoot(BrCond); 2644 } else { 2645 // Avoid emitting unnecessary branches to the next block. 2646 if (JT.MBB != NextBlock(SwitchBB)) 2647 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2648 DAG.getBasicBlock(JT.MBB))); 2649 else 2650 DAG.setRoot(CopyTo); 2651 } 2652 } 2653 2654 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2655 /// variable if there exists one. 2656 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2657 SDValue &Chain) { 2658 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2659 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2660 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2661 MachineFunction &MF = DAG.getMachineFunction(); 2662 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2663 MachineSDNode *Node = 2664 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2665 if (Global) { 2666 MachinePointerInfo MPInfo(Global); 2667 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2668 MachineMemOperand::MODereferenceable; 2669 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2670 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2671 DAG.setNodeMemRefs(Node, {MemRef}); 2672 } 2673 if (PtrTy != PtrMemTy) 2674 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2675 return SDValue(Node, 0); 2676 } 2677 2678 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2679 /// tail spliced into a stack protector check success bb. 2680 /// 2681 /// For a high level explanation of how this fits into the stack protector 2682 /// generation see the comment on the declaration of class 2683 /// StackProtectorDescriptor. 2684 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2685 MachineBasicBlock *ParentBB) { 2686 2687 // First create the loads to the guard/stack slot for the comparison. 2688 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2689 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2690 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2691 2692 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2693 int FI = MFI.getStackProtectorIndex(); 2694 2695 SDValue Guard; 2696 SDLoc dl = getCurSDLoc(); 2697 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2698 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2699 Align Align = 2700 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2701 2702 // Generate code to load the content of the guard slot. 2703 SDValue GuardVal = DAG.getLoad( 2704 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2705 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2706 MachineMemOperand::MOVolatile); 2707 2708 if (TLI.useStackGuardXorFP()) 2709 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2710 2711 // Retrieve guard check function, nullptr if instrumentation is inlined. 2712 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2713 // The target provides a guard check function to validate the guard value. 2714 // Generate a call to that function with the content of the guard slot as 2715 // argument. 2716 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2717 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2718 2719 TargetLowering::ArgListTy Args; 2720 TargetLowering::ArgListEntry Entry; 2721 Entry.Node = GuardVal; 2722 Entry.Ty = FnTy->getParamType(0); 2723 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2724 Entry.IsInReg = true; 2725 Args.push_back(Entry); 2726 2727 TargetLowering::CallLoweringInfo CLI(DAG); 2728 CLI.setDebugLoc(getCurSDLoc()) 2729 .setChain(DAG.getEntryNode()) 2730 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2731 getValue(GuardCheckFn), std::move(Args)); 2732 2733 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2734 DAG.setRoot(Result.second); 2735 return; 2736 } 2737 2738 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2739 // Otherwise, emit a volatile load to retrieve the stack guard value. 2740 SDValue Chain = DAG.getEntryNode(); 2741 if (TLI.useLoadStackGuardNode()) { 2742 Guard = getLoadStackGuard(DAG, dl, Chain); 2743 } else { 2744 const Value *IRGuard = TLI.getSDagStackGuard(M); 2745 SDValue GuardPtr = getValue(IRGuard); 2746 2747 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2748 MachinePointerInfo(IRGuard, 0), Align, 2749 MachineMemOperand::MOVolatile); 2750 } 2751 2752 // Perform the comparison via a getsetcc. 2753 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2754 *DAG.getContext(), 2755 Guard.getValueType()), 2756 Guard, GuardVal, ISD::SETNE); 2757 2758 // If the guard/stackslot do not equal, branch to failure MBB. 2759 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2760 MVT::Other, GuardVal.getOperand(0), 2761 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2762 // Otherwise branch to success MBB. 2763 SDValue Br = DAG.getNode(ISD::BR, dl, 2764 MVT::Other, BrCond, 2765 DAG.getBasicBlock(SPD.getSuccessMBB())); 2766 2767 DAG.setRoot(Br); 2768 } 2769 2770 /// Codegen the failure basic block for a stack protector check. 2771 /// 2772 /// A failure stack protector machine basic block consists simply of a call to 2773 /// __stack_chk_fail(). 2774 /// 2775 /// For a high level explanation of how this fits into the stack protector 2776 /// generation see the comment on the declaration of class 2777 /// StackProtectorDescriptor. 2778 void 2779 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2780 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2781 TargetLowering::MakeLibCallOptions CallOptions; 2782 CallOptions.setDiscardResult(true); 2783 SDValue Chain = 2784 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2785 None, CallOptions, getCurSDLoc()).second; 2786 // On PS4/PS5, the "return address" must still be within the calling 2787 // function, even if it's at the very end, so emit an explicit TRAP here. 2788 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2789 if (TM.getTargetTriple().isPS()) 2790 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2791 // WebAssembly needs an unreachable instruction after a non-returning call, 2792 // because the function return type can be different from __stack_chk_fail's 2793 // return type (void). 2794 if (TM.getTargetTriple().isWasm()) 2795 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2796 2797 DAG.setRoot(Chain); 2798 } 2799 2800 /// visitBitTestHeader - This function emits necessary code to produce value 2801 /// suitable for "bit tests" 2802 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2803 MachineBasicBlock *SwitchBB) { 2804 SDLoc dl = getCurSDLoc(); 2805 2806 // Subtract the minimum value. 2807 SDValue SwitchOp = getValue(B.SValue); 2808 EVT VT = SwitchOp.getValueType(); 2809 SDValue RangeSub = 2810 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2811 2812 // Determine the type of the test operands. 2813 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2814 bool UsePtrType = false; 2815 if (!TLI.isTypeLegal(VT)) { 2816 UsePtrType = true; 2817 } else { 2818 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2819 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2820 // Switch table case range are encoded into series of masks. 2821 // Just use pointer type, it's guaranteed to fit. 2822 UsePtrType = true; 2823 break; 2824 } 2825 } 2826 SDValue Sub = RangeSub; 2827 if (UsePtrType) { 2828 VT = TLI.getPointerTy(DAG.getDataLayout()); 2829 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2830 } 2831 2832 B.RegVT = VT.getSimpleVT(); 2833 B.Reg = FuncInfo.CreateReg(B.RegVT); 2834 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2835 2836 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2837 2838 if (!B.FallthroughUnreachable) 2839 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2840 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2841 SwitchBB->normalizeSuccProbs(); 2842 2843 SDValue Root = CopyTo; 2844 if (!B.FallthroughUnreachable) { 2845 // Conditional branch to the default block. 2846 SDValue RangeCmp = DAG.getSetCC(dl, 2847 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2848 RangeSub.getValueType()), 2849 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2850 ISD::SETUGT); 2851 2852 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2853 DAG.getBasicBlock(B.Default)); 2854 } 2855 2856 // Avoid emitting unnecessary branches to the next block. 2857 if (MBB != NextBlock(SwitchBB)) 2858 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2859 2860 DAG.setRoot(Root); 2861 } 2862 2863 /// visitBitTestCase - this function produces one "bit test" 2864 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2865 MachineBasicBlock* NextMBB, 2866 BranchProbability BranchProbToNext, 2867 unsigned Reg, 2868 BitTestCase &B, 2869 MachineBasicBlock *SwitchBB) { 2870 SDLoc dl = getCurSDLoc(); 2871 MVT VT = BB.RegVT; 2872 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2873 SDValue Cmp; 2874 unsigned PopCount = countPopulation(B.Mask); 2875 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2876 if (PopCount == 1) { 2877 // Testing for a single bit; just compare the shift count with what it 2878 // would need to be to shift a 1 bit in that position. 2879 Cmp = DAG.getSetCC( 2880 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2881 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2882 ISD::SETEQ); 2883 } else if (PopCount == BB.Range) { 2884 // There is only one zero bit in the range, test for it directly. 2885 Cmp = DAG.getSetCC( 2886 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2887 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2888 ISD::SETNE); 2889 } else { 2890 // Make desired shift 2891 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2892 DAG.getConstant(1, dl, VT), ShiftOp); 2893 2894 // Emit bit tests and jumps 2895 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2896 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2897 Cmp = DAG.getSetCC( 2898 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2899 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2900 } 2901 2902 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2903 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2904 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2905 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2906 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2907 // one as they are relative probabilities (and thus work more like weights), 2908 // and hence we need to normalize them to let the sum of them become one. 2909 SwitchBB->normalizeSuccProbs(); 2910 2911 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2912 MVT::Other, getControlRoot(), 2913 Cmp, DAG.getBasicBlock(B.TargetBB)); 2914 2915 // Avoid emitting unnecessary branches to the next block. 2916 if (NextMBB != NextBlock(SwitchBB)) 2917 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2918 DAG.getBasicBlock(NextMBB)); 2919 2920 DAG.setRoot(BrAnd); 2921 } 2922 2923 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2924 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2925 2926 // Retrieve successors. Look through artificial IR level blocks like 2927 // catchswitch for successors. 2928 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2929 const BasicBlock *EHPadBB = I.getSuccessor(1); 2930 2931 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2932 // have to do anything here to lower funclet bundles. 2933 assert(!I.hasOperandBundlesOtherThan( 2934 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2935 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2936 LLVMContext::OB_cfguardtarget, 2937 LLVMContext::OB_clang_arc_attachedcall}) && 2938 "Cannot lower invokes with arbitrary operand bundles yet!"); 2939 2940 const Value *Callee(I.getCalledOperand()); 2941 const Function *Fn = dyn_cast<Function>(Callee); 2942 if (isa<InlineAsm>(Callee)) 2943 visitInlineAsm(I, EHPadBB); 2944 else if (Fn && Fn->isIntrinsic()) { 2945 switch (Fn->getIntrinsicID()) { 2946 default: 2947 llvm_unreachable("Cannot invoke this intrinsic"); 2948 case Intrinsic::donothing: 2949 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2950 case Intrinsic::seh_try_begin: 2951 case Intrinsic::seh_scope_begin: 2952 case Intrinsic::seh_try_end: 2953 case Intrinsic::seh_scope_end: 2954 break; 2955 case Intrinsic::experimental_patchpoint_void: 2956 case Intrinsic::experimental_patchpoint_i64: 2957 visitPatchpoint(I, EHPadBB); 2958 break; 2959 case Intrinsic::experimental_gc_statepoint: 2960 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2961 break; 2962 case Intrinsic::wasm_rethrow: { 2963 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2964 // special because it can be invoked, so we manually lower it to a DAG 2965 // node here. 2966 SmallVector<SDValue, 8> Ops; 2967 Ops.push_back(getRoot()); // inchain 2968 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2969 Ops.push_back( 2970 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2971 TLI.getPointerTy(DAG.getDataLayout()))); 2972 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2973 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2974 break; 2975 } 2976 } 2977 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2978 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2979 // Eventually we will support lowering the @llvm.experimental.deoptimize 2980 // intrinsic, and right now there are no plans to support other intrinsics 2981 // with deopt state. 2982 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2983 } else { 2984 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 2985 } 2986 2987 // If the value of the invoke is used outside of its defining block, make it 2988 // available as a virtual register. 2989 // We already took care of the exported value for the statepoint instruction 2990 // during call to the LowerStatepoint. 2991 if (!isa<GCStatepointInst>(I)) { 2992 CopyToExportRegsIfNeeded(&I); 2993 } 2994 2995 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2996 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2997 BranchProbability EHPadBBProb = 2998 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2999 : BranchProbability::getZero(); 3000 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3001 3002 // Update successor info. 3003 addSuccessorWithProb(InvokeMBB, Return); 3004 for (auto &UnwindDest : UnwindDests) { 3005 UnwindDest.first->setIsEHPad(); 3006 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3007 } 3008 InvokeMBB->normalizeSuccProbs(); 3009 3010 // Drop into normal successor. 3011 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3012 DAG.getBasicBlock(Return))); 3013 } 3014 3015 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3016 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3017 3018 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3019 // have to do anything here to lower funclet bundles. 3020 assert(!I.hasOperandBundlesOtherThan( 3021 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3022 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3023 3024 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3025 visitInlineAsm(I); 3026 CopyToExportRegsIfNeeded(&I); 3027 3028 // Retrieve successors. 3029 SmallPtrSet<BasicBlock *, 8> Dests; 3030 Dests.insert(I.getDefaultDest()); 3031 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3032 3033 // Update successor info. 3034 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3035 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3036 BasicBlock *Dest = I.getIndirectDest(i); 3037 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3038 Target->setIsInlineAsmBrIndirectTarget(); 3039 Target->setMachineBlockAddressTaken(); 3040 Target->setLabelMustBeEmitted(); 3041 // Don't add duplicate machine successors. 3042 if (Dests.insert(Dest).second) 3043 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3044 } 3045 CallBrMBB->normalizeSuccProbs(); 3046 3047 // Drop into default successor. 3048 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3049 MVT::Other, getControlRoot(), 3050 DAG.getBasicBlock(Return))); 3051 } 3052 3053 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3054 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3055 } 3056 3057 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3058 assert(FuncInfo.MBB->isEHPad() && 3059 "Call to landingpad not in landing pad!"); 3060 3061 // If there aren't registers to copy the values into (e.g., during SjLj 3062 // exceptions), then don't bother to create these DAG nodes. 3063 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3064 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3065 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3066 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3067 return; 3068 3069 // If landingpad's return type is token type, we don't create DAG nodes 3070 // for its exception pointer and selector value. The extraction of exception 3071 // pointer or selector value from token type landingpads is not currently 3072 // supported. 3073 if (LP.getType()->isTokenTy()) 3074 return; 3075 3076 SmallVector<EVT, 2> ValueVTs; 3077 SDLoc dl = getCurSDLoc(); 3078 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3079 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3080 3081 // Get the two live-in registers as SDValues. The physregs have already been 3082 // copied into virtual registers. 3083 SDValue Ops[2]; 3084 if (FuncInfo.ExceptionPointerVirtReg) { 3085 Ops[0] = DAG.getZExtOrTrunc( 3086 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3087 FuncInfo.ExceptionPointerVirtReg, 3088 TLI.getPointerTy(DAG.getDataLayout())), 3089 dl, ValueVTs[0]); 3090 } else { 3091 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3092 } 3093 Ops[1] = DAG.getZExtOrTrunc( 3094 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3095 FuncInfo.ExceptionSelectorVirtReg, 3096 TLI.getPointerTy(DAG.getDataLayout())), 3097 dl, ValueVTs[1]); 3098 3099 // Merge into one. 3100 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3101 DAG.getVTList(ValueVTs), Ops); 3102 setValue(&LP, Res); 3103 } 3104 3105 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3106 MachineBasicBlock *Last) { 3107 // Update JTCases. 3108 for (JumpTableBlock &JTB : SL->JTCases) 3109 if (JTB.first.HeaderBB == First) 3110 JTB.first.HeaderBB = Last; 3111 3112 // Update BitTestCases. 3113 for (BitTestBlock &BTB : SL->BitTestCases) 3114 if (BTB.Parent == First) 3115 BTB.Parent = Last; 3116 } 3117 3118 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3119 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3120 3121 // Update machine-CFG edges with unique successors. 3122 SmallSet<BasicBlock*, 32> Done; 3123 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3124 BasicBlock *BB = I.getSuccessor(i); 3125 bool Inserted = Done.insert(BB).second; 3126 if (!Inserted) 3127 continue; 3128 3129 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3130 addSuccessorWithProb(IndirectBrMBB, Succ); 3131 } 3132 IndirectBrMBB->normalizeSuccProbs(); 3133 3134 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3135 MVT::Other, getControlRoot(), 3136 getValue(I.getAddress()))); 3137 } 3138 3139 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3140 if (!DAG.getTarget().Options.TrapUnreachable) 3141 return; 3142 3143 // We may be able to ignore unreachable behind a noreturn call. 3144 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3145 const BasicBlock &BB = *I.getParent(); 3146 if (&I != &BB.front()) { 3147 BasicBlock::const_iterator PredI = 3148 std::prev(BasicBlock::const_iterator(&I)); 3149 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3150 if (Call->doesNotReturn()) 3151 return; 3152 } 3153 } 3154 } 3155 3156 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3157 } 3158 3159 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3160 SDNodeFlags Flags; 3161 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3162 Flags.copyFMF(*FPOp); 3163 3164 SDValue Op = getValue(I.getOperand(0)); 3165 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3166 Op, Flags); 3167 setValue(&I, UnNodeValue); 3168 } 3169 3170 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3171 SDNodeFlags Flags; 3172 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3173 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3174 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3175 } 3176 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3177 Flags.setExact(ExactOp->isExact()); 3178 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3179 Flags.copyFMF(*FPOp); 3180 3181 SDValue Op1 = getValue(I.getOperand(0)); 3182 SDValue Op2 = getValue(I.getOperand(1)); 3183 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3184 Op1, Op2, Flags); 3185 setValue(&I, BinNodeValue); 3186 } 3187 3188 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3189 SDValue Op1 = getValue(I.getOperand(0)); 3190 SDValue Op2 = getValue(I.getOperand(1)); 3191 3192 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3193 Op1.getValueType(), DAG.getDataLayout()); 3194 3195 // Coerce the shift amount to the right type if we can. This exposes the 3196 // truncate or zext to optimization early. 3197 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3198 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3199 "Unexpected shift type"); 3200 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3201 } 3202 3203 bool nuw = false; 3204 bool nsw = false; 3205 bool exact = false; 3206 3207 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3208 3209 if (const OverflowingBinaryOperator *OFBinOp = 3210 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3211 nuw = OFBinOp->hasNoUnsignedWrap(); 3212 nsw = OFBinOp->hasNoSignedWrap(); 3213 } 3214 if (const PossiblyExactOperator *ExactOp = 3215 dyn_cast<const PossiblyExactOperator>(&I)) 3216 exact = ExactOp->isExact(); 3217 } 3218 SDNodeFlags Flags; 3219 Flags.setExact(exact); 3220 Flags.setNoSignedWrap(nsw); 3221 Flags.setNoUnsignedWrap(nuw); 3222 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3223 Flags); 3224 setValue(&I, Res); 3225 } 3226 3227 void SelectionDAGBuilder::visitSDiv(const User &I) { 3228 SDValue Op1 = getValue(I.getOperand(0)); 3229 SDValue Op2 = getValue(I.getOperand(1)); 3230 3231 SDNodeFlags Flags; 3232 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3233 cast<PossiblyExactOperator>(&I)->isExact()); 3234 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3235 Op2, Flags)); 3236 } 3237 3238 void SelectionDAGBuilder::visitICmp(const User &I) { 3239 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3240 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3241 predicate = IC->getPredicate(); 3242 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3243 predicate = ICmpInst::Predicate(IC->getPredicate()); 3244 SDValue Op1 = getValue(I.getOperand(0)); 3245 SDValue Op2 = getValue(I.getOperand(1)); 3246 ISD::CondCode Opcode = getICmpCondCode(predicate); 3247 3248 auto &TLI = DAG.getTargetLoweringInfo(); 3249 EVT MemVT = 3250 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3251 3252 // If a pointer's DAG type is larger than its memory type then the DAG values 3253 // are zero-extended. This breaks signed comparisons so truncate back to the 3254 // underlying type before doing the compare. 3255 if (Op1.getValueType() != MemVT) { 3256 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3257 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3258 } 3259 3260 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3261 I.getType()); 3262 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3263 } 3264 3265 void SelectionDAGBuilder::visitFCmp(const User &I) { 3266 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3267 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3268 predicate = FC->getPredicate(); 3269 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3270 predicate = FCmpInst::Predicate(FC->getPredicate()); 3271 SDValue Op1 = getValue(I.getOperand(0)); 3272 SDValue Op2 = getValue(I.getOperand(1)); 3273 3274 ISD::CondCode Condition = getFCmpCondCode(predicate); 3275 auto *FPMO = cast<FPMathOperator>(&I); 3276 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3277 Condition = getFCmpCodeWithoutNaN(Condition); 3278 3279 SDNodeFlags Flags; 3280 Flags.copyFMF(*FPMO); 3281 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3282 3283 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3284 I.getType()); 3285 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3286 } 3287 3288 // Check if the condition of the select has one use or two users that are both 3289 // selects with the same condition. 3290 static bool hasOnlySelectUsers(const Value *Cond) { 3291 return llvm::all_of(Cond->users(), [](const Value *V) { 3292 return isa<SelectInst>(V); 3293 }); 3294 } 3295 3296 void SelectionDAGBuilder::visitSelect(const User &I) { 3297 SmallVector<EVT, 4> ValueVTs; 3298 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3299 ValueVTs); 3300 unsigned NumValues = ValueVTs.size(); 3301 if (NumValues == 0) return; 3302 3303 SmallVector<SDValue, 4> Values(NumValues); 3304 SDValue Cond = getValue(I.getOperand(0)); 3305 SDValue LHSVal = getValue(I.getOperand(1)); 3306 SDValue RHSVal = getValue(I.getOperand(2)); 3307 SmallVector<SDValue, 1> BaseOps(1, Cond); 3308 ISD::NodeType OpCode = 3309 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3310 3311 bool IsUnaryAbs = false; 3312 bool Negate = false; 3313 3314 SDNodeFlags Flags; 3315 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3316 Flags.copyFMF(*FPOp); 3317 3318 // Min/max matching is only viable if all output VTs are the same. 3319 if (all_equal(ValueVTs)) { 3320 EVT VT = ValueVTs[0]; 3321 LLVMContext &Ctx = *DAG.getContext(); 3322 auto &TLI = DAG.getTargetLoweringInfo(); 3323 3324 // We care about the legality of the operation after it has been type 3325 // legalized. 3326 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3327 VT = TLI.getTypeToTransformTo(Ctx, VT); 3328 3329 // If the vselect is legal, assume we want to leave this as a vector setcc + 3330 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3331 // min/max is legal on the scalar type. 3332 bool UseScalarMinMax = VT.isVector() && 3333 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3334 3335 Value *LHS, *RHS; 3336 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3337 ISD::NodeType Opc = ISD::DELETED_NODE; 3338 switch (SPR.Flavor) { 3339 case SPF_UMAX: Opc = ISD::UMAX; break; 3340 case SPF_UMIN: Opc = ISD::UMIN; break; 3341 case SPF_SMAX: Opc = ISD::SMAX; break; 3342 case SPF_SMIN: Opc = ISD::SMIN; break; 3343 case SPF_FMINNUM: 3344 switch (SPR.NaNBehavior) { 3345 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3346 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3347 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3348 case SPNB_RETURNS_ANY: { 3349 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3350 Opc = ISD::FMINNUM; 3351 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3352 Opc = ISD::FMINIMUM; 3353 else if (UseScalarMinMax) 3354 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3355 ISD::FMINNUM : ISD::FMINIMUM; 3356 break; 3357 } 3358 } 3359 break; 3360 case SPF_FMAXNUM: 3361 switch (SPR.NaNBehavior) { 3362 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3363 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3364 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3365 case SPNB_RETURNS_ANY: 3366 3367 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3368 Opc = ISD::FMAXNUM; 3369 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3370 Opc = ISD::FMAXIMUM; 3371 else if (UseScalarMinMax) 3372 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3373 ISD::FMAXNUM : ISD::FMAXIMUM; 3374 break; 3375 } 3376 break; 3377 case SPF_NABS: 3378 Negate = true; 3379 [[fallthrough]]; 3380 case SPF_ABS: 3381 IsUnaryAbs = true; 3382 Opc = ISD::ABS; 3383 break; 3384 default: break; 3385 } 3386 3387 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3388 (TLI.isOperationLegalOrCustom(Opc, VT) || 3389 (UseScalarMinMax && 3390 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3391 // If the underlying comparison instruction is used by any other 3392 // instruction, the consumed instructions won't be destroyed, so it is 3393 // not profitable to convert to a min/max. 3394 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3395 OpCode = Opc; 3396 LHSVal = getValue(LHS); 3397 RHSVal = getValue(RHS); 3398 BaseOps.clear(); 3399 } 3400 3401 if (IsUnaryAbs) { 3402 OpCode = Opc; 3403 LHSVal = getValue(LHS); 3404 BaseOps.clear(); 3405 } 3406 } 3407 3408 if (IsUnaryAbs) { 3409 for (unsigned i = 0; i != NumValues; ++i) { 3410 SDLoc dl = getCurSDLoc(); 3411 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3412 Values[i] = 3413 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3414 if (Negate) 3415 Values[i] = DAG.getNegative(Values[i], dl, VT); 3416 } 3417 } else { 3418 for (unsigned i = 0; i != NumValues; ++i) { 3419 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3420 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3421 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3422 Values[i] = DAG.getNode( 3423 OpCode, getCurSDLoc(), 3424 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3425 } 3426 } 3427 3428 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3429 DAG.getVTList(ValueVTs), Values)); 3430 } 3431 3432 void SelectionDAGBuilder::visitTrunc(const User &I) { 3433 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3434 SDValue N = getValue(I.getOperand(0)); 3435 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3436 I.getType()); 3437 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3438 } 3439 3440 void SelectionDAGBuilder::visitZExt(const User &I) { 3441 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3442 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3443 SDValue N = getValue(I.getOperand(0)); 3444 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3445 I.getType()); 3446 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3447 } 3448 3449 void SelectionDAGBuilder::visitSExt(const User &I) { 3450 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3451 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3452 SDValue N = getValue(I.getOperand(0)); 3453 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3454 I.getType()); 3455 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3456 } 3457 3458 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3459 // FPTrunc is never a no-op cast, no need to check 3460 SDValue N = getValue(I.getOperand(0)); 3461 SDLoc dl = getCurSDLoc(); 3462 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3463 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3464 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3465 DAG.getTargetConstant( 3466 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3467 } 3468 3469 void SelectionDAGBuilder::visitFPExt(const User &I) { 3470 // FPExt is never a no-op cast, no need to check 3471 SDValue N = getValue(I.getOperand(0)); 3472 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3473 I.getType()); 3474 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3475 } 3476 3477 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3478 // FPToUI is never a no-op cast, no need to check 3479 SDValue N = getValue(I.getOperand(0)); 3480 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3481 I.getType()); 3482 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3483 } 3484 3485 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3486 // FPToSI is never a no-op cast, no need to check 3487 SDValue N = getValue(I.getOperand(0)); 3488 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3489 I.getType()); 3490 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3491 } 3492 3493 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3494 // UIToFP is never a no-op cast, no need to check 3495 SDValue N = getValue(I.getOperand(0)); 3496 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3497 I.getType()); 3498 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3499 } 3500 3501 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3502 // SIToFP is never a no-op cast, no need to check 3503 SDValue N = getValue(I.getOperand(0)); 3504 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3505 I.getType()); 3506 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3507 } 3508 3509 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3510 // What to do depends on the size of the integer and the size of the pointer. 3511 // We can either truncate, zero extend, or no-op, accordingly. 3512 SDValue N = getValue(I.getOperand(0)); 3513 auto &TLI = DAG.getTargetLoweringInfo(); 3514 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3515 I.getType()); 3516 EVT PtrMemVT = 3517 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3518 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3519 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3520 setValue(&I, N); 3521 } 3522 3523 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3524 // What to do depends on the size of the integer and the size of the pointer. 3525 // We can either truncate, zero extend, or no-op, accordingly. 3526 SDValue N = getValue(I.getOperand(0)); 3527 auto &TLI = DAG.getTargetLoweringInfo(); 3528 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3529 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3530 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3531 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3532 setValue(&I, N); 3533 } 3534 3535 void SelectionDAGBuilder::visitBitCast(const User &I) { 3536 SDValue N = getValue(I.getOperand(0)); 3537 SDLoc dl = getCurSDLoc(); 3538 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3539 I.getType()); 3540 3541 // BitCast assures us that source and destination are the same size so this is 3542 // either a BITCAST or a no-op. 3543 if (DestVT != N.getValueType()) 3544 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3545 DestVT, N)); // convert types. 3546 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3547 // might fold any kind of constant expression to an integer constant and that 3548 // is not what we are looking for. Only recognize a bitcast of a genuine 3549 // constant integer as an opaque constant. 3550 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3551 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3552 /*isOpaque*/true)); 3553 else 3554 setValue(&I, N); // noop cast. 3555 } 3556 3557 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3558 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3559 const Value *SV = I.getOperand(0); 3560 SDValue N = getValue(SV); 3561 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3562 3563 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3564 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3565 3566 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3567 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3568 3569 setValue(&I, N); 3570 } 3571 3572 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3573 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3574 SDValue InVec = getValue(I.getOperand(0)); 3575 SDValue InVal = getValue(I.getOperand(1)); 3576 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3577 TLI.getVectorIdxTy(DAG.getDataLayout())); 3578 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3579 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3580 InVec, InVal, InIdx)); 3581 } 3582 3583 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3584 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3585 SDValue InVec = getValue(I.getOperand(0)); 3586 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3587 TLI.getVectorIdxTy(DAG.getDataLayout())); 3588 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3589 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3590 InVec, InIdx)); 3591 } 3592 3593 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3594 SDValue Src1 = getValue(I.getOperand(0)); 3595 SDValue Src2 = getValue(I.getOperand(1)); 3596 ArrayRef<int> Mask; 3597 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3598 Mask = SVI->getShuffleMask(); 3599 else 3600 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3601 SDLoc DL = getCurSDLoc(); 3602 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3603 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3604 EVT SrcVT = Src1.getValueType(); 3605 3606 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3607 VT.isScalableVector()) { 3608 // Canonical splat form of first element of first input vector. 3609 SDValue FirstElt = 3610 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3611 DAG.getVectorIdxConstant(0, DL)); 3612 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3613 return; 3614 } 3615 3616 // For now, we only handle splats for scalable vectors. 3617 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3618 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3619 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3620 3621 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3622 unsigned MaskNumElts = Mask.size(); 3623 3624 if (SrcNumElts == MaskNumElts) { 3625 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3626 return; 3627 } 3628 3629 // Normalize the shuffle vector since mask and vector length don't match. 3630 if (SrcNumElts < MaskNumElts) { 3631 // Mask is longer than the source vectors. We can use concatenate vector to 3632 // make the mask and vectors lengths match. 3633 3634 if (MaskNumElts % SrcNumElts == 0) { 3635 // Mask length is a multiple of the source vector length. 3636 // Check if the shuffle is some kind of concatenation of the input 3637 // vectors. 3638 unsigned NumConcat = MaskNumElts / SrcNumElts; 3639 bool IsConcat = true; 3640 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3641 for (unsigned i = 0; i != MaskNumElts; ++i) { 3642 int Idx = Mask[i]; 3643 if (Idx < 0) 3644 continue; 3645 // Ensure the indices in each SrcVT sized piece are sequential and that 3646 // the same source is used for the whole piece. 3647 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3648 (ConcatSrcs[i / SrcNumElts] >= 0 && 3649 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3650 IsConcat = false; 3651 break; 3652 } 3653 // Remember which source this index came from. 3654 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3655 } 3656 3657 // The shuffle is concatenating multiple vectors together. Just emit 3658 // a CONCAT_VECTORS operation. 3659 if (IsConcat) { 3660 SmallVector<SDValue, 8> ConcatOps; 3661 for (auto Src : ConcatSrcs) { 3662 if (Src < 0) 3663 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3664 else if (Src == 0) 3665 ConcatOps.push_back(Src1); 3666 else 3667 ConcatOps.push_back(Src2); 3668 } 3669 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3670 return; 3671 } 3672 } 3673 3674 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3675 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3676 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3677 PaddedMaskNumElts); 3678 3679 // Pad both vectors with undefs to make them the same length as the mask. 3680 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3681 3682 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3683 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3684 MOps1[0] = Src1; 3685 MOps2[0] = Src2; 3686 3687 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3688 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3689 3690 // Readjust mask for new input vector length. 3691 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3692 for (unsigned i = 0; i != MaskNumElts; ++i) { 3693 int Idx = Mask[i]; 3694 if (Idx >= (int)SrcNumElts) 3695 Idx -= SrcNumElts - PaddedMaskNumElts; 3696 MappedOps[i] = Idx; 3697 } 3698 3699 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3700 3701 // If the concatenated vector was padded, extract a subvector with the 3702 // correct number of elements. 3703 if (MaskNumElts != PaddedMaskNumElts) 3704 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3705 DAG.getVectorIdxConstant(0, DL)); 3706 3707 setValue(&I, Result); 3708 return; 3709 } 3710 3711 if (SrcNumElts > MaskNumElts) { 3712 // Analyze the access pattern of the vector to see if we can extract 3713 // two subvectors and do the shuffle. 3714 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3715 bool CanExtract = true; 3716 for (int Idx : Mask) { 3717 unsigned Input = 0; 3718 if (Idx < 0) 3719 continue; 3720 3721 if (Idx >= (int)SrcNumElts) { 3722 Input = 1; 3723 Idx -= SrcNumElts; 3724 } 3725 3726 // If all the indices come from the same MaskNumElts sized portion of 3727 // the sources we can use extract. Also make sure the extract wouldn't 3728 // extract past the end of the source. 3729 int NewStartIdx = alignDown(Idx, MaskNumElts); 3730 if (NewStartIdx + MaskNumElts > SrcNumElts || 3731 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3732 CanExtract = false; 3733 // Make sure we always update StartIdx as we use it to track if all 3734 // elements are undef. 3735 StartIdx[Input] = NewStartIdx; 3736 } 3737 3738 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3739 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3740 return; 3741 } 3742 if (CanExtract) { 3743 // Extract appropriate subvector and generate a vector shuffle 3744 for (unsigned Input = 0; Input < 2; ++Input) { 3745 SDValue &Src = Input == 0 ? Src1 : Src2; 3746 if (StartIdx[Input] < 0) 3747 Src = DAG.getUNDEF(VT); 3748 else { 3749 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3750 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3751 } 3752 } 3753 3754 // Calculate new mask. 3755 SmallVector<int, 8> MappedOps(Mask); 3756 for (int &Idx : MappedOps) { 3757 if (Idx >= (int)SrcNumElts) 3758 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3759 else if (Idx >= 0) 3760 Idx -= StartIdx[0]; 3761 } 3762 3763 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3764 return; 3765 } 3766 } 3767 3768 // We can't use either concat vectors or extract subvectors so fall back to 3769 // replacing the shuffle with extract and build vector. 3770 // to insert and build vector. 3771 EVT EltVT = VT.getVectorElementType(); 3772 SmallVector<SDValue,8> Ops; 3773 for (int Idx : Mask) { 3774 SDValue Res; 3775 3776 if (Idx < 0) { 3777 Res = DAG.getUNDEF(EltVT); 3778 } else { 3779 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3780 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3781 3782 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3783 DAG.getVectorIdxConstant(Idx, DL)); 3784 } 3785 3786 Ops.push_back(Res); 3787 } 3788 3789 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3790 } 3791 3792 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3793 ArrayRef<unsigned> Indices = I.getIndices(); 3794 const Value *Op0 = I.getOperand(0); 3795 const Value *Op1 = I.getOperand(1); 3796 Type *AggTy = I.getType(); 3797 Type *ValTy = Op1->getType(); 3798 bool IntoUndef = isa<UndefValue>(Op0); 3799 bool FromUndef = isa<UndefValue>(Op1); 3800 3801 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3802 3803 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3804 SmallVector<EVT, 4> AggValueVTs; 3805 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3806 SmallVector<EVT, 4> ValValueVTs; 3807 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3808 3809 unsigned NumAggValues = AggValueVTs.size(); 3810 unsigned NumValValues = ValValueVTs.size(); 3811 SmallVector<SDValue, 4> Values(NumAggValues); 3812 3813 // Ignore an insertvalue that produces an empty object 3814 if (!NumAggValues) { 3815 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3816 return; 3817 } 3818 3819 SDValue Agg = getValue(Op0); 3820 unsigned i = 0; 3821 // Copy the beginning value(s) from the original aggregate. 3822 for (; i != LinearIndex; ++i) 3823 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3824 SDValue(Agg.getNode(), Agg.getResNo() + i); 3825 // Copy values from the inserted value(s). 3826 if (NumValValues) { 3827 SDValue Val = getValue(Op1); 3828 for (; i != LinearIndex + NumValValues; ++i) 3829 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3830 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3831 } 3832 // Copy remaining value(s) from the original aggregate. 3833 for (; i != NumAggValues; ++i) 3834 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3835 SDValue(Agg.getNode(), Agg.getResNo() + i); 3836 3837 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3838 DAG.getVTList(AggValueVTs), Values)); 3839 } 3840 3841 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3842 ArrayRef<unsigned> Indices = I.getIndices(); 3843 const Value *Op0 = I.getOperand(0); 3844 Type *AggTy = Op0->getType(); 3845 Type *ValTy = I.getType(); 3846 bool OutOfUndef = isa<UndefValue>(Op0); 3847 3848 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3849 3850 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3851 SmallVector<EVT, 4> ValValueVTs; 3852 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3853 3854 unsigned NumValValues = ValValueVTs.size(); 3855 3856 // Ignore a extractvalue that produces an empty object 3857 if (!NumValValues) { 3858 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3859 return; 3860 } 3861 3862 SmallVector<SDValue, 4> Values(NumValValues); 3863 3864 SDValue Agg = getValue(Op0); 3865 // Copy out the selected value(s). 3866 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3867 Values[i - LinearIndex] = 3868 OutOfUndef ? 3869 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3870 SDValue(Agg.getNode(), Agg.getResNo() + i); 3871 3872 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3873 DAG.getVTList(ValValueVTs), Values)); 3874 } 3875 3876 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3877 Value *Op0 = I.getOperand(0); 3878 // Note that the pointer operand may be a vector of pointers. Take the scalar 3879 // element which holds a pointer. 3880 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3881 SDValue N = getValue(Op0); 3882 SDLoc dl = getCurSDLoc(); 3883 auto &TLI = DAG.getTargetLoweringInfo(); 3884 3885 // Normalize Vector GEP - all scalar operands should be converted to the 3886 // splat vector. 3887 bool IsVectorGEP = I.getType()->isVectorTy(); 3888 ElementCount VectorElementCount = 3889 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3890 : ElementCount::getFixed(0); 3891 3892 if (IsVectorGEP && !N.getValueType().isVector()) { 3893 LLVMContext &Context = *DAG.getContext(); 3894 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3895 N = DAG.getSplat(VT, dl, N); 3896 } 3897 3898 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3899 GTI != E; ++GTI) { 3900 const Value *Idx = GTI.getOperand(); 3901 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3902 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3903 if (Field) { 3904 // N = N + Offset 3905 uint64_t Offset = 3906 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3907 3908 // In an inbounds GEP with an offset that is nonnegative even when 3909 // interpreted as signed, assume there is no unsigned overflow. 3910 SDNodeFlags Flags; 3911 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3912 Flags.setNoUnsignedWrap(true); 3913 3914 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3915 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3916 } 3917 } else { 3918 // IdxSize is the width of the arithmetic according to IR semantics. 3919 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3920 // (and fix up the result later). 3921 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3922 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3923 TypeSize ElementSize = 3924 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3925 // We intentionally mask away the high bits here; ElementSize may not 3926 // fit in IdxTy. 3927 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3928 bool ElementScalable = ElementSize.isScalable(); 3929 3930 // If this is a scalar constant or a splat vector of constants, 3931 // handle it quickly. 3932 const auto *C = dyn_cast<Constant>(Idx); 3933 if (C && isa<VectorType>(C->getType())) 3934 C = C->getSplatValue(); 3935 3936 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3937 if (CI && CI->isZero()) 3938 continue; 3939 if (CI && !ElementScalable) { 3940 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3941 LLVMContext &Context = *DAG.getContext(); 3942 SDValue OffsVal; 3943 if (IsVectorGEP) 3944 OffsVal = DAG.getConstant( 3945 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3946 else 3947 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3948 3949 // In an inbounds GEP with an offset that is nonnegative even when 3950 // interpreted as signed, assume there is no unsigned overflow. 3951 SDNodeFlags Flags; 3952 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3953 Flags.setNoUnsignedWrap(true); 3954 3955 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3956 3957 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3958 continue; 3959 } 3960 3961 // N = N + Idx * ElementMul; 3962 SDValue IdxN = getValue(Idx); 3963 3964 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3965 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3966 VectorElementCount); 3967 IdxN = DAG.getSplat(VT, dl, IdxN); 3968 } 3969 3970 // If the index is smaller or larger than intptr_t, truncate or extend 3971 // it. 3972 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3973 3974 if (ElementScalable) { 3975 EVT VScaleTy = N.getValueType().getScalarType(); 3976 SDValue VScale = DAG.getNode( 3977 ISD::VSCALE, dl, VScaleTy, 3978 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3979 if (IsVectorGEP) 3980 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3981 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3982 } else { 3983 // If this is a multiply by a power of two, turn it into a shl 3984 // immediately. This is a very common case. 3985 if (ElementMul != 1) { 3986 if (ElementMul.isPowerOf2()) { 3987 unsigned Amt = ElementMul.logBase2(); 3988 IdxN = DAG.getNode(ISD::SHL, dl, 3989 N.getValueType(), IdxN, 3990 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3991 } else { 3992 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3993 IdxN.getValueType()); 3994 IdxN = DAG.getNode(ISD::MUL, dl, 3995 N.getValueType(), IdxN, Scale); 3996 } 3997 } 3998 } 3999 4000 N = DAG.getNode(ISD::ADD, dl, 4001 N.getValueType(), N, IdxN); 4002 } 4003 } 4004 4005 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4006 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4007 if (IsVectorGEP) { 4008 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4009 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4010 } 4011 4012 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4013 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4014 4015 setValue(&I, N); 4016 } 4017 4018 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4019 // If this is a fixed sized alloca in the entry block of the function, 4020 // allocate it statically on the stack. 4021 if (FuncInfo.StaticAllocaMap.count(&I)) 4022 return; // getValue will auto-populate this. 4023 4024 SDLoc dl = getCurSDLoc(); 4025 Type *Ty = I.getAllocatedType(); 4026 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4027 auto &DL = DAG.getDataLayout(); 4028 TypeSize TySize = DL.getTypeAllocSize(Ty); 4029 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4030 4031 SDValue AllocSize = getValue(I.getArraySize()); 4032 4033 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 4034 if (AllocSize.getValueType() != IntPtr) 4035 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4036 4037 if (TySize.isScalable()) 4038 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4039 DAG.getVScale(dl, IntPtr, 4040 APInt(IntPtr.getScalarSizeInBits(), 4041 TySize.getKnownMinValue()))); 4042 else 4043 AllocSize = 4044 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4045 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4046 4047 // Handle alignment. If the requested alignment is less than or equal to 4048 // the stack alignment, ignore it. If the size is greater than or equal to 4049 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4050 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4051 if (*Alignment <= StackAlign) 4052 Alignment = None; 4053 4054 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4055 // Round the size of the allocation up to the stack alignment size 4056 // by add SA-1 to the size. This doesn't overflow because we're computing 4057 // an address inside an alloca. 4058 SDNodeFlags Flags; 4059 Flags.setNoUnsignedWrap(true); 4060 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4061 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4062 4063 // Mask out the low bits for alignment purposes. 4064 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4065 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4066 4067 SDValue Ops[] = { 4068 getRoot(), AllocSize, 4069 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4070 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4071 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4072 setValue(&I, DSA); 4073 DAG.setRoot(DSA.getValue(1)); 4074 4075 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4076 } 4077 4078 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4079 if (I.isAtomic()) 4080 return visitAtomicLoad(I); 4081 4082 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4083 const Value *SV = I.getOperand(0); 4084 if (TLI.supportSwiftError()) { 4085 // Swifterror values can come from either a function parameter with 4086 // swifterror attribute or an alloca with swifterror attribute. 4087 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4088 if (Arg->hasSwiftErrorAttr()) 4089 return visitLoadFromSwiftError(I); 4090 } 4091 4092 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4093 if (Alloca->isSwiftError()) 4094 return visitLoadFromSwiftError(I); 4095 } 4096 } 4097 4098 SDValue Ptr = getValue(SV); 4099 4100 Type *Ty = I.getType(); 4101 SmallVector<EVT, 4> ValueVTs, MemVTs; 4102 SmallVector<uint64_t, 4> Offsets; 4103 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4104 unsigned NumValues = ValueVTs.size(); 4105 if (NumValues == 0) 4106 return; 4107 4108 Align Alignment = I.getAlign(); 4109 AAMDNodes AAInfo = I.getAAMetadata(); 4110 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4111 bool isVolatile = I.isVolatile(); 4112 MachineMemOperand::Flags MMOFlags = 4113 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4114 4115 SDValue Root; 4116 bool ConstantMemory = false; 4117 if (isVolatile) 4118 // Serialize volatile loads with other side effects. 4119 Root = getRoot(); 4120 else if (NumValues > MaxParallelChains) 4121 Root = getMemoryRoot(); 4122 else if (AA && 4123 AA->pointsToConstantMemory(MemoryLocation( 4124 SV, 4125 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4126 AAInfo))) { 4127 // Do not serialize (non-volatile) loads of constant memory with anything. 4128 Root = DAG.getEntryNode(); 4129 ConstantMemory = true; 4130 MMOFlags |= MachineMemOperand::MOInvariant; 4131 } else { 4132 // Do not serialize non-volatile loads against each other. 4133 Root = DAG.getRoot(); 4134 } 4135 4136 if (isDereferenceableAndAlignedPointer(SV, Ty, Alignment, DAG.getDataLayout(), 4137 &I, AC, nullptr, LibInfo)) 4138 MMOFlags |= MachineMemOperand::MODereferenceable; 4139 4140 SDLoc dl = getCurSDLoc(); 4141 4142 if (isVolatile) 4143 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4144 4145 // An aggregate load cannot wrap around the address space, so offsets to its 4146 // parts don't wrap either. 4147 SDNodeFlags Flags; 4148 Flags.setNoUnsignedWrap(true); 4149 4150 SmallVector<SDValue, 4> Values(NumValues); 4151 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4152 EVT PtrVT = Ptr.getValueType(); 4153 4154 unsigned ChainI = 0; 4155 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4156 // Serializing loads here may result in excessive register pressure, and 4157 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4158 // could recover a bit by hoisting nodes upward in the chain by recognizing 4159 // they are side-effect free or do not alias. The optimizer should really 4160 // avoid this case by converting large object/array copies to llvm.memcpy 4161 // (MaxParallelChains should always remain as failsafe). 4162 if (ChainI == MaxParallelChains) { 4163 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4164 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4165 makeArrayRef(Chains.data(), ChainI)); 4166 Root = Chain; 4167 ChainI = 0; 4168 } 4169 SDValue A = DAG.getNode(ISD::ADD, dl, 4170 PtrVT, Ptr, 4171 DAG.getConstant(Offsets[i], dl, PtrVT), 4172 Flags); 4173 4174 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4175 MachinePointerInfo(SV, Offsets[i]), Alignment, 4176 MMOFlags, AAInfo, Ranges); 4177 Chains[ChainI] = L.getValue(1); 4178 4179 if (MemVTs[i] != ValueVTs[i]) 4180 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4181 4182 Values[i] = L; 4183 } 4184 4185 if (!ConstantMemory) { 4186 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4187 makeArrayRef(Chains.data(), ChainI)); 4188 if (isVolatile) 4189 DAG.setRoot(Chain); 4190 else 4191 PendingLoads.push_back(Chain); 4192 } 4193 4194 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4195 DAG.getVTList(ValueVTs), Values)); 4196 } 4197 4198 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4199 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4200 "call visitStoreToSwiftError when backend supports swifterror"); 4201 4202 SmallVector<EVT, 4> ValueVTs; 4203 SmallVector<uint64_t, 4> Offsets; 4204 const Value *SrcV = I.getOperand(0); 4205 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4206 SrcV->getType(), ValueVTs, &Offsets); 4207 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4208 "expect a single EVT for swifterror"); 4209 4210 SDValue Src = getValue(SrcV); 4211 // Create a virtual register, then update the virtual register. 4212 Register VReg = 4213 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4214 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4215 // Chain can be getRoot or getControlRoot. 4216 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4217 SDValue(Src.getNode(), Src.getResNo())); 4218 DAG.setRoot(CopyNode); 4219 } 4220 4221 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4222 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4223 "call visitLoadFromSwiftError when backend supports swifterror"); 4224 4225 assert(!I.isVolatile() && 4226 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4227 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4228 "Support volatile, non temporal, invariant for load_from_swift_error"); 4229 4230 const Value *SV = I.getOperand(0); 4231 Type *Ty = I.getType(); 4232 assert( 4233 (!AA || 4234 !AA->pointsToConstantMemory(MemoryLocation( 4235 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4236 I.getAAMetadata()))) && 4237 "load_from_swift_error should not be constant memory"); 4238 4239 SmallVector<EVT, 4> ValueVTs; 4240 SmallVector<uint64_t, 4> Offsets; 4241 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4242 ValueVTs, &Offsets); 4243 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4244 "expect a single EVT for swifterror"); 4245 4246 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4247 SDValue L = DAG.getCopyFromReg( 4248 getRoot(), getCurSDLoc(), 4249 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4250 4251 setValue(&I, L); 4252 } 4253 4254 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4255 if (I.isAtomic()) 4256 return visitAtomicStore(I); 4257 4258 const Value *SrcV = I.getOperand(0); 4259 const Value *PtrV = I.getOperand(1); 4260 4261 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4262 if (TLI.supportSwiftError()) { 4263 // Swifterror values can come from either a function parameter with 4264 // swifterror attribute or an alloca with swifterror attribute. 4265 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4266 if (Arg->hasSwiftErrorAttr()) 4267 return visitStoreToSwiftError(I); 4268 } 4269 4270 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4271 if (Alloca->isSwiftError()) 4272 return visitStoreToSwiftError(I); 4273 } 4274 } 4275 4276 SmallVector<EVT, 4> ValueVTs, MemVTs; 4277 SmallVector<uint64_t, 4> Offsets; 4278 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4279 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4280 unsigned NumValues = ValueVTs.size(); 4281 if (NumValues == 0) 4282 return; 4283 4284 // Get the lowered operands. Note that we do this after 4285 // checking if NumResults is zero, because with zero results 4286 // the operands won't have values in the map. 4287 SDValue Src = getValue(SrcV); 4288 SDValue Ptr = getValue(PtrV); 4289 4290 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4291 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4292 SDLoc dl = getCurSDLoc(); 4293 Align Alignment = I.getAlign(); 4294 AAMDNodes AAInfo = I.getAAMetadata(); 4295 4296 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4297 4298 // An aggregate load cannot wrap around the address space, so offsets to its 4299 // parts don't wrap either. 4300 SDNodeFlags Flags; 4301 Flags.setNoUnsignedWrap(true); 4302 4303 unsigned ChainI = 0; 4304 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4305 // See visitLoad comments. 4306 if (ChainI == MaxParallelChains) { 4307 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4308 makeArrayRef(Chains.data(), ChainI)); 4309 Root = Chain; 4310 ChainI = 0; 4311 } 4312 SDValue Add = 4313 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4314 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4315 if (MemVTs[i] != ValueVTs[i]) 4316 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4317 SDValue St = 4318 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4319 Alignment, MMOFlags, AAInfo); 4320 Chains[ChainI] = St; 4321 } 4322 4323 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4324 makeArrayRef(Chains.data(), ChainI)); 4325 setValue(&I, StoreNode); 4326 DAG.setRoot(StoreNode); 4327 } 4328 4329 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4330 bool IsCompressing) { 4331 SDLoc sdl = getCurSDLoc(); 4332 4333 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4334 MaybeAlign &Alignment) { 4335 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4336 Src0 = I.getArgOperand(0); 4337 Ptr = I.getArgOperand(1); 4338 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4339 Mask = I.getArgOperand(3); 4340 }; 4341 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4342 MaybeAlign &Alignment) { 4343 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4344 Src0 = I.getArgOperand(0); 4345 Ptr = I.getArgOperand(1); 4346 Mask = I.getArgOperand(2); 4347 Alignment = None; 4348 }; 4349 4350 Value *PtrOperand, *MaskOperand, *Src0Operand; 4351 MaybeAlign Alignment; 4352 if (IsCompressing) 4353 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4354 else 4355 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4356 4357 SDValue Ptr = getValue(PtrOperand); 4358 SDValue Src0 = getValue(Src0Operand); 4359 SDValue Mask = getValue(MaskOperand); 4360 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4361 4362 EVT VT = Src0.getValueType(); 4363 if (!Alignment) 4364 Alignment = DAG.getEVTAlign(VT); 4365 4366 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4367 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4368 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4369 SDValue StoreNode = 4370 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4371 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4372 DAG.setRoot(StoreNode); 4373 setValue(&I, StoreNode); 4374 } 4375 4376 // Get a uniform base for the Gather/Scatter intrinsic. 4377 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4378 // We try to represent it as a base pointer + vector of indices. 4379 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4380 // The first operand of the GEP may be a single pointer or a vector of pointers 4381 // Example: 4382 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4383 // or 4384 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4385 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4386 // 4387 // When the first GEP operand is a single pointer - it is the uniform base we 4388 // are looking for. If first operand of the GEP is a splat vector - we 4389 // extract the splat value and use it as a uniform base. 4390 // In all other cases the function returns 'false'. 4391 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4392 ISD::MemIndexType &IndexType, SDValue &Scale, 4393 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4394 uint64_t ElemSize) { 4395 SelectionDAG& DAG = SDB->DAG; 4396 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4397 const DataLayout &DL = DAG.getDataLayout(); 4398 4399 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4400 4401 // Handle splat constant pointer. 4402 if (auto *C = dyn_cast<Constant>(Ptr)) { 4403 C = C->getSplatValue(); 4404 if (!C) 4405 return false; 4406 4407 Base = SDB->getValue(C); 4408 4409 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4410 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4411 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4412 IndexType = ISD::SIGNED_SCALED; 4413 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4414 return true; 4415 } 4416 4417 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4418 if (!GEP || GEP->getParent() != CurBB) 4419 return false; 4420 4421 if (GEP->getNumOperands() != 2) 4422 return false; 4423 4424 const Value *BasePtr = GEP->getPointerOperand(); 4425 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4426 4427 // Make sure the base is scalar and the index is a vector. 4428 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4429 return false; 4430 4431 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4432 4433 // Target may not support the required addressing mode. 4434 if (ScaleVal != 1 && 4435 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4436 return false; 4437 4438 Base = SDB->getValue(BasePtr); 4439 Index = SDB->getValue(IndexVal); 4440 IndexType = ISD::SIGNED_SCALED; 4441 4442 Scale = 4443 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4444 return true; 4445 } 4446 4447 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4448 SDLoc sdl = getCurSDLoc(); 4449 4450 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4451 const Value *Ptr = I.getArgOperand(1); 4452 SDValue Src0 = getValue(I.getArgOperand(0)); 4453 SDValue Mask = getValue(I.getArgOperand(3)); 4454 EVT VT = Src0.getValueType(); 4455 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4456 ->getMaybeAlignValue() 4457 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4458 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4459 4460 SDValue Base; 4461 SDValue Index; 4462 ISD::MemIndexType IndexType; 4463 SDValue Scale; 4464 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4465 I.getParent(), VT.getScalarStoreSize()); 4466 4467 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4468 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4469 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4470 // TODO: Make MachineMemOperands aware of scalable 4471 // vectors. 4472 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4473 if (!UniformBase) { 4474 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4475 Index = getValue(Ptr); 4476 IndexType = ISD::SIGNED_SCALED; 4477 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4478 } 4479 4480 EVT IdxVT = Index.getValueType(); 4481 EVT EltTy = IdxVT.getVectorElementType(); 4482 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4483 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4484 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4485 } 4486 4487 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4488 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4489 Ops, MMO, IndexType, false); 4490 DAG.setRoot(Scatter); 4491 setValue(&I, Scatter); 4492 } 4493 4494 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4495 SDLoc sdl = getCurSDLoc(); 4496 4497 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4498 MaybeAlign &Alignment) { 4499 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4500 Ptr = I.getArgOperand(0); 4501 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4502 Mask = I.getArgOperand(2); 4503 Src0 = I.getArgOperand(3); 4504 }; 4505 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4506 MaybeAlign &Alignment) { 4507 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4508 Ptr = I.getArgOperand(0); 4509 Alignment = None; 4510 Mask = I.getArgOperand(1); 4511 Src0 = I.getArgOperand(2); 4512 }; 4513 4514 Value *PtrOperand, *MaskOperand, *Src0Operand; 4515 MaybeAlign Alignment; 4516 if (IsExpanding) 4517 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4518 else 4519 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4520 4521 SDValue Ptr = getValue(PtrOperand); 4522 SDValue Src0 = getValue(Src0Operand); 4523 SDValue Mask = getValue(MaskOperand); 4524 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4525 4526 EVT VT = Src0.getValueType(); 4527 if (!Alignment) 4528 Alignment = DAG.getEVTAlign(VT); 4529 4530 AAMDNodes AAInfo = I.getAAMetadata(); 4531 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4532 4533 // Do not serialize masked loads of constant memory with anything. 4534 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4535 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4536 4537 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4538 4539 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4540 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4541 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4542 4543 SDValue Load = 4544 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4545 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4546 if (AddToChain) 4547 PendingLoads.push_back(Load.getValue(1)); 4548 setValue(&I, Load); 4549 } 4550 4551 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4552 SDLoc sdl = getCurSDLoc(); 4553 4554 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4555 const Value *Ptr = I.getArgOperand(0); 4556 SDValue Src0 = getValue(I.getArgOperand(3)); 4557 SDValue Mask = getValue(I.getArgOperand(2)); 4558 4559 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4560 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4561 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4562 ->getMaybeAlignValue() 4563 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4564 4565 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4566 4567 SDValue Root = DAG.getRoot(); 4568 SDValue Base; 4569 SDValue Index; 4570 ISD::MemIndexType IndexType; 4571 SDValue Scale; 4572 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4573 I.getParent(), VT.getScalarStoreSize()); 4574 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4575 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4576 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4577 // TODO: Make MachineMemOperands aware of scalable 4578 // vectors. 4579 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4580 4581 if (!UniformBase) { 4582 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4583 Index = getValue(Ptr); 4584 IndexType = ISD::SIGNED_SCALED; 4585 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4586 } 4587 4588 EVT IdxVT = Index.getValueType(); 4589 EVT EltTy = IdxVT.getVectorElementType(); 4590 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4591 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4592 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4593 } 4594 4595 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4596 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4597 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4598 4599 PendingLoads.push_back(Gather.getValue(1)); 4600 setValue(&I, Gather); 4601 } 4602 4603 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4604 SDLoc dl = getCurSDLoc(); 4605 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4606 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4607 SyncScope::ID SSID = I.getSyncScopeID(); 4608 4609 SDValue InChain = getRoot(); 4610 4611 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4612 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4613 4614 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4615 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4616 4617 MachineFunction &MF = DAG.getMachineFunction(); 4618 MachineMemOperand *MMO = MF.getMachineMemOperand( 4619 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4620 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4621 FailureOrdering); 4622 4623 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4624 dl, MemVT, VTs, InChain, 4625 getValue(I.getPointerOperand()), 4626 getValue(I.getCompareOperand()), 4627 getValue(I.getNewValOperand()), MMO); 4628 4629 SDValue OutChain = L.getValue(2); 4630 4631 setValue(&I, L); 4632 DAG.setRoot(OutChain); 4633 } 4634 4635 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4636 SDLoc dl = getCurSDLoc(); 4637 ISD::NodeType NT; 4638 switch (I.getOperation()) { 4639 default: llvm_unreachable("Unknown atomicrmw operation"); 4640 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4641 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4642 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4643 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4644 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4645 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4646 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4647 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4648 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4649 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4650 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4651 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4652 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4653 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4654 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4655 } 4656 AtomicOrdering Ordering = I.getOrdering(); 4657 SyncScope::ID SSID = I.getSyncScopeID(); 4658 4659 SDValue InChain = getRoot(); 4660 4661 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4663 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4664 4665 MachineFunction &MF = DAG.getMachineFunction(); 4666 MachineMemOperand *MMO = MF.getMachineMemOperand( 4667 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4668 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4669 4670 SDValue L = 4671 DAG.getAtomic(NT, dl, MemVT, InChain, 4672 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4673 MMO); 4674 4675 SDValue OutChain = L.getValue(1); 4676 4677 setValue(&I, L); 4678 DAG.setRoot(OutChain); 4679 } 4680 4681 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4682 SDLoc dl = getCurSDLoc(); 4683 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4684 SDValue Ops[3]; 4685 Ops[0] = getRoot(); 4686 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4687 TLI.getFenceOperandTy(DAG.getDataLayout())); 4688 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4689 TLI.getFenceOperandTy(DAG.getDataLayout())); 4690 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4691 setValue(&I, N); 4692 DAG.setRoot(N); 4693 } 4694 4695 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4696 SDLoc dl = getCurSDLoc(); 4697 AtomicOrdering Order = I.getOrdering(); 4698 SyncScope::ID SSID = I.getSyncScopeID(); 4699 4700 SDValue InChain = getRoot(); 4701 4702 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4703 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4704 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4705 4706 if (!TLI.supportsUnalignedAtomics() && 4707 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4708 report_fatal_error("Cannot generate unaligned atomic load"); 4709 4710 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4711 4712 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4713 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4714 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4715 4716 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4717 4718 SDValue Ptr = getValue(I.getPointerOperand()); 4719 4720 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4721 // TODO: Once this is better exercised by tests, it should be merged with 4722 // the normal path for loads to prevent future divergence. 4723 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4724 if (MemVT != VT) 4725 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4726 4727 setValue(&I, L); 4728 SDValue OutChain = L.getValue(1); 4729 if (!I.isUnordered()) 4730 DAG.setRoot(OutChain); 4731 else 4732 PendingLoads.push_back(OutChain); 4733 return; 4734 } 4735 4736 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4737 Ptr, MMO); 4738 4739 SDValue OutChain = L.getValue(1); 4740 if (MemVT != VT) 4741 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4742 4743 setValue(&I, L); 4744 DAG.setRoot(OutChain); 4745 } 4746 4747 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4748 SDLoc dl = getCurSDLoc(); 4749 4750 AtomicOrdering Ordering = I.getOrdering(); 4751 SyncScope::ID SSID = I.getSyncScopeID(); 4752 4753 SDValue InChain = getRoot(); 4754 4755 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4756 EVT MemVT = 4757 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4758 4759 if (!TLI.supportsUnalignedAtomics() && 4760 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4761 report_fatal_error("Cannot generate unaligned atomic store"); 4762 4763 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4764 4765 MachineFunction &MF = DAG.getMachineFunction(); 4766 MachineMemOperand *MMO = MF.getMachineMemOperand( 4767 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4768 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4769 4770 SDValue Val = getValue(I.getValueOperand()); 4771 if (Val.getValueType() != MemVT) 4772 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4773 SDValue Ptr = getValue(I.getPointerOperand()); 4774 4775 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4776 // TODO: Once this is better exercised by tests, it should be merged with 4777 // the normal path for stores to prevent future divergence. 4778 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4779 setValue(&I, S); 4780 DAG.setRoot(S); 4781 return; 4782 } 4783 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4784 Ptr, Val, MMO); 4785 4786 setValue(&I, OutChain); 4787 DAG.setRoot(OutChain); 4788 } 4789 4790 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4791 /// node. 4792 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4793 unsigned Intrinsic) { 4794 // Ignore the callsite's attributes. A specific call site may be marked with 4795 // readnone, but the lowering code will expect the chain based on the 4796 // definition. 4797 const Function *F = I.getCalledFunction(); 4798 bool HasChain = !F->doesNotAccessMemory(); 4799 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4800 4801 // Build the operand list. 4802 SmallVector<SDValue, 8> Ops; 4803 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4804 if (OnlyLoad) { 4805 // We don't need to serialize loads against other loads. 4806 Ops.push_back(DAG.getRoot()); 4807 } else { 4808 Ops.push_back(getRoot()); 4809 } 4810 } 4811 4812 // Info is set by getTgtMemIntrinsic 4813 TargetLowering::IntrinsicInfo Info; 4814 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4815 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4816 DAG.getMachineFunction(), 4817 Intrinsic); 4818 4819 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4820 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4821 Info.opc == ISD::INTRINSIC_W_CHAIN) 4822 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4823 TLI.getPointerTy(DAG.getDataLayout()))); 4824 4825 // Add all operands of the call to the operand list. 4826 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4827 const Value *Arg = I.getArgOperand(i); 4828 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4829 Ops.push_back(getValue(Arg)); 4830 continue; 4831 } 4832 4833 // Use TargetConstant instead of a regular constant for immarg. 4834 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4835 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4836 assert(CI->getBitWidth() <= 64 && 4837 "large intrinsic immediates not handled"); 4838 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4839 } else { 4840 Ops.push_back( 4841 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4842 } 4843 } 4844 4845 SmallVector<EVT, 4> ValueVTs; 4846 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4847 4848 if (HasChain) 4849 ValueVTs.push_back(MVT::Other); 4850 4851 SDVTList VTs = DAG.getVTList(ValueVTs); 4852 4853 // Propagate fast-math-flags from IR to node(s). 4854 SDNodeFlags Flags; 4855 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4856 Flags.copyFMF(*FPMO); 4857 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4858 4859 // Create the node. 4860 SDValue Result; 4861 // In some cases, custom collection of operands from CallInst I may be needed. 4862 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4863 if (IsTgtIntrinsic) { 4864 // This is target intrinsic that touches memory 4865 Result = 4866 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4867 MachinePointerInfo(Info.ptrVal, Info.offset), 4868 Info.align, Info.flags, Info.size, 4869 I.getAAMetadata()); 4870 } else if (!HasChain) { 4871 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4872 } else if (!I.getType()->isVoidTy()) { 4873 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4874 } else { 4875 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4876 } 4877 4878 if (HasChain) { 4879 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4880 if (OnlyLoad) 4881 PendingLoads.push_back(Chain); 4882 else 4883 DAG.setRoot(Chain); 4884 } 4885 4886 if (!I.getType()->isVoidTy()) { 4887 if (!isa<VectorType>(I.getType())) 4888 Result = lowerRangeToAssertZExt(DAG, I, Result); 4889 4890 MaybeAlign Alignment = I.getRetAlign(); 4891 if (!Alignment) 4892 Alignment = F->getAttributes().getRetAlignment(); 4893 // Insert `assertalign` node if there's an alignment. 4894 if (InsertAssertAlign && Alignment) { 4895 Result = 4896 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4897 } 4898 4899 setValue(&I, Result); 4900 } 4901 } 4902 4903 /// GetSignificand - Get the significand and build it into a floating-point 4904 /// number with exponent of 1: 4905 /// 4906 /// Op = (Op & 0x007fffff) | 0x3f800000; 4907 /// 4908 /// where Op is the hexadecimal representation of floating point value. 4909 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4910 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4911 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4912 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4913 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4914 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4915 } 4916 4917 /// GetExponent - Get the exponent: 4918 /// 4919 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4920 /// 4921 /// where Op is the hexadecimal representation of floating point value. 4922 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4923 const TargetLowering &TLI, const SDLoc &dl) { 4924 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4925 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4926 SDValue t1 = DAG.getNode( 4927 ISD::SRL, dl, MVT::i32, t0, 4928 DAG.getConstant(23, dl, 4929 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 4930 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4931 DAG.getConstant(127, dl, MVT::i32)); 4932 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4933 } 4934 4935 /// getF32Constant - Get 32-bit floating point constant. 4936 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4937 const SDLoc &dl) { 4938 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4939 MVT::f32); 4940 } 4941 4942 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4943 SelectionDAG &DAG) { 4944 // TODO: What fast-math-flags should be set on the floating-point nodes? 4945 4946 // IntegerPartOfX = ((int32_t)(t0); 4947 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4948 4949 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4950 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4951 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4952 4953 // IntegerPartOfX <<= 23; 4954 IntegerPartOfX = 4955 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4956 DAG.getConstant(23, dl, 4957 DAG.getTargetLoweringInfo().getShiftAmountTy( 4958 MVT::i32, DAG.getDataLayout()))); 4959 4960 SDValue TwoToFractionalPartOfX; 4961 if (LimitFloatPrecision <= 6) { 4962 // For floating-point precision of 6: 4963 // 4964 // TwoToFractionalPartOfX = 4965 // 0.997535578f + 4966 // (0.735607626f + 0.252464424f * x) * x; 4967 // 4968 // error 0.0144103317, which is 6 bits 4969 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4970 getF32Constant(DAG, 0x3e814304, dl)); 4971 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4972 getF32Constant(DAG, 0x3f3c50c8, dl)); 4973 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4974 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4975 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4976 } else if (LimitFloatPrecision <= 12) { 4977 // For floating-point precision of 12: 4978 // 4979 // TwoToFractionalPartOfX = 4980 // 0.999892986f + 4981 // (0.696457318f + 4982 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4983 // 4984 // error 0.000107046256, which is 13 to 14 bits 4985 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4986 getF32Constant(DAG, 0x3da235e3, dl)); 4987 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4988 getF32Constant(DAG, 0x3e65b8f3, dl)); 4989 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4990 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4991 getF32Constant(DAG, 0x3f324b07, dl)); 4992 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4993 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4994 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4995 } else { // LimitFloatPrecision <= 18 4996 // For floating-point precision of 18: 4997 // 4998 // TwoToFractionalPartOfX = 4999 // 0.999999982f + 5000 // (0.693148872f + 5001 // (0.240227044f + 5002 // (0.554906021e-1f + 5003 // (0.961591928e-2f + 5004 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5005 // error 2.47208000*10^(-7), which is better than 18 bits 5006 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5007 getF32Constant(DAG, 0x3924b03e, dl)); 5008 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5009 getF32Constant(DAG, 0x3ab24b87, dl)); 5010 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5011 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5012 getF32Constant(DAG, 0x3c1d8c17, dl)); 5013 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5014 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5015 getF32Constant(DAG, 0x3d634a1d, dl)); 5016 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5017 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5018 getF32Constant(DAG, 0x3e75fe14, dl)); 5019 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5020 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5021 getF32Constant(DAG, 0x3f317234, dl)); 5022 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5023 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5024 getF32Constant(DAG, 0x3f800000, dl)); 5025 } 5026 5027 // Add the exponent into the result in integer domain. 5028 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5029 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5030 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5031 } 5032 5033 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5034 /// limited-precision mode. 5035 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5036 const TargetLowering &TLI, SDNodeFlags Flags) { 5037 if (Op.getValueType() == MVT::f32 && 5038 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5039 5040 // Put the exponent in the right bit position for later addition to the 5041 // final result: 5042 // 5043 // t0 = Op * log2(e) 5044 5045 // TODO: What fast-math-flags should be set here? 5046 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5047 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5048 return getLimitedPrecisionExp2(t0, dl, DAG); 5049 } 5050 5051 // No special expansion. 5052 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5053 } 5054 5055 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5056 /// limited-precision mode. 5057 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5058 const TargetLowering &TLI, SDNodeFlags Flags) { 5059 // TODO: What fast-math-flags should be set on the floating-point nodes? 5060 5061 if (Op.getValueType() == MVT::f32 && 5062 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5063 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5064 5065 // Scale the exponent by log(2). 5066 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5067 SDValue LogOfExponent = 5068 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5069 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5070 5071 // Get the significand and build it into a floating-point number with 5072 // exponent of 1. 5073 SDValue X = GetSignificand(DAG, Op1, dl); 5074 5075 SDValue LogOfMantissa; 5076 if (LimitFloatPrecision <= 6) { 5077 // For floating-point precision of 6: 5078 // 5079 // LogofMantissa = 5080 // -1.1609546f + 5081 // (1.4034025f - 0.23903021f * x) * x; 5082 // 5083 // error 0.0034276066, which is better than 8 bits 5084 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5085 getF32Constant(DAG, 0xbe74c456, dl)); 5086 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5087 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5088 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5089 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5090 getF32Constant(DAG, 0x3f949a29, dl)); 5091 } else if (LimitFloatPrecision <= 12) { 5092 // For floating-point precision of 12: 5093 // 5094 // LogOfMantissa = 5095 // -1.7417939f + 5096 // (2.8212026f + 5097 // (-1.4699568f + 5098 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5099 // 5100 // error 0.000061011436, which is 14 bits 5101 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5102 getF32Constant(DAG, 0xbd67b6d6, dl)); 5103 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5104 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5105 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5106 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5107 getF32Constant(DAG, 0x3fbc278b, dl)); 5108 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5109 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5110 getF32Constant(DAG, 0x40348e95, dl)); 5111 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5112 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5113 getF32Constant(DAG, 0x3fdef31a, dl)); 5114 } else { // LimitFloatPrecision <= 18 5115 // For floating-point precision of 18: 5116 // 5117 // LogOfMantissa = 5118 // -2.1072184f + 5119 // (4.2372794f + 5120 // (-3.7029485f + 5121 // (2.2781945f + 5122 // (-0.87823314f + 5123 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5124 // 5125 // error 0.0000023660568, which is better than 18 bits 5126 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5127 getF32Constant(DAG, 0xbc91e5ac, dl)); 5128 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5129 getF32Constant(DAG, 0x3e4350aa, dl)); 5130 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5131 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5132 getF32Constant(DAG, 0x3f60d3e3, dl)); 5133 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5134 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5135 getF32Constant(DAG, 0x4011cdf0, dl)); 5136 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5137 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5138 getF32Constant(DAG, 0x406cfd1c, dl)); 5139 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5140 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5141 getF32Constant(DAG, 0x408797cb, dl)); 5142 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5143 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5144 getF32Constant(DAG, 0x4006dcab, dl)); 5145 } 5146 5147 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5148 } 5149 5150 // No special expansion. 5151 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5152 } 5153 5154 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5155 /// limited-precision mode. 5156 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5157 const TargetLowering &TLI, SDNodeFlags Flags) { 5158 // TODO: What fast-math-flags should be set on the floating-point nodes? 5159 5160 if (Op.getValueType() == MVT::f32 && 5161 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5162 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5163 5164 // Get the exponent. 5165 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5166 5167 // Get the significand and build it into a floating-point number with 5168 // exponent of 1. 5169 SDValue X = GetSignificand(DAG, Op1, dl); 5170 5171 // Different possible minimax approximations of significand in 5172 // floating-point for various degrees of accuracy over [1,2]. 5173 SDValue Log2ofMantissa; 5174 if (LimitFloatPrecision <= 6) { 5175 // For floating-point precision of 6: 5176 // 5177 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5178 // 5179 // error 0.0049451742, which is more than 7 bits 5180 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5181 getF32Constant(DAG, 0xbeb08fe0, dl)); 5182 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5183 getF32Constant(DAG, 0x40019463, dl)); 5184 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5185 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5186 getF32Constant(DAG, 0x3fd6633d, dl)); 5187 } else if (LimitFloatPrecision <= 12) { 5188 // For floating-point precision of 12: 5189 // 5190 // Log2ofMantissa = 5191 // -2.51285454f + 5192 // (4.07009056f + 5193 // (-2.12067489f + 5194 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5195 // 5196 // error 0.0000876136000, which is better than 13 bits 5197 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5198 getF32Constant(DAG, 0xbda7262e, dl)); 5199 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5200 getF32Constant(DAG, 0x3f25280b, dl)); 5201 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5202 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5203 getF32Constant(DAG, 0x4007b923, dl)); 5204 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5205 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5206 getF32Constant(DAG, 0x40823e2f, dl)); 5207 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5208 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5209 getF32Constant(DAG, 0x4020d29c, dl)); 5210 } else { // LimitFloatPrecision <= 18 5211 // For floating-point precision of 18: 5212 // 5213 // Log2ofMantissa = 5214 // -3.0400495f + 5215 // (6.1129976f + 5216 // (-5.3420409f + 5217 // (3.2865683f + 5218 // (-1.2669343f + 5219 // (0.27515199f - 5220 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5221 // 5222 // error 0.0000018516, which is better than 18 bits 5223 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5224 getF32Constant(DAG, 0xbcd2769e, dl)); 5225 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5226 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5227 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5228 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5229 getF32Constant(DAG, 0x3fa22ae7, dl)); 5230 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5231 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5232 getF32Constant(DAG, 0x40525723, dl)); 5233 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5234 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5235 getF32Constant(DAG, 0x40aaf200, dl)); 5236 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5237 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5238 getF32Constant(DAG, 0x40c39dad, dl)); 5239 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5240 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5241 getF32Constant(DAG, 0x4042902c, dl)); 5242 } 5243 5244 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5245 } 5246 5247 // No special expansion. 5248 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5249 } 5250 5251 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5252 /// limited-precision mode. 5253 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5254 const TargetLowering &TLI, SDNodeFlags Flags) { 5255 // TODO: What fast-math-flags should be set on the floating-point nodes? 5256 5257 if (Op.getValueType() == MVT::f32 && 5258 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5259 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5260 5261 // Scale the exponent by log10(2) [0.30102999f]. 5262 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5263 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5264 getF32Constant(DAG, 0x3e9a209a, dl)); 5265 5266 // Get the significand and build it into a floating-point number with 5267 // exponent of 1. 5268 SDValue X = GetSignificand(DAG, Op1, dl); 5269 5270 SDValue Log10ofMantissa; 5271 if (LimitFloatPrecision <= 6) { 5272 // For floating-point precision of 6: 5273 // 5274 // Log10ofMantissa = 5275 // -0.50419619f + 5276 // (0.60948995f - 0.10380950f * x) * x; 5277 // 5278 // error 0.0014886165, which is 6 bits 5279 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5280 getF32Constant(DAG, 0xbdd49a13, dl)); 5281 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5282 getF32Constant(DAG, 0x3f1c0789, dl)); 5283 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5284 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5285 getF32Constant(DAG, 0x3f011300, dl)); 5286 } else if (LimitFloatPrecision <= 12) { 5287 // For floating-point precision of 12: 5288 // 5289 // Log10ofMantissa = 5290 // -0.64831180f + 5291 // (0.91751397f + 5292 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5293 // 5294 // error 0.00019228036, which is better than 12 bits 5295 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5296 getF32Constant(DAG, 0x3d431f31, dl)); 5297 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5298 getF32Constant(DAG, 0x3ea21fb2, dl)); 5299 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5300 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5301 getF32Constant(DAG, 0x3f6ae232, dl)); 5302 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5303 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5304 getF32Constant(DAG, 0x3f25f7c3, dl)); 5305 } else { // LimitFloatPrecision <= 18 5306 // For floating-point precision of 18: 5307 // 5308 // Log10ofMantissa = 5309 // -0.84299375f + 5310 // (1.5327582f + 5311 // (-1.0688956f + 5312 // (0.49102474f + 5313 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5314 // 5315 // error 0.0000037995730, which is better than 18 bits 5316 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5317 getF32Constant(DAG, 0x3c5d51ce, dl)); 5318 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5319 getF32Constant(DAG, 0x3e00685a, dl)); 5320 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5321 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5322 getF32Constant(DAG, 0x3efb6798, dl)); 5323 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5324 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5325 getF32Constant(DAG, 0x3f88d192, dl)); 5326 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5327 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5328 getF32Constant(DAG, 0x3fc4316c, dl)); 5329 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5330 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5331 getF32Constant(DAG, 0x3f57ce70, dl)); 5332 } 5333 5334 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5335 } 5336 5337 // No special expansion. 5338 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5339 } 5340 5341 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5342 /// limited-precision mode. 5343 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5344 const TargetLowering &TLI, SDNodeFlags Flags) { 5345 if (Op.getValueType() == MVT::f32 && 5346 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5347 return getLimitedPrecisionExp2(Op, dl, DAG); 5348 5349 // No special expansion. 5350 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5351 } 5352 5353 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5354 /// limited-precision mode with x == 10.0f. 5355 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5356 SelectionDAG &DAG, const TargetLowering &TLI, 5357 SDNodeFlags Flags) { 5358 bool IsExp10 = false; 5359 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5360 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5361 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5362 APFloat Ten(10.0f); 5363 IsExp10 = LHSC->isExactlyValue(Ten); 5364 } 5365 } 5366 5367 // TODO: What fast-math-flags should be set on the FMUL node? 5368 if (IsExp10) { 5369 // Put the exponent in the right bit position for later addition to the 5370 // final result: 5371 // 5372 // #define LOG2OF10 3.3219281f 5373 // t0 = Op * LOG2OF10; 5374 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5375 getF32Constant(DAG, 0x40549a78, dl)); 5376 return getLimitedPrecisionExp2(t0, dl, DAG); 5377 } 5378 5379 // No special expansion. 5380 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5381 } 5382 5383 /// ExpandPowI - Expand a llvm.powi intrinsic. 5384 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5385 SelectionDAG &DAG) { 5386 // If RHS is a constant, we can expand this out to a multiplication tree if 5387 // it's beneficial on the target, otherwise we end up lowering to a call to 5388 // __powidf2 (for example). 5389 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5390 unsigned Val = RHSC->getSExtValue(); 5391 5392 // powi(x, 0) -> 1.0 5393 if (Val == 0) 5394 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5395 5396 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5397 Val, DAG.shouldOptForSize())) { 5398 // Get the exponent as a positive value. 5399 if ((int)Val < 0) 5400 Val = -Val; 5401 // We use the simple binary decomposition method to generate the multiply 5402 // sequence. There are more optimal ways to do this (for example, 5403 // powi(x,15) generates one more multiply than it should), but this has 5404 // the benefit of being both really simple and much better than a libcall. 5405 SDValue Res; // Logically starts equal to 1.0 5406 SDValue CurSquare = LHS; 5407 // TODO: Intrinsics should have fast-math-flags that propagate to these 5408 // nodes. 5409 while (Val) { 5410 if (Val & 1) { 5411 if (Res.getNode()) 5412 Res = 5413 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5414 else 5415 Res = CurSquare; // 1.0*CurSquare. 5416 } 5417 5418 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5419 CurSquare, CurSquare); 5420 Val >>= 1; 5421 } 5422 5423 // If the original was negative, invert the result, producing 1/(x*x*x). 5424 if (RHSC->getSExtValue() < 0) 5425 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5426 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5427 return Res; 5428 } 5429 } 5430 5431 // Otherwise, expand to a libcall. 5432 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5433 } 5434 5435 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5436 SDValue LHS, SDValue RHS, SDValue Scale, 5437 SelectionDAG &DAG, const TargetLowering &TLI) { 5438 EVT VT = LHS.getValueType(); 5439 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5440 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5441 LLVMContext &Ctx = *DAG.getContext(); 5442 5443 // If the type is legal but the operation isn't, this node might survive all 5444 // the way to operation legalization. If we end up there and we do not have 5445 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5446 // node. 5447 5448 // Coax the legalizer into expanding the node during type legalization instead 5449 // by bumping the size by one bit. This will force it to Promote, enabling the 5450 // early expansion and avoiding the need to expand later. 5451 5452 // We don't have to do this if Scale is 0; that can always be expanded, unless 5453 // it's a saturating signed operation. Those can experience true integer 5454 // division overflow, a case which we must avoid. 5455 5456 // FIXME: We wouldn't have to do this (or any of the early 5457 // expansion/promotion) if it was possible to expand a libcall of an 5458 // illegal type during operation legalization. But it's not, so things 5459 // get a bit hacky. 5460 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5461 if ((ScaleInt > 0 || (Saturating && Signed)) && 5462 (TLI.isTypeLegal(VT) || 5463 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5464 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5465 Opcode, VT, ScaleInt); 5466 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5467 EVT PromVT; 5468 if (VT.isScalarInteger()) 5469 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5470 else if (VT.isVector()) { 5471 PromVT = VT.getVectorElementType(); 5472 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5473 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5474 } else 5475 llvm_unreachable("Wrong VT for DIVFIX?"); 5476 if (Signed) { 5477 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5478 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5479 } else { 5480 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5481 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5482 } 5483 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5484 // For saturating operations, we need to shift up the LHS to get the 5485 // proper saturation width, and then shift down again afterwards. 5486 if (Saturating) 5487 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5488 DAG.getConstant(1, DL, ShiftTy)); 5489 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5490 if (Saturating) 5491 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5492 DAG.getConstant(1, DL, ShiftTy)); 5493 return DAG.getZExtOrTrunc(Res, DL, VT); 5494 } 5495 } 5496 5497 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5498 } 5499 5500 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5501 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5502 static void 5503 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5504 const SDValue &N) { 5505 switch (N.getOpcode()) { 5506 case ISD::CopyFromReg: { 5507 SDValue Op = N.getOperand(1); 5508 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5509 Op.getValueType().getSizeInBits()); 5510 return; 5511 } 5512 case ISD::BITCAST: 5513 case ISD::AssertZext: 5514 case ISD::AssertSext: 5515 case ISD::TRUNCATE: 5516 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5517 return; 5518 case ISD::BUILD_PAIR: 5519 case ISD::BUILD_VECTOR: 5520 case ISD::CONCAT_VECTORS: 5521 for (SDValue Op : N->op_values()) 5522 getUnderlyingArgRegs(Regs, Op); 5523 return; 5524 default: 5525 return; 5526 } 5527 } 5528 5529 /// If the DbgValueInst is a dbg_value of a function argument, create the 5530 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5531 /// instruction selection, they will be inserted to the entry BB. 5532 /// We don't currently support this for variadic dbg_values, as they shouldn't 5533 /// appear for function arguments or in the prologue. 5534 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5535 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5536 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5537 const Argument *Arg = dyn_cast<Argument>(V); 5538 if (!Arg) 5539 return false; 5540 5541 MachineFunction &MF = DAG.getMachineFunction(); 5542 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5543 5544 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5545 // we've been asked to pursue. 5546 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5547 bool Indirect) { 5548 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5549 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5550 // pointing at the VReg, which will be patched up later. 5551 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5552 auto MIB = BuildMI(MF, DL, Inst); 5553 MIB.addReg(Reg); 5554 MIB.addImm(0); 5555 MIB.addMetadata(Variable); 5556 auto *NewDIExpr = FragExpr; 5557 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5558 // the DIExpression. 5559 if (Indirect) 5560 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5561 MIB.addMetadata(NewDIExpr); 5562 return MIB; 5563 } else { 5564 // Create a completely standard DBG_VALUE. 5565 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5566 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5567 } 5568 }; 5569 5570 if (Kind == FuncArgumentDbgValueKind::Value) { 5571 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5572 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5573 // the entry block. 5574 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5575 if (!IsInEntryBlock) 5576 return false; 5577 5578 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5579 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5580 // variable that also is a param. 5581 // 5582 // Although, if we are at the top of the entry block already, we can still 5583 // emit using ArgDbgValue. This might catch some situations when the 5584 // dbg.value refers to an argument that isn't used in the entry block, so 5585 // any CopyToReg node would be optimized out and the only way to express 5586 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5587 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5588 // we should only emit as ArgDbgValue if the Variable is an argument to the 5589 // current function, and the dbg.value intrinsic is found in the entry 5590 // block. 5591 bool VariableIsFunctionInputArg = Variable->isParameter() && 5592 !DL->getInlinedAt(); 5593 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5594 if (!IsInPrologue && !VariableIsFunctionInputArg) 5595 return false; 5596 5597 // Here we assume that a function argument on IR level only can be used to 5598 // describe one input parameter on source level. If we for example have 5599 // source code like this 5600 // 5601 // struct A { long x, y; }; 5602 // void foo(struct A a, long b) { 5603 // ... 5604 // b = a.x; 5605 // ... 5606 // } 5607 // 5608 // and IR like this 5609 // 5610 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5611 // entry: 5612 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5613 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5614 // call void @llvm.dbg.value(metadata i32 %b, "b", 5615 // ... 5616 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5617 // ... 5618 // 5619 // then the last dbg.value is describing a parameter "b" using a value that 5620 // is an argument. But since we already has used %a1 to describe a parameter 5621 // we should not handle that last dbg.value here (that would result in an 5622 // incorrect hoisting of the DBG_VALUE to the function entry). 5623 // Notice that we allow one dbg.value per IR level argument, to accommodate 5624 // for the situation with fragments above. 5625 if (VariableIsFunctionInputArg) { 5626 unsigned ArgNo = Arg->getArgNo(); 5627 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5628 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5629 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5630 return false; 5631 FuncInfo.DescribedArgs.set(ArgNo); 5632 } 5633 } 5634 5635 bool IsIndirect = false; 5636 Optional<MachineOperand> Op; 5637 // Some arguments' frame index is recorded during argument lowering. 5638 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5639 if (FI != std::numeric_limits<int>::max()) 5640 Op = MachineOperand::CreateFI(FI); 5641 5642 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5643 if (!Op && N.getNode()) { 5644 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5645 Register Reg; 5646 if (ArgRegsAndSizes.size() == 1) 5647 Reg = ArgRegsAndSizes.front().first; 5648 5649 if (Reg && Reg.isVirtual()) { 5650 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5651 Register PR = RegInfo.getLiveInPhysReg(Reg); 5652 if (PR) 5653 Reg = PR; 5654 } 5655 if (Reg) { 5656 Op = MachineOperand::CreateReg(Reg, false); 5657 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5658 } 5659 } 5660 5661 if (!Op && N.getNode()) { 5662 // Check if frame index is available. 5663 SDValue LCandidate = peekThroughBitcasts(N); 5664 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5665 if (FrameIndexSDNode *FINode = 5666 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5667 Op = MachineOperand::CreateFI(FINode->getIndex()); 5668 } 5669 5670 if (!Op) { 5671 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5672 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5673 SplitRegs) { 5674 unsigned Offset = 0; 5675 for (const auto &RegAndSize : SplitRegs) { 5676 // If the expression is already a fragment, the current register 5677 // offset+size might extend beyond the fragment. In this case, only 5678 // the register bits that are inside the fragment are relevant. 5679 int RegFragmentSizeInBits = RegAndSize.second; 5680 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5681 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5682 // The register is entirely outside the expression fragment, 5683 // so is irrelevant for debug info. 5684 if (Offset >= ExprFragmentSizeInBits) 5685 break; 5686 // The register is partially outside the expression fragment, only 5687 // the low bits within the fragment are relevant for debug info. 5688 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5689 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5690 } 5691 } 5692 5693 auto FragmentExpr = DIExpression::createFragmentExpression( 5694 Expr, Offset, RegFragmentSizeInBits); 5695 Offset += RegAndSize.second; 5696 // If a valid fragment expression cannot be created, the variable's 5697 // correct value cannot be determined and so it is set as Undef. 5698 if (!FragmentExpr) { 5699 SDDbgValue *SDV = DAG.getConstantDbgValue( 5700 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5701 DAG.AddDbgValue(SDV, false); 5702 continue; 5703 } 5704 MachineInstr *NewMI = 5705 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5706 Kind != FuncArgumentDbgValueKind::Value); 5707 FuncInfo.ArgDbgValues.push_back(NewMI); 5708 } 5709 }; 5710 5711 // Check if ValueMap has reg number. 5712 DenseMap<const Value *, Register>::const_iterator 5713 VMI = FuncInfo.ValueMap.find(V); 5714 if (VMI != FuncInfo.ValueMap.end()) { 5715 const auto &TLI = DAG.getTargetLoweringInfo(); 5716 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5717 V->getType(), None); 5718 if (RFV.occupiesMultipleRegs()) { 5719 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5720 return true; 5721 } 5722 5723 Op = MachineOperand::CreateReg(VMI->second, false); 5724 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5725 } else if (ArgRegsAndSizes.size() > 1) { 5726 // This was split due to the calling convention, and no virtual register 5727 // mapping exists for the value. 5728 splitMultiRegDbgValue(ArgRegsAndSizes); 5729 return true; 5730 } 5731 } 5732 5733 if (!Op) 5734 return false; 5735 5736 assert(Variable->isValidLocationForIntrinsic(DL) && 5737 "Expected inlined-at fields to agree"); 5738 MachineInstr *NewMI = nullptr; 5739 5740 if (Op->isReg()) 5741 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5742 else 5743 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5744 Variable, Expr); 5745 5746 // Otherwise, use ArgDbgValues. 5747 FuncInfo.ArgDbgValues.push_back(NewMI); 5748 return true; 5749 } 5750 5751 /// Return the appropriate SDDbgValue based on N. 5752 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5753 DILocalVariable *Variable, 5754 DIExpression *Expr, 5755 const DebugLoc &dl, 5756 unsigned DbgSDNodeOrder) { 5757 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5758 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5759 // stack slot locations. 5760 // 5761 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5762 // debug values here after optimization: 5763 // 5764 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5765 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5766 // 5767 // Both describe the direct values of their associated variables. 5768 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5769 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5770 } 5771 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5772 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5773 } 5774 5775 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5776 switch (Intrinsic) { 5777 case Intrinsic::smul_fix: 5778 return ISD::SMULFIX; 5779 case Intrinsic::umul_fix: 5780 return ISD::UMULFIX; 5781 case Intrinsic::smul_fix_sat: 5782 return ISD::SMULFIXSAT; 5783 case Intrinsic::umul_fix_sat: 5784 return ISD::UMULFIXSAT; 5785 case Intrinsic::sdiv_fix: 5786 return ISD::SDIVFIX; 5787 case Intrinsic::udiv_fix: 5788 return ISD::UDIVFIX; 5789 case Intrinsic::sdiv_fix_sat: 5790 return ISD::SDIVFIXSAT; 5791 case Intrinsic::udiv_fix_sat: 5792 return ISD::UDIVFIXSAT; 5793 default: 5794 llvm_unreachable("Unhandled fixed point intrinsic"); 5795 } 5796 } 5797 5798 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5799 const char *FunctionName) { 5800 assert(FunctionName && "FunctionName must not be nullptr"); 5801 SDValue Callee = DAG.getExternalSymbol( 5802 FunctionName, 5803 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5804 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5805 } 5806 5807 /// Given a @llvm.call.preallocated.setup, return the corresponding 5808 /// preallocated call. 5809 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5810 assert(cast<CallBase>(PreallocatedSetup) 5811 ->getCalledFunction() 5812 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5813 "expected call_preallocated_setup Value"); 5814 for (const auto *U : PreallocatedSetup->users()) { 5815 auto *UseCall = cast<CallBase>(U); 5816 const Function *Fn = UseCall->getCalledFunction(); 5817 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5818 return UseCall; 5819 } 5820 } 5821 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5822 } 5823 5824 /// Lower the call to the specified intrinsic function. 5825 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5826 unsigned Intrinsic) { 5827 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5828 SDLoc sdl = getCurSDLoc(); 5829 DebugLoc dl = getCurDebugLoc(); 5830 SDValue Res; 5831 5832 SDNodeFlags Flags; 5833 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5834 Flags.copyFMF(*FPOp); 5835 5836 switch (Intrinsic) { 5837 default: 5838 // By default, turn this into a target intrinsic node. 5839 visitTargetIntrinsic(I, Intrinsic); 5840 return; 5841 case Intrinsic::vscale: { 5842 match(&I, m_VScale(DAG.getDataLayout())); 5843 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5844 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5845 return; 5846 } 5847 case Intrinsic::vastart: visitVAStart(I); return; 5848 case Intrinsic::vaend: visitVAEnd(I); return; 5849 case Intrinsic::vacopy: visitVACopy(I); return; 5850 case Intrinsic::returnaddress: 5851 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5852 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5853 getValue(I.getArgOperand(0)))); 5854 return; 5855 case Intrinsic::addressofreturnaddress: 5856 setValue(&I, 5857 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5858 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5859 return; 5860 case Intrinsic::sponentry: 5861 setValue(&I, 5862 DAG.getNode(ISD::SPONENTRY, sdl, 5863 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5864 return; 5865 case Intrinsic::frameaddress: 5866 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5867 TLI.getFrameIndexTy(DAG.getDataLayout()), 5868 getValue(I.getArgOperand(0)))); 5869 return; 5870 case Intrinsic::read_volatile_register: 5871 case Intrinsic::read_register: { 5872 Value *Reg = I.getArgOperand(0); 5873 SDValue Chain = getRoot(); 5874 SDValue RegName = 5875 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5876 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5877 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5878 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5879 setValue(&I, Res); 5880 DAG.setRoot(Res.getValue(1)); 5881 return; 5882 } 5883 case Intrinsic::write_register: { 5884 Value *Reg = I.getArgOperand(0); 5885 Value *RegValue = I.getArgOperand(1); 5886 SDValue Chain = getRoot(); 5887 SDValue RegName = 5888 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5889 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5890 RegName, getValue(RegValue))); 5891 return; 5892 } 5893 case Intrinsic::memcpy: { 5894 const auto &MCI = cast<MemCpyInst>(I); 5895 SDValue Op1 = getValue(I.getArgOperand(0)); 5896 SDValue Op2 = getValue(I.getArgOperand(1)); 5897 SDValue Op3 = getValue(I.getArgOperand(2)); 5898 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5899 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5900 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5901 Align Alignment = std::min(DstAlign, SrcAlign); 5902 bool isVol = MCI.isVolatile(); 5903 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5904 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5905 // node. 5906 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5907 SDValue MC = DAG.getMemcpy( 5908 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5909 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 5910 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5911 updateDAGForMaybeTailCall(MC); 5912 return; 5913 } 5914 case Intrinsic::memcpy_inline: { 5915 const auto &MCI = cast<MemCpyInlineInst>(I); 5916 SDValue Dst = getValue(I.getArgOperand(0)); 5917 SDValue Src = getValue(I.getArgOperand(1)); 5918 SDValue Size = getValue(I.getArgOperand(2)); 5919 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5920 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5921 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5922 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5923 Align Alignment = std::min(DstAlign, SrcAlign); 5924 bool isVol = MCI.isVolatile(); 5925 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5926 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5927 // node. 5928 SDValue MC = DAG.getMemcpy( 5929 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5930 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5931 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5932 updateDAGForMaybeTailCall(MC); 5933 return; 5934 } 5935 case Intrinsic::memset: { 5936 const auto &MSI = cast<MemSetInst>(I); 5937 SDValue Op1 = getValue(I.getArgOperand(0)); 5938 SDValue Op2 = getValue(I.getArgOperand(1)); 5939 SDValue Op3 = getValue(I.getArgOperand(2)); 5940 // @llvm.memset defines 0 and 1 to both mean no alignment. 5941 Align Alignment = MSI.getDestAlign().valueOrOne(); 5942 bool isVol = MSI.isVolatile(); 5943 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5944 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5945 SDValue MS = DAG.getMemset( 5946 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 5947 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 5948 updateDAGForMaybeTailCall(MS); 5949 return; 5950 } 5951 case Intrinsic::memset_inline: { 5952 const auto &MSII = cast<MemSetInlineInst>(I); 5953 SDValue Dst = getValue(I.getArgOperand(0)); 5954 SDValue Value = getValue(I.getArgOperand(1)); 5955 SDValue Size = getValue(I.getArgOperand(2)); 5956 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 5957 // @llvm.memset defines 0 and 1 to both mean no alignment. 5958 Align DstAlign = MSII.getDestAlign().valueOrOne(); 5959 bool isVol = MSII.isVolatile(); 5960 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5961 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5962 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 5963 /* AlwaysInline */ true, isTC, 5964 MachinePointerInfo(I.getArgOperand(0)), 5965 I.getAAMetadata()); 5966 updateDAGForMaybeTailCall(MC); 5967 return; 5968 } 5969 case Intrinsic::memmove: { 5970 const auto &MMI = cast<MemMoveInst>(I); 5971 SDValue Op1 = getValue(I.getArgOperand(0)); 5972 SDValue Op2 = getValue(I.getArgOperand(1)); 5973 SDValue Op3 = getValue(I.getArgOperand(2)); 5974 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5975 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5976 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5977 Align Alignment = std::min(DstAlign, SrcAlign); 5978 bool isVol = MMI.isVolatile(); 5979 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5980 // FIXME: Support passing different dest/src alignments to the memmove DAG 5981 // node. 5982 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5983 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5984 isTC, MachinePointerInfo(I.getArgOperand(0)), 5985 MachinePointerInfo(I.getArgOperand(1)), 5986 I.getAAMetadata(), AA); 5987 updateDAGForMaybeTailCall(MM); 5988 return; 5989 } 5990 case Intrinsic::memcpy_element_unordered_atomic: { 5991 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5992 SDValue Dst = getValue(MI.getRawDest()); 5993 SDValue Src = getValue(MI.getRawSource()); 5994 SDValue Length = getValue(MI.getLength()); 5995 5996 Type *LengthTy = MI.getLength()->getType(); 5997 unsigned ElemSz = MI.getElementSizeInBytes(); 5998 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5999 SDValue MC = 6000 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6001 isTC, MachinePointerInfo(MI.getRawDest()), 6002 MachinePointerInfo(MI.getRawSource())); 6003 updateDAGForMaybeTailCall(MC); 6004 return; 6005 } 6006 case Intrinsic::memmove_element_unordered_atomic: { 6007 auto &MI = cast<AtomicMemMoveInst>(I); 6008 SDValue Dst = getValue(MI.getRawDest()); 6009 SDValue Src = getValue(MI.getRawSource()); 6010 SDValue Length = getValue(MI.getLength()); 6011 6012 Type *LengthTy = MI.getLength()->getType(); 6013 unsigned ElemSz = MI.getElementSizeInBytes(); 6014 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6015 SDValue MC = 6016 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6017 isTC, MachinePointerInfo(MI.getRawDest()), 6018 MachinePointerInfo(MI.getRawSource())); 6019 updateDAGForMaybeTailCall(MC); 6020 return; 6021 } 6022 case Intrinsic::memset_element_unordered_atomic: { 6023 auto &MI = cast<AtomicMemSetInst>(I); 6024 SDValue Dst = getValue(MI.getRawDest()); 6025 SDValue Val = getValue(MI.getValue()); 6026 SDValue Length = getValue(MI.getLength()); 6027 6028 Type *LengthTy = MI.getLength()->getType(); 6029 unsigned ElemSz = MI.getElementSizeInBytes(); 6030 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6031 SDValue MC = 6032 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6033 isTC, MachinePointerInfo(MI.getRawDest())); 6034 updateDAGForMaybeTailCall(MC); 6035 return; 6036 } 6037 case Intrinsic::call_preallocated_setup: { 6038 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6039 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6040 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6041 getRoot(), SrcValue); 6042 setValue(&I, Res); 6043 DAG.setRoot(Res); 6044 return; 6045 } 6046 case Intrinsic::call_preallocated_arg: { 6047 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6048 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6049 SDValue Ops[3]; 6050 Ops[0] = getRoot(); 6051 Ops[1] = SrcValue; 6052 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6053 MVT::i32); // arg index 6054 SDValue Res = DAG.getNode( 6055 ISD::PREALLOCATED_ARG, sdl, 6056 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6057 setValue(&I, Res); 6058 DAG.setRoot(Res.getValue(1)); 6059 return; 6060 } 6061 case Intrinsic::dbg_addr: 6062 case Intrinsic::dbg_declare: { 6063 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6064 // they are non-variadic. 6065 const auto &DI = cast<DbgVariableIntrinsic>(I); 6066 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6067 DILocalVariable *Variable = DI.getVariable(); 6068 DIExpression *Expression = DI.getExpression(); 6069 dropDanglingDebugInfo(Variable, Expression); 6070 assert(Variable && "Missing variable"); 6071 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6072 << "\n"); 6073 // Check if address has undef value. 6074 const Value *Address = DI.getVariableLocationOp(0); 6075 if (!Address || isa<UndefValue>(Address) || 6076 (Address->use_empty() && !isa<Argument>(Address))) { 6077 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6078 << " (bad/undef/unused-arg address)\n"); 6079 return; 6080 } 6081 6082 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6083 6084 // Check if this variable can be described by a frame index, typically 6085 // either as a static alloca or a byval parameter. 6086 int FI = std::numeric_limits<int>::max(); 6087 if (const auto *AI = 6088 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6089 if (AI->isStaticAlloca()) { 6090 auto I = FuncInfo.StaticAllocaMap.find(AI); 6091 if (I != FuncInfo.StaticAllocaMap.end()) 6092 FI = I->second; 6093 } 6094 } else if (const auto *Arg = dyn_cast<Argument>( 6095 Address->stripInBoundsConstantOffsets())) { 6096 FI = FuncInfo.getArgumentFrameIndex(Arg); 6097 } 6098 6099 // llvm.dbg.addr is control dependent and always generates indirect 6100 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6101 // the MachineFunction variable table. 6102 if (FI != std::numeric_limits<int>::max()) { 6103 if (Intrinsic == Intrinsic::dbg_addr) { 6104 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6105 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6106 dl, SDNodeOrder); 6107 DAG.AddDbgValue(SDV, isParameter); 6108 } else { 6109 LLVM_DEBUG(dbgs() << "Skipping " << DI 6110 << " (variable info stashed in MF side table)\n"); 6111 } 6112 return; 6113 } 6114 6115 SDValue &N = NodeMap[Address]; 6116 if (!N.getNode() && isa<Argument>(Address)) 6117 // Check unused arguments map. 6118 N = UnusedArgNodeMap[Address]; 6119 SDDbgValue *SDV; 6120 if (N.getNode()) { 6121 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6122 Address = BCI->getOperand(0); 6123 // Parameters are handled specially. 6124 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6125 if (isParameter && FINode) { 6126 // Byval parameter. We have a frame index at this point. 6127 SDV = 6128 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6129 /*IsIndirect*/ true, dl, SDNodeOrder); 6130 } else if (isa<Argument>(Address)) { 6131 // Address is an argument, so try to emit its dbg value using 6132 // virtual register info from the FuncInfo.ValueMap. 6133 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6134 FuncArgumentDbgValueKind::Declare, N); 6135 return; 6136 } else { 6137 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6138 true, dl, SDNodeOrder); 6139 } 6140 DAG.AddDbgValue(SDV, isParameter); 6141 } else { 6142 // If Address is an argument then try to emit its dbg value using 6143 // virtual register info from the FuncInfo.ValueMap. 6144 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6145 FuncArgumentDbgValueKind::Declare, N)) { 6146 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6147 << " (could not emit func-arg dbg_value)\n"); 6148 } 6149 } 6150 return; 6151 } 6152 case Intrinsic::dbg_label: { 6153 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6154 DILabel *Label = DI.getLabel(); 6155 assert(Label && "Missing label"); 6156 6157 SDDbgLabel *SDV; 6158 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6159 DAG.AddDbgLabel(SDV); 6160 return; 6161 } 6162 case Intrinsic::dbg_value: { 6163 const DbgValueInst &DI = cast<DbgValueInst>(I); 6164 assert(DI.getVariable() && "Missing variable"); 6165 6166 DILocalVariable *Variable = DI.getVariable(); 6167 DIExpression *Expression = DI.getExpression(); 6168 dropDanglingDebugInfo(Variable, Expression); 6169 SmallVector<Value *, 4> Values(DI.getValues()); 6170 if (Values.empty()) 6171 return; 6172 6173 if (llvm::is_contained(Values, nullptr)) 6174 return; 6175 6176 bool IsVariadic = DI.hasArgList(); 6177 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6178 SDNodeOrder, IsVariadic)) 6179 addDanglingDebugInfo(&DI, SDNodeOrder); 6180 return; 6181 } 6182 6183 case Intrinsic::eh_typeid_for: { 6184 // Find the type id for the given typeinfo. 6185 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6186 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6187 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6188 setValue(&I, Res); 6189 return; 6190 } 6191 6192 case Intrinsic::eh_return_i32: 6193 case Intrinsic::eh_return_i64: 6194 DAG.getMachineFunction().setCallsEHReturn(true); 6195 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6196 MVT::Other, 6197 getControlRoot(), 6198 getValue(I.getArgOperand(0)), 6199 getValue(I.getArgOperand(1)))); 6200 return; 6201 case Intrinsic::eh_unwind_init: 6202 DAG.getMachineFunction().setCallsUnwindInit(true); 6203 return; 6204 case Intrinsic::eh_dwarf_cfa: 6205 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6206 TLI.getPointerTy(DAG.getDataLayout()), 6207 getValue(I.getArgOperand(0)))); 6208 return; 6209 case Intrinsic::eh_sjlj_callsite: { 6210 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6211 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6212 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6213 6214 MMI.setCurrentCallSite(CI->getZExtValue()); 6215 return; 6216 } 6217 case Intrinsic::eh_sjlj_functioncontext: { 6218 // Get and store the index of the function context. 6219 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6220 AllocaInst *FnCtx = 6221 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6222 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6223 MFI.setFunctionContextIndex(FI); 6224 return; 6225 } 6226 case Intrinsic::eh_sjlj_setjmp: { 6227 SDValue Ops[2]; 6228 Ops[0] = getRoot(); 6229 Ops[1] = getValue(I.getArgOperand(0)); 6230 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6231 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6232 setValue(&I, Op.getValue(0)); 6233 DAG.setRoot(Op.getValue(1)); 6234 return; 6235 } 6236 case Intrinsic::eh_sjlj_longjmp: 6237 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6238 getRoot(), getValue(I.getArgOperand(0)))); 6239 return; 6240 case Intrinsic::eh_sjlj_setup_dispatch: 6241 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6242 getRoot())); 6243 return; 6244 case Intrinsic::masked_gather: 6245 visitMaskedGather(I); 6246 return; 6247 case Intrinsic::masked_load: 6248 visitMaskedLoad(I); 6249 return; 6250 case Intrinsic::masked_scatter: 6251 visitMaskedScatter(I); 6252 return; 6253 case Intrinsic::masked_store: 6254 visitMaskedStore(I); 6255 return; 6256 case Intrinsic::masked_expandload: 6257 visitMaskedLoad(I, true /* IsExpanding */); 6258 return; 6259 case Intrinsic::masked_compressstore: 6260 visitMaskedStore(I, true /* IsCompressing */); 6261 return; 6262 case Intrinsic::powi: 6263 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6264 getValue(I.getArgOperand(1)), DAG)); 6265 return; 6266 case Intrinsic::log: 6267 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6268 return; 6269 case Intrinsic::log2: 6270 setValue(&I, 6271 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6272 return; 6273 case Intrinsic::log10: 6274 setValue(&I, 6275 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6276 return; 6277 case Intrinsic::exp: 6278 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6279 return; 6280 case Intrinsic::exp2: 6281 setValue(&I, 6282 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6283 return; 6284 case Intrinsic::pow: 6285 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6286 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6287 return; 6288 case Intrinsic::sqrt: 6289 case Intrinsic::fabs: 6290 case Intrinsic::sin: 6291 case Intrinsic::cos: 6292 case Intrinsic::floor: 6293 case Intrinsic::ceil: 6294 case Intrinsic::trunc: 6295 case Intrinsic::rint: 6296 case Intrinsic::nearbyint: 6297 case Intrinsic::round: 6298 case Intrinsic::roundeven: 6299 case Intrinsic::canonicalize: { 6300 unsigned Opcode; 6301 switch (Intrinsic) { 6302 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6303 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6304 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6305 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6306 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6307 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6308 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6309 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6310 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6311 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6312 case Intrinsic::round: Opcode = ISD::FROUND; break; 6313 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6314 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6315 } 6316 6317 setValue(&I, DAG.getNode(Opcode, sdl, 6318 getValue(I.getArgOperand(0)).getValueType(), 6319 getValue(I.getArgOperand(0)), Flags)); 6320 return; 6321 } 6322 case Intrinsic::lround: 6323 case Intrinsic::llround: 6324 case Intrinsic::lrint: 6325 case Intrinsic::llrint: { 6326 unsigned Opcode; 6327 switch (Intrinsic) { 6328 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6329 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6330 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6331 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6332 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6333 } 6334 6335 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6336 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6337 getValue(I.getArgOperand(0)))); 6338 return; 6339 } 6340 case Intrinsic::minnum: 6341 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6342 getValue(I.getArgOperand(0)).getValueType(), 6343 getValue(I.getArgOperand(0)), 6344 getValue(I.getArgOperand(1)), Flags)); 6345 return; 6346 case Intrinsic::maxnum: 6347 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6348 getValue(I.getArgOperand(0)).getValueType(), 6349 getValue(I.getArgOperand(0)), 6350 getValue(I.getArgOperand(1)), Flags)); 6351 return; 6352 case Intrinsic::minimum: 6353 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6354 getValue(I.getArgOperand(0)).getValueType(), 6355 getValue(I.getArgOperand(0)), 6356 getValue(I.getArgOperand(1)), Flags)); 6357 return; 6358 case Intrinsic::maximum: 6359 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6360 getValue(I.getArgOperand(0)).getValueType(), 6361 getValue(I.getArgOperand(0)), 6362 getValue(I.getArgOperand(1)), Flags)); 6363 return; 6364 case Intrinsic::copysign: 6365 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6366 getValue(I.getArgOperand(0)).getValueType(), 6367 getValue(I.getArgOperand(0)), 6368 getValue(I.getArgOperand(1)), Flags)); 6369 return; 6370 case Intrinsic::arithmetic_fence: { 6371 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6372 getValue(I.getArgOperand(0)).getValueType(), 6373 getValue(I.getArgOperand(0)), Flags)); 6374 return; 6375 } 6376 case Intrinsic::fma: 6377 setValue(&I, DAG.getNode( 6378 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6379 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6380 getValue(I.getArgOperand(2)), Flags)); 6381 return; 6382 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6383 case Intrinsic::INTRINSIC: 6384 #include "llvm/IR/ConstrainedOps.def" 6385 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6386 return; 6387 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6388 #include "llvm/IR/VPIntrinsics.def" 6389 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6390 return; 6391 case Intrinsic::fptrunc_round: { 6392 // Get the last argument, the metadata and convert it to an integer in the 6393 // call 6394 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6395 Optional<RoundingMode> RoundMode = 6396 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6397 6398 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6399 6400 // Propagate fast-math-flags from IR to node(s). 6401 SDNodeFlags Flags; 6402 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6403 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6404 6405 SDValue Result; 6406 Result = DAG.getNode( 6407 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6408 DAG.getTargetConstant((int)*RoundMode, sdl, 6409 TLI.getPointerTy(DAG.getDataLayout()))); 6410 setValue(&I, Result); 6411 6412 return; 6413 } 6414 case Intrinsic::fmuladd: { 6415 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6416 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6417 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6418 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6419 getValue(I.getArgOperand(0)).getValueType(), 6420 getValue(I.getArgOperand(0)), 6421 getValue(I.getArgOperand(1)), 6422 getValue(I.getArgOperand(2)), Flags)); 6423 } else { 6424 // TODO: Intrinsic calls should have fast-math-flags. 6425 SDValue Mul = DAG.getNode( 6426 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6427 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6428 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6429 getValue(I.getArgOperand(0)).getValueType(), 6430 Mul, getValue(I.getArgOperand(2)), Flags); 6431 setValue(&I, Add); 6432 } 6433 return; 6434 } 6435 case Intrinsic::convert_to_fp16: 6436 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6437 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6438 getValue(I.getArgOperand(0)), 6439 DAG.getTargetConstant(0, sdl, 6440 MVT::i32)))); 6441 return; 6442 case Intrinsic::convert_from_fp16: 6443 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6444 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6445 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6446 getValue(I.getArgOperand(0))))); 6447 return; 6448 case Intrinsic::fptosi_sat: { 6449 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6450 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6451 getValue(I.getArgOperand(0)), 6452 DAG.getValueType(VT.getScalarType()))); 6453 return; 6454 } 6455 case Intrinsic::fptoui_sat: { 6456 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6457 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6458 getValue(I.getArgOperand(0)), 6459 DAG.getValueType(VT.getScalarType()))); 6460 return; 6461 } 6462 case Intrinsic::set_rounding: 6463 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6464 {getRoot(), getValue(I.getArgOperand(0))}); 6465 setValue(&I, Res); 6466 DAG.setRoot(Res.getValue(0)); 6467 return; 6468 case Intrinsic::is_fpclass: { 6469 const DataLayout DLayout = DAG.getDataLayout(); 6470 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6471 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6472 unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6473 MachineFunction &MF = DAG.getMachineFunction(); 6474 const Function &F = MF.getFunction(); 6475 SDValue Op = getValue(I.getArgOperand(0)); 6476 SDNodeFlags Flags; 6477 Flags.setNoFPExcept( 6478 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6479 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6480 // expansion can use illegal types. Making expansion early allows 6481 // legalizing these types prior to selection. 6482 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6483 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6484 setValue(&I, Result); 6485 return; 6486 } 6487 6488 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6489 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6490 setValue(&I, V); 6491 return; 6492 } 6493 case Intrinsic::pcmarker: { 6494 SDValue Tmp = getValue(I.getArgOperand(0)); 6495 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6496 return; 6497 } 6498 case Intrinsic::readcyclecounter: { 6499 SDValue Op = getRoot(); 6500 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6501 DAG.getVTList(MVT::i64, MVT::Other), Op); 6502 setValue(&I, Res); 6503 DAG.setRoot(Res.getValue(1)); 6504 return; 6505 } 6506 case Intrinsic::bitreverse: 6507 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6508 getValue(I.getArgOperand(0)).getValueType(), 6509 getValue(I.getArgOperand(0)))); 6510 return; 6511 case Intrinsic::bswap: 6512 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6513 getValue(I.getArgOperand(0)).getValueType(), 6514 getValue(I.getArgOperand(0)))); 6515 return; 6516 case Intrinsic::cttz: { 6517 SDValue Arg = getValue(I.getArgOperand(0)); 6518 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6519 EVT Ty = Arg.getValueType(); 6520 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6521 sdl, Ty, Arg)); 6522 return; 6523 } 6524 case Intrinsic::ctlz: { 6525 SDValue Arg = getValue(I.getArgOperand(0)); 6526 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6527 EVT Ty = Arg.getValueType(); 6528 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6529 sdl, Ty, Arg)); 6530 return; 6531 } 6532 case Intrinsic::ctpop: { 6533 SDValue Arg = getValue(I.getArgOperand(0)); 6534 EVT Ty = Arg.getValueType(); 6535 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6536 return; 6537 } 6538 case Intrinsic::fshl: 6539 case Intrinsic::fshr: { 6540 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6541 SDValue X = getValue(I.getArgOperand(0)); 6542 SDValue Y = getValue(I.getArgOperand(1)); 6543 SDValue Z = getValue(I.getArgOperand(2)); 6544 EVT VT = X.getValueType(); 6545 6546 if (X == Y) { 6547 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6548 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6549 } else { 6550 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6551 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6552 } 6553 return; 6554 } 6555 case Intrinsic::sadd_sat: { 6556 SDValue Op1 = getValue(I.getArgOperand(0)); 6557 SDValue Op2 = getValue(I.getArgOperand(1)); 6558 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6559 return; 6560 } 6561 case Intrinsic::uadd_sat: { 6562 SDValue Op1 = getValue(I.getArgOperand(0)); 6563 SDValue Op2 = getValue(I.getArgOperand(1)); 6564 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6565 return; 6566 } 6567 case Intrinsic::ssub_sat: { 6568 SDValue Op1 = getValue(I.getArgOperand(0)); 6569 SDValue Op2 = getValue(I.getArgOperand(1)); 6570 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6571 return; 6572 } 6573 case Intrinsic::usub_sat: { 6574 SDValue Op1 = getValue(I.getArgOperand(0)); 6575 SDValue Op2 = getValue(I.getArgOperand(1)); 6576 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6577 return; 6578 } 6579 case Intrinsic::sshl_sat: { 6580 SDValue Op1 = getValue(I.getArgOperand(0)); 6581 SDValue Op2 = getValue(I.getArgOperand(1)); 6582 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6583 return; 6584 } 6585 case Intrinsic::ushl_sat: { 6586 SDValue Op1 = getValue(I.getArgOperand(0)); 6587 SDValue Op2 = getValue(I.getArgOperand(1)); 6588 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6589 return; 6590 } 6591 case Intrinsic::smul_fix: 6592 case Intrinsic::umul_fix: 6593 case Intrinsic::smul_fix_sat: 6594 case Intrinsic::umul_fix_sat: { 6595 SDValue Op1 = getValue(I.getArgOperand(0)); 6596 SDValue Op2 = getValue(I.getArgOperand(1)); 6597 SDValue Op3 = getValue(I.getArgOperand(2)); 6598 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6599 Op1.getValueType(), Op1, Op2, Op3)); 6600 return; 6601 } 6602 case Intrinsic::sdiv_fix: 6603 case Intrinsic::udiv_fix: 6604 case Intrinsic::sdiv_fix_sat: 6605 case Intrinsic::udiv_fix_sat: { 6606 SDValue Op1 = getValue(I.getArgOperand(0)); 6607 SDValue Op2 = getValue(I.getArgOperand(1)); 6608 SDValue Op3 = getValue(I.getArgOperand(2)); 6609 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6610 Op1, Op2, Op3, DAG, TLI)); 6611 return; 6612 } 6613 case Intrinsic::smax: { 6614 SDValue Op1 = getValue(I.getArgOperand(0)); 6615 SDValue Op2 = getValue(I.getArgOperand(1)); 6616 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6617 return; 6618 } 6619 case Intrinsic::smin: { 6620 SDValue Op1 = getValue(I.getArgOperand(0)); 6621 SDValue Op2 = getValue(I.getArgOperand(1)); 6622 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6623 return; 6624 } 6625 case Intrinsic::umax: { 6626 SDValue Op1 = getValue(I.getArgOperand(0)); 6627 SDValue Op2 = getValue(I.getArgOperand(1)); 6628 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6629 return; 6630 } 6631 case Intrinsic::umin: { 6632 SDValue Op1 = getValue(I.getArgOperand(0)); 6633 SDValue Op2 = getValue(I.getArgOperand(1)); 6634 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6635 return; 6636 } 6637 case Intrinsic::abs: { 6638 // TODO: Preserve "int min is poison" arg in SDAG? 6639 SDValue Op1 = getValue(I.getArgOperand(0)); 6640 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6641 return; 6642 } 6643 case Intrinsic::stacksave: { 6644 SDValue Op = getRoot(); 6645 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6646 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6647 setValue(&I, Res); 6648 DAG.setRoot(Res.getValue(1)); 6649 return; 6650 } 6651 case Intrinsic::stackrestore: 6652 Res = getValue(I.getArgOperand(0)); 6653 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6654 return; 6655 case Intrinsic::get_dynamic_area_offset: { 6656 SDValue Op = getRoot(); 6657 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6658 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6659 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6660 // target. 6661 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6662 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6663 " intrinsic!"); 6664 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6665 Op); 6666 DAG.setRoot(Op); 6667 setValue(&I, Res); 6668 return; 6669 } 6670 case Intrinsic::stackguard: { 6671 MachineFunction &MF = DAG.getMachineFunction(); 6672 const Module &M = *MF.getFunction().getParent(); 6673 SDValue Chain = getRoot(); 6674 if (TLI.useLoadStackGuardNode()) { 6675 Res = getLoadStackGuard(DAG, sdl, Chain); 6676 } else { 6677 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6678 const Value *Global = TLI.getSDagStackGuard(M); 6679 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6680 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6681 MachinePointerInfo(Global, 0), Align, 6682 MachineMemOperand::MOVolatile); 6683 } 6684 if (TLI.useStackGuardXorFP()) 6685 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6686 DAG.setRoot(Chain); 6687 setValue(&I, Res); 6688 return; 6689 } 6690 case Intrinsic::stackprotector: { 6691 // Emit code into the DAG to store the stack guard onto the stack. 6692 MachineFunction &MF = DAG.getMachineFunction(); 6693 MachineFrameInfo &MFI = MF.getFrameInfo(); 6694 SDValue Src, Chain = getRoot(); 6695 6696 if (TLI.useLoadStackGuardNode()) 6697 Src = getLoadStackGuard(DAG, sdl, Chain); 6698 else 6699 Src = getValue(I.getArgOperand(0)); // The guard's value. 6700 6701 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6702 6703 int FI = FuncInfo.StaticAllocaMap[Slot]; 6704 MFI.setStackProtectorIndex(FI); 6705 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6706 6707 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6708 6709 // Store the stack protector onto the stack. 6710 Res = DAG.getStore( 6711 Chain, sdl, Src, FIN, 6712 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6713 MaybeAlign(), MachineMemOperand::MOVolatile); 6714 setValue(&I, Res); 6715 DAG.setRoot(Res); 6716 return; 6717 } 6718 case Intrinsic::objectsize: 6719 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6720 6721 case Intrinsic::is_constant: 6722 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6723 6724 case Intrinsic::annotation: 6725 case Intrinsic::ptr_annotation: 6726 case Intrinsic::launder_invariant_group: 6727 case Intrinsic::strip_invariant_group: 6728 // Drop the intrinsic, but forward the value 6729 setValue(&I, getValue(I.getOperand(0))); 6730 return; 6731 6732 case Intrinsic::assume: 6733 case Intrinsic::experimental_noalias_scope_decl: 6734 case Intrinsic::var_annotation: 6735 case Intrinsic::sideeffect: 6736 // Discard annotate attributes, noalias scope declarations, assumptions, and 6737 // artificial side-effects. 6738 return; 6739 6740 case Intrinsic::codeview_annotation: { 6741 // Emit a label associated with this metadata. 6742 MachineFunction &MF = DAG.getMachineFunction(); 6743 MCSymbol *Label = 6744 MF.getMMI().getContext().createTempSymbol("annotation", true); 6745 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6746 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6747 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6748 DAG.setRoot(Res); 6749 return; 6750 } 6751 6752 case Intrinsic::init_trampoline: { 6753 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6754 6755 SDValue Ops[6]; 6756 Ops[0] = getRoot(); 6757 Ops[1] = getValue(I.getArgOperand(0)); 6758 Ops[2] = getValue(I.getArgOperand(1)); 6759 Ops[3] = getValue(I.getArgOperand(2)); 6760 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6761 Ops[5] = DAG.getSrcValue(F); 6762 6763 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6764 6765 DAG.setRoot(Res); 6766 return; 6767 } 6768 case Intrinsic::adjust_trampoline: 6769 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6770 TLI.getPointerTy(DAG.getDataLayout()), 6771 getValue(I.getArgOperand(0)))); 6772 return; 6773 case Intrinsic::gcroot: { 6774 assert(DAG.getMachineFunction().getFunction().hasGC() && 6775 "only valid in functions with gc specified, enforced by Verifier"); 6776 assert(GFI && "implied by previous"); 6777 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6778 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6779 6780 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6781 GFI->addStackRoot(FI->getIndex(), TypeMap); 6782 return; 6783 } 6784 case Intrinsic::gcread: 6785 case Intrinsic::gcwrite: 6786 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6787 case Intrinsic::flt_rounds: 6788 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6789 setValue(&I, Res); 6790 DAG.setRoot(Res.getValue(1)); 6791 return; 6792 6793 case Intrinsic::expect: 6794 // Just replace __builtin_expect(exp, c) with EXP. 6795 setValue(&I, getValue(I.getArgOperand(0))); 6796 return; 6797 6798 case Intrinsic::ubsantrap: 6799 case Intrinsic::debugtrap: 6800 case Intrinsic::trap: { 6801 StringRef TrapFuncName = 6802 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6803 if (TrapFuncName.empty()) { 6804 switch (Intrinsic) { 6805 case Intrinsic::trap: 6806 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6807 break; 6808 case Intrinsic::debugtrap: 6809 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6810 break; 6811 case Intrinsic::ubsantrap: 6812 DAG.setRoot(DAG.getNode( 6813 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6814 DAG.getTargetConstant( 6815 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6816 MVT::i32))); 6817 break; 6818 default: llvm_unreachable("unknown trap intrinsic"); 6819 } 6820 return; 6821 } 6822 TargetLowering::ArgListTy Args; 6823 if (Intrinsic == Intrinsic::ubsantrap) { 6824 Args.push_back(TargetLoweringBase::ArgListEntry()); 6825 Args[0].Val = I.getArgOperand(0); 6826 Args[0].Node = getValue(Args[0].Val); 6827 Args[0].Ty = Args[0].Val->getType(); 6828 } 6829 6830 TargetLowering::CallLoweringInfo CLI(DAG); 6831 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6832 CallingConv::C, I.getType(), 6833 DAG.getExternalSymbol(TrapFuncName.data(), 6834 TLI.getPointerTy(DAG.getDataLayout())), 6835 std::move(Args)); 6836 6837 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6838 DAG.setRoot(Result.second); 6839 return; 6840 } 6841 6842 case Intrinsic::uadd_with_overflow: 6843 case Intrinsic::sadd_with_overflow: 6844 case Intrinsic::usub_with_overflow: 6845 case Intrinsic::ssub_with_overflow: 6846 case Intrinsic::umul_with_overflow: 6847 case Intrinsic::smul_with_overflow: { 6848 ISD::NodeType Op; 6849 switch (Intrinsic) { 6850 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6851 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6852 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6853 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6854 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6855 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6856 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6857 } 6858 SDValue Op1 = getValue(I.getArgOperand(0)); 6859 SDValue Op2 = getValue(I.getArgOperand(1)); 6860 6861 EVT ResultVT = Op1.getValueType(); 6862 EVT OverflowVT = MVT::i1; 6863 if (ResultVT.isVector()) 6864 OverflowVT = EVT::getVectorVT( 6865 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6866 6867 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6868 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6869 return; 6870 } 6871 case Intrinsic::prefetch: { 6872 SDValue Ops[5]; 6873 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6874 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6875 Ops[0] = DAG.getRoot(); 6876 Ops[1] = getValue(I.getArgOperand(0)); 6877 Ops[2] = getValue(I.getArgOperand(1)); 6878 Ops[3] = getValue(I.getArgOperand(2)); 6879 Ops[4] = getValue(I.getArgOperand(3)); 6880 SDValue Result = DAG.getMemIntrinsicNode( 6881 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6882 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6883 /* align */ None, Flags); 6884 6885 // Chain the prefetch in parallell with any pending loads, to stay out of 6886 // the way of later optimizations. 6887 PendingLoads.push_back(Result); 6888 Result = getRoot(); 6889 DAG.setRoot(Result); 6890 return; 6891 } 6892 case Intrinsic::lifetime_start: 6893 case Intrinsic::lifetime_end: { 6894 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6895 // Stack coloring is not enabled in O0, discard region information. 6896 if (TM.getOptLevel() == CodeGenOpt::None) 6897 return; 6898 6899 const int64_t ObjectSize = 6900 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6901 Value *const ObjectPtr = I.getArgOperand(1); 6902 SmallVector<const Value *, 4> Allocas; 6903 getUnderlyingObjects(ObjectPtr, Allocas); 6904 6905 for (const Value *Alloca : Allocas) { 6906 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6907 6908 // Could not find an Alloca. 6909 if (!LifetimeObject) 6910 continue; 6911 6912 // First check that the Alloca is static, otherwise it won't have a 6913 // valid frame index. 6914 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6915 if (SI == FuncInfo.StaticAllocaMap.end()) 6916 return; 6917 6918 const int FrameIndex = SI->second; 6919 int64_t Offset; 6920 if (GetPointerBaseWithConstantOffset( 6921 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6922 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6923 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6924 Offset); 6925 DAG.setRoot(Res); 6926 } 6927 return; 6928 } 6929 case Intrinsic::pseudoprobe: { 6930 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6931 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6932 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6933 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6934 DAG.setRoot(Res); 6935 return; 6936 } 6937 case Intrinsic::invariant_start: 6938 // Discard region information. 6939 setValue(&I, 6940 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6941 return; 6942 case Intrinsic::invariant_end: 6943 // Discard region information. 6944 return; 6945 case Intrinsic::clear_cache: 6946 /// FunctionName may be null. 6947 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6948 lowerCallToExternalSymbol(I, FunctionName); 6949 return; 6950 case Intrinsic::donothing: 6951 case Intrinsic::seh_try_begin: 6952 case Intrinsic::seh_scope_begin: 6953 case Intrinsic::seh_try_end: 6954 case Intrinsic::seh_scope_end: 6955 // ignore 6956 return; 6957 case Intrinsic::experimental_stackmap: 6958 visitStackmap(I); 6959 return; 6960 case Intrinsic::experimental_patchpoint_void: 6961 case Intrinsic::experimental_patchpoint_i64: 6962 visitPatchpoint(I); 6963 return; 6964 case Intrinsic::experimental_gc_statepoint: 6965 LowerStatepoint(cast<GCStatepointInst>(I)); 6966 return; 6967 case Intrinsic::experimental_gc_result: 6968 visitGCResult(cast<GCResultInst>(I)); 6969 return; 6970 case Intrinsic::experimental_gc_relocate: 6971 visitGCRelocate(cast<GCRelocateInst>(I)); 6972 return; 6973 case Intrinsic::instrprof_cover: 6974 llvm_unreachable("instrprof failed to lower a cover"); 6975 case Intrinsic::instrprof_increment: 6976 llvm_unreachable("instrprof failed to lower an increment"); 6977 case Intrinsic::instrprof_value_profile: 6978 llvm_unreachable("instrprof failed to lower a value profiling call"); 6979 case Intrinsic::localescape: { 6980 MachineFunction &MF = DAG.getMachineFunction(); 6981 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6982 6983 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6984 // is the same on all targets. 6985 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 6986 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6987 if (isa<ConstantPointerNull>(Arg)) 6988 continue; // Skip null pointers. They represent a hole in index space. 6989 AllocaInst *Slot = cast<AllocaInst>(Arg); 6990 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6991 "can only escape static allocas"); 6992 int FI = FuncInfo.StaticAllocaMap[Slot]; 6993 MCSymbol *FrameAllocSym = 6994 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6995 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6996 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6997 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6998 .addSym(FrameAllocSym) 6999 .addFrameIndex(FI); 7000 } 7001 7002 return; 7003 } 7004 7005 case Intrinsic::localrecover: { 7006 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7007 MachineFunction &MF = DAG.getMachineFunction(); 7008 7009 // Get the symbol that defines the frame offset. 7010 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7011 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7012 unsigned IdxVal = 7013 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7014 MCSymbol *FrameAllocSym = 7015 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7016 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7017 7018 Value *FP = I.getArgOperand(1); 7019 SDValue FPVal = getValue(FP); 7020 EVT PtrVT = FPVal.getValueType(); 7021 7022 // Create a MCSymbol for the label to avoid any target lowering 7023 // that would make this PC relative. 7024 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7025 SDValue OffsetVal = 7026 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7027 7028 // Add the offset to the FP. 7029 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7030 setValue(&I, Add); 7031 7032 return; 7033 } 7034 7035 case Intrinsic::eh_exceptionpointer: 7036 case Intrinsic::eh_exceptioncode: { 7037 // Get the exception pointer vreg, copy from it, and resize it to fit. 7038 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7039 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7040 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7041 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7042 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7043 if (Intrinsic == Intrinsic::eh_exceptioncode) 7044 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7045 setValue(&I, N); 7046 return; 7047 } 7048 case Intrinsic::xray_customevent: { 7049 // Here we want to make sure that the intrinsic behaves as if it has a 7050 // specific calling convention, and only for x86_64. 7051 // FIXME: Support other platforms later. 7052 const auto &Triple = DAG.getTarget().getTargetTriple(); 7053 if (Triple.getArch() != Triple::x86_64) 7054 return; 7055 7056 SmallVector<SDValue, 8> Ops; 7057 7058 // We want to say that we always want the arguments in registers. 7059 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7060 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7061 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7062 SDValue Chain = getRoot(); 7063 Ops.push_back(LogEntryVal); 7064 Ops.push_back(StrSizeVal); 7065 Ops.push_back(Chain); 7066 7067 // We need to enforce the calling convention for the callsite, so that 7068 // argument ordering is enforced correctly, and that register allocation can 7069 // see that some registers may be assumed clobbered and have to preserve 7070 // them across calls to the intrinsic. 7071 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7072 sdl, NodeTys, Ops); 7073 SDValue patchableNode = SDValue(MN, 0); 7074 DAG.setRoot(patchableNode); 7075 setValue(&I, patchableNode); 7076 return; 7077 } 7078 case Intrinsic::xray_typedevent: { 7079 // Here we want to make sure that the intrinsic behaves as if it has a 7080 // specific calling convention, and only for x86_64. 7081 // FIXME: Support other platforms later. 7082 const auto &Triple = DAG.getTarget().getTargetTriple(); 7083 if (Triple.getArch() != Triple::x86_64) 7084 return; 7085 7086 SmallVector<SDValue, 8> Ops; 7087 7088 // We want to say that we always want the arguments in registers. 7089 // It's unclear to me how manipulating the selection DAG here forces callers 7090 // to provide arguments in registers instead of on the stack. 7091 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7092 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7093 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7094 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7095 SDValue Chain = getRoot(); 7096 Ops.push_back(LogTypeId); 7097 Ops.push_back(LogEntryVal); 7098 Ops.push_back(StrSizeVal); 7099 Ops.push_back(Chain); 7100 7101 // We need to enforce the calling convention for the callsite, so that 7102 // argument ordering is enforced correctly, and that register allocation can 7103 // see that some registers may be assumed clobbered and have to preserve 7104 // them across calls to the intrinsic. 7105 MachineSDNode *MN = DAG.getMachineNode( 7106 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7107 SDValue patchableNode = SDValue(MN, 0); 7108 DAG.setRoot(patchableNode); 7109 setValue(&I, patchableNode); 7110 return; 7111 } 7112 case Intrinsic::experimental_deoptimize: 7113 LowerDeoptimizeCall(&I); 7114 return; 7115 case Intrinsic::experimental_stepvector: 7116 visitStepVector(I); 7117 return; 7118 case Intrinsic::vector_reduce_fadd: 7119 case Intrinsic::vector_reduce_fmul: 7120 case Intrinsic::vector_reduce_add: 7121 case Intrinsic::vector_reduce_mul: 7122 case Intrinsic::vector_reduce_and: 7123 case Intrinsic::vector_reduce_or: 7124 case Intrinsic::vector_reduce_xor: 7125 case Intrinsic::vector_reduce_smax: 7126 case Intrinsic::vector_reduce_smin: 7127 case Intrinsic::vector_reduce_umax: 7128 case Intrinsic::vector_reduce_umin: 7129 case Intrinsic::vector_reduce_fmax: 7130 case Intrinsic::vector_reduce_fmin: 7131 visitVectorReduce(I, Intrinsic); 7132 return; 7133 7134 case Intrinsic::icall_branch_funnel: { 7135 SmallVector<SDValue, 16> Ops; 7136 Ops.push_back(getValue(I.getArgOperand(0))); 7137 7138 int64_t Offset; 7139 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7140 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7141 if (!Base) 7142 report_fatal_error( 7143 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7144 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7145 7146 struct BranchFunnelTarget { 7147 int64_t Offset; 7148 SDValue Target; 7149 }; 7150 SmallVector<BranchFunnelTarget, 8> Targets; 7151 7152 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7153 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7154 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7155 if (ElemBase != Base) 7156 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7157 "to the same GlobalValue"); 7158 7159 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7160 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7161 if (!GA) 7162 report_fatal_error( 7163 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7164 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7165 GA->getGlobal(), sdl, Val.getValueType(), 7166 GA->getOffset())}); 7167 } 7168 llvm::sort(Targets, 7169 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7170 return T1.Offset < T2.Offset; 7171 }); 7172 7173 for (auto &T : Targets) { 7174 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7175 Ops.push_back(T.Target); 7176 } 7177 7178 Ops.push_back(DAG.getRoot()); // Chain 7179 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7180 MVT::Other, Ops), 7181 0); 7182 DAG.setRoot(N); 7183 setValue(&I, N); 7184 HasTailCall = true; 7185 return; 7186 } 7187 7188 case Intrinsic::wasm_landingpad_index: 7189 // Information this intrinsic contained has been transferred to 7190 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7191 // delete it now. 7192 return; 7193 7194 case Intrinsic::aarch64_settag: 7195 case Intrinsic::aarch64_settag_zero: { 7196 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7197 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7198 SDValue Val = TSI.EmitTargetCodeForSetTag( 7199 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7200 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7201 ZeroMemory); 7202 DAG.setRoot(Val); 7203 setValue(&I, Val); 7204 return; 7205 } 7206 case Intrinsic::ptrmask: { 7207 SDValue Ptr = getValue(I.getOperand(0)); 7208 SDValue Const = getValue(I.getOperand(1)); 7209 7210 EVT PtrVT = Ptr.getValueType(); 7211 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7212 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7213 return; 7214 } 7215 case Intrinsic::threadlocal_address: { 7216 setValue(&I, getValue(I.getOperand(0))); 7217 return; 7218 } 7219 case Intrinsic::get_active_lane_mask: { 7220 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7221 SDValue Index = getValue(I.getOperand(0)); 7222 EVT ElementVT = Index.getValueType(); 7223 7224 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7225 visitTargetIntrinsic(I, Intrinsic); 7226 return; 7227 } 7228 7229 SDValue TripCount = getValue(I.getOperand(1)); 7230 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7231 7232 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7233 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7234 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7235 SDValue VectorInduction = DAG.getNode( 7236 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7237 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7238 VectorTripCount, ISD::CondCode::SETULT); 7239 setValue(&I, SetCC); 7240 return; 7241 } 7242 case Intrinsic::vector_insert: { 7243 SDValue Vec = getValue(I.getOperand(0)); 7244 SDValue SubVec = getValue(I.getOperand(1)); 7245 SDValue Index = getValue(I.getOperand(2)); 7246 7247 // The intrinsic's index type is i64, but the SDNode requires an index type 7248 // suitable for the target. Convert the index as required. 7249 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7250 if (Index.getValueType() != VectorIdxTy) 7251 Index = DAG.getVectorIdxConstant( 7252 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7253 7254 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7255 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7256 Index)); 7257 return; 7258 } 7259 case Intrinsic::vector_extract: { 7260 SDValue Vec = getValue(I.getOperand(0)); 7261 SDValue Index = getValue(I.getOperand(1)); 7262 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7263 7264 // The intrinsic's index type is i64, but the SDNode requires an index type 7265 // suitable for the target. Convert the index as required. 7266 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7267 if (Index.getValueType() != VectorIdxTy) 7268 Index = DAG.getVectorIdxConstant( 7269 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7270 7271 setValue(&I, 7272 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7273 return; 7274 } 7275 case Intrinsic::experimental_vector_reverse: 7276 visitVectorReverse(I); 7277 return; 7278 case Intrinsic::experimental_vector_splice: 7279 visitVectorSplice(I); 7280 return; 7281 } 7282 } 7283 7284 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7285 const ConstrainedFPIntrinsic &FPI) { 7286 SDLoc sdl = getCurSDLoc(); 7287 7288 // We do not need to serialize constrained FP intrinsics against 7289 // each other or against (nonvolatile) loads, so they can be 7290 // chained like loads. 7291 SDValue Chain = DAG.getRoot(); 7292 SmallVector<SDValue, 4> Opers; 7293 Opers.push_back(Chain); 7294 if (FPI.isUnaryOp()) { 7295 Opers.push_back(getValue(FPI.getArgOperand(0))); 7296 } else if (FPI.isTernaryOp()) { 7297 Opers.push_back(getValue(FPI.getArgOperand(0))); 7298 Opers.push_back(getValue(FPI.getArgOperand(1))); 7299 Opers.push_back(getValue(FPI.getArgOperand(2))); 7300 } else { 7301 Opers.push_back(getValue(FPI.getArgOperand(0))); 7302 Opers.push_back(getValue(FPI.getArgOperand(1))); 7303 } 7304 7305 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7306 assert(Result.getNode()->getNumValues() == 2); 7307 7308 // Push node to the appropriate list so that future instructions can be 7309 // chained up correctly. 7310 SDValue OutChain = Result.getValue(1); 7311 switch (EB) { 7312 case fp::ExceptionBehavior::ebIgnore: 7313 // The only reason why ebIgnore nodes still need to be chained is that 7314 // they might depend on the current rounding mode, and therefore must 7315 // not be moved across instruction that may change that mode. 7316 [[fallthrough]]; 7317 case fp::ExceptionBehavior::ebMayTrap: 7318 // These must not be moved across calls or instructions that may change 7319 // floating-point exception masks. 7320 PendingConstrainedFP.push_back(OutChain); 7321 break; 7322 case fp::ExceptionBehavior::ebStrict: 7323 // These must not be moved across calls or instructions that may change 7324 // floating-point exception masks or read floating-point exception flags. 7325 // In addition, they cannot be optimized out even if unused. 7326 PendingConstrainedFPStrict.push_back(OutChain); 7327 break; 7328 } 7329 }; 7330 7331 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7332 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7333 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7334 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7335 7336 SDNodeFlags Flags; 7337 if (EB == fp::ExceptionBehavior::ebIgnore) 7338 Flags.setNoFPExcept(true); 7339 7340 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7341 Flags.copyFMF(*FPOp); 7342 7343 unsigned Opcode; 7344 switch (FPI.getIntrinsicID()) { 7345 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7346 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7347 case Intrinsic::INTRINSIC: \ 7348 Opcode = ISD::STRICT_##DAGN; \ 7349 break; 7350 #include "llvm/IR/ConstrainedOps.def" 7351 case Intrinsic::experimental_constrained_fmuladd: { 7352 Opcode = ISD::STRICT_FMA; 7353 // Break fmuladd into fmul and fadd. 7354 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7355 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7356 Opers.pop_back(); 7357 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7358 pushOutChain(Mul, EB); 7359 Opcode = ISD::STRICT_FADD; 7360 Opers.clear(); 7361 Opers.push_back(Mul.getValue(1)); 7362 Opers.push_back(Mul.getValue(0)); 7363 Opers.push_back(getValue(FPI.getArgOperand(2))); 7364 } 7365 break; 7366 } 7367 } 7368 7369 // A few strict DAG nodes carry additional operands that are not 7370 // set up by the default code above. 7371 switch (Opcode) { 7372 default: break; 7373 case ISD::STRICT_FP_ROUND: 7374 Opers.push_back( 7375 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7376 break; 7377 case ISD::STRICT_FSETCC: 7378 case ISD::STRICT_FSETCCS: { 7379 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7380 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7381 if (TM.Options.NoNaNsFPMath) 7382 Condition = getFCmpCodeWithoutNaN(Condition); 7383 Opers.push_back(DAG.getCondCode(Condition)); 7384 break; 7385 } 7386 } 7387 7388 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7389 pushOutChain(Result, EB); 7390 7391 SDValue FPResult = Result.getValue(0); 7392 setValue(&FPI, FPResult); 7393 } 7394 7395 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7396 Optional<unsigned> ResOPC; 7397 switch (VPIntrin.getIntrinsicID()) { 7398 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7399 case Intrinsic::VPID: \ 7400 ResOPC = ISD::VPSD; \ 7401 break; 7402 #include "llvm/IR/VPIntrinsics.def" 7403 } 7404 7405 if (!ResOPC) 7406 llvm_unreachable( 7407 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7408 7409 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7410 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7411 if (VPIntrin.getFastMathFlags().allowReassoc()) 7412 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7413 : ISD::VP_REDUCE_FMUL; 7414 } 7415 7416 return *ResOPC; 7417 } 7418 7419 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT, 7420 SmallVector<SDValue, 7> &OpValues) { 7421 SDLoc DL = getCurSDLoc(); 7422 Value *PtrOperand = VPIntrin.getArgOperand(0); 7423 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7424 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7425 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7426 SDValue LD; 7427 bool AddToChain = true; 7428 // Do not serialize variable-length loads of constant memory with 7429 // anything. 7430 if (!Alignment) 7431 Alignment = DAG.getEVTAlign(VT); 7432 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7433 AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7434 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7435 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7436 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7437 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7438 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7439 MMO, false /*IsExpanding */); 7440 if (AddToChain) 7441 PendingLoads.push_back(LD.getValue(1)); 7442 setValue(&VPIntrin, LD); 7443 } 7444 7445 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT, 7446 SmallVector<SDValue, 7> &OpValues) { 7447 SDLoc DL = getCurSDLoc(); 7448 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7449 Value *PtrOperand = VPIntrin.getArgOperand(0); 7450 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7451 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7452 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7453 SDValue LD; 7454 if (!Alignment) 7455 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7456 unsigned AS = 7457 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7458 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7459 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7460 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7461 SDValue Base, Index, Scale; 7462 ISD::MemIndexType IndexType; 7463 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7464 this, VPIntrin.getParent(), 7465 VT.getScalarStoreSize()); 7466 if (!UniformBase) { 7467 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7468 Index = getValue(PtrOperand); 7469 IndexType = ISD::SIGNED_SCALED; 7470 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7471 } 7472 EVT IdxVT = Index.getValueType(); 7473 EVT EltTy = IdxVT.getVectorElementType(); 7474 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7475 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7476 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7477 } 7478 LD = DAG.getGatherVP( 7479 DAG.getVTList(VT, MVT::Other), VT, DL, 7480 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7481 IndexType); 7482 PendingLoads.push_back(LD.getValue(1)); 7483 setValue(&VPIntrin, LD); 7484 } 7485 7486 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin, 7487 SmallVector<SDValue, 7> &OpValues) { 7488 SDLoc DL = getCurSDLoc(); 7489 Value *PtrOperand = VPIntrin.getArgOperand(1); 7490 EVT VT = OpValues[0].getValueType(); 7491 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7492 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7493 SDValue ST; 7494 if (!Alignment) 7495 Alignment = DAG.getEVTAlign(VT); 7496 SDValue Ptr = OpValues[1]; 7497 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7498 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7499 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7500 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7501 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7502 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7503 /* IsTruncating */ false, /*IsCompressing*/ false); 7504 DAG.setRoot(ST); 7505 setValue(&VPIntrin, ST); 7506 } 7507 7508 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin, 7509 SmallVector<SDValue, 7> &OpValues) { 7510 SDLoc DL = getCurSDLoc(); 7511 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7512 Value *PtrOperand = VPIntrin.getArgOperand(1); 7513 EVT VT = OpValues[0].getValueType(); 7514 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7515 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7516 SDValue ST; 7517 if (!Alignment) 7518 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7519 unsigned AS = 7520 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7521 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7522 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7523 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7524 SDValue Base, Index, Scale; 7525 ISD::MemIndexType IndexType; 7526 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7527 this, VPIntrin.getParent(), 7528 VT.getScalarStoreSize()); 7529 if (!UniformBase) { 7530 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7531 Index = getValue(PtrOperand); 7532 IndexType = ISD::SIGNED_SCALED; 7533 Scale = 7534 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7535 } 7536 EVT IdxVT = Index.getValueType(); 7537 EVT EltTy = IdxVT.getVectorElementType(); 7538 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7539 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7540 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7541 } 7542 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7543 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7544 OpValues[2], OpValues[3]}, 7545 MMO, IndexType); 7546 DAG.setRoot(ST); 7547 setValue(&VPIntrin, ST); 7548 } 7549 7550 void SelectionDAGBuilder::visitVPStridedLoad( 7551 const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) { 7552 SDLoc DL = getCurSDLoc(); 7553 Value *PtrOperand = VPIntrin.getArgOperand(0); 7554 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7555 if (!Alignment) 7556 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7557 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7558 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7559 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7560 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7561 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7562 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7563 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7564 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7565 7566 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7567 OpValues[2], OpValues[3], MMO, 7568 false /*IsExpanding*/); 7569 7570 if (AddToChain) 7571 PendingLoads.push_back(LD.getValue(1)); 7572 setValue(&VPIntrin, LD); 7573 } 7574 7575 void SelectionDAGBuilder::visitVPStridedStore( 7576 const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) { 7577 SDLoc DL = getCurSDLoc(); 7578 Value *PtrOperand = VPIntrin.getArgOperand(1); 7579 EVT VT = OpValues[0].getValueType(); 7580 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7581 if (!Alignment) 7582 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7583 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7584 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7585 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7586 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7587 7588 SDValue ST = DAG.getStridedStoreVP( 7589 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7590 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7591 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7592 /*IsCompressing*/ false); 7593 7594 DAG.setRoot(ST); 7595 setValue(&VPIntrin, ST); 7596 } 7597 7598 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7599 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7600 SDLoc DL = getCurSDLoc(); 7601 7602 ISD::CondCode Condition; 7603 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7604 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7605 if (IsFP) { 7606 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7607 // flags, but calls that don't return floating-point types can't be 7608 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7609 Condition = getFCmpCondCode(CondCode); 7610 if (TM.Options.NoNaNsFPMath) 7611 Condition = getFCmpCodeWithoutNaN(Condition); 7612 } else { 7613 Condition = getICmpCondCode(CondCode); 7614 } 7615 7616 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7617 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7618 // #2 is the condition code 7619 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7620 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7621 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7622 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7623 "Unexpected target EVL type"); 7624 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7625 7626 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7627 VPIntrin.getType()); 7628 setValue(&VPIntrin, 7629 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7630 } 7631 7632 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7633 const VPIntrinsic &VPIntrin) { 7634 SDLoc DL = getCurSDLoc(); 7635 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7636 7637 auto IID = VPIntrin.getIntrinsicID(); 7638 7639 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7640 return visitVPCmp(*CmpI); 7641 7642 SmallVector<EVT, 4> ValueVTs; 7643 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7644 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7645 SDVTList VTs = DAG.getVTList(ValueVTs); 7646 7647 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7648 7649 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7650 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7651 "Unexpected target EVL type"); 7652 7653 // Request operands. 7654 SmallVector<SDValue, 7> OpValues; 7655 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7656 auto Op = getValue(VPIntrin.getArgOperand(I)); 7657 if (I == EVLParamPos) 7658 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7659 OpValues.push_back(Op); 7660 } 7661 7662 switch (Opcode) { 7663 default: { 7664 SDNodeFlags SDFlags; 7665 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7666 SDFlags.copyFMF(*FPMO); 7667 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7668 setValue(&VPIntrin, Result); 7669 break; 7670 } 7671 case ISD::VP_LOAD: 7672 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7673 break; 7674 case ISD::VP_GATHER: 7675 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7676 break; 7677 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7678 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7679 break; 7680 case ISD::VP_STORE: 7681 visitVPStore(VPIntrin, OpValues); 7682 break; 7683 case ISD::VP_SCATTER: 7684 visitVPScatter(VPIntrin, OpValues); 7685 break; 7686 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7687 visitVPStridedStore(VPIntrin, OpValues); 7688 break; 7689 case ISD::VP_FMULADD: { 7690 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7691 SDNodeFlags SDFlags; 7692 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7693 SDFlags.copyFMF(*FPMO); 7694 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7695 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7696 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7697 } else { 7698 SDValue Mul = DAG.getNode( 7699 ISD::VP_FMUL, DL, VTs, 7700 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7701 SDValue Add = 7702 DAG.getNode(ISD::VP_FADD, DL, VTs, 7703 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7704 setValue(&VPIntrin, Add); 7705 } 7706 break; 7707 } 7708 case ISD::VP_INTTOPTR: { 7709 SDValue N = OpValues[0]; 7710 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 7711 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 7712 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7713 OpValues[2]); 7714 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7715 OpValues[2]); 7716 setValue(&VPIntrin, N); 7717 break; 7718 } 7719 case ISD::VP_PTRTOINT: { 7720 SDValue N = OpValues[0]; 7721 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7722 VPIntrin.getType()); 7723 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 7724 VPIntrin.getOperand(0)->getType()); 7725 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7726 OpValues[2]); 7727 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7728 OpValues[2]); 7729 setValue(&VPIntrin, N); 7730 break; 7731 } 7732 } 7733 } 7734 7735 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7736 const BasicBlock *EHPadBB, 7737 MCSymbol *&BeginLabel) { 7738 MachineFunction &MF = DAG.getMachineFunction(); 7739 MachineModuleInfo &MMI = MF.getMMI(); 7740 7741 // Insert a label before the invoke call to mark the try range. This can be 7742 // used to detect deletion of the invoke via the MachineModuleInfo. 7743 BeginLabel = MMI.getContext().createTempSymbol(); 7744 7745 // For SjLj, keep track of which landing pads go with which invokes 7746 // so as to maintain the ordering of pads in the LSDA. 7747 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7748 if (CallSiteIndex) { 7749 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7750 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7751 7752 // Now that the call site is handled, stop tracking it. 7753 MMI.setCurrentCallSite(0); 7754 } 7755 7756 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7757 } 7758 7759 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7760 const BasicBlock *EHPadBB, 7761 MCSymbol *BeginLabel) { 7762 assert(BeginLabel && "BeginLabel should've been set"); 7763 7764 MachineFunction &MF = DAG.getMachineFunction(); 7765 MachineModuleInfo &MMI = MF.getMMI(); 7766 7767 // Insert a label at the end of the invoke call to mark the try range. This 7768 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7769 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7770 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7771 7772 // Inform MachineModuleInfo of range. 7773 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7774 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7775 // actually use outlined funclets and their LSDA info style. 7776 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7777 assert(II && "II should've been set"); 7778 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7779 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7780 } else if (!isScopedEHPersonality(Pers)) { 7781 assert(EHPadBB); 7782 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7783 } 7784 7785 return Chain; 7786 } 7787 7788 std::pair<SDValue, SDValue> 7789 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7790 const BasicBlock *EHPadBB) { 7791 MCSymbol *BeginLabel = nullptr; 7792 7793 if (EHPadBB) { 7794 // Both PendingLoads and PendingExports must be flushed here; 7795 // this call might not return. 7796 (void)getRoot(); 7797 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7798 CLI.setChain(getRoot()); 7799 } 7800 7801 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7802 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7803 7804 assert((CLI.IsTailCall || Result.second.getNode()) && 7805 "Non-null chain expected with non-tail call!"); 7806 assert((Result.second.getNode() || !Result.first.getNode()) && 7807 "Null value expected with tail call!"); 7808 7809 if (!Result.second.getNode()) { 7810 // As a special case, a null chain means that a tail call has been emitted 7811 // and the DAG root is already updated. 7812 HasTailCall = true; 7813 7814 // Since there's no actual continuation from this block, nothing can be 7815 // relying on us setting vregs for them. 7816 PendingExports.clear(); 7817 } else { 7818 DAG.setRoot(Result.second); 7819 } 7820 7821 if (EHPadBB) { 7822 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7823 BeginLabel)); 7824 } 7825 7826 return Result; 7827 } 7828 7829 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7830 bool isTailCall, 7831 bool isMustTailCall, 7832 const BasicBlock *EHPadBB) { 7833 auto &DL = DAG.getDataLayout(); 7834 FunctionType *FTy = CB.getFunctionType(); 7835 Type *RetTy = CB.getType(); 7836 7837 TargetLowering::ArgListTy Args; 7838 Args.reserve(CB.arg_size()); 7839 7840 const Value *SwiftErrorVal = nullptr; 7841 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7842 7843 if (isTailCall) { 7844 // Avoid emitting tail calls in functions with the disable-tail-calls 7845 // attribute. 7846 auto *Caller = CB.getParent()->getParent(); 7847 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7848 "true" && !isMustTailCall) 7849 isTailCall = false; 7850 7851 // We can't tail call inside a function with a swifterror argument. Lowering 7852 // does not support this yet. It would have to move into the swifterror 7853 // register before the call. 7854 if (TLI.supportSwiftError() && 7855 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7856 isTailCall = false; 7857 } 7858 7859 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7860 TargetLowering::ArgListEntry Entry; 7861 const Value *V = *I; 7862 7863 // Skip empty types 7864 if (V->getType()->isEmptyTy()) 7865 continue; 7866 7867 SDValue ArgNode = getValue(V); 7868 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7869 7870 Entry.setAttributes(&CB, I - CB.arg_begin()); 7871 7872 // Use swifterror virtual register as input to the call. 7873 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7874 SwiftErrorVal = V; 7875 // We find the virtual register for the actual swifterror argument. 7876 // Instead of using the Value, we use the virtual register instead. 7877 Entry.Node = 7878 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7879 EVT(TLI.getPointerTy(DL))); 7880 } 7881 7882 Args.push_back(Entry); 7883 7884 // If we have an explicit sret argument that is an Instruction, (i.e., it 7885 // might point to function-local memory), we can't meaningfully tail-call. 7886 if (Entry.IsSRet && isa<Instruction>(V)) 7887 isTailCall = false; 7888 } 7889 7890 // If call site has a cfguardtarget operand bundle, create and add an 7891 // additional ArgListEntry. 7892 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7893 TargetLowering::ArgListEntry Entry; 7894 Value *V = Bundle->Inputs[0]; 7895 SDValue ArgNode = getValue(V); 7896 Entry.Node = ArgNode; 7897 Entry.Ty = V->getType(); 7898 Entry.IsCFGuardTarget = true; 7899 Args.push_back(Entry); 7900 } 7901 7902 // Check if target-independent constraints permit a tail call here. 7903 // Target-dependent constraints are checked within TLI->LowerCallTo. 7904 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7905 isTailCall = false; 7906 7907 // Disable tail calls if there is an swifterror argument. Targets have not 7908 // been updated to support tail calls. 7909 if (TLI.supportSwiftError() && SwiftErrorVal) 7910 isTailCall = false; 7911 7912 ConstantInt *CFIType = nullptr; 7913 if (CB.isIndirectCall()) { 7914 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 7915 if (!TLI.supportKCFIBundles()) 7916 report_fatal_error( 7917 "Target doesn't support calls with kcfi operand bundles."); 7918 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 7919 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 7920 } 7921 } 7922 7923 TargetLowering::CallLoweringInfo CLI(DAG); 7924 CLI.setDebugLoc(getCurSDLoc()) 7925 .setChain(getRoot()) 7926 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7927 .setTailCall(isTailCall) 7928 .setConvergent(CB.isConvergent()) 7929 .setIsPreallocated( 7930 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 7931 .setCFIType(CFIType); 7932 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7933 7934 if (Result.first.getNode()) { 7935 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7936 setValue(&CB, Result.first); 7937 } 7938 7939 // The last element of CLI.InVals has the SDValue for swifterror return. 7940 // Here we copy it to a virtual register and update SwiftErrorMap for 7941 // book-keeping. 7942 if (SwiftErrorVal && TLI.supportSwiftError()) { 7943 // Get the last element of InVals. 7944 SDValue Src = CLI.InVals.back(); 7945 Register VReg = 7946 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7947 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7948 DAG.setRoot(CopyNode); 7949 } 7950 } 7951 7952 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7953 SelectionDAGBuilder &Builder) { 7954 // Check to see if this load can be trivially constant folded, e.g. if the 7955 // input is from a string literal. 7956 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7957 // Cast pointer to the type we really want to load. 7958 Type *LoadTy = 7959 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7960 if (LoadVT.isVector()) 7961 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7962 7963 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7964 PointerType::getUnqual(LoadTy)); 7965 7966 if (const Constant *LoadCst = 7967 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 7968 LoadTy, Builder.DAG.getDataLayout())) 7969 return Builder.getValue(LoadCst); 7970 } 7971 7972 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7973 // still constant memory, the input chain can be the entry node. 7974 SDValue Root; 7975 bool ConstantMemory = false; 7976 7977 // Do not serialize (non-volatile) loads of constant memory with anything. 7978 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7979 Root = Builder.DAG.getEntryNode(); 7980 ConstantMemory = true; 7981 } else { 7982 // Do not serialize non-volatile loads against each other. 7983 Root = Builder.DAG.getRoot(); 7984 } 7985 7986 SDValue Ptr = Builder.getValue(PtrVal); 7987 SDValue LoadVal = 7988 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7989 MachinePointerInfo(PtrVal), Align(1)); 7990 7991 if (!ConstantMemory) 7992 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7993 return LoadVal; 7994 } 7995 7996 /// Record the value for an instruction that produces an integer result, 7997 /// converting the type where necessary. 7998 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7999 SDValue Value, 8000 bool IsSigned) { 8001 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8002 I.getType(), true); 8003 if (IsSigned) 8004 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 8005 else 8006 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 8007 setValue(&I, Value); 8008 } 8009 8010 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8011 /// true and lower it. Otherwise return false, and it will be lowered like a 8012 /// normal call. 8013 /// The caller already checked that \p I calls the appropriate LibFunc with a 8014 /// correct prototype. 8015 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8016 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8017 const Value *Size = I.getArgOperand(2); 8018 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8019 if (CSize && CSize->getZExtValue() == 0) { 8020 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8021 I.getType(), true); 8022 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8023 return true; 8024 } 8025 8026 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8027 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8028 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8029 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8030 if (Res.first.getNode()) { 8031 processIntegerCallValue(I, Res.first, true); 8032 PendingLoads.push_back(Res.second); 8033 return true; 8034 } 8035 8036 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8037 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8038 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8039 return false; 8040 8041 // If the target has a fast compare for the given size, it will return a 8042 // preferred load type for that size. Require that the load VT is legal and 8043 // that the target supports unaligned loads of that type. Otherwise, return 8044 // INVALID. 8045 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8046 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8047 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8048 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8049 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8050 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8051 // TODO: Check alignment of src and dest ptrs. 8052 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8053 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8054 if (!TLI.isTypeLegal(LVT) || 8055 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8056 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8057 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8058 } 8059 8060 return LVT; 8061 }; 8062 8063 // This turns into unaligned loads. We only do this if the target natively 8064 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8065 // we'll only produce a small number of byte loads. 8066 MVT LoadVT; 8067 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8068 switch (NumBitsToCompare) { 8069 default: 8070 return false; 8071 case 16: 8072 LoadVT = MVT::i16; 8073 break; 8074 case 32: 8075 LoadVT = MVT::i32; 8076 break; 8077 case 64: 8078 case 128: 8079 case 256: 8080 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8081 break; 8082 } 8083 8084 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8085 return false; 8086 8087 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8088 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8089 8090 // Bitcast to a wide integer type if the loads are vectors. 8091 if (LoadVT.isVector()) { 8092 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8093 LoadL = DAG.getBitcast(CmpVT, LoadL); 8094 LoadR = DAG.getBitcast(CmpVT, LoadR); 8095 } 8096 8097 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8098 processIntegerCallValue(I, Cmp, false); 8099 return true; 8100 } 8101 8102 /// See if we can lower a memchr call into an optimized form. If so, return 8103 /// true and lower it. Otherwise return false, and it will be lowered like a 8104 /// normal call. 8105 /// The caller already checked that \p I calls the appropriate LibFunc with a 8106 /// correct prototype. 8107 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8108 const Value *Src = I.getArgOperand(0); 8109 const Value *Char = I.getArgOperand(1); 8110 const Value *Length = I.getArgOperand(2); 8111 8112 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8113 std::pair<SDValue, SDValue> Res = 8114 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8115 getValue(Src), getValue(Char), getValue(Length), 8116 MachinePointerInfo(Src)); 8117 if (Res.first.getNode()) { 8118 setValue(&I, Res.first); 8119 PendingLoads.push_back(Res.second); 8120 return true; 8121 } 8122 8123 return false; 8124 } 8125 8126 /// See if we can lower a mempcpy call into an optimized form. If so, return 8127 /// true and lower it. Otherwise return false, and it will be lowered like a 8128 /// normal call. 8129 /// The caller already checked that \p I calls the appropriate LibFunc with a 8130 /// correct prototype. 8131 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8132 SDValue Dst = getValue(I.getArgOperand(0)); 8133 SDValue Src = getValue(I.getArgOperand(1)); 8134 SDValue Size = getValue(I.getArgOperand(2)); 8135 8136 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8137 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8138 // DAG::getMemcpy needs Alignment to be defined. 8139 Align Alignment = std::min(DstAlign, SrcAlign); 8140 8141 bool isVol = false; 8142 SDLoc sdl = getCurSDLoc(); 8143 8144 // In the mempcpy context we need to pass in a false value for isTailCall 8145 // because the return pointer needs to be adjusted by the size of 8146 // the copied memory. 8147 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 8148 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 8149 /*isTailCall=*/false, 8150 MachinePointerInfo(I.getArgOperand(0)), 8151 MachinePointerInfo(I.getArgOperand(1)), 8152 I.getAAMetadata()); 8153 assert(MC.getNode() != nullptr && 8154 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8155 DAG.setRoot(MC); 8156 8157 // Check if Size needs to be truncated or extended. 8158 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8159 8160 // Adjust return pointer to point just past the last dst byte. 8161 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8162 Dst, Size); 8163 setValue(&I, DstPlusSize); 8164 return true; 8165 } 8166 8167 /// See if we can lower a strcpy call into an optimized form. If so, return 8168 /// true and lower it, otherwise return false and it will be lowered like a 8169 /// normal call. 8170 /// The caller already checked that \p I calls the appropriate LibFunc with a 8171 /// correct prototype. 8172 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8173 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8174 8175 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8176 std::pair<SDValue, SDValue> Res = 8177 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8178 getValue(Arg0), getValue(Arg1), 8179 MachinePointerInfo(Arg0), 8180 MachinePointerInfo(Arg1), isStpcpy); 8181 if (Res.first.getNode()) { 8182 setValue(&I, Res.first); 8183 DAG.setRoot(Res.second); 8184 return true; 8185 } 8186 8187 return false; 8188 } 8189 8190 /// See if we can lower a strcmp call into an optimized form. If so, return 8191 /// true and lower it, otherwise return false and it will be lowered like a 8192 /// normal call. 8193 /// The caller already checked that \p I calls the appropriate LibFunc with a 8194 /// correct prototype. 8195 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8196 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8197 8198 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8199 std::pair<SDValue, SDValue> Res = 8200 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8201 getValue(Arg0), getValue(Arg1), 8202 MachinePointerInfo(Arg0), 8203 MachinePointerInfo(Arg1)); 8204 if (Res.first.getNode()) { 8205 processIntegerCallValue(I, Res.first, true); 8206 PendingLoads.push_back(Res.second); 8207 return true; 8208 } 8209 8210 return false; 8211 } 8212 8213 /// See if we can lower a strlen call into an optimized form. If so, return 8214 /// true and lower it, otherwise return false and it will be lowered like a 8215 /// normal call. 8216 /// The caller already checked that \p I calls the appropriate LibFunc with a 8217 /// correct prototype. 8218 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8219 const Value *Arg0 = I.getArgOperand(0); 8220 8221 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8222 std::pair<SDValue, SDValue> Res = 8223 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8224 getValue(Arg0), MachinePointerInfo(Arg0)); 8225 if (Res.first.getNode()) { 8226 processIntegerCallValue(I, Res.first, false); 8227 PendingLoads.push_back(Res.second); 8228 return true; 8229 } 8230 8231 return false; 8232 } 8233 8234 /// See if we can lower a strnlen call into an optimized form. If so, return 8235 /// true and lower it, otherwise return false and it will be lowered like a 8236 /// normal call. 8237 /// The caller already checked that \p I calls the appropriate LibFunc with a 8238 /// correct prototype. 8239 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8240 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8241 8242 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8243 std::pair<SDValue, SDValue> Res = 8244 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8245 getValue(Arg0), getValue(Arg1), 8246 MachinePointerInfo(Arg0)); 8247 if (Res.first.getNode()) { 8248 processIntegerCallValue(I, Res.first, false); 8249 PendingLoads.push_back(Res.second); 8250 return true; 8251 } 8252 8253 return false; 8254 } 8255 8256 /// See if we can lower a unary floating-point operation into an SDNode with 8257 /// the specified Opcode. If so, return true and lower it, otherwise return 8258 /// false and it will be lowered like a normal call. 8259 /// The caller already checked that \p I calls the appropriate LibFunc with a 8260 /// correct prototype. 8261 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8262 unsigned Opcode) { 8263 // We already checked this call's prototype; verify it doesn't modify errno. 8264 if (!I.onlyReadsMemory()) 8265 return false; 8266 8267 SDNodeFlags Flags; 8268 Flags.copyFMF(cast<FPMathOperator>(I)); 8269 8270 SDValue Tmp = getValue(I.getArgOperand(0)); 8271 setValue(&I, 8272 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8273 return true; 8274 } 8275 8276 /// See if we can lower a binary floating-point operation into an SDNode with 8277 /// the specified Opcode. If so, return true and lower it. Otherwise return 8278 /// false, and it will be lowered like a normal call. 8279 /// The caller already checked that \p I calls the appropriate LibFunc with a 8280 /// correct prototype. 8281 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8282 unsigned Opcode) { 8283 // We already checked this call's prototype; verify it doesn't modify errno. 8284 if (!I.onlyReadsMemory()) 8285 return false; 8286 8287 SDNodeFlags Flags; 8288 Flags.copyFMF(cast<FPMathOperator>(I)); 8289 8290 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8291 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8292 EVT VT = Tmp0.getValueType(); 8293 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8294 return true; 8295 } 8296 8297 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8298 // Handle inline assembly differently. 8299 if (I.isInlineAsm()) { 8300 visitInlineAsm(I); 8301 return; 8302 } 8303 8304 if (Function *F = I.getCalledFunction()) { 8305 diagnoseDontCall(I); 8306 8307 if (F->isDeclaration()) { 8308 // Is this an LLVM intrinsic or a target-specific intrinsic? 8309 unsigned IID = F->getIntrinsicID(); 8310 if (!IID) 8311 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8312 IID = II->getIntrinsicID(F); 8313 8314 if (IID) { 8315 visitIntrinsicCall(I, IID); 8316 return; 8317 } 8318 } 8319 8320 // Check for well-known libc/libm calls. If the function is internal, it 8321 // can't be a library call. Don't do the check if marked as nobuiltin for 8322 // some reason or the call site requires strict floating point semantics. 8323 LibFunc Func; 8324 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8325 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8326 LibInfo->hasOptimizedCodeGen(Func)) { 8327 switch (Func) { 8328 default: break; 8329 case LibFunc_bcmp: 8330 if (visitMemCmpBCmpCall(I)) 8331 return; 8332 break; 8333 case LibFunc_copysign: 8334 case LibFunc_copysignf: 8335 case LibFunc_copysignl: 8336 // We already checked this call's prototype; verify it doesn't modify 8337 // errno. 8338 if (I.onlyReadsMemory()) { 8339 SDValue LHS = getValue(I.getArgOperand(0)); 8340 SDValue RHS = getValue(I.getArgOperand(1)); 8341 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8342 LHS.getValueType(), LHS, RHS)); 8343 return; 8344 } 8345 break; 8346 case LibFunc_fabs: 8347 case LibFunc_fabsf: 8348 case LibFunc_fabsl: 8349 if (visitUnaryFloatCall(I, ISD::FABS)) 8350 return; 8351 break; 8352 case LibFunc_fmin: 8353 case LibFunc_fminf: 8354 case LibFunc_fminl: 8355 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8356 return; 8357 break; 8358 case LibFunc_fmax: 8359 case LibFunc_fmaxf: 8360 case LibFunc_fmaxl: 8361 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8362 return; 8363 break; 8364 case LibFunc_sin: 8365 case LibFunc_sinf: 8366 case LibFunc_sinl: 8367 if (visitUnaryFloatCall(I, ISD::FSIN)) 8368 return; 8369 break; 8370 case LibFunc_cos: 8371 case LibFunc_cosf: 8372 case LibFunc_cosl: 8373 if (visitUnaryFloatCall(I, ISD::FCOS)) 8374 return; 8375 break; 8376 case LibFunc_sqrt: 8377 case LibFunc_sqrtf: 8378 case LibFunc_sqrtl: 8379 case LibFunc_sqrt_finite: 8380 case LibFunc_sqrtf_finite: 8381 case LibFunc_sqrtl_finite: 8382 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8383 return; 8384 break; 8385 case LibFunc_floor: 8386 case LibFunc_floorf: 8387 case LibFunc_floorl: 8388 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8389 return; 8390 break; 8391 case LibFunc_nearbyint: 8392 case LibFunc_nearbyintf: 8393 case LibFunc_nearbyintl: 8394 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8395 return; 8396 break; 8397 case LibFunc_ceil: 8398 case LibFunc_ceilf: 8399 case LibFunc_ceill: 8400 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8401 return; 8402 break; 8403 case LibFunc_rint: 8404 case LibFunc_rintf: 8405 case LibFunc_rintl: 8406 if (visitUnaryFloatCall(I, ISD::FRINT)) 8407 return; 8408 break; 8409 case LibFunc_round: 8410 case LibFunc_roundf: 8411 case LibFunc_roundl: 8412 if (visitUnaryFloatCall(I, ISD::FROUND)) 8413 return; 8414 break; 8415 case LibFunc_trunc: 8416 case LibFunc_truncf: 8417 case LibFunc_truncl: 8418 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8419 return; 8420 break; 8421 case LibFunc_log2: 8422 case LibFunc_log2f: 8423 case LibFunc_log2l: 8424 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8425 return; 8426 break; 8427 case LibFunc_exp2: 8428 case LibFunc_exp2f: 8429 case LibFunc_exp2l: 8430 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8431 return; 8432 break; 8433 case LibFunc_memcmp: 8434 if (visitMemCmpBCmpCall(I)) 8435 return; 8436 break; 8437 case LibFunc_mempcpy: 8438 if (visitMemPCpyCall(I)) 8439 return; 8440 break; 8441 case LibFunc_memchr: 8442 if (visitMemChrCall(I)) 8443 return; 8444 break; 8445 case LibFunc_strcpy: 8446 if (visitStrCpyCall(I, false)) 8447 return; 8448 break; 8449 case LibFunc_stpcpy: 8450 if (visitStrCpyCall(I, true)) 8451 return; 8452 break; 8453 case LibFunc_strcmp: 8454 if (visitStrCmpCall(I)) 8455 return; 8456 break; 8457 case LibFunc_strlen: 8458 if (visitStrLenCall(I)) 8459 return; 8460 break; 8461 case LibFunc_strnlen: 8462 if (visitStrNLenCall(I)) 8463 return; 8464 break; 8465 } 8466 } 8467 } 8468 8469 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8470 // have to do anything here to lower funclet bundles. 8471 // CFGuardTarget bundles are lowered in LowerCallTo. 8472 assert(!I.hasOperandBundlesOtherThan( 8473 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8474 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8475 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8476 "Cannot lower calls with arbitrary operand bundles!"); 8477 8478 SDValue Callee = getValue(I.getCalledOperand()); 8479 8480 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8481 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8482 else 8483 // Check if we can potentially perform a tail call. More detailed checking 8484 // is be done within LowerCallTo, after more information about the call is 8485 // known. 8486 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8487 } 8488 8489 namespace { 8490 8491 /// AsmOperandInfo - This contains information for each constraint that we are 8492 /// lowering. 8493 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8494 public: 8495 /// CallOperand - If this is the result output operand or a clobber 8496 /// this is null, otherwise it is the incoming operand to the CallInst. 8497 /// This gets modified as the asm is processed. 8498 SDValue CallOperand; 8499 8500 /// AssignedRegs - If this is a register or register class operand, this 8501 /// contains the set of register corresponding to the operand. 8502 RegsForValue AssignedRegs; 8503 8504 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8505 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8506 } 8507 8508 /// Whether or not this operand accesses memory 8509 bool hasMemory(const TargetLowering &TLI) const { 8510 // Indirect operand accesses access memory. 8511 if (isIndirect) 8512 return true; 8513 8514 for (const auto &Code : Codes) 8515 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8516 return true; 8517 8518 return false; 8519 } 8520 }; 8521 8522 8523 } // end anonymous namespace 8524 8525 /// Make sure that the output operand \p OpInfo and its corresponding input 8526 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8527 /// out). 8528 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8529 SDISelAsmOperandInfo &MatchingOpInfo, 8530 SelectionDAG &DAG) { 8531 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8532 return; 8533 8534 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8535 const auto &TLI = DAG.getTargetLoweringInfo(); 8536 8537 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8538 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8539 OpInfo.ConstraintVT); 8540 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8541 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8542 MatchingOpInfo.ConstraintVT); 8543 if ((OpInfo.ConstraintVT.isInteger() != 8544 MatchingOpInfo.ConstraintVT.isInteger()) || 8545 (MatchRC.second != InputRC.second)) { 8546 // FIXME: error out in a more elegant fashion 8547 report_fatal_error("Unsupported asm: input constraint" 8548 " with a matching output constraint of" 8549 " incompatible type!"); 8550 } 8551 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8552 } 8553 8554 /// Get a direct memory input to behave well as an indirect operand. 8555 /// This may introduce stores, hence the need for a \p Chain. 8556 /// \return The (possibly updated) chain. 8557 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8558 SDISelAsmOperandInfo &OpInfo, 8559 SelectionDAG &DAG) { 8560 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8561 8562 // If we don't have an indirect input, put it in the constpool if we can, 8563 // otherwise spill it to a stack slot. 8564 // TODO: This isn't quite right. We need to handle these according to 8565 // the addressing mode that the constraint wants. Also, this may take 8566 // an additional register for the computation and we don't want that 8567 // either. 8568 8569 // If the operand is a float, integer, or vector constant, spill to a 8570 // constant pool entry to get its address. 8571 const Value *OpVal = OpInfo.CallOperandVal; 8572 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8573 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8574 OpInfo.CallOperand = DAG.getConstantPool( 8575 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8576 return Chain; 8577 } 8578 8579 // Otherwise, create a stack slot and emit a store to it before the asm. 8580 Type *Ty = OpVal->getType(); 8581 auto &DL = DAG.getDataLayout(); 8582 uint64_t TySize = DL.getTypeAllocSize(Ty); 8583 MachineFunction &MF = DAG.getMachineFunction(); 8584 int SSFI = MF.getFrameInfo().CreateStackObject( 8585 TySize, DL.getPrefTypeAlign(Ty), false); 8586 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8587 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8588 MachinePointerInfo::getFixedStack(MF, SSFI), 8589 TLI.getMemValueType(DL, Ty)); 8590 OpInfo.CallOperand = StackSlot; 8591 8592 return Chain; 8593 } 8594 8595 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8596 /// specified operand. We prefer to assign virtual registers, to allow the 8597 /// register allocator to handle the assignment process. However, if the asm 8598 /// uses features that we can't model on machineinstrs, we have SDISel do the 8599 /// allocation. This produces generally horrible, but correct, code. 8600 /// 8601 /// OpInfo describes the operand 8602 /// RefOpInfo describes the matching operand if any, the operand otherwise 8603 static std::optional<unsigned> 8604 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8605 SDISelAsmOperandInfo &OpInfo, 8606 SDISelAsmOperandInfo &RefOpInfo) { 8607 LLVMContext &Context = *DAG.getContext(); 8608 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8609 8610 MachineFunction &MF = DAG.getMachineFunction(); 8611 SmallVector<unsigned, 4> Regs; 8612 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8613 8614 // No work to do for memory/address operands. 8615 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8616 OpInfo.ConstraintType == TargetLowering::C_Address) 8617 return std::nullopt; 8618 8619 // If this is a constraint for a single physreg, or a constraint for a 8620 // register class, find it. 8621 unsigned AssignedReg; 8622 const TargetRegisterClass *RC; 8623 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8624 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8625 // RC is unset only on failure. Return immediately. 8626 if (!RC) 8627 return std::nullopt; 8628 8629 // Get the actual register value type. This is important, because the user 8630 // may have asked for (e.g.) the AX register in i32 type. We need to 8631 // remember that AX is actually i16 to get the right extension. 8632 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8633 8634 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8635 // If this is an FP operand in an integer register (or visa versa), or more 8636 // generally if the operand value disagrees with the register class we plan 8637 // to stick it in, fix the operand type. 8638 // 8639 // If this is an input value, the bitcast to the new type is done now. 8640 // Bitcast for output value is done at the end of visitInlineAsm(). 8641 if ((OpInfo.Type == InlineAsm::isOutput || 8642 OpInfo.Type == InlineAsm::isInput) && 8643 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8644 // Try to convert to the first EVT that the reg class contains. If the 8645 // types are identical size, use a bitcast to convert (e.g. two differing 8646 // vector types). Note: output bitcast is done at the end of 8647 // visitInlineAsm(). 8648 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8649 // Exclude indirect inputs while they are unsupported because the code 8650 // to perform the load is missing and thus OpInfo.CallOperand still 8651 // refers to the input address rather than the pointed-to value. 8652 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8653 OpInfo.CallOperand = 8654 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8655 OpInfo.ConstraintVT = RegVT; 8656 // If the operand is an FP value and we want it in integer registers, 8657 // use the corresponding integer type. This turns an f64 value into 8658 // i64, which can be passed with two i32 values on a 32-bit machine. 8659 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8660 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8661 if (OpInfo.Type == InlineAsm::isInput) 8662 OpInfo.CallOperand = 8663 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8664 OpInfo.ConstraintVT = VT; 8665 } 8666 } 8667 } 8668 8669 // No need to allocate a matching input constraint since the constraint it's 8670 // matching to has already been allocated. 8671 if (OpInfo.isMatchingInputConstraint()) 8672 return std::nullopt; 8673 8674 EVT ValueVT = OpInfo.ConstraintVT; 8675 if (OpInfo.ConstraintVT == MVT::Other) 8676 ValueVT = RegVT; 8677 8678 // Initialize NumRegs. 8679 unsigned NumRegs = 1; 8680 if (OpInfo.ConstraintVT != MVT::Other) 8681 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8682 8683 // If this is a constraint for a specific physical register, like {r17}, 8684 // assign it now. 8685 8686 // If this associated to a specific register, initialize iterator to correct 8687 // place. If virtual, make sure we have enough registers 8688 8689 // Initialize iterator if necessary 8690 TargetRegisterClass::iterator I = RC->begin(); 8691 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8692 8693 // Do not check for single registers. 8694 if (AssignedReg) { 8695 I = std::find(I, RC->end(), AssignedReg); 8696 if (I == RC->end()) { 8697 // RC does not contain the selected register, which indicates a 8698 // mismatch between the register and the required type/bitwidth. 8699 return {AssignedReg}; 8700 } 8701 } 8702 8703 for (; NumRegs; --NumRegs, ++I) { 8704 assert(I != RC->end() && "Ran out of registers to allocate!"); 8705 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8706 Regs.push_back(R); 8707 } 8708 8709 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8710 return std::nullopt; 8711 } 8712 8713 static unsigned 8714 findMatchingInlineAsmOperand(unsigned OperandNo, 8715 const std::vector<SDValue> &AsmNodeOperands) { 8716 // Scan until we find the definition we already emitted of this operand. 8717 unsigned CurOp = InlineAsm::Op_FirstOperand; 8718 for (; OperandNo; --OperandNo) { 8719 // Advance to the next operand. 8720 unsigned OpFlag = 8721 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8722 assert((InlineAsm::isRegDefKind(OpFlag) || 8723 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8724 InlineAsm::isMemKind(OpFlag)) && 8725 "Skipped past definitions?"); 8726 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8727 } 8728 return CurOp; 8729 } 8730 8731 namespace { 8732 8733 class ExtraFlags { 8734 unsigned Flags = 0; 8735 8736 public: 8737 explicit ExtraFlags(const CallBase &Call) { 8738 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8739 if (IA->hasSideEffects()) 8740 Flags |= InlineAsm::Extra_HasSideEffects; 8741 if (IA->isAlignStack()) 8742 Flags |= InlineAsm::Extra_IsAlignStack; 8743 if (Call.isConvergent()) 8744 Flags |= InlineAsm::Extra_IsConvergent; 8745 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8746 } 8747 8748 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8749 // Ideally, we would only check against memory constraints. However, the 8750 // meaning of an Other constraint can be target-specific and we can't easily 8751 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8752 // for Other constraints as well. 8753 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8754 OpInfo.ConstraintType == TargetLowering::C_Other) { 8755 if (OpInfo.Type == InlineAsm::isInput) 8756 Flags |= InlineAsm::Extra_MayLoad; 8757 else if (OpInfo.Type == InlineAsm::isOutput) 8758 Flags |= InlineAsm::Extra_MayStore; 8759 else if (OpInfo.Type == InlineAsm::isClobber) 8760 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8761 } 8762 } 8763 8764 unsigned get() const { return Flags; } 8765 }; 8766 8767 } // end anonymous namespace 8768 8769 static bool isFunction(SDValue Op) { 8770 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 8771 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8772 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 8773 8774 // In normal "call dllimport func" instruction (non-inlineasm) it force 8775 // indirect access by specifing call opcode. And usually specially print 8776 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 8777 // not do in this way now. (In fact, this is similar with "Data Access" 8778 // action). So here we ignore dllimport function. 8779 if (Fn && !Fn->hasDLLImportStorageClass()) 8780 return true; 8781 } 8782 } 8783 return false; 8784 } 8785 8786 /// visitInlineAsm - Handle a call to an InlineAsm object. 8787 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8788 const BasicBlock *EHPadBB) { 8789 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8790 8791 /// ConstraintOperands - Information about all of the constraints. 8792 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8793 8794 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8795 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8796 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8797 8798 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8799 // AsmDialect, MayLoad, MayStore). 8800 bool HasSideEffect = IA->hasSideEffects(); 8801 ExtraFlags ExtraInfo(Call); 8802 8803 for (auto &T : TargetConstraints) { 8804 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8805 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8806 8807 if (OpInfo.CallOperandVal) 8808 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8809 8810 if (!HasSideEffect) 8811 HasSideEffect = OpInfo.hasMemory(TLI); 8812 8813 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8814 // FIXME: Could we compute this on OpInfo rather than T? 8815 8816 // Compute the constraint code and ConstraintType to use. 8817 TLI.ComputeConstraintToUse(T, SDValue()); 8818 8819 if (T.ConstraintType == TargetLowering::C_Immediate && 8820 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8821 // We've delayed emitting a diagnostic like the "n" constraint because 8822 // inlining could cause an integer showing up. 8823 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8824 "' expects an integer constant " 8825 "expression"); 8826 8827 ExtraInfo.update(T); 8828 } 8829 8830 // We won't need to flush pending loads if this asm doesn't touch 8831 // memory and is nonvolatile. 8832 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8833 8834 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8835 if (EmitEHLabels) { 8836 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8837 } 8838 bool IsCallBr = isa<CallBrInst>(Call); 8839 8840 if (IsCallBr || EmitEHLabels) { 8841 // If this is a callbr or invoke we need to flush pending exports since 8842 // inlineasm_br and invoke are terminators. 8843 // We need to do this before nodes are glued to the inlineasm_br node. 8844 Chain = getControlRoot(); 8845 } 8846 8847 MCSymbol *BeginLabel = nullptr; 8848 if (EmitEHLabels) { 8849 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8850 } 8851 8852 int OpNo = -1; 8853 SmallVector<StringRef> AsmStrs; 8854 IA->collectAsmStrs(AsmStrs); 8855 8856 // Second pass over the constraints: compute which constraint option to use. 8857 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8858 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 8859 OpNo++; 8860 8861 // If this is an output operand with a matching input operand, look up the 8862 // matching input. If their types mismatch, e.g. one is an integer, the 8863 // other is floating point, or their sizes are different, flag it as an 8864 // error. 8865 if (OpInfo.hasMatchingInput()) { 8866 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8867 patchMatchingInput(OpInfo, Input, DAG); 8868 } 8869 8870 // Compute the constraint code and ConstraintType to use. 8871 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8872 8873 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 8874 OpInfo.Type == InlineAsm::isClobber) || 8875 OpInfo.ConstraintType == TargetLowering::C_Address) 8876 continue; 8877 8878 // In Linux PIC model, there are 4 cases about value/label addressing: 8879 // 8880 // 1: Function call or Label jmp inside the module. 8881 // 2: Data access (such as global variable, static variable) inside module. 8882 // 3: Function call or Label jmp outside the module. 8883 // 4: Data access (such as global variable) outside the module. 8884 // 8885 // Due to current llvm inline asm architecture designed to not "recognize" 8886 // the asm code, there are quite troubles for us to treat mem addressing 8887 // differently for same value/adress used in different instuctions. 8888 // For example, in pic model, call a func may in plt way or direclty 8889 // pc-related, but lea/mov a function adress may use got. 8890 // 8891 // Here we try to "recognize" function call for the case 1 and case 3 in 8892 // inline asm. And try to adjust the constraint for them. 8893 // 8894 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 8895 // label, so here we don't handle jmp function label now, but we need to 8896 // enhance it (especilly in PIC model) if we meet meaningful requirements. 8897 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 8898 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 8899 TM.getCodeModel() != CodeModel::Large) { 8900 OpInfo.isIndirect = false; 8901 OpInfo.ConstraintType = TargetLowering::C_Address; 8902 } 8903 8904 // If this is a memory input, and if the operand is not indirect, do what we 8905 // need to provide an address for the memory input. 8906 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8907 !OpInfo.isIndirect) { 8908 assert((OpInfo.isMultipleAlternative || 8909 (OpInfo.Type == InlineAsm::isInput)) && 8910 "Can only indirectify direct input operands!"); 8911 8912 // Memory operands really want the address of the value. 8913 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8914 8915 // There is no longer a Value* corresponding to this operand. 8916 OpInfo.CallOperandVal = nullptr; 8917 8918 // It is now an indirect operand. 8919 OpInfo.isIndirect = true; 8920 } 8921 8922 } 8923 8924 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8925 std::vector<SDValue> AsmNodeOperands; 8926 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8927 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8928 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8929 8930 // If we have a !srcloc metadata node associated with it, we want to attach 8931 // this to the ultimately generated inline asm machineinstr. To do this, we 8932 // pass in the third operand as this (potentially null) inline asm MDNode. 8933 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8934 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8935 8936 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8937 // bits as operand 3. 8938 AsmNodeOperands.push_back(DAG.getTargetConstant( 8939 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8940 8941 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8942 // this, assign virtual and physical registers for inputs and otput. 8943 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8944 // Assign Registers. 8945 SDISelAsmOperandInfo &RefOpInfo = 8946 OpInfo.isMatchingInputConstraint() 8947 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8948 : OpInfo; 8949 const auto RegError = 8950 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8951 if (RegError) { 8952 const MachineFunction &MF = DAG.getMachineFunction(); 8953 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8954 const char *RegName = TRI.getName(RegError.value()); 8955 emitInlineAsmError(Call, "register '" + Twine(RegName) + 8956 "' allocated for constraint '" + 8957 Twine(OpInfo.ConstraintCode) + 8958 "' does not match required type"); 8959 return; 8960 } 8961 8962 auto DetectWriteToReservedRegister = [&]() { 8963 const MachineFunction &MF = DAG.getMachineFunction(); 8964 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8965 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8966 if (Register::isPhysicalRegister(Reg) && 8967 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8968 const char *RegName = TRI.getName(Reg); 8969 emitInlineAsmError(Call, "write to reserved register '" + 8970 Twine(RegName) + "'"); 8971 return true; 8972 } 8973 } 8974 return false; 8975 }; 8976 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 8977 (OpInfo.Type == InlineAsm::isInput && 8978 !OpInfo.isMatchingInputConstraint())) && 8979 "Only address as input operand is allowed."); 8980 8981 switch (OpInfo.Type) { 8982 case InlineAsm::isOutput: 8983 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8984 unsigned ConstraintID = 8985 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8986 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8987 "Failed to convert memory constraint code to constraint id."); 8988 8989 // Add information to the INLINEASM node to know about this output. 8990 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8991 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8992 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8993 MVT::i32)); 8994 AsmNodeOperands.push_back(OpInfo.CallOperand); 8995 } else { 8996 // Otherwise, this outputs to a register (directly for C_Register / 8997 // C_RegisterClass, and a target-defined fashion for 8998 // C_Immediate/C_Other). Find a register that we can use. 8999 if (OpInfo.AssignedRegs.Regs.empty()) { 9000 emitInlineAsmError( 9001 Call, "couldn't allocate output register for constraint '" + 9002 Twine(OpInfo.ConstraintCode) + "'"); 9003 return; 9004 } 9005 9006 if (DetectWriteToReservedRegister()) 9007 return; 9008 9009 // Add information to the INLINEASM node to know that this register is 9010 // set. 9011 OpInfo.AssignedRegs.AddInlineAsmOperands( 9012 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 9013 : InlineAsm::Kind_RegDef, 9014 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9015 } 9016 break; 9017 9018 case InlineAsm::isInput: 9019 case InlineAsm::isLabel: { 9020 SDValue InOperandVal = OpInfo.CallOperand; 9021 9022 if (OpInfo.isMatchingInputConstraint()) { 9023 // If this is required to match an output register we have already set, 9024 // just use its register. 9025 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9026 AsmNodeOperands); 9027 unsigned OpFlag = 9028 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9029 if (InlineAsm::isRegDefKind(OpFlag) || 9030 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9031 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9032 if (OpInfo.isIndirect) { 9033 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9034 emitInlineAsmError(Call, "inline asm not supported yet: " 9035 "don't know how to handle tied " 9036 "indirect register inputs"); 9037 return; 9038 } 9039 9040 SmallVector<unsigned, 4> Regs; 9041 MachineFunction &MF = DAG.getMachineFunction(); 9042 MachineRegisterInfo &MRI = MF.getRegInfo(); 9043 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9044 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9045 Register TiedReg = R->getReg(); 9046 MVT RegVT = R->getSimpleValueType(0); 9047 const TargetRegisterClass *RC = 9048 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9049 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9050 : TRI.getMinimalPhysRegClass(TiedReg); 9051 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9052 for (unsigned i = 0; i != NumRegs; ++i) 9053 Regs.push_back(MRI.createVirtualRegister(RC)); 9054 9055 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9056 9057 SDLoc dl = getCurSDLoc(); 9058 // Use the produced MatchedRegs object to 9059 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 9060 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9061 true, OpInfo.getMatchedOperand(), dl, 9062 DAG, AsmNodeOperands); 9063 break; 9064 } 9065 9066 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9067 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9068 "Unexpected number of operands"); 9069 // Add information to the INLINEASM node to know about this input. 9070 // See InlineAsm.h isUseOperandTiedToDef. 9071 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9072 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9073 OpInfo.getMatchedOperand()); 9074 AsmNodeOperands.push_back(DAG.getTargetConstant( 9075 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9076 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9077 break; 9078 } 9079 9080 // Treat indirect 'X' constraint as memory. 9081 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9082 OpInfo.isIndirect) 9083 OpInfo.ConstraintType = TargetLowering::C_Memory; 9084 9085 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9086 OpInfo.ConstraintType == TargetLowering::C_Other) { 9087 std::vector<SDValue> Ops; 9088 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9089 Ops, DAG); 9090 if (Ops.empty()) { 9091 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9092 if (isa<ConstantSDNode>(InOperandVal)) { 9093 emitInlineAsmError(Call, "value out of range for constraint '" + 9094 Twine(OpInfo.ConstraintCode) + "'"); 9095 return; 9096 } 9097 9098 emitInlineAsmError(Call, 9099 "invalid operand for inline asm constraint '" + 9100 Twine(OpInfo.ConstraintCode) + "'"); 9101 return; 9102 } 9103 9104 // Add information to the INLINEASM node to know about this input. 9105 unsigned ResOpType = 9106 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9107 AsmNodeOperands.push_back(DAG.getTargetConstant( 9108 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9109 llvm::append_range(AsmNodeOperands, Ops); 9110 break; 9111 } 9112 9113 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9114 assert((OpInfo.isIndirect || 9115 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9116 "Operand must be indirect to be a mem!"); 9117 assert(InOperandVal.getValueType() == 9118 TLI.getPointerTy(DAG.getDataLayout()) && 9119 "Memory operands expect pointer values"); 9120 9121 unsigned ConstraintID = 9122 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9123 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9124 "Failed to convert memory constraint code to constraint id."); 9125 9126 // Add information to the INLINEASM node to know about this input. 9127 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9128 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9129 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9130 getCurSDLoc(), 9131 MVT::i32)); 9132 AsmNodeOperands.push_back(InOperandVal); 9133 break; 9134 } 9135 9136 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9137 assert(InOperandVal.getValueType() == 9138 TLI.getPointerTy(DAG.getDataLayout()) && 9139 "Address operands expect pointer values"); 9140 9141 unsigned ConstraintID = 9142 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9143 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9144 "Failed to convert memory constraint code to constraint id."); 9145 9146 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9147 9148 SDValue AsmOp = InOperandVal; 9149 if (isFunction(InOperandVal)) { 9150 auto *GA = dyn_cast<GlobalAddressSDNode>(InOperandVal); 9151 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9152 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9153 InOperandVal.getValueType(), 9154 GA->getOffset()); 9155 } 9156 9157 // Add information to the INLINEASM node to know about this input. 9158 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9159 9160 AsmNodeOperands.push_back( 9161 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9162 9163 AsmNodeOperands.push_back(AsmOp); 9164 break; 9165 } 9166 9167 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9168 OpInfo.ConstraintType == TargetLowering::C_Register) && 9169 "Unknown constraint type!"); 9170 9171 // TODO: Support this. 9172 if (OpInfo.isIndirect) { 9173 emitInlineAsmError( 9174 Call, "Don't know how to handle indirect register inputs yet " 9175 "for constraint '" + 9176 Twine(OpInfo.ConstraintCode) + "'"); 9177 return; 9178 } 9179 9180 // Copy the input into the appropriate registers. 9181 if (OpInfo.AssignedRegs.Regs.empty()) { 9182 emitInlineAsmError(Call, 9183 "couldn't allocate input reg for constraint '" + 9184 Twine(OpInfo.ConstraintCode) + "'"); 9185 return; 9186 } 9187 9188 if (DetectWriteToReservedRegister()) 9189 return; 9190 9191 SDLoc dl = getCurSDLoc(); 9192 9193 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 9194 &Call); 9195 9196 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9197 dl, DAG, AsmNodeOperands); 9198 break; 9199 } 9200 case InlineAsm::isClobber: 9201 // Add the clobbered value to the operand list, so that the register 9202 // allocator is aware that the physreg got clobbered. 9203 if (!OpInfo.AssignedRegs.Regs.empty()) 9204 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9205 false, 0, getCurSDLoc(), DAG, 9206 AsmNodeOperands); 9207 break; 9208 } 9209 } 9210 9211 // Finish up input operands. Set the input chain and add the flag last. 9212 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9213 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 9214 9215 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9216 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9217 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9218 Flag = Chain.getValue(1); 9219 9220 // Do additional work to generate outputs. 9221 9222 SmallVector<EVT, 1> ResultVTs; 9223 SmallVector<SDValue, 1> ResultValues; 9224 SmallVector<SDValue, 8> OutChains; 9225 9226 llvm::Type *CallResultType = Call.getType(); 9227 ArrayRef<Type *> ResultTypes; 9228 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9229 ResultTypes = StructResult->elements(); 9230 else if (!CallResultType->isVoidTy()) 9231 ResultTypes = makeArrayRef(CallResultType); 9232 9233 auto CurResultType = ResultTypes.begin(); 9234 auto handleRegAssign = [&](SDValue V) { 9235 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9236 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9237 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9238 ++CurResultType; 9239 // If the type of the inline asm call site return value is different but has 9240 // same size as the type of the asm output bitcast it. One example of this 9241 // is for vectors with different width / number of elements. This can 9242 // happen for register classes that can contain multiple different value 9243 // types. The preg or vreg allocated may not have the same VT as was 9244 // expected. 9245 // 9246 // This can also happen for a return value that disagrees with the register 9247 // class it is put in, eg. a double in a general-purpose register on a 9248 // 32-bit machine. 9249 if (ResultVT != V.getValueType() && 9250 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9251 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9252 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9253 V.getValueType().isInteger()) { 9254 // If a result value was tied to an input value, the computed result 9255 // may have a wider width than the expected result. Extract the 9256 // relevant portion. 9257 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9258 } 9259 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9260 ResultVTs.push_back(ResultVT); 9261 ResultValues.push_back(V); 9262 }; 9263 9264 // Deal with output operands. 9265 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9266 if (OpInfo.Type == InlineAsm::isOutput) { 9267 SDValue Val; 9268 // Skip trivial output operands. 9269 if (OpInfo.AssignedRegs.Regs.empty()) 9270 continue; 9271 9272 switch (OpInfo.ConstraintType) { 9273 case TargetLowering::C_Register: 9274 case TargetLowering::C_RegisterClass: 9275 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9276 Chain, &Flag, &Call); 9277 break; 9278 case TargetLowering::C_Immediate: 9279 case TargetLowering::C_Other: 9280 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 9281 OpInfo, DAG); 9282 break; 9283 case TargetLowering::C_Memory: 9284 break; // Already handled. 9285 case TargetLowering::C_Address: 9286 break; // Silence warning. 9287 case TargetLowering::C_Unknown: 9288 assert(false && "Unexpected unknown constraint"); 9289 } 9290 9291 // Indirect output manifest as stores. Record output chains. 9292 if (OpInfo.isIndirect) { 9293 const Value *Ptr = OpInfo.CallOperandVal; 9294 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9295 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9296 MachinePointerInfo(Ptr)); 9297 OutChains.push_back(Store); 9298 } else { 9299 // generate CopyFromRegs to associated registers. 9300 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9301 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9302 for (const SDValue &V : Val->op_values()) 9303 handleRegAssign(V); 9304 } else 9305 handleRegAssign(Val); 9306 } 9307 } 9308 } 9309 9310 // Set results. 9311 if (!ResultValues.empty()) { 9312 assert(CurResultType == ResultTypes.end() && 9313 "Mismatch in number of ResultTypes"); 9314 assert(ResultValues.size() == ResultTypes.size() && 9315 "Mismatch in number of output operands in asm result"); 9316 9317 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9318 DAG.getVTList(ResultVTs), ResultValues); 9319 setValue(&Call, V); 9320 } 9321 9322 // Collect store chains. 9323 if (!OutChains.empty()) 9324 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9325 9326 if (EmitEHLabels) { 9327 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9328 } 9329 9330 // Only Update Root if inline assembly has a memory effect. 9331 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9332 EmitEHLabels) 9333 DAG.setRoot(Chain); 9334 } 9335 9336 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9337 const Twine &Message) { 9338 LLVMContext &Ctx = *DAG.getContext(); 9339 Ctx.emitError(&Call, Message); 9340 9341 // Make sure we leave the DAG in a valid state 9342 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9343 SmallVector<EVT, 1> ValueVTs; 9344 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9345 9346 if (ValueVTs.empty()) 9347 return; 9348 9349 SmallVector<SDValue, 1> Ops; 9350 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9351 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9352 9353 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9354 } 9355 9356 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9357 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9358 MVT::Other, getRoot(), 9359 getValue(I.getArgOperand(0)), 9360 DAG.getSrcValue(I.getArgOperand(0)))); 9361 } 9362 9363 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9364 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9365 const DataLayout &DL = DAG.getDataLayout(); 9366 SDValue V = DAG.getVAArg( 9367 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9368 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9369 DL.getABITypeAlign(I.getType()).value()); 9370 DAG.setRoot(V.getValue(1)); 9371 9372 if (I.getType()->isPointerTy()) 9373 V = DAG.getPtrExtOrTrunc( 9374 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9375 setValue(&I, V); 9376 } 9377 9378 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9379 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9380 MVT::Other, getRoot(), 9381 getValue(I.getArgOperand(0)), 9382 DAG.getSrcValue(I.getArgOperand(0)))); 9383 } 9384 9385 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9386 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9387 MVT::Other, getRoot(), 9388 getValue(I.getArgOperand(0)), 9389 getValue(I.getArgOperand(1)), 9390 DAG.getSrcValue(I.getArgOperand(0)), 9391 DAG.getSrcValue(I.getArgOperand(1)))); 9392 } 9393 9394 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9395 const Instruction &I, 9396 SDValue Op) { 9397 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9398 if (!Range) 9399 return Op; 9400 9401 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9402 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9403 return Op; 9404 9405 APInt Lo = CR.getUnsignedMin(); 9406 if (!Lo.isMinValue()) 9407 return Op; 9408 9409 APInt Hi = CR.getUnsignedMax(); 9410 unsigned Bits = std::max(Hi.getActiveBits(), 9411 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9412 9413 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9414 9415 SDLoc SL = getCurSDLoc(); 9416 9417 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9418 DAG.getValueType(SmallVT)); 9419 unsigned NumVals = Op.getNode()->getNumValues(); 9420 if (NumVals == 1) 9421 return ZExt; 9422 9423 SmallVector<SDValue, 4> Ops; 9424 9425 Ops.push_back(ZExt); 9426 for (unsigned I = 1; I != NumVals; ++I) 9427 Ops.push_back(Op.getValue(I)); 9428 9429 return DAG.getMergeValues(Ops, SL); 9430 } 9431 9432 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9433 /// the call being lowered. 9434 /// 9435 /// This is a helper for lowering intrinsics that follow a target calling 9436 /// convention or require stack pointer adjustment. Only a subset of the 9437 /// intrinsic's operands need to participate in the calling convention. 9438 void SelectionDAGBuilder::populateCallLoweringInfo( 9439 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9440 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9441 bool IsPatchPoint) { 9442 TargetLowering::ArgListTy Args; 9443 Args.reserve(NumArgs); 9444 9445 // Populate the argument list. 9446 // Attributes for args start at offset 1, after the return attribute. 9447 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9448 ArgI != ArgE; ++ArgI) { 9449 const Value *V = Call->getOperand(ArgI); 9450 9451 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9452 9453 TargetLowering::ArgListEntry Entry; 9454 Entry.Node = getValue(V); 9455 Entry.Ty = V->getType(); 9456 Entry.setAttributes(Call, ArgI); 9457 Args.push_back(Entry); 9458 } 9459 9460 CLI.setDebugLoc(getCurSDLoc()) 9461 .setChain(getRoot()) 9462 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9463 .setDiscardResult(Call->use_empty()) 9464 .setIsPatchPoint(IsPatchPoint) 9465 .setIsPreallocated( 9466 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9467 } 9468 9469 /// Add a stack map intrinsic call's live variable operands to a stackmap 9470 /// or patchpoint target node's operand list. 9471 /// 9472 /// Constants are converted to TargetConstants purely as an optimization to 9473 /// avoid constant materialization and register allocation. 9474 /// 9475 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9476 /// generate addess computation nodes, and so FinalizeISel can convert the 9477 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9478 /// address materialization and register allocation, but may also be required 9479 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9480 /// alloca in the entry block, then the runtime may assume that the alloca's 9481 /// StackMap location can be read immediately after compilation and that the 9482 /// location is valid at any point during execution (this is similar to the 9483 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9484 /// only available in a register, then the runtime would need to trap when 9485 /// execution reaches the StackMap in order to read the alloca's location. 9486 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9487 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9488 SelectionDAGBuilder &Builder) { 9489 SelectionDAG &DAG = Builder.DAG; 9490 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9491 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9492 9493 // Things on the stack are pointer-typed, meaning that they are already 9494 // legal and can be emitted directly to target nodes. 9495 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9496 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9497 } else { 9498 // Otherwise emit a target independent node to be legalised. 9499 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9500 } 9501 } 9502 } 9503 9504 /// Lower llvm.experimental.stackmap. 9505 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9506 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9507 // [live variables...]) 9508 9509 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9510 9511 SDValue Chain, InFlag, Callee; 9512 SmallVector<SDValue, 32> Ops; 9513 9514 SDLoc DL = getCurSDLoc(); 9515 Callee = getValue(CI.getCalledOperand()); 9516 9517 // The stackmap intrinsic only records the live variables (the arguments 9518 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9519 // intrinsic, this won't be lowered to a function call. This means we don't 9520 // have to worry about calling conventions and target specific lowering code. 9521 // Instead we perform the call lowering right here. 9522 // 9523 // chain, flag = CALLSEQ_START(chain, 0, 0) 9524 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9525 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9526 // 9527 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9528 InFlag = Chain.getValue(1); 9529 9530 // Add the STACKMAP operands, starting with DAG house-keeping. 9531 Ops.push_back(Chain); 9532 Ops.push_back(InFlag); 9533 9534 // Add the <id>, <numShadowBytes> operands. 9535 // 9536 // These do not require legalisation, and can be emitted directly to target 9537 // constant nodes. 9538 SDValue ID = getValue(CI.getArgOperand(0)); 9539 assert(ID.getValueType() == MVT::i64); 9540 SDValue IDConst = DAG.getTargetConstant( 9541 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9542 Ops.push_back(IDConst); 9543 9544 SDValue Shad = getValue(CI.getArgOperand(1)); 9545 assert(Shad.getValueType() == MVT::i32); 9546 SDValue ShadConst = DAG.getTargetConstant( 9547 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9548 Ops.push_back(ShadConst); 9549 9550 // Add the live variables. 9551 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9552 9553 // Create the STACKMAP node. 9554 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9555 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9556 InFlag = Chain.getValue(1); 9557 9558 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL); 9559 9560 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9561 9562 // Set the root to the target-lowered call chain. 9563 DAG.setRoot(Chain); 9564 9565 // Inform the Frame Information that we have a stackmap in this function. 9566 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9567 } 9568 9569 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9570 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9571 const BasicBlock *EHPadBB) { 9572 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9573 // i32 <numBytes>, 9574 // i8* <target>, 9575 // i32 <numArgs>, 9576 // [Args...], 9577 // [live variables...]) 9578 9579 CallingConv::ID CC = CB.getCallingConv(); 9580 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9581 bool HasDef = !CB.getType()->isVoidTy(); 9582 SDLoc dl = getCurSDLoc(); 9583 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9584 9585 // Handle immediate and symbolic callees. 9586 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9587 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9588 /*isTarget=*/true); 9589 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9590 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9591 SDLoc(SymbolicCallee), 9592 SymbolicCallee->getValueType(0)); 9593 9594 // Get the real number of arguments participating in the call <numArgs> 9595 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9596 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9597 9598 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9599 // Intrinsics include all meta-operands up to but not including CC. 9600 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9601 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9602 "Not enough arguments provided to the patchpoint intrinsic"); 9603 9604 // For AnyRegCC the arguments are lowered later on manually. 9605 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9606 Type *ReturnTy = 9607 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9608 9609 TargetLowering::CallLoweringInfo CLI(DAG); 9610 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9611 ReturnTy, true); 9612 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9613 9614 SDNode *CallEnd = Result.second.getNode(); 9615 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9616 CallEnd = CallEnd->getOperand(0).getNode(); 9617 9618 /// Get a call instruction from the call sequence chain. 9619 /// Tail calls are not allowed. 9620 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9621 "Expected a callseq node."); 9622 SDNode *Call = CallEnd->getOperand(0).getNode(); 9623 bool HasGlue = Call->getGluedNode(); 9624 9625 // Replace the target specific call node with the patchable intrinsic. 9626 SmallVector<SDValue, 8> Ops; 9627 9628 // Push the chain. 9629 Ops.push_back(*(Call->op_begin())); 9630 9631 // Optionally, push the glue (if any). 9632 if (HasGlue) 9633 Ops.push_back(*(Call->op_end() - 1)); 9634 9635 // Push the register mask info. 9636 if (HasGlue) 9637 Ops.push_back(*(Call->op_end() - 2)); 9638 else 9639 Ops.push_back(*(Call->op_end() - 1)); 9640 9641 // Add the <id> and <numBytes> constants. 9642 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9643 Ops.push_back(DAG.getTargetConstant( 9644 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9645 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9646 Ops.push_back(DAG.getTargetConstant( 9647 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9648 MVT::i32)); 9649 9650 // Add the callee. 9651 Ops.push_back(Callee); 9652 9653 // Adjust <numArgs> to account for any arguments that have been passed on the 9654 // stack instead. 9655 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9656 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9657 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9658 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9659 9660 // Add the calling convention 9661 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9662 9663 // Add the arguments we omitted previously. The register allocator should 9664 // place these in any free register. 9665 if (IsAnyRegCC) 9666 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9667 Ops.push_back(getValue(CB.getArgOperand(i))); 9668 9669 // Push the arguments from the call instruction. 9670 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9671 Ops.append(Call->op_begin() + 2, e); 9672 9673 // Push live variables for the stack map. 9674 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9675 9676 SDVTList NodeTys; 9677 if (IsAnyRegCC && HasDef) { 9678 // Create the return types based on the intrinsic definition 9679 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9680 SmallVector<EVT, 3> ValueVTs; 9681 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9682 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9683 9684 // There is always a chain and a glue type at the end 9685 ValueVTs.push_back(MVT::Other); 9686 ValueVTs.push_back(MVT::Glue); 9687 NodeTys = DAG.getVTList(ValueVTs); 9688 } else 9689 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9690 9691 // Replace the target specific call node with a PATCHPOINT node. 9692 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9693 9694 // Update the NodeMap. 9695 if (HasDef) { 9696 if (IsAnyRegCC) 9697 setValue(&CB, SDValue(PPV.getNode(), 0)); 9698 else 9699 setValue(&CB, Result.first); 9700 } 9701 9702 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9703 // call sequence. Furthermore the location of the chain and glue can change 9704 // when the AnyReg calling convention is used and the intrinsic returns a 9705 // value. 9706 if (IsAnyRegCC && HasDef) { 9707 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9708 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9709 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9710 } else 9711 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9712 DAG.DeleteNode(Call); 9713 9714 // Inform the Frame Information that we have a patchpoint in this function. 9715 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9716 } 9717 9718 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9719 unsigned Intrinsic) { 9720 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9721 SDValue Op1 = getValue(I.getArgOperand(0)); 9722 SDValue Op2; 9723 if (I.arg_size() > 1) 9724 Op2 = getValue(I.getArgOperand(1)); 9725 SDLoc dl = getCurSDLoc(); 9726 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9727 SDValue Res; 9728 SDNodeFlags SDFlags; 9729 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9730 SDFlags.copyFMF(*FPMO); 9731 9732 switch (Intrinsic) { 9733 case Intrinsic::vector_reduce_fadd: 9734 if (SDFlags.hasAllowReassociation()) 9735 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9736 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9737 SDFlags); 9738 else 9739 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9740 break; 9741 case Intrinsic::vector_reduce_fmul: 9742 if (SDFlags.hasAllowReassociation()) 9743 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9744 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9745 SDFlags); 9746 else 9747 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9748 break; 9749 case Intrinsic::vector_reduce_add: 9750 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9751 break; 9752 case Intrinsic::vector_reduce_mul: 9753 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9754 break; 9755 case Intrinsic::vector_reduce_and: 9756 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9757 break; 9758 case Intrinsic::vector_reduce_or: 9759 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9760 break; 9761 case Intrinsic::vector_reduce_xor: 9762 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9763 break; 9764 case Intrinsic::vector_reduce_smax: 9765 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9766 break; 9767 case Intrinsic::vector_reduce_smin: 9768 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9769 break; 9770 case Intrinsic::vector_reduce_umax: 9771 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9772 break; 9773 case Intrinsic::vector_reduce_umin: 9774 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9775 break; 9776 case Intrinsic::vector_reduce_fmax: 9777 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9778 break; 9779 case Intrinsic::vector_reduce_fmin: 9780 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9781 break; 9782 default: 9783 llvm_unreachable("Unhandled vector reduce intrinsic"); 9784 } 9785 setValue(&I, Res); 9786 } 9787 9788 /// Returns an AttributeList representing the attributes applied to the return 9789 /// value of the given call. 9790 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9791 SmallVector<Attribute::AttrKind, 2> Attrs; 9792 if (CLI.RetSExt) 9793 Attrs.push_back(Attribute::SExt); 9794 if (CLI.RetZExt) 9795 Attrs.push_back(Attribute::ZExt); 9796 if (CLI.IsInReg) 9797 Attrs.push_back(Attribute::InReg); 9798 9799 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9800 Attrs); 9801 } 9802 9803 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9804 /// implementation, which just calls LowerCall. 9805 /// FIXME: When all targets are 9806 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9807 std::pair<SDValue, SDValue> 9808 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9809 // Handle the incoming return values from the call. 9810 CLI.Ins.clear(); 9811 Type *OrigRetTy = CLI.RetTy; 9812 SmallVector<EVT, 4> RetTys; 9813 SmallVector<uint64_t, 4> Offsets; 9814 auto &DL = CLI.DAG.getDataLayout(); 9815 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9816 9817 if (CLI.IsPostTypeLegalization) { 9818 // If we are lowering a libcall after legalization, split the return type. 9819 SmallVector<EVT, 4> OldRetTys; 9820 SmallVector<uint64_t, 4> OldOffsets; 9821 RetTys.swap(OldRetTys); 9822 Offsets.swap(OldOffsets); 9823 9824 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9825 EVT RetVT = OldRetTys[i]; 9826 uint64_t Offset = OldOffsets[i]; 9827 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9828 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9829 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9830 RetTys.append(NumRegs, RegisterVT); 9831 for (unsigned j = 0; j != NumRegs; ++j) 9832 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9833 } 9834 } 9835 9836 SmallVector<ISD::OutputArg, 4> Outs; 9837 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9838 9839 bool CanLowerReturn = 9840 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9841 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9842 9843 SDValue DemoteStackSlot; 9844 int DemoteStackIdx = -100; 9845 if (!CanLowerReturn) { 9846 // FIXME: equivalent assert? 9847 // assert(!CS.hasInAllocaArgument() && 9848 // "sret demotion is incompatible with inalloca"); 9849 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9850 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9851 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9852 DemoteStackIdx = 9853 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9854 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9855 DL.getAllocaAddrSpace()); 9856 9857 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9858 ArgListEntry Entry; 9859 Entry.Node = DemoteStackSlot; 9860 Entry.Ty = StackSlotPtrType; 9861 Entry.IsSExt = false; 9862 Entry.IsZExt = false; 9863 Entry.IsInReg = false; 9864 Entry.IsSRet = true; 9865 Entry.IsNest = false; 9866 Entry.IsByVal = false; 9867 Entry.IsByRef = false; 9868 Entry.IsReturned = false; 9869 Entry.IsSwiftSelf = false; 9870 Entry.IsSwiftAsync = false; 9871 Entry.IsSwiftError = false; 9872 Entry.IsCFGuardTarget = false; 9873 Entry.Alignment = Alignment; 9874 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9875 CLI.NumFixedArgs += 1; 9876 CLI.getArgs()[0].IndirectType = CLI.RetTy; 9877 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9878 9879 // sret demotion isn't compatible with tail-calls, since the sret argument 9880 // points into the callers stack frame. 9881 CLI.IsTailCall = false; 9882 } else { 9883 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9884 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9885 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9886 ISD::ArgFlagsTy Flags; 9887 if (NeedsRegBlock) { 9888 Flags.setInConsecutiveRegs(); 9889 if (I == RetTys.size() - 1) 9890 Flags.setInConsecutiveRegsLast(); 9891 } 9892 EVT VT = RetTys[I]; 9893 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9894 CLI.CallConv, VT); 9895 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9896 CLI.CallConv, VT); 9897 for (unsigned i = 0; i != NumRegs; ++i) { 9898 ISD::InputArg MyFlags; 9899 MyFlags.Flags = Flags; 9900 MyFlags.VT = RegisterVT; 9901 MyFlags.ArgVT = VT; 9902 MyFlags.Used = CLI.IsReturnValueUsed; 9903 if (CLI.RetTy->isPointerTy()) { 9904 MyFlags.Flags.setPointer(); 9905 MyFlags.Flags.setPointerAddrSpace( 9906 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9907 } 9908 if (CLI.RetSExt) 9909 MyFlags.Flags.setSExt(); 9910 if (CLI.RetZExt) 9911 MyFlags.Flags.setZExt(); 9912 if (CLI.IsInReg) 9913 MyFlags.Flags.setInReg(); 9914 CLI.Ins.push_back(MyFlags); 9915 } 9916 } 9917 } 9918 9919 // We push in swifterror return as the last element of CLI.Ins. 9920 ArgListTy &Args = CLI.getArgs(); 9921 if (supportSwiftError()) { 9922 for (const ArgListEntry &Arg : Args) { 9923 if (Arg.IsSwiftError) { 9924 ISD::InputArg MyFlags; 9925 MyFlags.VT = getPointerTy(DL); 9926 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9927 MyFlags.Flags.setSwiftError(); 9928 CLI.Ins.push_back(MyFlags); 9929 } 9930 } 9931 } 9932 9933 // Handle all of the outgoing arguments. 9934 CLI.Outs.clear(); 9935 CLI.OutVals.clear(); 9936 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9937 SmallVector<EVT, 4> ValueVTs; 9938 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9939 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9940 Type *FinalType = Args[i].Ty; 9941 if (Args[i].IsByVal) 9942 FinalType = Args[i].IndirectType; 9943 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9944 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 9945 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9946 ++Value) { 9947 EVT VT = ValueVTs[Value]; 9948 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9949 SDValue Op = SDValue(Args[i].Node.getNode(), 9950 Args[i].Node.getResNo() + Value); 9951 ISD::ArgFlagsTy Flags; 9952 9953 // Certain targets (such as MIPS), may have a different ABI alignment 9954 // for a type depending on the context. Give the target a chance to 9955 // specify the alignment it wants. 9956 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9957 Flags.setOrigAlign(OriginalAlignment); 9958 9959 if (Args[i].Ty->isPointerTy()) { 9960 Flags.setPointer(); 9961 Flags.setPointerAddrSpace( 9962 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9963 } 9964 if (Args[i].IsZExt) 9965 Flags.setZExt(); 9966 if (Args[i].IsSExt) 9967 Flags.setSExt(); 9968 if (Args[i].IsInReg) { 9969 // If we are using vectorcall calling convention, a structure that is 9970 // passed InReg - is surely an HVA 9971 if (CLI.CallConv == CallingConv::X86_VectorCall && 9972 isa<StructType>(FinalType)) { 9973 // The first value of a structure is marked 9974 if (0 == Value) 9975 Flags.setHvaStart(); 9976 Flags.setHva(); 9977 } 9978 // Set InReg Flag 9979 Flags.setInReg(); 9980 } 9981 if (Args[i].IsSRet) 9982 Flags.setSRet(); 9983 if (Args[i].IsSwiftSelf) 9984 Flags.setSwiftSelf(); 9985 if (Args[i].IsSwiftAsync) 9986 Flags.setSwiftAsync(); 9987 if (Args[i].IsSwiftError) 9988 Flags.setSwiftError(); 9989 if (Args[i].IsCFGuardTarget) 9990 Flags.setCFGuardTarget(); 9991 if (Args[i].IsByVal) 9992 Flags.setByVal(); 9993 if (Args[i].IsByRef) 9994 Flags.setByRef(); 9995 if (Args[i].IsPreallocated) { 9996 Flags.setPreallocated(); 9997 // Set the byval flag for CCAssignFn callbacks that don't know about 9998 // preallocated. This way we can know how many bytes we should've 9999 // allocated and how many bytes a callee cleanup function will pop. If 10000 // we port preallocated to more targets, we'll have to add custom 10001 // preallocated handling in the various CC lowering callbacks. 10002 Flags.setByVal(); 10003 } 10004 if (Args[i].IsInAlloca) { 10005 Flags.setInAlloca(); 10006 // Set the byval flag for CCAssignFn callbacks that don't know about 10007 // inalloca. This way we can know how many bytes we should've allocated 10008 // and how many bytes a callee cleanup function will pop. If we port 10009 // inalloca to more targets, we'll have to add custom inalloca handling 10010 // in the various CC lowering callbacks. 10011 Flags.setByVal(); 10012 } 10013 Align MemAlign; 10014 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10015 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10016 Flags.setByValSize(FrameSize); 10017 10018 // info is not there but there are cases it cannot get right. 10019 if (auto MA = Args[i].Alignment) 10020 MemAlign = *MA; 10021 else 10022 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10023 } else if (auto MA = Args[i].Alignment) { 10024 MemAlign = *MA; 10025 } else { 10026 MemAlign = OriginalAlignment; 10027 } 10028 Flags.setMemAlign(MemAlign); 10029 if (Args[i].IsNest) 10030 Flags.setNest(); 10031 if (NeedsRegBlock) 10032 Flags.setInConsecutiveRegs(); 10033 10034 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10035 CLI.CallConv, VT); 10036 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10037 CLI.CallConv, VT); 10038 SmallVector<SDValue, 4> Parts(NumParts); 10039 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10040 10041 if (Args[i].IsSExt) 10042 ExtendKind = ISD::SIGN_EXTEND; 10043 else if (Args[i].IsZExt) 10044 ExtendKind = ISD::ZERO_EXTEND; 10045 10046 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10047 // for now. 10048 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10049 CanLowerReturn) { 10050 assert((CLI.RetTy == Args[i].Ty || 10051 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10052 CLI.RetTy->getPointerAddressSpace() == 10053 Args[i].Ty->getPointerAddressSpace())) && 10054 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10055 // Before passing 'returned' to the target lowering code, ensure that 10056 // either the register MVT and the actual EVT are the same size or that 10057 // the return value and argument are extended in the same way; in these 10058 // cases it's safe to pass the argument register value unchanged as the 10059 // return register value (although it's at the target's option whether 10060 // to do so) 10061 // TODO: allow code generation to take advantage of partially preserved 10062 // registers rather than clobbering the entire register when the 10063 // parameter extension method is not compatible with the return 10064 // extension method 10065 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10066 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10067 CLI.RetZExt == Args[i].IsZExt)) 10068 Flags.setReturned(); 10069 } 10070 10071 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10072 CLI.CallConv, ExtendKind); 10073 10074 for (unsigned j = 0; j != NumParts; ++j) { 10075 // if it isn't first piece, alignment must be 1 10076 // For scalable vectors the scalable part is currently handled 10077 // by individual targets, so we just use the known minimum size here. 10078 ISD::OutputArg MyFlags( 10079 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10080 i < CLI.NumFixedArgs, i, 10081 j * Parts[j].getValueType().getStoreSize().getKnownMinSize()); 10082 if (NumParts > 1 && j == 0) 10083 MyFlags.Flags.setSplit(); 10084 else if (j != 0) { 10085 MyFlags.Flags.setOrigAlign(Align(1)); 10086 if (j == NumParts - 1) 10087 MyFlags.Flags.setSplitEnd(); 10088 } 10089 10090 CLI.Outs.push_back(MyFlags); 10091 CLI.OutVals.push_back(Parts[j]); 10092 } 10093 10094 if (NeedsRegBlock && Value == NumValues - 1) 10095 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10096 } 10097 } 10098 10099 SmallVector<SDValue, 4> InVals; 10100 CLI.Chain = LowerCall(CLI, InVals); 10101 10102 // Update CLI.InVals to use outside of this function. 10103 CLI.InVals = InVals; 10104 10105 // Verify that the target's LowerCall behaved as expected. 10106 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10107 "LowerCall didn't return a valid chain!"); 10108 assert((!CLI.IsTailCall || InVals.empty()) && 10109 "LowerCall emitted a return value for a tail call!"); 10110 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10111 "LowerCall didn't emit the correct number of values!"); 10112 10113 // For a tail call, the return value is merely live-out and there aren't 10114 // any nodes in the DAG representing it. Return a special value to 10115 // indicate that a tail call has been emitted and no more Instructions 10116 // should be processed in the current block. 10117 if (CLI.IsTailCall) { 10118 CLI.DAG.setRoot(CLI.Chain); 10119 return std::make_pair(SDValue(), SDValue()); 10120 } 10121 10122 #ifndef NDEBUG 10123 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10124 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10125 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10126 "LowerCall emitted a value with the wrong type!"); 10127 } 10128 #endif 10129 10130 SmallVector<SDValue, 4> ReturnValues; 10131 if (!CanLowerReturn) { 10132 // The instruction result is the result of loading from the 10133 // hidden sret parameter. 10134 SmallVector<EVT, 1> PVTs; 10135 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10136 10137 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10138 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10139 EVT PtrVT = PVTs[0]; 10140 10141 unsigned NumValues = RetTys.size(); 10142 ReturnValues.resize(NumValues); 10143 SmallVector<SDValue, 4> Chains(NumValues); 10144 10145 // An aggregate return value cannot wrap around the address space, so 10146 // offsets to its parts don't wrap either. 10147 SDNodeFlags Flags; 10148 Flags.setNoUnsignedWrap(true); 10149 10150 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10151 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10152 for (unsigned i = 0; i < NumValues; ++i) { 10153 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10154 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10155 PtrVT), Flags); 10156 SDValue L = CLI.DAG.getLoad( 10157 RetTys[i], CLI.DL, CLI.Chain, Add, 10158 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10159 DemoteStackIdx, Offsets[i]), 10160 HiddenSRetAlign); 10161 ReturnValues[i] = L; 10162 Chains[i] = L.getValue(1); 10163 } 10164 10165 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10166 } else { 10167 // Collect the legal value parts into potentially illegal values 10168 // that correspond to the original function's return values. 10169 Optional<ISD::NodeType> AssertOp; 10170 if (CLI.RetSExt) 10171 AssertOp = ISD::AssertSext; 10172 else if (CLI.RetZExt) 10173 AssertOp = ISD::AssertZext; 10174 unsigned CurReg = 0; 10175 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10176 EVT VT = RetTys[I]; 10177 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10178 CLI.CallConv, VT); 10179 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10180 CLI.CallConv, VT); 10181 10182 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10183 NumRegs, RegisterVT, VT, nullptr, 10184 CLI.CallConv, AssertOp)); 10185 CurReg += NumRegs; 10186 } 10187 10188 // For a function returning void, there is no return value. We can't create 10189 // such a node, so we just return a null return value in that case. In 10190 // that case, nothing will actually look at the value. 10191 if (ReturnValues.empty()) 10192 return std::make_pair(SDValue(), CLI.Chain); 10193 } 10194 10195 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10196 CLI.DAG.getVTList(RetTys), ReturnValues); 10197 return std::make_pair(Res, CLI.Chain); 10198 } 10199 10200 /// Places new result values for the node in Results (their number 10201 /// and types must exactly match those of the original return values of 10202 /// the node), or leaves Results empty, which indicates that the node is not 10203 /// to be custom lowered after all. 10204 void TargetLowering::LowerOperationWrapper(SDNode *N, 10205 SmallVectorImpl<SDValue> &Results, 10206 SelectionDAG &DAG) const { 10207 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10208 10209 if (!Res.getNode()) 10210 return; 10211 10212 // If the original node has one result, take the return value from 10213 // LowerOperation as is. It might not be result number 0. 10214 if (N->getNumValues() == 1) { 10215 Results.push_back(Res); 10216 return; 10217 } 10218 10219 // If the original node has multiple results, then the return node should 10220 // have the same number of results. 10221 assert((N->getNumValues() == Res->getNumValues()) && 10222 "Lowering returned the wrong number of results!"); 10223 10224 // Places new result values base on N result number. 10225 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10226 Results.push_back(Res.getValue(I)); 10227 } 10228 10229 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10230 llvm_unreachable("LowerOperation not implemented for this target!"); 10231 } 10232 10233 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10234 unsigned Reg, 10235 ISD::NodeType ExtendType) { 10236 SDValue Op = getNonRegisterValue(V); 10237 assert((Op.getOpcode() != ISD::CopyFromReg || 10238 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10239 "Copy from a reg to the same reg!"); 10240 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10241 10242 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10243 // If this is an InlineAsm we have to match the registers required, not the 10244 // notional registers required by the type. 10245 10246 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10247 None); // This is not an ABI copy. 10248 SDValue Chain = DAG.getEntryNode(); 10249 10250 if (ExtendType == ISD::ANY_EXTEND) { 10251 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10252 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10253 ExtendType = PreferredExtendIt->second; 10254 } 10255 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10256 PendingExports.push_back(Chain); 10257 } 10258 10259 #include "llvm/CodeGen/SelectionDAGISel.h" 10260 10261 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10262 /// entry block, return true. This includes arguments used by switches, since 10263 /// the switch may expand into multiple basic blocks. 10264 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10265 // With FastISel active, we may be splitting blocks, so force creation 10266 // of virtual registers for all non-dead arguments. 10267 if (FastISel) 10268 return A->use_empty(); 10269 10270 const BasicBlock &Entry = A->getParent()->front(); 10271 for (const User *U : A->users()) 10272 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10273 return false; // Use not in entry block. 10274 10275 return true; 10276 } 10277 10278 using ArgCopyElisionMapTy = 10279 DenseMap<const Argument *, 10280 std::pair<const AllocaInst *, const StoreInst *>>; 10281 10282 /// Scan the entry block of the function in FuncInfo for arguments that look 10283 /// like copies into a local alloca. Record any copied arguments in 10284 /// ArgCopyElisionCandidates. 10285 static void 10286 findArgumentCopyElisionCandidates(const DataLayout &DL, 10287 FunctionLoweringInfo *FuncInfo, 10288 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10289 // Record the state of every static alloca used in the entry block. Argument 10290 // allocas are all used in the entry block, so we need approximately as many 10291 // entries as we have arguments. 10292 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10293 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10294 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10295 StaticAllocas.reserve(NumArgs * 2); 10296 10297 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10298 if (!V) 10299 return nullptr; 10300 V = V->stripPointerCasts(); 10301 const auto *AI = dyn_cast<AllocaInst>(V); 10302 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10303 return nullptr; 10304 auto Iter = StaticAllocas.insert({AI, Unknown}); 10305 return &Iter.first->second; 10306 }; 10307 10308 // Look for stores of arguments to static allocas. Look through bitcasts and 10309 // GEPs to handle type coercions, as long as the alloca is fully initialized 10310 // by the store. Any non-store use of an alloca escapes it and any subsequent 10311 // unanalyzed store might write it. 10312 // FIXME: Handle structs initialized with multiple stores. 10313 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10314 // Look for stores, and handle non-store uses conservatively. 10315 const auto *SI = dyn_cast<StoreInst>(&I); 10316 if (!SI) { 10317 // We will look through cast uses, so ignore them completely. 10318 if (I.isCast()) 10319 continue; 10320 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10321 // to allocas. 10322 if (I.isDebugOrPseudoInst()) 10323 continue; 10324 // This is an unknown instruction. Assume it escapes or writes to all 10325 // static alloca operands. 10326 for (const Use &U : I.operands()) { 10327 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10328 *Info = StaticAllocaInfo::Clobbered; 10329 } 10330 continue; 10331 } 10332 10333 // If the stored value is a static alloca, mark it as escaped. 10334 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10335 *Info = StaticAllocaInfo::Clobbered; 10336 10337 // Check if the destination is a static alloca. 10338 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10339 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10340 if (!Info) 10341 continue; 10342 const AllocaInst *AI = cast<AllocaInst>(Dst); 10343 10344 // Skip allocas that have been initialized or clobbered. 10345 if (*Info != StaticAllocaInfo::Unknown) 10346 continue; 10347 10348 // Check if the stored value is an argument, and that this store fully 10349 // initializes the alloca. 10350 // If the argument type has padding bits we can't directly forward a pointer 10351 // as the upper bits may contain garbage. 10352 // Don't elide copies from the same argument twice. 10353 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10354 const auto *Arg = dyn_cast<Argument>(Val); 10355 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10356 Arg->getType()->isEmptyTy() || 10357 DL.getTypeStoreSize(Arg->getType()) != 10358 DL.getTypeAllocSize(AI->getAllocatedType()) || 10359 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10360 ArgCopyElisionCandidates.count(Arg)) { 10361 *Info = StaticAllocaInfo::Clobbered; 10362 continue; 10363 } 10364 10365 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10366 << '\n'); 10367 10368 // Mark this alloca and store for argument copy elision. 10369 *Info = StaticAllocaInfo::Elidable; 10370 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10371 10372 // Stop scanning if we've seen all arguments. This will happen early in -O0 10373 // builds, which is useful, because -O0 builds have large entry blocks and 10374 // many allocas. 10375 if (ArgCopyElisionCandidates.size() == NumArgs) 10376 break; 10377 } 10378 } 10379 10380 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10381 /// ArgVal is a load from a suitable fixed stack object. 10382 static void tryToElideArgumentCopy( 10383 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10384 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10385 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10386 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10387 SDValue ArgVal, bool &ArgHasUses) { 10388 // Check if this is a load from a fixed stack object. 10389 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10390 if (!LNode) 10391 return; 10392 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10393 if (!FINode) 10394 return; 10395 10396 // Check that the fixed stack object is the right size and alignment. 10397 // Look at the alignment that the user wrote on the alloca instead of looking 10398 // at the stack object. 10399 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10400 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10401 const AllocaInst *AI = ArgCopyIter->second.first; 10402 int FixedIndex = FINode->getIndex(); 10403 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10404 int OldIndex = AllocaIndex; 10405 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10406 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10407 LLVM_DEBUG( 10408 dbgs() << " argument copy elision failed due to bad fixed stack " 10409 "object size\n"); 10410 return; 10411 } 10412 Align RequiredAlignment = AI->getAlign(); 10413 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10414 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10415 "greater than stack argument alignment (" 10416 << DebugStr(RequiredAlignment) << " vs " 10417 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10418 return; 10419 } 10420 10421 // Perform the elision. Delete the old stack object and replace its only use 10422 // in the variable info map. Mark the stack object as mutable. 10423 LLVM_DEBUG({ 10424 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10425 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10426 << '\n'; 10427 }); 10428 MFI.RemoveStackObject(OldIndex); 10429 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10430 AllocaIndex = FixedIndex; 10431 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10432 Chains.push_back(ArgVal.getValue(1)); 10433 10434 // Avoid emitting code for the store implementing the copy. 10435 const StoreInst *SI = ArgCopyIter->second.second; 10436 ElidedArgCopyInstrs.insert(SI); 10437 10438 // Check for uses of the argument again so that we can avoid exporting ArgVal 10439 // if it is't used by anything other than the store. 10440 for (const Value *U : Arg.users()) { 10441 if (U != SI) { 10442 ArgHasUses = true; 10443 break; 10444 } 10445 } 10446 } 10447 10448 void SelectionDAGISel::LowerArguments(const Function &F) { 10449 SelectionDAG &DAG = SDB->DAG; 10450 SDLoc dl = SDB->getCurSDLoc(); 10451 const DataLayout &DL = DAG.getDataLayout(); 10452 SmallVector<ISD::InputArg, 16> Ins; 10453 10454 // In Naked functions we aren't going to save any registers. 10455 if (F.hasFnAttribute(Attribute::Naked)) 10456 return; 10457 10458 if (!FuncInfo->CanLowerReturn) { 10459 // Put in an sret pointer parameter before all the other parameters. 10460 SmallVector<EVT, 1> ValueVTs; 10461 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10462 F.getReturnType()->getPointerTo( 10463 DAG.getDataLayout().getAllocaAddrSpace()), 10464 ValueVTs); 10465 10466 // NOTE: Assuming that a pointer will never break down to more than one VT 10467 // or one register. 10468 ISD::ArgFlagsTy Flags; 10469 Flags.setSRet(); 10470 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10471 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10472 ISD::InputArg::NoArgIndex, 0); 10473 Ins.push_back(RetArg); 10474 } 10475 10476 // Look for stores of arguments to static allocas. Mark such arguments with a 10477 // flag to ask the target to give us the memory location of that argument if 10478 // available. 10479 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10480 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10481 ArgCopyElisionCandidates); 10482 10483 // Set up the incoming argument description vector. 10484 for (const Argument &Arg : F.args()) { 10485 unsigned ArgNo = Arg.getArgNo(); 10486 SmallVector<EVT, 4> ValueVTs; 10487 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10488 bool isArgValueUsed = !Arg.use_empty(); 10489 unsigned PartBase = 0; 10490 Type *FinalType = Arg.getType(); 10491 if (Arg.hasAttribute(Attribute::ByVal)) 10492 FinalType = Arg.getParamByValType(); 10493 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10494 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10495 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10496 Value != NumValues; ++Value) { 10497 EVT VT = ValueVTs[Value]; 10498 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10499 ISD::ArgFlagsTy Flags; 10500 10501 10502 if (Arg.getType()->isPointerTy()) { 10503 Flags.setPointer(); 10504 Flags.setPointerAddrSpace( 10505 cast<PointerType>(Arg.getType())->getAddressSpace()); 10506 } 10507 if (Arg.hasAttribute(Attribute::ZExt)) 10508 Flags.setZExt(); 10509 if (Arg.hasAttribute(Attribute::SExt)) 10510 Flags.setSExt(); 10511 if (Arg.hasAttribute(Attribute::InReg)) { 10512 // If we are using vectorcall calling convention, a structure that is 10513 // passed InReg - is surely an HVA 10514 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10515 isa<StructType>(Arg.getType())) { 10516 // The first value of a structure is marked 10517 if (0 == Value) 10518 Flags.setHvaStart(); 10519 Flags.setHva(); 10520 } 10521 // Set InReg Flag 10522 Flags.setInReg(); 10523 } 10524 if (Arg.hasAttribute(Attribute::StructRet)) 10525 Flags.setSRet(); 10526 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10527 Flags.setSwiftSelf(); 10528 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10529 Flags.setSwiftAsync(); 10530 if (Arg.hasAttribute(Attribute::SwiftError)) 10531 Flags.setSwiftError(); 10532 if (Arg.hasAttribute(Attribute::ByVal)) 10533 Flags.setByVal(); 10534 if (Arg.hasAttribute(Attribute::ByRef)) 10535 Flags.setByRef(); 10536 if (Arg.hasAttribute(Attribute::InAlloca)) { 10537 Flags.setInAlloca(); 10538 // Set the byval flag for CCAssignFn callbacks that don't know about 10539 // inalloca. This way we can know how many bytes we should've allocated 10540 // and how many bytes a callee cleanup function will pop. If we port 10541 // inalloca to more targets, we'll have to add custom inalloca handling 10542 // in the various CC lowering callbacks. 10543 Flags.setByVal(); 10544 } 10545 if (Arg.hasAttribute(Attribute::Preallocated)) { 10546 Flags.setPreallocated(); 10547 // Set the byval flag for CCAssignFn callbacks that don't know about 10548 // preallocated. This way we can know how many bytes we should've 10549 // allocated and how many bytes a callee cleanup function will pop. If 10550 // we port preallocated to more targets, we'll have to add custom 10551 // preallocated handling in the various CC lowering callbacks. 10552 Flags.setByVal(); 10553 } 10554 10555 // Certain targets (such as MIPS), may have a different ABI alignment 10556 // for a type depending on the context. Give the target a chance to 10557 // specify the alignment it wants. 10558 const Align OriginalAlignment( 10559 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10560 Flags.setOrigAlign(OriginalAlignment); 10561 10562 Align MemAlign; 10563 Type *ArgMemTy = nullptr; 10564 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10565 Flags.isByRef()) { 10566 if (!ArgMemTy) 10567 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10568 10569 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10570 10571 // For in-memory arguments, size and alignment should be passed from FE. 10572 // BE will guess if this info is not there but there are cases it cannot 10573 // get right. 10574 if (auto ParamAlign = Arg.getParamStackAlign()) 10575 MemAlign = *ParamAlign; 10576 else if ((ParamAlign = Arg.getParamAlign())) 10577 MemAlign = *ParamAlign; 10578 else 10579 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10580 if (Flags.isByRef()) 10581 Flags.setByRefSize(MemSize); 10582 else 10583 Flags.setByValSize(MemSize); 10584 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10585 MemAlign = *ParamAlign; 10586 } else { 10587 MemAlign = OriginalAlignment; 10588 } 10589 Flags.setMemAlign(MemAlign); 10590 10591 if (Arg.hasAttribute(Attribute::Nest)) 10592 Flags.setNest(); 10593 if (NeedsRegBlock) 10594 Flags.setInConsecutiveRegs(); 10595 if (ArgCopyElisionCandidates.count(&Arg)) 10596 Flags.setCopyElisionCandidate(); 10597 if (Arg.hasAttribute(Attribute::Returned)) 10598 Flags.setReturned(); 10599 10600 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10601 *CurDAG->getContext(), F.getCallingConv(), VT); 10602 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10603 *CurDAG->getContext(), F.getCallingConv(), VT); 10604 for (unsigned i = 0; i != NumRegs; ++i) { 10605 // For scalable vectors, use the minimum size; individual targets 10606 // are responsible for handling scalable vector arguments and 10607 // return values. 10608 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10609 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10610 if (NumRegs > 1 && i == 0) 10611 MyFlags.Flags.setSplit(); 10612 // if it isn't first piece, alignment must be 1 10613 else if (i > 0) { 10614 MyFlags.Flags.setOrigAlign(Align(1)); 10615 if (i == NumRegs - 1) 10616 MyFlags.Flags.setSplitEnd(); 10617 } 10618 Ins.push_back(MyFlags); 10619 } 10620 if (NeedsRegBlock && Value == NumValues - 1) 10621 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10622 PartBase += VT.getStoreSize().getKnownMinSize(); 10623 } 10624 } 10625 10626 // Call the target to set up the argument values. 10627 SmallVector<SDValue, 8> InVals; 10628 SDValue NewRoot = TLI->LowerFormalArguments( 10629 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10630 10631 // Verify that the target's LowerFormalArguments behaved as expected. 10632 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10633 "LowerFormalArguments didn't return a valid chain!"); 10634 assert(InVals.size() == Ins.size() && 10635 "LowerFormalArguments didn't emit the correct number of values!"); 10636 LLVM_DEBUG({ 10637 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10638 assert(InVals[i].getNode() && 10639 "LowerFormalArguments emitted a null value!"); 10640 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10641 "LowerFormalArguments emitted a value with the wrong type!"); 10642 } 10643 }); 10644 10645 // Update the DAG with the new chain value resulting from argument lowering. 10646 DAG.setRoot(NewRoot); 10647 10648 // Set up the argument values. 10649 unsigned i = 0; 10650 if (!FuncInfo->CanLowerReturn) { 10651 // Create a virtual register for the sret pointer, and put in a copy 10652 // from the sret argument into it. 10653 SmallVector<EVT, 1> ValueVTs; 10654 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10655 F.getReturnType()->getPointerTo( 10656 DAG.getDataLayout().getAllocaAddrSpace()), 10657 ValueVTs); 10658 MVT VT = ValueVTs[0].getSimpleVT(); 10659 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10660 Optional<ISD::NodeType> AssertOp; 10661 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10662 nullptr, F.getCallingConv(), AssertOp); 10663 10664 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10665 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10666 Register SRetReg = 10667 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10668 FuncInfo->DemoteRegister = SRetReg; 10669 NewRoot = 10670 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10671 DAG.setRoot(NewRoot); 10672 10673 // i indexes lowered arguments. Bump it past the hidden sret argument. 10674 ++i; 10675 } 10676 10677 SmallVector<SDValue, 4> Chains; 10678 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10679 for (const Argument &Arg : F.args()) { 10680 SmallVector<SDValue, 4> ArgValues; 10681 SmallVector<EVT, 4> ValueVTs; 10682 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10683 unsigned NumValues = ValueVTs.size(); 10684 if (NumValues == 0) 10685 continue; 10686 10687 bool ArgHasUses = !Arg.use_empty(); 10688 10689 // Elide the copying store if the target loaded this argument from a 10690 // suitable fixed stack object. 10691 if (Ins[i].Flags.isCopyElisionCandidate()) { 10692 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10693 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10694 InVals[i], ArgHasUses); 10695 } 10696 10697 // If this argument is unused then remember its value. It is used to generate 10698 // debugging information. 10699 bool isSwiftErrorArg = 10700 TLI->supportSwiftError() && 10701 Arg.hasAttribute(Attribute::SwiftError); 10702 if (!ArgHasUses && !isSwiftErrorArg) { 10703 SDB->setUnusedArgValue(&Arg, InVals[i]); 10704 10705 // Also remember any frame index for use in FastISel. 10706 if (FrameIndexSDNode *FI = 10707 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10708 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10709 } 10710 10711 for (unsigned Val = 0; Val != NumValues; ++Val) { 10712 EVT VT = ValueVTs[Val]; 10713 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10714 F.getCallingConv(), VT); 10715 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10716 *CurDAG->getContext(), F.getCallingConv(), VT); 10717 10718 // Even an apparent 'unused' swifterror argument needs to be returned. So 10719 // we do generate a copy for it that can be used on return from the 10720 // function. 10721 if (ArgHasUses || isSwiftErrorArg) { 10722 Optional<ISD::NodeType> AssertOp; 10723 if (Arg.hasAttribute(Attribute::SExt)) 10724 AssertOp = ISD::AssertSext; 10725 else if (Arg.hasAttribute(Attribute::ZExt)) 10726 AssertOp = ISD::AssertZext; 10727 10728 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10729 PartVT, VT, nullptr, 10730 F.getCallingConv(), AssertOp)); 10731 } 10732 10733 i += NumParts; 10734 } 10735 10736 // We don't need to do anything else for unused arguments. 10737 if (ArgValues.empty()) 10738 continue; 10739 10740 // Note down frame index. 10741 if (FrameIndexSDNode *FI = 10742 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10743 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10744 10745 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10746 SDB->getCurSDLoc()); 10747 10748 SDB->setValue(&Arg, Res); 10749 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10750 // We want to associate the argument with the frame index, among 10751 // involved operands, that correspond to the lowest address. The 10752 // getCopyFromParts function, called earlier, is swapping the order of 10753 // the operands to BUILD_PAIR depending on endianness. The result of 10754 // that swapping is that the least significant bits of the argument will 10755 // be in the first operand of the BUILD_PAIR node, and the most 10756 // significant bits will be in the second operand. 10757 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10758 if (LoadSDNode *LNode = 10759 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10760 if (FrameIndexSDNode *FI = 10761 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10762 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10763 } 10764 10765 // Analyses past this point are naive and don't expect an assertion. 10766 if (Res.getOpcode() == ISD::AssertZext) 10767 Res = Res.getOperand(0); 10768 10769 // Update the SwiftErrorVRegDefMap. 10770 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10771 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10772 if (Register::isVirtualRegister(Reg)) 10773 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10774 Reg); 10775 } 10776 10777 // If this argument is live outside of the entry block, insert a copy from 10778 // wherever we got it to the vreg that other BB's will reference it as. 10779 if (Res.getOpcode() == ISD::CopyFromReg) { 10780 // If we can, though, try to skip creating an unnecessary vreg. 10781 // FIXME: This isn't very clean... it would be nice to make this more 10782 // general. 10783 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10784 if (Register::isVirtualRegister(Reg)) { 10785 FuncInfo->ValueMap[&Arg] = Reg; 10786 continue; 10787 } 10788 } 10789 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10790 FuncInfo->InitializeRegForValue(&Arg); 10791 SDB->CopyToExportRegsIfNeeded(&Arg); 10792 } 10793 } 10794 10795 if (!Chains.empty()) { 10796 Chains.push_back(NewRoot); 10797 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10798 } 10799 10800 DAG.setRoot(NewRoot); 10801 10802 assert(i == InVals.size() && "Argument register count mismatch!"); 10803 10804 // If any argument copy elisions occurred and we have debug info, update the 10805 // stale frame indices used in the dbg.declare variable info table. 10806 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10807 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10808 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10809 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10810 if (I != ArgCopyElisionFrameIndexMap.end()) 10811 VI.Slot = I->second; 10812 } 10813 } 10814 10815 // Finally, if the target has anything special to do, allow it to do so. 10816 emitFunctionEntryCode(); 10817 } 10818 10819 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10820 /// ensure constants are generated when needed. Remember the virtual registers 10821 /// that need to be added to the Machine PHI nodes as input. We cannot just 10822 /// directly add them, because expansion might result in multiple MBB's for one 10823 /// BB. As such, the start of the BB might correspond to a different MBB than 10824 /// the end. 10825 void 10826 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10827 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10828 10829 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10830 10831 // Check PHI nodes in successors that expect a value to be available from this 10832 // block. 10833 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 10834 if (!isa<PHINode>(SuccBB->begin())) continue; 10835 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10836 10837 // If this terminator has multiple identical successors (common for 10838 // switches), only handle each succ once. 10839 if (!SuccsHandled.insert(SuccMBB).second) 10840 continue; 10841 10842 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10843 10844 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10845 // nodes and Machine PHI nodes, but the incoming operands have not been 10846 // emitted yet. 10847 for (const PHINode &PN : SuccBB->phis()) { 10848 // Ignore dead phi's. 10849 if (PN.use_empty()) 10850 continue; 10851 10852 // Skip empty types 10853 if (PN.getType()->isEmptyTy()) 10854 continue; 10855 10856 unsigned Reg; 10857 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10858 10859 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 10860 unsigned &RegOut = ConstantsOut[C]; 10861 if (RegOut == 0) { 10862 RegOut = FuncInfo.CreateRegs(C); 10863 // We need to zero/sign extend ConstantInt phi operands to match 10864 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 10865 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 10866 if (auto *CI = dyn_cast<ConstantInt>(C)) 10867 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 10868 : ISD::ZERO_EXTEND; 10869 CopyValueToVirtualRegister(C, RegOut, ExtendType); 10870 } 10871 Reg = RegOut; 10872 } else { 10873 DenseMap<const Value *, Register>::iterator I = 10874 FuncInfo.ValueMap.find(PHIOp); 10875 if (I != FuncInfo.ValueMap.end()) 10876 Reg = I->second; 10877 else { 10878 assert(isa<AllocaInst>(PHIOp) && 10879 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10880 "Didn't codegen value into a register!??"); 10881 Reg = FuncInfo.CreateRegs(PHIOp); 10882 CopyValueToVirtualRegister(PHIOp, Reg); 10883 } 10884 } 10885 10886 // Remember that this register needs to added to the machine PHI node as 10887 // the input for this MBB. 10888 SmallVector<EVT, 4> ValueVTs; 10889 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10890 for (EVT VT : ValueVTs) { 10891 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10892 for (unsigned i = 0; i != NumRegisters; ++i) 10893 FuncInfo.PHINodesToUpdate.push_back( 10894 std::make_pair(&*MBBI++, Reg + i)); 10895 Reg += NumRegisters; 10896 } 10897 } 10898 } 10899 10900 ConstantsOut.clear(); 10901 } 10902 10903 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10904 MachineFunction::iterator I(MBB); 10905 if (++I == FuncInfo.MF->end()) 10906 return nullptr; 10907 return &*I; 10908 } 10909 10910 /// During lowering new call nodes can be created (such as memset, etc.). 10911 /// Those will become new roots of the current DAG, but complications arise 10912 /// when they are tail calls. In such cases, the call lowering will update 10913 /// the root, but the builder still needs to know that a tail call has been 10914 /// lowered in order to avoid generating an additional return. 10915 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10916 // If the node is null, we do have a tail call. 10917 if (MaybeTC.getNode() != nullptr) 10918 DAG.setRoot(MaybeTC); 10919 else 10920 HasTailCall = true; 10921 } 10922 10923 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10924 MachineBasicBlock *SwitchMBB, 10925 MachineBasicBlock *DefaultMBB) { 10926 MachineFunction *CurMF = FuncInfo.MF; 10927 MachineBasicBlock *NextMBB = nullptr; 10928 MachineFunction::iterator BBI(W.MBB); 10929 if (++BBI != FuncInfo.MF->end()) 10930 NextMBB = &*BBI; 10931 10932 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10933 10934 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10935 10936 if (Size == 2 && W.MBB == SwitchMBB) { 10937 // If any two of the cases has the same destination, and if one value 10938 // is the same as the other, but has one bit unset that the other has set, 10939 // use bit manipulation to do two compares at once. For example: 10940 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10941 // TODO: This could be extended to merge any 2 cases in switches with 3 10942 // cases. 10943 // TODO: Handle cases where W.CaseBB != SwitchBB. 10944 CaseCluster &Small = *W.FirstCluster; 10945 CaseCluster &Big = *W.LastCluster; 10946 10947 if (Small.Low == Small.High && Big.Low == Big.High && 10948 Small.MBB == Big.MBB) { 10949 const APInt &SmallValue = Small.Low->getValue(); 10950 const APInt &BigValue = Big.Low->getValue(); 10951 10952 // Check that there is only one bit different. 10953 APInt CommonBit = BigValue ^ SmallValue; 10954 if (CommonBit.isPowerOf2()) { 10955 SDValue CondLHS = getValue(Cond); 10956 EVT VT = CondLHS.getValueType(); 10957 SDLoc DL = getCurSDLoc(); 10958 10959 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10960 DAG.getConstant(CommonBit, DL, VT)); 10961 SDValue Cond = DAG.getSetCC( 10962 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10963 ISD::SETEQ); 10964 10965 // Update successor info. 10966 // Both Small and Big will jump to Small.BB, so we sum up the 10967 // probabilities. 10968 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10969 if (BPI) 10970 addSuccessorWithProb( 10971 SwitchMBB, DefaultMBB, 10972 // The default destination is the first successor in IR. 10973 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10974 else 10975 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10976 10977 // Insert the true branch. 10978 SDValue BrCond = 10979 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10980 DAG.getBasicBlock(Small.MBB)); 10981 // Insert the false branch. 10982 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10983 DAG.getBasicBlock(DefaultMBB)); 10984 10985 DAG.setRoot(BrCond); 10986 return; 10987 } 10988 } 10989 } 10990 10991 if (TM.getOptLevel() != CodeGenOpt::None) { 10992 // Here, we order cases by probability so the most likely case will be 10993 // checked first. However, two clusters can have the same probability in 10994 // which case their relative ordering is non-deterministic. So we use Low 10995 // as a tie-breaker as clusters are guaranteed to never overlap. 10996 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10997 [](const CaseCluster &a, const CaseCluster &b) { 10998 return a.Prob != b.Prob ? 10999 a.Prob > b.Prob : 11000 a.Low->getValue().slt(b.Low->getValue()); 11001 }); 11002 11003 // Rearrange the case blocks so that the last one falls through if possible 11004 // without changing the order of probabilities. 11005 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11006 --I; 11007 if (I->Prob > W.LastCluster->Prob) 11008 break; 11009 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11010 std::swap(*I, *W.LastCluster); 11011 break; 11012 } 11013 } 11014 } 11015 11016 // Compute total probability. 11017 BranchProbability DefaultProb = W.DefaultProb; 11018 BranchProbability UnhandledProbs = DefaultProb; 11019 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11020 UnhandledProbs += I->Prob; 11021 11022 MachineBasicBlock *CurMBB = W.MBB; 11023 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11024 bool FallthroughUnreachable = false; 11025 MachineBasicBlock *Fallthrough; 11026 if (I == W.LastCluster) { 11027 // For the last cluster, fall through to the default destination. 11028 Fallthrough = DefaultMBB; 11029 FallthroughUnreachable = isa<UnreachableInst>( 11030 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11031 } else { 11032 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11033 CurMF->insert(BBI, Fallthrough); 11034 // Put Cond in a virtual register to make it available from the new blocks. 11035 ExportFromCurrentBlock(Cond); 11036 } 11037 UnhandledProbs -= I->Prob; 11038 11039 switch (I->Kind) { 11040 case CC_JumpTable: { 11041 // FIXME: Optimize away range check based on pivot comparisons. 11042 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11043 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11044 11045 // The jump block hasn't been inserted yet; insert it here. 11046 MachineBasicBlock *JumpMBB = JT->MBB; 11047 CurMF->insert(BBI, JumpMBB); 11048 11049 auto JumpProb = I->Prob; 11050 auto FallthroughProb = UnhandledProbs; 11051 11052 // If the default statement is a target of the jump table, we evenly 11053 // distribute the default probability to successors of CurMBB. Also 11054 // update the probability on the edge from JumpMBB to Fallthrough. 11055 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11056 SE = JumpMBB->succ_end(); 11057 SI != SE; ++SI) { 11058 if (*SI == DefaultMBB) { 11059 JumpProb += DefaultProb / 2; 11060 FallthroughProb -= DefaultProb / 2; 11061 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11062 JumpMBB->normalizeSuccProbs(); 11063 break; 11064 } 11065 } 11066 11067 if (FallthroughUnreachable) 11068 JTH->FallthroughUnreachable = true; 11069 11070 if (!JTH->FallthroughUnreachable) 11071 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11072 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11073 CurMBB->normalizeSuccProbs(); 11074 11075 // The jump table header will be inserted in our current block, do the 11076 // range check, and fall through to our fallthrough block. 11077 JTH->HeaderBB = CurMBB; 11078 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11079 11080 // If we're in the right place, emit the jump table header right now. 11081 if (CurMBB == SwitchMBB) { 11082 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11083 JTH->Emitted = true; 11084 } 11085 break; 11086 } 11087 case CC_BitTests: { 11088 // FIXME: Optimize away range check based on pivot comparisons. 11089 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11090 11091 // The bit test blocks haven't been inserted yet; insert them here. 11092 for (BitTestCase &BTC : BTB->Cases) 11093 CurMF->insert(BBI, BTC.ThisBB); 11094 11095 // Fill in fields of the BitTestBlock. 11096 BTB->Parent = CurMBB; 11097 BTB->Default = Fallthrough; 11098 11099 BTB->DefaultProb = UnhandledProbs; 11100 // If the cases in bit test don't form a contiguous range, we evenly 11101 // distribute the probability on the edge to Fallthrough to two 11102 // successors of CurMBB. 11103 if (!BTB->ContiguousRange) { 11104 BTB->Prob += DefaultProb / 2; 11105 BTB->DefaultProb -= DefaultProb / 2; 11106 } 11107 11108 if (FallthroughUnreachable) 11109 BTB->FallthroughUnreachable = true; 11110 11111 // If we're in the right place, emit the bit test header right now. 11112 if (CurMBB == SwitchMBB) { 11113 visitBitTestHeader(*BTB, SwitchMBB); 11114 BTB->Emitted = true; 11115 } 11116 break; 11117 } 11118 case CC_Range: { 11119 const Value *RHS, *LHS, *MHS; 11120 ISD::CondCode CC; 11121 if (I->Low == I->High) { 11122 // Check Cond == I->Low. 11123 CC = ISD::SETEQ; 11124 LHS = Cond; 11125 RHS=I->Low; 11126 MHS = nullptr; 11127 } else { 11128 // Check I->Low <= Cond <= I->High. 11129 CC = ISD::SETLE; 11130 LHS = I->Low; 11131 MHS = Cond; 11132 RHS = I->High; 11133 } 11134 11135 // If Fallthrough is unreachable, fold away the comparison. 11136 if (FallthroughUnreachable) 11137 CC = ISD::SETTRUE; 11138 11139 // The false probability is the sum of all unhandled cases. 11140 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11141 getCurSDLoc(), I->Prob, UnhandledProbs); 11142 11143 if (CurMBB == SwitchMBB) 11144 visitSwitchCase(CB, SwitchMBB); 11145 else 11146 SL->SwitchCases.push_back(CB); 11147 11148 break; 11149 } 11150 } 11151 CurMBB = Fallthrough; 11152 } 11153 } 11154 11155 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11156 CaseClusterIt First, 11157 CaseClusterIt Last) { 11158 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11159 if (X.Prob != CC.Prob) 11160 return X.Prob > CC.Prob; 11161 11162 // Ties are broken by comparing the case value. 11163 return X.Low->getValue().slt(CC.Low->getValue()); 11164 }); 11165 } 11166 11167 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11168 const SwitchWorkListItem &W, 11169 Value *Cond, 11170 MachineBasicBlock *SwitchMBB) { 11171 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11172 "Clusters not sorted?"); 11173 11174 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11175 11176 // Balance the tree based on branch probabilities to create a near-optimal (in 11177 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11178 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11179 CaseClusterIt LastLeft = W.FirstCluster; 11180 CaseClusterIt FirstRight = W.LastCluster; 11181 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11182 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11183 11184 // Move LastLeft and FirstRight towards each other from opposite directions to 11185 // find a partitioning of the clusters which balances the probability on both 11186 // sides. If LeftProb and RightProb are equal, alternate which side is 11187 // taken to ensure 0-probability nodes are distributed evenly. 11188 unsigned I = 0; 11189 while (LastLeft + 1 < FirstRight) { 11190 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11191 LeftProb += (++LastLeft)->Prob; 11192 else 11193 RightProb += (--FirstRight)->Prob; 11194 I++; 11195 } 11196 11197 while (true) { 11198 // Our binary search tree differs from a typical BST in that ours can have up 11199 // to three values in each leaf. The pivot selection above doesn't take that 11200 // into account, which means the tree might require more nodes and be less 11201 // efficient. We compensate for this here. 11202 11203 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11204 unsigned NumRight = W.LastCluster - FirstRight + 1; 11205 11206 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11207 // If one side has less than 3 clusters, and the other has more than 3, 11208 // consider taking a cluster from the other side. 11209 11210 if (NumLeft < NumRight) { 11211 // Consider moving the first cluster on the right to the left side. 11212 CaseCluster &CC = *FirstRight; 11213 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11214 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11215 if (LeftSideRank <= RightSideRank) { 11216 // Moving the cluster to the left does not demote it. 11217 ++LastLeft; 11218 ++FirstRight; 11219 continue; 11220 } 11221 } else { 11222 assert(NumRight < NumLeft); 11223 // Consider moving the last element on the left to the right side. 11224 CaseCluster &CC = *LastLeft; 11225 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11226 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11227 if (RightSideRank <= LeftSideRank) { 11228 // Moving the cluster to the right does not demot it. 11229 --LastLeft; 11230 --FirstRight; 11231 continue; 11232 } 11233 } 11234 } 11235 break; 11236 } 11237 11238 assert(LastLeft + 1 == FirstRight); 11239 assert(LastLeft >= W.FirstCluster); 11240 assert(FirstRight <= W.LastCluster); 11241 11242 // Use the first element on the right as pivot since we will make less-than 11243 // comparisons against it. 11244 CaseClusterIt PivotCluster = FirstRight; 11245 assert(PivotCluster > W.FirstCluster); 11246 assert(PivotCluster <= W.LastCluster); 11247 11248 CaseClusterIt FirstLeft = W.FirstCluster; 11249 CaseClusterIt LastRight = W.LastCluster; 11250 11251 const ConstantInt *Pivot = PivotCluster->Low; 11252 11253 // New blocks will be inserted immediately after the current one. 11254 MachineFunction::iterator BBI(W.MBB); 11255 ++BBI; 11256 11257 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11258 // we can branch to its destination directly if it's squeezed exactly in 11259 // between the known lower bound and Pivot - 1. 11260 MachineBasicBlock *LeftMBB; 11261 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11262 FirstLeft->Low == W.GE && 11263 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11264 LeftMBB = FirstLeft->MBB; 11265 } else { 11266 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11267 FuncInfo.MF->insert(BBI, LeftMBB); 11268 WorkList.push_back( 11269 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11270 // Put Cond in a virtual register to make it available from the new blocks. 11271 ExportFromCurrentBlock(Cond); 11272 } 11273 11274 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11275 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11276 // directly if RHS.High equals the current upper bound. 11277 MachineBasicBlock *RightMBB; 11278 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11279 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11280 RightMBB = FirstRight->MBB; 11281 } else { 11282 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11283 FuncInfo.MF->insert(BBI, RightMBB); 11284 WorkList.push_back( 11285 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11286 // Put Cond in a virtual register to make it available from the new blocks. 11287 ExportFromCurrentBlock(Cond); 11288 } 11289 11290 // Create the CaseBlock record that will be used to lower the branch. 11291 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11292 getCurSDLoc(), LeftProb, RightProb); 11293 11294 if (W.MBB == SwitchMBB) 11295 visitSwitchCase(CB, SwitchMBB); 11296 else 11297 SL->SwitchCases.push_back(CB); 11298 } 11299 11300 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11301 // from the swith statement. 11302 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11303 BranchProbability PeeledCaseProb) { 11304 if (PeeledCaseProb == BranchProbability::getOne()) 11305 return BranchProbability::getZero(); 11306 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11307 11308 uint32_t Numerator = CaseProb.getNumerator(); 11309 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11310 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11311 } 11312 11313 // Try to peel the top probability case if it exceeds the threshold. 11314 // Return current MachineBasicBlock for the switch statement if the peeling 11315 // does not occur. 11316 // If the peeling is performed, return the newly created MachineBasicBlock 11317 // for the peeled switch statement. Also update Clusters to remove the peeled 11318 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11319 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11320 const SwitchInst &SI, CaseClusterVector &Clusters, 11321 BranchProbability &PeeledCaseProb) { 11322 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11323 // Don't perform if there is only one cluster or optimizing for size. 11324 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11325 TM.getOptLevel() == CodeGenOpt::None || 11326 SwitchMBB->getParent()->getFunction().hasMinSize()) 11327 return SwitchMBB; 11328 11329 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11330 unsigned PeeledCaseIndex = 0; 11331 bool SwitchPeeled = false; 11332 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11333 CaseCluster &CC = Clusters[Index]; 11334 if (CC.Prob < TopCaseProb) 11335 continue; 11336 TopCaseProb = CC.Prob; 11337 PeeledCaseIndex = Index; 11338 SwitchPeeled = true; 11339 } 11340 if (!SwitchPeeled) 11341 return SwitchMBB; 11342 11343 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11344 << TopCaseProb << "\n"); 11345 11346 // Record the MBB for the peeled switch statement. 11347 MachineFunction::iterator BBI(SwitchMBB); 11348 ++BBI; 11349 MachineBasicBlock *PeeledSwitchMBB = 11350 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11351 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11352 11353 ExportFromCurrentBlock(SI.getCondition()); 11354 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11355 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11356 nullptr, nullptr, TopCaseProb.getCompl()}; 11357 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11358 11359 Clusters.erase(PeeledCaseIt); 11360 for (CaseCluster &CC : Clusters) { 11361 LLVM_DEBUG( 11362 dbgs() << "Scale the probablity for one cluster, before scaling: " 11363 << CC.Prob << "\n"); 11364 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11365 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11366 } 11367 PeeledCaseProb = TopCaseProb; 11368 return PeeledSwitchMBB; 11369 } 11370 11371 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11372 // Extract cases from the switch. 11373 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11374 CaseClusterVector Clusters; 11375 Clusters.reserve(SI.getNumCases()); 11376 for (auto I : SI.cases()) { 11377 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11378 const ConstantInt *CaseVal = I.getCaseValue(); 11379 BranchProbability Prob = 11380 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11381 : BranchProbability(1, SI.getNumCases() + 1); 11382 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11383 } 11384 11385 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11386 11387 // Cluster adjacent cases with the same destination. We do this at all 11388 // optimization levels because it's cheap to do and will make codegen faster 11389 // if there are many clusters. 11390 sortAndRangeify(Clusters); 11391 11392 // The branch probablity of the peeled case. 11393 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11394 MachineBasicBlock *PeeledSwitchMBB = 11395 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11396 11397 // If there is only the default destination, jump there directly. 11398 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11399 if (Clusters.empty()) { 11400 assert(PeeledSwitchMBB == SwitchMBB); 11401 SwitchMBB->addSuccessor(DefaultMBB); 11402 if (DefaultMBB != NextBlock(SwitchMBB)) { 11403 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11404 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11405 } 11406 return; 11407 } 11408 11409 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11410 SL->findBitTestClusters(Clusters, &SI); 11411 11412 LLVM_DEBUG({ 11413 dbgs() << "Case clusters: "; 11414 for (const CaseCluster &C : Clusters) { 11415 if (C.Kind == CC_JumpTable) 11416 dbgs() << "JT:"; 11417 if (C.Kind == CC_BitTests) 11418 dbgs() << "BT:"; 11419 11420 C.Low->getValue().print(dbgs(), true); 11421 if (C.Low != C.High) { 11422 dbgs() << '-'; 11423 C.High->getValue().print(dbgs(), true); 11424 } 11425 dbgs() << ' '; 11426 } 11427 dbgs() << '\n'; 11428 }); 11429 11430 assert(!Clusters.empty()); 11431 SwitchWorkList WorkList; 11432 CaseClusterIt First = Clusters.begin(); 11433 CaseClusterIt Last = Clusters.end() - 1; 11434 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11435 // Scale the branchprobability for DefaultMBB if the peel occurs and 11436 // DefaultMBB is not replaced. 11437 if (PeeledCaseProb != BranchProbability::getZero() && 11438 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11439 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11440 WorkList.push_back( 11441 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11442 11443 while (!WorkList.empty()) { 11444 SwitchWorkListItem W = WorkList.pop_back_val(); 11445 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11446 11447 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11448 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11449 // For optimized builds, lower large range as a balanced binary tree. 11450 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11451 continue; 11452 } 11453 11454 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11455 } 11456 } 11457 11458 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11459 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11460 auto DL = getCurSDLoc(); 11461 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11462 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11463 } 11464 11465 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11466 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11467 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11468 11469 SDLoc DL = getCurSDLoc(); 11470 SDValue V = getValue(I.getOperand(0)); 11471 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11472 11473 if (VT.isScalableVector()) { 11474 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11475 return; 11476 } 11477 11478 // Use VECTOR_SHUFFLE for the fixed-length vector 11479 // to maintain existing behavior. 11480 SmallVector<int, 8> Mask; 11481 unsigned NumElts = VT.getVectorMinNumElements(); 11482 for (unsigned i = 0; i != NumElts; ++i) 11483 Mask.push_back(NumElts - 1 - i); 11484 11485 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11486 } 11487 11488 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11489 SmallVector<EVT, 4> ValueVTs; 11490 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11491 ValueVTs); 11492 unsigned NumValues = ValueVTs.size(); 11493 if (NumValues == 0) return; 11494 11495 SmallVector<SDValue, 4> Values(NumValues); 11496 SDValue Op = getValue(I.getOperand(0)); 11497 11498 for (unsigned i = 0; i != NumValues; ++i) 11499 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11500 SDValue(Op.getNode(), Op.getResNo() + i)); 11501 11502 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11503 DAG.getVTList(ValueVTs), Values)); 11504 } 11505 11506 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11507 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11508 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11509 11510 SDLoc DL = getCurSDLoc(); 11511 SDValue V1 = getValue(I.getOperand(0)); 11512 SDValue V2 = getValue(I.getOperand(1)); 11513 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11514 11515 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11516 if (VT.isScalableVector()) { 11517 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11518 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11519 DAG.getConstant(Imm, DL, IdxVT))); 11520 return; 11521 } 11522 11523 unsigned NumElts = VT.getVectorNumElements(); 11524 11525 uint64_t Idx = (NumElts + Imm) % NumElts; 11526 11527 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11528 SmallVector<int, 8> Mask; 11529 for (unsigned i = 0; i < NumElts; ++i) 11530 Mask.push_back(Idx + i); 11531 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11532 } 11533