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 <tuple> 104 105 using namespace llvm; 106 using namespace PatternMatch; 107 using namespace SwitchCG; 108 109 #define DEBUG_TYPE "isel" 110 111 /// LimitFloatPrecision - Generate low-precision inline sequences for 112 /// some float libcalls (6, 8 or 12 bits). 113 static unsigned LimitFloatPrecision; 114 115 static cl::opt<bool> 116 InsertAssertAlign("insert-assert-align", cl::init(true), 117 cl::desc("Insert the experimental `assertalign` node."), 118 cl::ReallyHidden); 119 120 static cl::opt<unsigned, true> 121 LimitFPPrecision("limit-float-precision", 122 cl::desc("Generate low-precision inline sequences " 123 "for some float libcalls"), 124 cl::location(LimitFloatPrecision), cl::Hidden, 125 cl::init(0)); 126 127 static cl::opt<unsigned> SwitchPeelThreshold( 128 "switch-peel-threshold", cl::Hidden, cl::init(66), 129 cl::desc("Set the case probability threshold for peeling the case from a " 130 "switch statement. A value greater than 100 will void this " 131 "optimization")); 132 133 // Limit the width of DAG chains. This is important in general to prevent 134 // DAG-based analysis from blowing up. For example, alias analysis and 135 // load clustering may not complete in reasonable time. It is difficult to 136 // recognize and avoid this situation within each individual analysis, and 137 // future analyses are likely to have the same behavior. Limiting DAG width is 138 // the safe approach and will be especially important with global DAGs. 139 // 140 // MaxParallelChains default is arbitrarily high to avoid affecting 141 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 142 // sequence over this should have been converted to llvm.memcpy by the 143 // frontend. It is easy to induce this behavior with .ll code such as: 144 // %buffer = alloca [4096 x i8] 145 // %data = load [4096 x i8]* %argPtr 146 // store [4096 x i8] %data, [4096 x i8]* %buffer 147 static const unsigned MaxParallelChains = 64; 148 149 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 150 const SDValue *Parts, unsigned NumParts, 151 MVT PartVT, EVT ValueVT, const Value *V, 152 Optional<CallingConv::ID> CC); 153 154 /// getCopyFromParts - Create a value that contains the specified legal parts 155 /// combined into the value they represent. If the parts combine to a type 156 /// larger than ValueVT then AssertOp can be used to specify whether the extra 157 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 158 /// (ISD::AssertSext). 159 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 160 const SDValue *Parts, unsigned NumParts, 161 MVT PartVT, EVT ValueVT, const Value *V, 162 Optional<CallingConv::ID> CC = None, 163 Optional<ISD::NodeType> AssertOp = None) { 164 // Let the target assemble the parts if it wants to 165 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 166 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 167 PartVT, ValueVT, CC)) 168 return Val; 169 170 if (ValueVT.isVector()) 171 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 172 CC); 173 174 assert(NumParts > 0 && "No parts to assemble!"); 175 SDValue Val = Parts[0]; 176 177 if (NumParts > 1) { 178 // Assemble the value from multiple parts. 179 if (ValueVT.isInteger()) { 180 unsigned PartBits = PartVT.getSizeInBits(); 181 unsigned ValueBits = ValueVT.getSizeInBits(); 182 183 // Assemble the power of 2 part. 184 unsigned RoundParts = 185 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 186 unsigned RoundBits = PartBits * RoundParts; 187 EVT RoundVT = RoundBits == ValueBits ? 188 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 189 SDValue Lo, Hi; 190 191 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 192 193 if (RoundParts > 2) { 194 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 195 PartVT, HalfVT, V); 196 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 197 RoundParts / 2, PartVT, HalfVT, V); 198 } else { 199 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 200 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 201 } 202 203 if (DAG.getDataLayout().isBigEndian()) 204 std::swap(Lo, Hi); 205 206 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 207 208 if (RoundParts < NumParts) { 209 // Assemble the trailing non-power-of-2 part. 210 unsigned OddParts = NumParts - RoundParts; 211 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 212 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 213 OddVT, V, CC); 214 215 // Combine the round and odd parts. 216 Lo = Val; 217 if (DAG.getDataLayout().isBigEndian()) 218 std::swap(Lo, Hi); 219 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 220 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 221 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 222 DAG.getConstant(Lo.getValueSizeInBits(), DL, 223 TLI.getShiftAmountTy( 224 TotalVT, DAG.getDataLayout()))); 225 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 226 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 227 } 228 } else if (PartVT.isFloatingPoint()) { 229 // FP split into multiple FP parts (for ppcf128) 230 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 231 "Unexpected split"); 232 SDValue Lo, Hi; 233 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 234 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 235 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 236 std::swap(Lo, Hi); 237 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 238 } else { 239 // FP split into integer parts (soft fp) 240 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 241 !PartVT.isVector() && "Unexpected split"); 242 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 243 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 244 } 245 } 246 247 // There is now one part, held in Val. Correct it to match ValueVT. 248 // PartEVT is the type of the register class that holds the value. 249 // ValueVT is the type of the inline asm operation. 250 EVT PartEVT = Val.getValueType(); 251 252 if (PartEVT == ValueVT) 253 return Val; 254 255 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 256 ValueVT.bitsLT(PartEVT)) { 257 // For an FP value in an integer part, we need to truncate to the right 258 // width first. 259 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 260 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 261 } 262 263 // Handle types that have the same size. 264 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 265 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 266 267 // Handle types with different sizes. 268 if (PartEVT.isInteger() && ValueVT.isInteger()) { 269 if (ValueVT.bitsLT(PartEVT)) { 270 // For a truncate, see if we have any information to 271 // indicate whether the truncated bits will always be 272 // zero or sign-extension. 273 if (AssertOp) 274 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 275 DAG.getValueType(ValueVT)); 276 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 277 } 278 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 279 } 280 281 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 282 // FP_ROUND's are always exact here. 283 if (ValueVT.bitsLT(Val.getValueType())) 284 return DAG.getNode( 285 ISD::FP_ROUND, DL, ValueVT, Val, 286 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 287 288 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 289 } 290 291 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 292 // then truncating. 293 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 294 ValueVT.bitsLT(PartEVT)) { 295 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 296 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 297 } 298 299 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 300 } 301 302 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 303 const Twine &ErrMsg) { 304 const Instruction *I = dyn_cast_or_null<Instruction>(V); 305 if (!V) 306 return Ctx.emitError(ErrMsg); 307 308 const char *AsmError = ", possible invalid constraint for vector type"; 309 if (const CallInst *CI = dyn_cast<CallInst>(I)) 310 if (CI->isInlineAsm()) 311 return Ctx.emitError(I, ErrMsg + AsmError); 312 313 return Ctx.emitError(I, ErrMsg); 314 } 315 316 /// getCopyFromPartsVector - Create a value that contains the specified legal 317 /// parts combined into the value they represent. If the parts combine to a 318 /// type larger than ValueVT then AssertOp can be used to specify whether the 319 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 320 /// ValueVT (ISD::AssertSext). 321 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 322 const SDValue *Parts, unsigned NumParts, 323 MVT PartVT, EVT ValueVT, const Value *V, 324 Optional<CallingConv::ID> CallConv) { 325 assert(ValueVT.isVector() && "Not a vector value"); 326 assert(NumParts > 0 && "No parts to assemble!"); 327 const bool IsABIRegCopy = CallConv.has_value(); 328 329 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 330 SDValue Val = Parts[0]; 331 332 // Handle a multi-element vector. 333 if (NumParts > 1) { 334 EVT IntermediateVT; 335 MVT RegisterVT; 336 unsigned NumIntermediates; 337 unsigned NumRegs; 338 339 if (IsABIRegCopy) { 340 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 341 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 342 NumIntermediates, RegisterVT); 343 } else { 344 NumRegs = 345 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 346 NumIntermediates, RegisterVT); 347 } 348 349 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 350 NumParts = NumRegs; // Silence a compiler warning. 351 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 352 assert(RegisterVT.getSizeInBits() == 353 Parts[0].getSimpleValueType().getSizeInBits() && 354 "Part type sizes don't match!"); 355 356 // Assemble the parts into intermediate operands. 357 SmallVector<SDValue, 8> Ops(NumIntermediates); 358 if (NumIntermediates == NumParts) { 359 // If the register was not expanded, truncate or copy the value, 360 // as appropriate. 361 for (unsigned i = 0; i != NumParts; ++i) 362 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 363 PartVT, IntermediateVT, V, CallConv); 364 } else if (NumParts > 0) { 365 // If the intermediate type was expanded, build the intermediate 366 // operands from the parts. 367 assert(NumParts % NumIntermediates == 0 && 368 "Must expand into a divisible number of parts!"); 369 unsigned Factor = NumParts / NumIntermediates; 370 for (unsigned i = 0; i != NumIntermediates; ++i) 371 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 372 PartVT, IntermediateVT, V, CallConv); 373 } 374 375 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 376 // intermediate operands. 377 EVT BuiltVectorTy = 378 IntermediateVT.isVector() 379 ? EVT::getVectorVT( 380 *DAG.getContext(), IntermediateVT.getScalarType(), 381 IntermediateVT.getVectorElementCount() * NumParts) 382 : EVT::getVectorVT(*DAG.getContext(), 383 IntermediateVT.getScalarType(), 384 NumIntermediates); 385 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 386 : ISD::BUILD_VECTOR, 387 DL, BuiltVectorTy, Ops); 388 } 389 390 // There is now one part, held in Val. Correct it to match ValueVT. 391 EVT PartEVT = Val.getValueType(); 392 393 if (PartEVT == ValueVT) 394 return Val; 395 396 if (PartEVT.isVector()) { 397 // Vector/Vector bitcast. 398 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 399 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 400 401 // If the element type of the source/dest vectors are the same, but the 402 // parts vector has more elements than the value vector, then we have a 403 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 404 // 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 } 419 420 // Promoted vector extract 421 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 422 } 423 424 // Trivial bitcast if the types are the same size and the destination 425 // vector type is legal. 426 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 427 TLI.isTypeLegal(ValueVT)) 428 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 429 430 if (ValueVT.getVectorNumElements() != 1) { 431 // Certain ABIs require that vectors are passed as integers. For vectors 432 // are the same size, this is an obvious bitcast. 433 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 434 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 435 } else if (ValueVT.bitsLT(PartEVT)) { 436 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 437 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 438 // Drop the extra bits. 439 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 440 return DAG.getBitcast(ValueVT, Val); 441 } 442 443 diagnosePossiblyInvalidConstraint( 444 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 445 return DAG.getUNDEF(ValueVT); 446 } 447 448 // Handle cases such as i8 -> <1 x i1> 449 EVT ValueSVT = ValueVT.getVectorElementType(); 450 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 451 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 452 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 453 else 454 Val = ValueVT.isFloatingPoint() 455 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 456 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 457 } 458 459 return DAG.getBuildVector(ValueVT, DL, Val); 460 } 461 462 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 463 SDValue Val, SDValue *Parts, unsigned NumParts, 464 MVT PartVT, const Value *V, 465 Optional<CallingConv::ID> CallConv); 466 467 /// getCopyToParts - Create a series of nodes that contain the specified value 468 /// split into legal parts. If the parts contain more bits than Val, then, for 469 /// integers, ExtendKind can be used to specify how to generate the extra bits. 470 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 471 SDValue *Parts, unsigned NumParts, MVT PartVT, 472 const Value *V, 473 Optional<CallingConv::ID> CallConv = None, 474 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 475 // Let the target split the parts if it wants to 476 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 477 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 478 CallConv)) 479 return; 480 EVT ValueVT = Val.getValueType(); 481 482 // Handle the vector case separately. 483 if (ValueVT.isVector()) 484 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 485 CallConv); 486 487 unsigned PartBits = PartVT.getSizeInBits(); 488 unsigned OrigNumParts = NumParts; 489 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 490 "Copying to an illegal type!"); 491 492 if (NumParts == 0) 493 return; 494 495 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 496 EVT PartEVT = PartVT; 497 if (PartEVT == ValueVT) { 498 assert(NumParts == 1 && "No-op copy with multiple parts!"); 499 Parts[0] = Val; 500 return; 501 } 502 503 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 504 // If the parts cover more bits than the value has, promote the value. 505 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 506 assert(NumParts == 1 && "Do not know what to promote to!"); 507 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 508 } else { 509 if (ValueVT.isFloatingPoint()) { 510 // FP values need to be bitcast, then extended if they are being put 511 // into a larger container. 512 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 513 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 514 } 515 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 516 ValueVT.isInteger() && 517 "Unknown mismatch!"); 518 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 519 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 520 if (PartVT == MVT::x86mmx) 521 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 522 } 523 } else if (PartBits == ValueVT.getSizeInBits()) { 524 // Different types of the same size. 525 assert(NumParts == 1 && PartEVT != ValueVT); 526 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 527 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 528 // If the parts cover less bits than value has, truncate the value. 529 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 530 ValueVT.isInteger() && 531 "Unknown mismatch!"); 532 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 533 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 534 if (PartVT == MVT::x86mmx) 535 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 536 } 537 538 // The value may have changed - recompute ValueVT. 539 ValueVT = Val.getValueType(); 540 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 541 "Failed to tile the value with PartVT!"); 542 543 if (NumParts == 1) { 544 if (PartEVT != ValueVT) { 545 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 546 "scalar-to-vector conversion failed"); 547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 548 } 549 550 Parts[0] = Val; 551 return; 552 } 553 554 // Expand the value into multiple parts. 555 if (NumParts & (NumParts - 1)) { 556 // The number of parts is not a power of 2. Split off and copy the tail. 557 assert(PartVT.isInteger() && ValueVT.isInteger() && 558 "Do not know what to expand to!"); 559 unsigned RoundParts = 1 << Log2_32(NumParts); 560 unsigned RoundBits = RoundParts * PartBits; 561 unsigned OddParts = NumParts - RoundParts; 562 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 563 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 564 565 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 566 CallConv); 567 568 if (DAG.getDataLayout().isBigEndian()) 569 // The odd parts were reversed by getCopyToParts - unreverse them. 570 std::reverse(Parts + RoundParts, Parts + NumParts); 571 572 NumParts = RoundParts; 573 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 574 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 575 } 576 577 // The number of parts is a power of 2. Repeatedly bisect the value using 578 // EXTRACT_ELEMENT. 579 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 580 EVT::getIntegerVT(*DAG.getContext(), 581 ValueVT.getSizeInBits()), 582 Val); 583 584 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 585 for (unsigned i = 0; i < NumParts; i += StepSize) { 586 unsigned ThisBits = StepSize * PartBits / 2; 587 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 588 SDValue &Part0 = Parts[i]; 589 SDValue &Part1 = Parts[i+StepSize/2]; 590 591 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 592 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 593 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 594 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 595 596 if (ThisBits == PartBits && ThisVT != PartVT) { 597 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 598 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 599 } 600 } 601 } 602 603 if (DAG.getDataLayout().isBigEndian()) 604 std::reverse(Parts, Parts + OrigNumParts); 605 } 606 607 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 608 const SDLoc &DL, EVT PartVT) { 609 if (!PartVT.isVector()) 610 return SDValue(); 611 612 EVT ValueVT = Val.getValueType(); 613 ElementCount PartNumElts = PartVT.getVectorElementCount(); 614 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 615 616 // We only support widening vectors with equivalent element types and 617 // fixed/scalable properties. If a target needs to widen a fixed-length type 618 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 619 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 620 PartNumElts.isScalable() != ValueNumElts.isScalable() || 621 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 622 return SDValue(); 623 624 // Widening a scalable vector to another scalable vector is done by inserting 625 // the vector into a larger undef one. 626 if (PartNumElts.isScalable()) 627 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 628 Val, DAG.getVectorIdxConstant(0, DL)); 629 630 EVT ElementVT = PartVT.getVectorElementType(); 631 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 632 // undef elements. 633 SmallVector<SDValue, 16> Ops; 634 DAG.ExtractVectorElements(Val, Ops); 635 SDValue EltUndef = DAG.getUNDEF(ElementVT); 636 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 637 638 // FIXME: Use CONCAT for 2x -> 4x. 639 return DAG.getBuildVector(PartVT, DL, Ops); 640 } 641 642 /// getCopyToPartsVector - Create a series of nodes that contain the specified 643 /// value split into legal parts. 644 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 645 SDValue Val, SDValue *Parts, unsigned NumParts, 646 MVT PartVT, const Value *V, 647 Optional<CallingConv::ID> CallConv) { 648 EVT ValueVT = Val.getValueType(); 649 assert(ValueVT.isVector() && "Not a vector"); 650 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 651 const bool IsABIRegCopy = CallConv.has_value(); 652 653 if (NumParts == 1) { 654 EVT PartEVT = PartVT; 655 if (PartEVT == ValueVT) { 656 // Nothing to do. 657 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 658 // Bitconvert vector->vector case. 659 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 660 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 661 Val = Widened; 662 } else if (PartVT.isVector() && 663 PartEVT.getVectorElementType().bitsGE( 664 ValueVT.getVectorElementType()) && 665 PartEVT.getVectorElementCount() == 666 ValueVT.getVectorElementCount()) { 667 668 // Promoted vector extract 669 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 670 } else if (PartEVT.isVector() && 671 PartEVT.getVectorElementType() != 672 ValueVT.getVectorElementType() && 673 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 674 TargetLowering::TypeWidenVector) { 675 // Combination of widening and promotion. 676 EVT WidenVT = 677 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 678 PartVT.getVectorElementCount()); 679 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 680 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 681 } else { 682 if (ValueVT.getVectorElementCount().isScalar()) { 683 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 684 DAG.getVectorIdxConstant(0, DL)); 685 } else { 686 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 687 assert(PartVT.getFixedSizeInBits() > ValueSize && 688 "lossy conversion of vector to scalar type"); 689 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 690 Val = DAG.getBitcast(IntermediateType, Val); 691 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 692 } 693 } 694 695 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 696 Parts[0] = Val; 697 return; 698 } 699 700 // Handle a multi-element vector. 701 EVT IntermediateVT; 702 MVT RegisterVT; 703 unsigned NumIntermediates; 704 unsigned NumRegs; 705 if (IsABIRegCopy) { 706 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 707 *DAG.getContext(), CallConv.value(), ValueVT, IntermediateVT, 708 NumIntermediates, RegisterVT); 709 } else { 710 NumRegs = 711 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 712 NumIntermediates, RegisterVT); 713 } 714 715 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 716 NumParts = NumRegs; // Silence a compiler warning. 717 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 718 719 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 720 "Mixing scalable and fixed vectors when copying in parts"); 721 722 Optional<ElementCount> DestEltCnt; 723 724 if (IntermediateVT.isVector()) 725 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 726 else 727 DestEltCnt = ElementCount::getFixed(NumIntermediates); 728 729 EVT BuiltVectorTy = EVT::getVectorVT( 730 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 731 732 if (ValueVT == BuiltVectorTy) { 733 // Nothing to do. 734 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 735 // Bitconvert vector->vector case. 736 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 737 } else { 738 if (BuiltVectorTy.getVectorElementType().bitsGT( 739 ValueVT.getVectorElementType())) { 740 // Integer promotion. 741 ValueVT = EVT::getVectorVT(*DAG.getContext(), 742 BuiltVectorTy.getVectorElementType(), 743 ValueVT.getVectorElementCount()); 744 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 745 } 746 747 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 748 Val = Widened; 749 } 750 } 751 752 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 753 754 // Split the vector into intermediate operands. 755 SmallVector<SDValue, 8> Ops(NumIntermediates); 756 for (unsigned i = 0; i != NumIntermediates; ++i) { 757 if (IntermediateVT.isVector()) { 758 // This does something sensible for scalable vectors - see the 759 // definition of EXTRACT_SUBVECTOR for further details. 760 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 761 Ops[i] = 762 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 763 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 764 } else { 765 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 766 DAG.getVectorIdxConstant(i, DL)); 767 } 768 } 769 770 // Split the intermediate operands into legal parts. 771 if (NumParts == NumIntermediates) { 772 // If the register was not expanded, promote or copy the value, 773 // as appropriate. 774 for (unsigned i = 0; i != NumParts; ++i) 775 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 776 } else if (NumParts > 0) { 777 // If the intermediate type was expanded, split each the value into 778 // legal parts. 779 assert(NumIntermediates != 0 && "division by zero"); 780 assert(NumParts % NumIntermediates == 0 && 781 "Must expand into a divisible number of parts!"); 782 unsigned Factor = NumParts / NumIntermediates; 783 for (unsigned i = 0; i != NumIntermediates; ++i) 784 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 785 CallConv); 786 } 787 } 788 789 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 790 EVT valuevt, Optional<CallingConv::ID> CC) 791 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 792 RegCount(1, regs.size()), CallConv(CC) {} 793 794 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 795 const DataLayout &DL, unsigned Reg, Type *Ty, 796 Optional<CallingConv::ID> CC) { 797 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 798 799 CallConv = CC; 800 801 for (EVT ValueVT : ValueVTs) { 802 unsigned NumRegs = 803 isABIMangled() 804 ? TLI.getNumRegistersForCallingConv(Context, CC.value(), ValueVT) 805 : TLI.getNumRegisters(Context, ValueVT); 806 MVT RegisterVT = 807 isABIMangled() 808 ? TLI.getRegisterTypeForCallingConv(Context, CC.value(), ValueVT) 809 : TLI.getRegisterType(Context, ValueVT); 810 for (unsigned i = 0; i != NumRegs; ++i) 811 Regs.push_back(Reg + i); 812 RegVTs.push_back(RegisterVT); 813 RegCount.push_back(NumRegs); 814 Reg += NumRegs; 815 } 816 } 817 818 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 819 FunctionLoweringInfo &FuncInfo, 820 const SDLoc &dl, SDValue &Chain, 821 SDValue *Flag, const Value *V) const { 822 // A Value with type {} or [0 x %t] needs no registers. 823 if (ValueVTs.empty()) 824 return SDValue(); 825 826 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 827 828 // Assemble the legal parts into the final values. 829 SmallVector<SDValue, 4> Values(ValueVTs.size()); 830 SmallVector<SDValue, 8> Parts; 831 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 832 // Copy the legal parts from the registers. 833 EVT ValueVT = ValueVTs[Value]; 834 unsigned NumRegs = RegCount[Value]; 835 MVT RegisterVT = 836 isABIMangled() ? TLI.getRegisterTypeForCallingConv( 837 *DAG.getContext(), CallConv.value(), RegVTs[Value]) 838 : RegVTs[Value]; 839 840 Parts.resize(NumRegs); 841 for (unsigned i = 0; i != NumRegs; ++i) { 842 SDValue P; 843 if (!Flag) { 844 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 845 } else { 846 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 847 *Flag = P.getValue(2); 848 } 849 850 Chain = P.getValue(1); 851 Parts[i] = P; 852 853 // If the source register was virtual and if we know something about it, 854 // add an assert node. 855 if (!Register::isVirtualRegister(Regs[Part + i]) || 856 !RegisterVT.isInteger()) 857 continue; 858 859 const FunctionLoweringInfo::LiveOutInfo *LOI = 860 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 861 if (!LOI) 862 continue; 863 864 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 865 unsigned NumSignBits = LOI->NumSignBits; 866 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 867 868 if (NumZeroBits == RegSize) { 869 // The current value is a zero. 870 // Explicitly express that as it would be easier for 871 // optimizations to kick in. 872 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 873 continue; 874 } 875 876 // FIXME: We capture more information than the dag can represent. For 877 // now, just use the tightest assertzext/assertsext possible. 878 bool isSExt; 879 EVT FromVT(MVT::Other); 880 if (NumZeroBits) { 881 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 882 isSExt = false; 883 } else if (NumSignBits > 1) { 884 FromVT = 885 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 886 isSExt = true; 887 } else { 888 continue; 889 } 890 // Add an assertion node. 891 assert(FromVT != MVT::Other); 892 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 893 RegisterVT, P, DAG.getValueType(FromVT)); 894 } 895 896 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 897 RegisterVT, ValueVT, V, CallConv); 898 Part += NumRegs; 899 Parts.clear(); 900 } 901 902 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 903 } 904 905 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 906 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 907 const Value *V, 908 ISD::NodeType PreferredExtendType) const { 909 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 910 ISD::NodeType ExtendKind = PreferredExtendType; 911 912 // Get the list of the values's legal parts. 913 unsigned NumRegs = Regs.size(); 914 SmallVector<SDValue, 8> Parts(NumRegs); 915 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 916 unsigned NumParts = RegCount[Value]; 917 918 MVT RegisterVT = 919 isABIMangled() ? TLI.getRegisterTypeForCallingConv( 920 *DAG.getContext(), CallConv.value(), RegVTs[Value]) 921 : RegVTs[Value]; 922 923 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 924 ExtendKind = ISD::ZERO_EXTEND; 925 926 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 927 NumParts, RegisterVT, V, CallConv, ExtendKind); 928 Part += NumParts; 929 } 930 931 // Copy the parts into the registers. 932 SmallVector<SDValue, 8> Chains(NumRegs); 933 for (unsigned i = 0; i != NumRegs; ++i) { 934 SDValue Part; 935 if (!Flag) { 936 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 937 } else { 938 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 939 *Flag = Part.getValue(1); 940 } 941 942 Chains[i] = Part.getValue(0); 943 } 944 945 if (NumRegs == 1 || Flag) 946 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 947 // flagged to it. That is the CopyToReg nodes and the user are considered 948 // a single scheduling unit. If we create a TokenFactor and return it as 949 // chain, then the TokenFactor is both a predecessor (operand) of the 950 // user as well as a successor (the TF operands are flagged to the user). 951 // c1, f1 = CopyToReg 952 // c2, f2 = CopyToReg 953 // c3 = TokenFactor c1, c2 954 // ... 955 // = op c3, ..., f2 956 Chain = Chains[NumRegs-1]; 957 else 958 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 959 } 960 961 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 962 unsigned MatchingIdx, const SDLoc &dl, 963 SelectionDAG &DAG, 964 std::vector<SDValue> &Ops) const { 965 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 966 967 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 968 if (HasMatching) 969 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 970 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 971 // Put the register class of the virtual registers in the flag word. That 972 // way, later passes can recompute register class constraints for inline 973 // assembly as well as normal instructions. 974 // Don't do this for tied operands that can use the regclass information 975 // from the def. 976 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 977 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 978 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 979 } 980 981 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 982 Ops.push_back(Res); 983 984 if (Code == InlineAsm::Kind_Clobber) { 985 // Clobbers should always have a 1:1 mapping with registers, and may 986 // reference registers that have illegal (e.g. vector) types. Hence, we 987 // shouldn't try to apply any sort of splitting logic to them. 988 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 989 "No 1:1 mapping from clobbers to regs?"); 990 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 991 (void)SP; 992 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 993 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 994 assert( 995 (Regs[I] != SP || 996 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 997 "If we clobbered the stack pointer, MFI should know about it."); 998 } 999 return; 1000 } 1001 1002 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1003 MVT RegisterVT = RegVTs[Value]; 1004 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1005 RegisterVT); 1006 for (unsigned i = 0; i != NumRegs; ++i) { 1007 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1008 unsigned TheReg = Regs[Reg++]; 1009 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1010 } 1011 } 1012 } 1013 1014 SmallVector<std::pair<unsigned, TypeSize>, 4> 1015 RegsForValue::getRegsAndSizes() const { 1016 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1017 unsigned I = 0; 1018 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1019 unsigned RegCount = std::get<0>(CountAndVT); 1020 MVT RegisterVT = std::get<1>(CountAndVT); 1021 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1022 for (unsigned E = I + RegCount; I != E; ++I) 1023 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1024 } 1025 return OutVec; 1026 } 1027 1028 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1029 const TargetLibraryInfo *li) { 1030 AA = aa; 1031 GFI = gfi; 1032 LibInfo = li; 1033 Context = DAG.getContext(); 1034 LPadToCallSiteMap.clear(); 1035 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1036 } 1037 1038 void SelectionDAGBuilder::clear() { 1039 NodeMap.clear(); 1040 UnusedArgNodeMap.clear(); 1041 PendingLoads.clear(); 1042 PendingExports.clear(); 1043 PendingConstrainedFP.clear(); 1044 PendingConstrainedFPStrict.clear(); 1045 CurInst = nullptr; 1046 HasTailCall = false; 1047 SDNodeOrder = LowestSDNodeOrder; 1048 StatepointLowering.clear(); 1049 } 1050 1051 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1052 DanglingDebugInfoMap.clear(); 1053 } 1054 1055 // Update DAG root to include dependencies on Pending chains. 1056 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1057 SDValue Root = DAG.getRoot(); 1058 1059 if (Pending.empty()) 1060 return Root; 1061 1062 // Add current root to PendingChains, unless we already indirectly 1063 // depend on it. 1064 if (Root.getOpcode() != ISD::EntryToken) { 1065 unsigned i = 0, e = Pending.size(); 1066 for (; i != e; ++i) { 1067 assert(Pending[i].getNode()->getNumOperands() > 1); 1068 if (Pending[i].getNode()->getOperand(0) == Root) 1069 break; // Don't add the root if we already indirectly depend on it. 1070 } 1071 1072 if (i == e) 1073 Pending.push_back(Root); 1074 } 1075 1076 if (Pending.size() == 1) 1077 Root = Pending[0]; 1078 else 1079 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1080 1081 DAG.setRoot(Root); 1082 Pending.clear(); 1083 return Root; 1084 } 1085 1086 SDValue SelectionDAGBuilder::getMemoryRoot() { 1087 return updateRoot(PendingLoads); 1088 } 1089 1090 SDValue SelectionDAGBuilder::getRoot() { 1091 // Chain up all pending constrained intrinsics together with all 1092 // pending loads, by simply appending them to PendingLoads and 1093 // then calling getMemoryRoot(). 1094 PendingLoads.reserve(PendingLoads.size() + 1095 PendingConstrainedFP.size() + 1096 PendingConstrainedFPStrict.size()); 1097 PendingLoads.append(PendingConstrainedFP.begin(), 1098 PendingConstrainedFP.end()); 1099 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1100 PendingConstrainedFPStrict.end()); 1101 PendingConstrainedFP.clear(); 1102 PendingConstrainedFPStrict.clear(); 1103 return getMemoryRoot(); 1104 } 1105 1106 SDValue SelectionDAGBuilder::getControlRoot() { 1107 // We need to emit pending fpexcept.strict constrained intrinsics, 1108 // so append them to the PendingExports list. 1109 PendingExports.append(PendingConstrainedFPStrict.begin(), 1110 PendingConstrainedFPStrict.end()); 1111 PendingConstrainedFPStrict.clear(); 1112 return updateRoot(PendingExports); 1113 } 1114 1115 void SelectionDAGBuilder::visit(const Instruction &I) { 1116 // Set up outgoing PHI node register values before emitting the terminator. 1117 if (I.isTerminator()) { 1118 HandlePHINodesInSuccessorBlocks(I.getParent()); 1119 } 1120 1121 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1122 if (!isa<DbgInfoIntrinsic>(I)) 1123 ++SDNodeOrder; 1124 1125 CurInst = &I; 1126 1127 // Set inserted listener only if required. 1128 bool NodeInserted = false; 1129 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1130 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1131 if (PCSectionsMD) { 1132 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1133 DAG, [&](SDNode *) { NodeInserted = true; }); 1134 } 1135 1136 visit(I.getOpcode(), I); 1137 1138 if (!I.isTerminator() && !HasTailCall && 1139 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1140 CopyToExportRegsIfNeeded(&I); 1141 1142 // Handle metadata. 1143 if (PCSectionsMD) { 1144 auto It = NodeMap.find(&I); 1145 if (It != NodeMap.end()) { 1146 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1147 } else if (NodeInserted) { 1148 // This should not happen; if it does, don't let it go unnoticed so we can 1149 // fix it. Relevant visit*() function is probably missing a setValue(). 1150 errs() << "warning: loosing !pcsections metadata [" 1151 << I.getModule()->getName() << "]\n"; 1152 LLVM_DEBUG(I.dump()); 1153 assert(false); 1154 } 1155 } 1156 1157 CurInst = nullptr; 1158 } 1159 1160 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1161 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1162 } 1163 1164 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1165 // Note: this doesn't use InstVisitor, because it has to work with 1166 // ConstantExpr's in addition to instructions. 1167 switch (Opcode) { 1168 default: llvm_unreachable("Unknown instruction type encountered!"); 1169 // Build the switch statement using the Instruction.def file. 1170 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1171 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1172 #include "llvm/IR/Instruction.def" 1173 } 1174 } 1175 1176 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1177 DebugLoc DL, unsigned Order) { 1178 // We treat variadic dbg_values differently at this stage. 1179 if (DI->hasArgList()) { 1180 // For variadic dbg_values we will now insert an undef. 1181 // FIXME: We can potentially recover these! 1182 SmallVector<SDDbgOperand, 2> Locs; 1183 for (const Value *V : DI->getValues()) { 1184 auto Undef = UndefValue::get(V->getType()); 1185 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1186 } 1187 SDDbgValue *SDV = DAG.getDbgValueList( 1188 DI->getVariable(), DI->getExpression(), Locs, {}, 1189 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1190 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1191 } else { 1192 // TODO: Dangling debug info will eventually either be resolved or produce 1193 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1194 // between the original dbg.value location and its resolved DBG_VALUE, 1195 // which we should ideally fill with an extra Undef DBG_VALUE. 1196 assert(DI->getNumVariableLocationOps() == 1 && 1197 "DbgValueInst without an ArgList should have a single location " 1198 "operand."); 1199 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1200 } 1201 } 1202 1203 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1204 const DIExpression *Expr) { 1205 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1206 const DbgValueInst *DI = DDI.getDI(); 1207 DIVariable *DanglingVariable = DI->getVariable(); 1208 DIExpression *DanglingExpr = DI->getExpression(); 1209 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1210 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1211 return true; 1212 } 1213 return false; 1214 }; 1215 1216 for (auto &DDIMI : DanglingDebugInfoMap) { 1217 DanglingDebugInfoVector &DDIV = DDIMI.second; 1218 1219 // If debug info is to be dropped, run it through final checks to see 1220 // whether it can be salvaged. 1221 for (auto &DDI : DDIV) 1222 if (isMatchingDbgValue(DDI)) 1223 salvageUnresolvedDbgValue(DDI); 1224 1225 erase_if(DDIV, isMatchingDbgValue); 1226 } 1227 } 1228 1229 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1230 // generate the debug data structures now that we've seen its definition. 1231 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1232 SDValue Val) { 1233 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1234 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1235 return; 1236 1237 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1238 for (auto &DDI : DDIV) { 1239 const DbgValueInst *DI = DDI.getDI(); 1240 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1241 assert(DI && "Ill-formed DanglingDebugInfo"); 1242 DebugLoc dl = DDI.getdl(); 1243 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1244 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1245 DILocalVariable *Variable = DI->getVariable(); 1246 DIExpression *Expr = DI->getExpression(); 1247 assert(Variable->isValidLocationForIntrinsic(dl) && 1248 "Expected inlined-at fields to agree"); 1249 SDDbgValue *SDV; 1250 if (Val.getNode()) { 1251 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1252 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1253 // we couldn't resolve it directly when examining the DbgValue intrinsic 1254 // in the first place we should not be more successful here). Unless we 1255 // have some test case that prove this to be correct we should avoid 1256 // calling EmitFuncArgumentDbgValue here. 1257 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, 1258 FuncArgumentDbgValueKind::Value, Val)) { 1259 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1260 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1261 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1262 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1263 // inserted after the definition of Val when emitting the instructions 1264 // after ISel. An alternative could be to teach 1265 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1266 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1267 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1268 << ValSDNodeOrder << "\n"); 1269 SDV = getDbgValue(Val, Variable, Expr, dl, 1270 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1271 DAG.AddDbgValue(SDV, false); 1272 } else 1273 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1274 << "in EmitFuncArgumentDbgValue\n"); 1275 } else { 1276 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1277 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1278 auto SDV = 1279 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1280 DAG.AddDbgValue(SDV, false); 1281 } 1282 } 1283 DDIV.clear(); 1284 } 1285 1286 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1287 // TODO: For the variadic implementation, instead of only checking the fail 1288 // state of `handleDebugValue`, we need know specifically which values were 1289 // invalid, so that we attempt to salvage only those values when processing 1290 // a DIArgList. 1291 assert(!DDI.getDI()->hasArgList() && 1292 "Not implemented for variadic dbg_values"); 1293 Value *V = DDI.getDI()->getValue(0); 1294 DILocalVariable *Var = DDI.getDI()->getVariable(); 1295 DIExpression *Expr = DDI.getDI()->getExpression(); 1296 DebugLoc DL = DDI.getdl(); 1297 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1298 unsigned SDOrder = DDI.getSDNodeOrder(); 1299 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1300 // that DW_OP_stack_value is desired. 1301 assert(isa<DbgValueInst>(DDI.getDI())); 1302 bool StackValue = true; 1303 1304 // Can this Value can be encoded without any further work? 1305 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1306 return; 1307 1308 // Attempt to salvage back through as many instructions as possible. Bail if 1309 // a non-instruction is seen, such as a constant expression or global 1310 // variable. FIXME: Further work could recover those too. 1311 while (isa<Instruction>(V)) { 1312 Instruction &VAsInst = *cast<Instruction>(V); 1313 // Temporary "0", awaiting real implementation. 1314 SmallVector<uint64_t, 16> Ops; 1315 SmallVector<Value *, 4> AdditionalValues; 1316 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1317 AdditionalValues); 1318 // If we cannot salvage any further, and haven't yet found a suitable debug 1319 // expression, bail out. 1320 if (!V) 1321 break; 1322 1323 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1324 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1325 // here for variadic dbg_values, remove that condition. 1326 if (!AdditionalValues.empty()) 1327 break; 1328 1329 // New value and expr now represent this debuginfo. 1330 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1331 1332 // Some kind of simplification occurred: check whether the operand of the 1333 // salvaged debug expression can be encoded in this DAG. 1334 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1335 /*IsVariadic=*/false)) { 1336 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1337 << *DDI.getDI() << "\nBy stripping back to:\n " << *V); 1338 return; 1339 } 1340 } 1341 1342 // This was the final opportunity to salvage this debug information, and it 1343 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1344 // any earlier variable location. 1345 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1346 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1347 DAG.AddDbgValue(SDV, false); 1348 1349 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << *DDI.getDI() 1350 << "\n"); 1351 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1352 << "\n"); 1353 } 1354 1355 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1356 DILocalVariable *Var, 1357 DIExpression *Expr, DebugLoc dl, 1358 DebugLoc InstDL, unsigned Order, 1359 bool IsVariadic) { 1360 if (Values.empty()) 1361 return true; 1362 SmallVector<SDDbgOperand> LocationOps; 1363 SmallVector<SDNode *> Dependencies; 1364 for (const Value *V : Values) { 1365 // Constant value. 1366 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1367 isa<ConstantPointerNull>(V)) { 1368 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1369 continue; 1370 } 1371 1372 // Look through IntToPtr constants. 1373 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1374 if (CE->getOpcode() == Instruction::IntToPtr) { 1375 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1376 continue; 1377 } 1378 1379 // If the Value is a frame index, we can create a FrameIndex debug value 1380 // without relying on the DAG at all. 1381 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1382 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1383 if (SI != FuncInfo.StaticAllocaMap.end()) { 1384 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1385 continue; 1386 } 1387 } 1388 1389 // Do not use getValue() in here; we don't want to generate code at 1390 // this point if it hasn't been done yet. 1391 SDValue N = NodeMap[V]; 1392 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1393 N = UnusedArgNodeMap[V]; 1394 if (N.getNode()) { 1395 // Only emit func arg dbg value for non-variadic dbg.values for now. 1396 if (!IsVariadic && 1397 EmitFuncArgumentDbgValue(V, Var, Expr, dl, 1398 FuncArgumentDbgValueKind::Value, N)) 1399 return true; 1400 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1401 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1402 // describe stack slot locations. 1403 // 1404 // Consider "int x = 0; int *px = &x;". There are two kinds of 1405 // interesting debug values here after optimization: 1406 // 1407 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1408 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1409 // 1410 // Both describe the direct values of their associated variables. 1411 Dependencies.push_back(N.getNode()); 1412 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1413 continue; 1414 } 1415 LocationOps.emplace_back( 1416 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1417 continue; 1418 } 1419 1420 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1421 // Special rules apply for the first dbg.values of parameter variables in a 1422 // function. Identify them by the fact they reference Argument Values, that 1423 // they're parameters, and they are parameters of the current function. We 1424 // need to let them dangle until they get an SDNode. 1425 bool IsParamOfFunc = 1426 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1427 if (IsParamOfFunc) 1428 return false; 1429 1430 // The value is not used in this block yet (or it would have an SDNode). 1431 // We still want the value to appear for the user if possible -- if it has 1432 // an associated VReg, we can refer to that instead. 1433 auto VMI = FuncInfo.ValueMap.find(V); 1434 if (VMI != FuncInfo.ValueMap.end()) { 1435 unsigned Reg = VMI->second; 1436 // If this is a PHI node, it may be split up into several MI PHI nodes 1437 // (in FunctionLoweringInfo::set). 1438 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1439 V->getType(), None); 1440 if (RFV.occupiesMultipleRegs()) { 1441 // FIXME: We could potentially support variadic dbg_values here. 1442 if (IsVariadic) 1443 return false; 1444 unsigned Offset = 0; 1445 unsigned BitsToDescribe = 0; 1446 if (auto VarSize = Var->getSizeInBits()) 1447 BitsToDescribe = *VarSize; 1448 if (auto Fragment = Expr->getFragmentInfo()) 1449 BitsToDescribe = Fragment->SizeInBits; 1450 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1451 // Bail out if all bits are described already. 1452 if (Offset >= BitsToDescribe) 1453 break; 1454 // TODO: handle scalable vectors. 1455 unsigned RegisterSize = RegAndSize.second; 1456 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1457 ? BitsToDescribe - Offset 1458 : RegisterSize; 1459 auto FragmentExpr = DIExpression::createFragmentExpression( 1460 Expr, Offset, FragmentSize); 1461 if (!FragmentExpr) 1462 continue; 1463 SDDbgValue *SDV = DAG.getVRegDbgValue( 1464 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1465 DAG.AddDbgValue(SDV, false); 1466 Offset += RegisterSize; 1467 } 1468 return true; 1469 } 1470 // We can use simple vreg locations for variadic dbg_values as well. 1471 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1472 continue; 1473 } 1474 // We failed to create a SDDbgOperand for V. 1475 return false; 1476 } 1477 1478 // We have created a SDDbgOperand for each Value in Values. 1479 // Should use Order instead of SDNodeOrder? 1480 assert(!LocationOps.empty()); 1481 SDDbgValue *SDV = 1482 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1483 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1484 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1485 return true; 1486 } 1487 1488 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1489 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1490 for (auto &Pair : DanglingDebugInfoMap) 1491 for (auto &DDI : Pair.second) 1492 salvageUnresolvedDbgValue(DDI); 1493 clearDanglingDebugInfo(); 1494 } 1495 1496 /// getCopyFromRegs - If there was virtual register allocated for the value V 1497 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1498 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1499 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1500 SDValue Result; 1501 1502 if (It != FuncInfo.ValueMap.end()) { 1503 Register InReg = It->second; 1504 1505 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1506 DAG.getDataLayout(), InReg, Ty, 1507 None); // This is not an ABI copy. 1508 SDValue Chain = DAG.getEntryNode(); 1509 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1510 V); 1511 resolveDanglingDebugInfo(V, Result); 1512 } 1513 1514 return Result; 1515 } 1516 1517 /// getValue - Return an SDValue for the given Value. 1518 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1519 // If we already have an SDValue for this value, use it. It's important 1520 // to do this first, so that we don't create a CopyFromReg if we already 1521 // have a regular SDValue. 1522 SDValue &N = NodeMap[V]; 1523 if (N.getNode()) return N; 1524 1525 // If there's a virtual register allocated and initialized for this 1526 // value, use it. 1527 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1528 return copyFromReg; 1529 1530 // Otherwise create a new SDValue and remember it. 1531 SDValue Val = getValueImpl(V); 1532 NodeMap[V] = Val; 1533 resolveDanglingDebugInfo(V, Val); 1534 return Val; 1535 } 1536 1537 /// getNonRegisterValue - Return an SDValue for the given Value, but 1538 /// don't look in FuncInfo.ValueMap for a virtual register. 1539 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1540 // If we already have an SDValue for this value, use it. 1541 SDValue &N = NodeMap[V]; 1542 if (N.getNode()) { 1543 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1544 // Remove the debug location from the node as the node is about to be used 1545 // in a location which may differ from the original debug location. This 1546 // is relevant to Constant and ConstantFP nodes because they can appear 1547 // as constant expressions inside PHI nodes. 1548 N->setDebugLoc(DebugLoc()); 1549 } 1550 return N; 1551 } 1552 1553 // Otherwise create a new SDValue and remember it. 1554 SDValue Val = getValueImpl(V); 1555 NodeMap[V] = Val; 1556 resolveDanglingDebugInfo(V, Val); 1557 return Val; 1558 } 1559 1560 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1561 /// Create an SDValue for the given value. 1562 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1563 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1564 1565 if (const Constant *C = dyn_cast<Constant>(V)) { 1566 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1567 1568 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1569 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1570 1571 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1572 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1573 1574 if (isa<ConstantPointerNull>(C)) { 1575 unsigned AS = V->getType()->getPointerAddressSpace(); 1576 return DAG.getConstant(0, getCurSDLoc(), 1577 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1578 } 1579 1580 if (match(C, m_VScale(DAG.getDataLayout()))) 1581 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1582 1583 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1584 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1585 1586 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1587 return DAG.getUNDEF(VT); 1588 1589 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1590 visit(CE->getOpcode(), *CE); 1591 SDValue N1 = NodeMap[V]; 1592 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1593 return N1; 1594 } 1595 1596 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1597 SmallVector<SDValue, 4> Constants; 1598 for (const Use &U : C->operands()) { 1599 SDNode *Val = getValue(U).getNode(); 1600 // If the operand is an empty aggregate, there are no values. 1601 if (!Val) continue; 1602 // Add each leaf value from the operand to the Constants list 1603 // to form a flattened list of all the values. 1604 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1605 Constants.push_back(SDValue(Val, i)); 1606 } 1607 1608 return DAG.getMergeValues(Constants, getCurSDLoc()); 1609 } 1610 1611 if (const ConstantDataSequential *CDS = 1612 dyn_cast<ConstantDataSequential>(C)) { 1613 SmallVector<SDValue, 4> Ops; 1614 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1615 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1616 // Add each leaf value from the operand to the Constants list 1617 // to form a flattened list of all the values. 1618 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1619 Ops.push_back(SDValue(Val, i)); 1620 } 1621 1622 if (isa<ArrayType>(CDS->getType())) 1623 return DAG.getMergeValues(Ops, getCurSDLoc()); 1624 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1625 } 1626 1627 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1628 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1629 "Unknown struct or array constant!"); 1630 1631 SmallVector<EVT, 4> ValueVTs; 1632 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1633 unsigned NumElts = ValueVTs.size(); 1634 if (NumElts == 0) 1635 return SDValue(); // empty struct 1636 SmallVector<SDValue, 4> Constants(NumElts); 1637 for (unsigned i = 0; i != NumElts; ++i) { 1638 EVT EltVT = ValueVTs[i]; 1639 if (isa<UndefValue>(C)) 1640 Constants[i] = DAG.getUNDEF(EltVT); 1641 else if (EltVT.isFloatingPoint()) 1642 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1643 else 1644 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1645 } 1646 1647 return DAG.getMergeValues(Constants, getCurSDLoc()); 1648 } 1649 1650 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1651 return DAG.getBlockAddress(BA, VT); 1652 1653 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1654 return getValue(Equiv->getGlobalValue()); 1655 1656 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1657 return getValue(NC->getGlobalValue()); 1658 1659 VectorType *VecTy = cast<VectorType>(V->getType()); 1660 1661 // Now that we know the number and type of the elements, get that number of 1662 // elements into the Ops array based on what kind of constant it is. 1663 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1664 SmallVector<SDValue, 16> Ops; 1665 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1666 for (unsigned i = 0; i != NumElements; ++i) 1667 Ops.push_back(getValue(CV->getOperand(i))); 1668 1669 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1670 } 1671 1672 if (isa<ConstantAggregateZero>(C)) { 1673 EVT EltVT = 1674 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1675 1676 SDValue Op; 1677 if (EltVT.isFloatingPoint()) 1678 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1679 else 1680 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1681 1682 if (isa<ScalableVectorType>(VecTy)) 1683 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1684 1685 SmallVector<SDValue, 16> Ops; 1686 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1687 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1688 } 1689 1690 llvm_unreachable("Unknown vector constant"); 1691 } 1692 1693 // If this is a static alloca, generate it as the frameindex instead of 1694 // computation. 1695 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1696 DenseMap<const AllocaInst*, int>::iterator SI = 1697 FuncInfo.StaticAllocaMap.find(AI); 1698 if (SI != FuncInfo.StaticAllocaMap.end()) 1699 return DAG.getFrameIndex(SI->second, 1700 TLI.getFrameIndexTy(DAG.getDataLayout())); 1701 } 1702 1703 // If this is an instruction which fast-isel has deferred, select it now. 1704 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1705 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1706 1707 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1708 Inst->getType(), None); 1709 SDValue Chain = DAG.getEntryNode(); 1710 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1711 } 1712 1713 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1714 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1715 1716 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1717 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1718 1719 llvm_unreachable("Can't get register for value!"); 1720 } 1721 1722 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1723 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1724 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1725 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1726 bool IsSEH = isAsynchronousEHPersonality(Pers); 1727 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1728 if (!IsSEH) 1729 CatchPadMBB->setIsEHScopeEntry(); 1730 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1731 if (IsMSVCCXX || IsCoreCLR) 1732 CatchPadMBB->setIsEHFuncletEntry(); 1733 } 1734 1735 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1736 // Update machine-CFG edge. 1737 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1738 FuncInfo.MBB->addSuccessor(TargetMBB); 1739 TargetMBB->setIsEHCatchretTarget(true); 1740 DAG.getMachineFunction().setHasEHCatchret(true); 1741 1742 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1743 bool IsSEH = isAsynchronousEHPersonality(Pers); 1744 if (IsSEH) { 1745 // If this is not a fall-through branch or optimizations are switched off, 1746 // emit the branch. 1747 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1748 TM.getOptLevel() == CodeGenOpt::None) 1749 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1750 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1751 return; 1752 } 1753 1754 // Figure out the funclet membership for the catchret's successor. 1755 // This will be used by the FuncletLayout pass to determine how to order the 1756 // BB's. 1757 // A 'catchret' returns to the outer scope's color. 1758 Value *ParentPad = I.getCatchSwitchParentPad(); 1759 const BasicBlock *SuccessorColor; 1760 if (isa<ConstantTokenNone>(ParentPad)) 1761 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1762 else 1763 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1764 assert(SuccessorColor && "No parent funclet for catchret!"); 1765 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1766 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1767 1768 // Create the terminator node. 1769 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1770 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1771 DAG.getBasicBlock(SuccessorColorMBB)); 1772 DAG.setRoot(Ret); 1773 } 1774 1775 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1776 // Don't emit any special code for the cleanuppad instruction. It just marks 1777 // the start of an EH scope/funclet. 1778 FuncInfo.MBB->setIsEHScopeEntry(); 1779 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1780 if (Pers != EHPersonality::Wasm_CXX) { 1781 FuncInfo.MBB->setIsEHFuncletEntry(); 1782 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1783 } 1784 } 1785 1786 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1787 // not match, it is OK to add only the first unwind destination catchpad to the 1788 // successors, because there will be at least one invoke instruction within the 1789 // catch scope that points to the next unwind destination, if one exists, so 1790 // CFGSort cannot mess up with BB sorting order. 1791 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1792 // call within them, and catchpads only consisting of 'catch (...)' have a 1793 // '__cxa_end_catch' call within them, both of which generate invokes in case 1794 // the next unwind destination exists, i.e., the next unwind destination is not 1795 // the caller.) 1796 // 1797 // Having at most one EH pad successor is also simpler and helps later 1798 // transformations. 1799 // 1800 // For example, 1801 // current: 1802 // invoke void @foo to ... unwind label %catch.dispatch 1803 // catch.dispatch: 1804 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1805 // catch.start: 1806 // ... 1807 // ... in this BB or some other child BB dominated by this BB there will be an 1808 // invoke that points to 'next' BB as an unwind destination 1809 // 1810 // next: ; We don't need to add this to 'current' BB's successor 1811 // ... 1812 static void findWasmUnwindDestinations( 1813 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1814 BranchProbability Prob, 1815 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1816 &UnwindDests) { 1817 while (EHPadBB) { 1818 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1819 if (isa<CleanupPadInst>(Pad)) { 1820 // Stop on cleanup pads. 1821 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1822 UnwindDests.back().first->setIsEHScopeEntry(); 1823 break; 1824 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1825 // Add the catchpad handlers to the possible destinations. We don't 1826 // continue to the unwind destination of the catchswitch for wasm. 1827 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1828 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1829 UnwindDests.back().first->setIsEHScopeEntry(); 1830 } 1831 break; 1832 } else { 1833 continue; 1834 } 1835 } 1836 } 1837 1838 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1839 /// many places it could ultimately go. In the IR, we have a single unwind 1840 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1841 /// This function skips over imaginary basic blocks that hold catchswitch 1842 /// instructions, and finds all the "real" machine 1843 /// basic block destinations. As those destinations may not be successors of 1844 /// EHPadBB, here we also calculate the edge probability to those destinations. 1845 /// The passed-in Prob is the edge probability to EHPadBB. 1846 static void findUnwindDestinations( 1847 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1848 BranchProbability Prob, 1849 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1850 &UnwindDests) { 1851 EHPersonality Personality = 1852 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1853 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1854 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1855 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1856 bool IsSEH = isAsynchronousEHPersonality(Personality); 1857 1858 if (IsWasmCXX) { 1859 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1860 assert(UnwindDests.size() <= 1 && 1861 "There should be at most one unwind destination for wasm"); 1862 return; 1863 } 1864 1865 while (EHPadBB) { 1866 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1867 BasicBlock *NewEHPadBB = nullptr; 1868 if (isa<LandingPadInst>(Pad)) { 1869 // Stop on landingpads. They are not funclets. 1870 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1871 break; 1872 } else if (isa<CleanupPadInst>(Pad)) { 1873 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1874 // personalities. 1875 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1876 UnwindDests.back().first->setIsEHScopeEntry(); 1877 UnwindDests.back().first->setIsEHFuncletEntry(); 1878 break; 1879 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1880 // Add the catchpad handlers to the possible destinations. 1881 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1882 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1883 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1884 if (IsMSVCCXX || IsCoreCLR) 1885 UnwindDests.back().first->setIsEHFuncletEntry(); 1886 if (!IsSEH) 1887 UnwindDests.back().first->setIsEHScopeEntry(); 1888 } 1889 NewEHPadBB = CatchSwitch->getUnwindDest(); 1890 } else { 1891 continue; 1892 } 1893 1894 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1895 if (BPI && NewEHPadBB) 1896 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1897 EHPadBB = NewEHPadBB; 1898 } 1899 } 1900 1901 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1902 // Update successor info. 1903 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1904 auto UnwindDest = I.getUnwindDest(); 1905 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1906 BranchProbability UnwindDestProb = 1907 (BPI && UnwindDest) 1908 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1909 : BranchProbability::getZero(); 1910 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1911 for (auto &UnwindDest : UnwindDests) { 1912 UnwindDest.first->setIsEHPad(); 1913 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1914 } 1915 FuncInfo.MBB->normalizeSuccProbs(); 1916 1917 // Create the terminator node. 1918 SDValue Ret = 1919 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1920 DAG.setRoot(Ret); 1921 } 1922 1923 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1924 report_fatal_error("visitCatchSwitch not yet implemented!"); 1925 } 1926 1927 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1928 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1929 auto &DL = DAG.getDataLayout(); 1930 SDValue Chain = getControlRoot(); 1931 SmallVector<ISD::OutputArg, 8> Outs; 1932 SmallVector<SDValue, 8> OutVals; 1933 1934 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1935 // lower 1936 // 1937 // %val = call <ty> @llvm.experimental.deoptimize() 1938 // ret <ty> %val 1939 // 1940 // differently. 1941 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1942 LowerDeoptimizingReturn(); 1943 return; 1944 } 1945 1946 if (!FuncInfo.CanLowerReturn) { 1947 unsigned DemoteReg = FuncInfo.DemoteRegister; 1948 const Function *F = I.getParent()->getParent(); 1949 1950 // Emit a store of the return value through the virtual register. 1951 // Leave Outs empty so that LowerReturn won't try to load return 1952 // registers the usual way. 1953 SmallVector<EVT, 1> PtrValueVTs; 1954 ComputeValueVTs(TLI, DL, 1955 F->getReturnType()->getPointerTo( 1956 DAG.getDataLayout().getAllocaAddrSpace()), 1957 PtrValueVTs); 1958 1959 SDValue RetPtr = 1960 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 1961 SDValue RetOp = getValue(I.getOperand(0)); 1962 1963 SmallVector<EVT, 4> ValueVTs, MemVTs; 1964 SmallVector<uint64_t, 4> Offsets; 1965 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1966 &Offsets); 1967 unsigned NumValues = ValueVTs.size(); 1968 1969 SmallVector<SDValue, 4> Chains(NumValues); 1970 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1971 for (unsigned i = 0; i != NumValues; ++i) { 1972 // An aggregate return value cannot wrap around the address space, so 1973 // offsets to its parts don't wrap either. 1974 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1975 TypeSize::Fixed(Offsets[i])); 1976 1977 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1978 if (MemVTs[i] != ValueVTs[i]) 1979 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1980 Chains[i] = DAG.getStore( 1981 Chain, getCurSDLoc(), Val, 1982 // FIXME: better loc info would be nice. 1983 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1984 commonAlignment(BaseAlign, Offsets[i])); 1985 } 1986 1987 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1988 MVT::Other, Chains); 1989 } else if (I.getNumOperands() != 0) { 1990 SmallVector<EVT, 4> ValueVTs; 1991 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1992 unsigned NumValues = ValueVTs.size(); 1993 if (NumValues) { 1994 SDValue RetOp = getValue(I.getOperand(0)); 1995 1996 const Function *F = I.getParent()->getParent(); 1997 1998 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1999 I.getOperand(0)->getType(), F->getCallingConv(), 2000 /*IsVarArg*/ false, DL); 2001 2002 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2003 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2004 ExtendKind = ISD::SIGN_EXTEND; 2005 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2006 ExtendKind = ISD::ZERO_EXTEND; 2007 2008 LLVMContext &Context = F->getContext(); 2009 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2010 2011 for (unsigned j = 0; j != NumValues; ++j) { 2012 EVT VT = ValueVTs[j]; 2013 2014 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2015 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2016 2017 CallingConv::ID CC = F->getCallingConv(); 2018 2019 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2020 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2021 SmallVector<SDValue, 4> Parts(NumParts); 2022 getCopyToParts(DAG, getCurSDLoc(), 2023 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2024 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2025 2026 // 'inreg' on function refers to return value 2027 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2028 if (RetInReg) 2029 Flags.setInReg(); 2030 2031 if (I.getOperand(0)->getType()->isPointerTy()) { 2032 Flags.setPointer(); 2033 Flags.setPointerAddrSpace( 2034 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2035 } 2036 2037 if (NeedsRegBlock) { 2038 Flags.setInConsecutiveRegs(); 2039 if (j == NumValues - 1) 2040 Flags.setInConsecutiveRegsLast(); 2041 } 2042 2043 // Propagate extension type if any 2044 if (ExtendKind == ISD::SIGN_EXTEND) 2045 Flags.setSExt(); 2046 else if (ExtendKind == ISD::ZERO_EXTEND) 2047 Flags.setZExt(); 2048 2049 for (unsigned i = 0; i < NumParts; ++i) { 2050 Outs.push_back(ISD::OutputArg(Flags, 2051 Parts[i].getValueType().getSimpleVT(), 2052 VT, /*isfixed=*/true, 0, 0)); 2053 OutVals.push_back(Parts[i]); 2054 } 2055 } 2056 } 2057 } 2058 2059 // Push in swifterror virtual register as the last element of Outs. This makes 2060 // sure swifterror virtual register will be returned in the swifterror 2061 // physical register. 2062 const Function *F = I.getParent()->getParent(); 2063 if (TLI.supportSwiftError() && 2064 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2065 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2066 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2067 Flags.setSwiftError(); 2068 Outs.push_back(ISD::OutputArg( 2069 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2070 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2071 // Create SDNode for the swifterror virtual register. 2072 OutVals.push_back( 2073 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2074 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2075 EVT(TLI.getPointerTy(DL)))); 2076 } 2077 2078 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2079 CallingConv::ID CallConv = 2080 DAG.getMachineFunction().getFunction().getCallingConv(); 2081 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2082 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2083 2084 // Verify that the target's LowerReturn behaved as expected. 2085 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2086 "LowerReturn didn't return a valid chain!"); 2087 2088 // Update the DAG with the new chain value resulting from return lowering. 2089 DAG.setRoot(Chain); 2090 } 2091 2092 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2093 /// created for it, emit nodes to copy the value into the virtual 2094 /// registers. 2095 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2096 // Skip empty types 2097 if (V->getType()->isEmptyTy()) 2098 return; 2099 2100 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2101 if (VMI != FuncInfo.ValueMap.end()) { 2102 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2103 CopyValueToVirtualRegister(V, VMI->second); 2104 } 2105 } 2106 2107 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2108 /// the current basic block, add it to ValueMap now so that we'll get a 2109 /// CopyTo/FromReg. 2110 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2111 // No need to export constants. 2112 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2113 2114 // Already exported? 2115 if (FuncInfo.isExportedInst(V)) return; 2116 2117 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2118 CopyValueToVirtualRegister(V, Reg); 2119 } 2120 2121 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2122 const BasicBlock *FromBB) { 2123 // The operands of the setcc have to be in this block. We don't know 2124 // how to export them from some other block. 2125 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2126 // Can export from current BB. 2127 if (VI->getParent() == FromBB) 2128 return true; 2129 2130 // Is already exported, noop. 2131 return FuncInfo.isExportedInst(V); 2132 } 2133 2134 // If this is an argument, we can export it if the BB is the entry block or 2135 // if it is already exported. 2136 if (isa<Argument>(V)) { 2137 if (FromBB->isEntryBlock()) 2138 return true; 2139 2140 // Otherwise, can only export this if it is already exported. 2141 return FuncInfo.isExportedInst(V); 2142 } 2143 2144 // Otherwise, constants can always be exported. 2145 return true; 2146 } 2147 2148 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2149 BranchProbability 2150 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2151 const MachineBasicBlock *Dst) const { 2152 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2153 const BasicBlock *SrcBB = Src->getBasicBlock(); 2154 const BasicBlock *DstBB = Dst->getBasicBlock(); 2155 if (!BPI) { 2156 // If BPI is not available, set the default probability as 1 / N, where N is 2157 // the number of successors. 2158 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2159 return BranchProbability(1, SuccSize); 2160 } 2161 return BPI->getEdgeProbability(SrcBB, DstBB); 2162 } 2163 2164 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2165 MachineBasicBlock *Dst, 2166 BranchProbability Prob) { 2167 if (!FuncInfo.BPI) 2168 Src->addSuccessorWithoutProb(Dst); 2169 else { 2170 if (Prob.isUnknown()) 2171 Prob = getEdgeProbability(Src, Dst); 2172 Src->addSuccessor(Dst, Prob); 2173 } 2174 } 2175 2176 static bool InBlock(const Value *V, const BasicBlock *BB) { 2177 if (const Instruction *I = dyn_cast<Instruction>(V)) 2178 return I->getParent() == BB; 2179 return true; 2180 } 2181 2182 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2183 /// This function emits a branch and is used at the leaves of an OR or an 2184 /// AND operator tree. 2185 void 2186 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2187 MachineBasicBlock *TBB, 2188 MachineBasicBlock *FBB, 2189 MachineBasicBlock *CurBB, 2190 MachineBasicBlock *SwitchBB, 2191 BranchProbability TProb, 2192 BranchProbability FProb, 2193 bool InvertCond) { 2194 const BasicBlock *BB = CurBB->getBasicBlock(); 2195 2196 // If the leaf of the tree is a comparison, merge the condition into 2197 // the caseblock. 2198 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2199 // The operands of the cmp have to be in this block. We don't know 2200 // how to export them from some other block. If this is the first block 2201 // of the sequence, no exporting is needed. 2202 if (CurBB == SwitchBB || 2203 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2204 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2205 ISD::CondCode Condition; 2206 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2207 ICmpInst::Predicate Pred = 2208 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2209 Condition = getICmpCondCode(Pred); 2210 } else { 2211 const FCmpInst *FC = cast<FCmpInst>(Cond); 2212 FCmpInst::Predicate Pred = 2213 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2214 Condition = getFCmpCondCode(Pred); 2215 if (TM.Options.NoNaNsFPMath) 2216 Condition = getFCmpCodeWithoutNaN(Condition); 2217 } 2218 2219 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2220 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2221 SL->SwitchCases.push_back(CB); 2222 return; 2223 } 2224 } 2225 2226 // Create a CaseBlock record representing this branch. 2227 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2228 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2229 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2230 SL->SwitchCases.push_back(CB); 2231 } 2232 2233 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2234 MachineBasicBlock *TBB, 2235 MachineBasicBlock *FBB, 2236 MachineBasicBlock *CurBB, 2237 MachineBasicBlock *SwitchBB, 2238 Instruction::BinaryOps Opc, 2239 BranchProbability TProb, 2240 BranchProbability FProb, 2241 bool InvertCond) { 2242 // Skip over not part of the tree and remember to invert op and operands at 2243 // next level. 2244 Value *NotCond; 2245 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2246 InBlock(NotCond, CurBB->getBasicBlock())) { 2247 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2248 !InvertCond); 2249 return; 2250 } 2251 2252 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2253 const Value *BOpOp0, *BOpOp1; 2254 // Compute the effective opcode for Cond, taking into account whether it needs 2255 // to be inverted, e.g. 2256 // and (not (or A, B)), C 2257 // gets lowered as 2258 // and (and (not A, not B), C) 2259 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2260 if (BOp) { 2261 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2262 ? Instruction::And 2263 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2264 ? Instruction::Or 2265 : (Instruction::BinaryOps)0); 2266 if (InvertCond) { 2267 if (BOpc == Instruction::And) 2268 BOpc = Instruction::Or; 2269 else if (BOpc == Instruction::Or) 2270 BOpc = Instruction::And; 2271 } 2272 } 2273 2274 // If this node is not part of the or/and tree, emit it as a branch. 2275 // Note that all nodes in the tree should have same opcode. 2276 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2277 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2278 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2279 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2280 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2281 TProb, FProb, InvertCond); 2282 return; 2283 } 2284 2285 // Create TmpBB after CurBB. 2286 MachineFunction::iterator BBI(CurBB); 2287 MachineFunction &MF = DAG.getMachineFunction(); 2288 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2289 CurBB->getParent()->insert(++BBI, TmpBB); 2290 2291 if (Opc == Instruction::Or) { 2292 // Codegen X | Y as: 2293 // BB1: 2294 // jmp_if_X TBB 2295 // jmp TmpBB 2296 // TmpBB: 2297 // jmp_if_Y TBB 2298 // jmp FBB 2299 // 2300 2301 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2302 // The requirement is that 2303 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2304 // = TrueProb for original BB. 2305 // Assuming the original probabilities are A and B, one choice is to set 2306 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2307 // A/(1+B) and 2B/(1+B). This choice assumes that 2308 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2309 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2310 // TmpBB, but the math is more complicated. 2311 2312 auto NewTrueProb = TProb / 2; 2313 auto NewFalseProb = TProb / 2 + FProb; 2314 // Emit the LHS condition. 2315 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2316 NewFalseProb, InvertCond); 2317 2318 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2319 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2320 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2321 // Emit the RHS condition into TmpBB. 2322 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2323 Probs[1], InvertCond); 2324 } else { 2325 assert(Opc == Instruction::And && "Unknown merge op!"); 2326 // Codegen X & Y as: 2327 // BB1: 2328 // jmp_if_X TmpBB 2329 // jmp FBB 2330 // TmpBB: 2331 // jmp_if_Y TBB 2332 // jmp FBB 2333 // 2334 // This requires creation of TmpBB after CurBB. 2335 2336 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2337 // The requirement is that 2338 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2339 // = FalseProb for original BB. 2340 // Assuming the original probabilities are A and B, one choice is to set 2341 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2342 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2343 // TrueProb for BB1 * FalseProb for TmpBB. 2344 2345 auto NewTrueProb = TProb + FProb / 2; 2346 auto NewFalseProb = FProb / 2; 2347 // Emit the LHS condition. 2348 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2349 NewFalseProb, InvertCond); 2350 2351 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2352 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2353 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2354 // Emit the RHS condition into TmpBB. 2355 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2356 Probs[1], InvertCond); 2357 } 2358 } 2359 2360 /// If the set of cases should be emitted as a series of branches, return true. 2361 /// If we should emit this as a bunch of and/or'd together conditions, return 2362 /// false. 2363 bool 2364 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2365 if (Cases.size() != 2) return true; 2366 2367 // If this is two comparisons of the same values or'd or and'd together, they 2368 // will get folded into a single comparison, so don't emit two blocks. 2369 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2370 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2371 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2372 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2373 return false; 2374 } 2375 2376 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2377 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2378 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2379 Cases[0].CC == Cases[1].CC && 2380 isa<Constant>(Cases[0].CmpRHS) && 2381 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2382 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2383 return false; 2384 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2385 return false; 2386 } 2387 2388 return true; 2389 } 2390 2391 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2392 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2393 2394 // Update machine-CFG edges. 2395 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2396 2397 if (I.isUnconditional()) { 2398 // Update machine-CFG edges. 2399 BrMBB->addSuccessor(Succ0MBB); 2400 2401 // If this is not a fall-through branch or optimizations are switched off, 2402 // emit the branch. 2403 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2404 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2405 MVT::Other, getControlRoot(), 2406 DAG.getBasicBlock(Succ0MBB))); 2407 2408 return; 2409 } 2410 2411 // If this condition is one of the special cases we handle, do special stuff 2412 // now. 2413 const Value *CondVal = I.getCondition(); 2414 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2415 2416 // If this is a series of conditions that are or'd or and'd together, emit 2417 // this as a sequence of branches instead of setcc's with and/or operations. 2418 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2419 // unpredictable branches, and vector extracts because those jumps are likely 2420 // expensive for any target), this should improve performance. 2421 // For example, instead of something like: 2422 // cmp A, B 2423 // C = seteq 2424 // cmp D, E 2425 // F = setle 2426 // or C, F 2427 // jnz foo 2428 // Emit: 2429 // cmp A, B 2430 // je foo 2431 // cmp D, E 2432 // jle foo 2433 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2434 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2435 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2436 Value *Vec; 2437 const Value *BOp0, *BOp1; 2438 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2439 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2440 Opcode = Instruction::And; 2441 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2442 Opcode = Instruction::Or; 2443 2444 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2445 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2446 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2447 getEdgeProbability(BrMBB, Succ0MBB), 2448 getEdgeProbability(BrMBB, Succ1MBB), 2449 /*InvertCond=*/false); 2450 // If the compares in later blocks need to use values not currently 2451 // exported from this block, export them now. This block should always 2452 // be the first entry. 2453 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2454 2455 // Allow some cases to be rejected. 2456 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2457 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2458 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2459 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2460 } 2461 2462 // Emit the branch for this block. 2463 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2464 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2465 return; 2466 } 2467 2468 // Okay, we decided not to do this, remove any inserted MBB's and clear 2469 // SwitchCases. 2470 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2471 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2472 2473 SL->SwitchCases.clear(); 2474 } 2475 } 2476 2477 // Create a CaseBlock record representing this branch. 2478 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2479 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2480 2481 // Use visitSwitchCase to actually insert the fast branch sequence for this 2482 // cond branch. 2483 visitSwitchCase(CB, BrMBB); 2484 } 2485 2486 /// visitSwitchCase - Emits the necessary code to represent a single node in 2487 /// the binary search tree resulting from lowering a switch instruction. 2488 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2489 MachineBasicBlock *SwitchBB) { 2490 SDValue Cond; 2491 SDValue CondLHS = getValue(CB.CmpLHS); 2492 SDLoc dl = CB.DL; 2493 2494 if (CB.CC == ISD::SETTRUE) { 2495 // Branch or fall through to TrueBB. 2496 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2497 SwitchBB->normalizeSuccProbs(); 2498 if (CB.TrueBB != NextBlock(SwitchBB)) { 2499 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2500 DAG.getBasicBlock(CB.TrueBB))); 2501 } 2502 return; 2503 } 2504 2505 auto &TLI = DAG.getTargetLoweringInfo(); 2506 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2507 2508 // Build the setcc now. 2509 if (!CB.CmpMHS) { 2510 // Fold "(X == true)" to X and "(X == false)" to !X to 2511 // handle common cases produced by branch lowering. 2512 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2513 CB.CC == ISD::SETEQ) 2514 Cond = CondLHS; 2515 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2516 CB.CC == ISD::SETEQ) { 2517 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2518 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2519 } else { 2520 SDValue CondRHS = getValue(CB.CmpRHS); 2521 2522 // If a pointer's DAG type is larger than its memory type then the DAG 2523 // values are zero-extended. This breaks signed comparisons so truncate 2524 // back to the underlying type before doing the compare. 2525 if (CondLHS.getValueType() != MemVT) { 2526 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2527 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2528 } 2529 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2530 } 2531 } else { 2532 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2533 2534 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2535 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2536 2537 SDValue CmpOp = getValue(CB.CmpMHS); 2538 EVT VT = CmpOp.getValueType(); 2539 2540 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2541 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2542 ISD::SETLE); 2543 } else { 2544 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2545 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2546 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2547 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2548 } 2549 } 2550 2551 // Update successor info 2552 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2553 // TrueBB and FalseBB are always different unless the incoming IR is 2554 // degenerate. This only happens when running llc on weird IR. 2555 if (CB.TrueBB != CB.FalseBB) 2556 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2557 SwitchBB->normalizeSuccProbs(); 2558 2559 // If the lhs block is the next block, invert the condition so that we can 2560 // fall through to the lhs instead of the rhs block. 2561 if (CB.TrueBB == NextBlock(SwitchBB)) { 2562 std::swap(CB.TrueBB, CB.FalseBB); 2563 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2564 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2565 } 2566 2567 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2568 MVT::Other, getControlRoot(), Cond, 2569 DAG.getBasicBlock(CB.TrueBB)); 2570 2571 setValue(CurInst, BrCond); 2572 2573 // Insert the false branch. Do this even if it's a fall through branch, 2574 // this makes it easier to do DAG optimizations which require inverting 2575 // the branch condition. 2576 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2577 DAG.getBasicBlock(CB.FalseBB)); 2578 2579 DAG.setRoot(BrCond); 2580 } 2581 2582 /// visitJumpTable - Emit JumpTable node in the current MBB 2583 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2584 // Emit the code for the jump table 2585 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2586 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2587 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2588 JT.Reg, PTy); 2589 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2590 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2591 MVT::Other, Index.getValue(1), 2592 Table, Index); 2593 DAG.setRoot(BrJumpTable); 2594 } 2595 2596 /// visitJumpTableHeader - This function emits necessary code to produce index 2597 /// in the JumpTable from switch case. 2598 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2599 JumpTableHeader &JTH, 2600 MachineBasicBlock *SwitchBB) { 2601 SDLoc dl = getCurSDLoc(); 2602 2603 // Subtract the lowest switch case value from the value being switched on. 2604 SDValue SwitchOp = getValue(JTH.SValue); 2605 EVT VT = SwitchOp.getValueType(); 2606 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2607 DAG.getConstant(JTH.First, dl, VT)); 2608 2609 // The SDNode we just created, which holds the value being switched on minus 2610 // the smallest case value, needs to be copied to a virtual register so it 2611 // can be used as an index into the jump table in a subsequent basic block. 2612 // This value may be smaller or larger than the target's pointer type, and 2613 // therefore require extension or truncating. 2614 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2615 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2616 2617 unsigned JumpTableReg = 2618 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2619 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2620 JumpTableReg, SwitchOp); 2621 JT.Reg = JumpTableReg; 2622 2623 if (!JTH.FallthroughUnreachable) { 2624 // Emit the range check for the jump table, and branch to the default block 2625 // for the switch statement if the value being switched on exceeds the 2626 // largest case in the switch. 2627 SDValue CMP = DAG.getSetCC( 2628 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2629 Sub.getValueType()), 2630 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2631 2632 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2633 MVT::Other, CopyTo, CMP, 2634 DAG.getBasicBlock(JT.Default)); 2635 2636 // Avoid emitting unnecessary branches to the next block. 2637 if (JT.MBB != NextBlock(SwitchBB)) 2638 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2639 DAG.getBasicBlock(JT.MBB)); 2640 2641 DAG.setRoot(BrCond); 2642 } else { 2643 // Avoid emitting unnecessary branches to the next block. 2644 if (JT.MBB != NextBlock(SwitchBB)) 2645 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2646 DAG.getBasicBlock(JT.MBB))); 2647 else 2648 DAG.setRoot(CopyTo); 2649 } 2650 } 2651 2652 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2653 /// variable if there exists one. 2654 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2655 SDValue &Chain) { 2656 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2657 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2658 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2659 MachineFunction &MF = DAG.getMachineFunction(); 2660 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2661 MachineSDNode *Node = 2662 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2663 if (Global) { 2664 MachinePointerInfo MPInfo(Global); 2665 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2666 MachineMemOperand::MODereferenceable; 2667 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2668 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2669 DAG.setNodeMemRefs(Node, {MemRef}); 2670 } 2671 if (PtrTy != PtrMemTy) 2672 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2673 return SDValue(Node, 0); 2674 } 2675 2676 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2677 /// tail spliced into a stack protector check success bb. 2678 /// 2679 /// For a high level explanation of how this fits into the stack protector 2680 /// generation see the comment on the declaration of class 2681 /// StackProtectorDescriptor. 2682 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2683 MachineBasicBlock *ParentBB) { 2684 2685 // First create the loads to the guard/stack slot for the comparison. 2686 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2687 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2688 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2689 2690 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2691 int FI = MFI.getStackProtectorIndex(); 2692 2693 SDValue Guard; 2694 SDLoc dl = getCurSDLoc(); 2695 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2696 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2697 Align Align = 2698 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2699 2700 // Generate code to load the content of the guard slot. 2701 SDValue GuardVal = DAG.getLoad( 2702 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2703 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2704 MachineMemOperand::MOVolatile); 2705 2706 if (TLI.useStackGuardXorFP()) 2707 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2708 2709 // Retrieve guard check function, nullptr if instrumentation is inlined. 2710 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2711 // The target provides a guard check function to validate the guard value. 2712 // Generate a call to that function with the content of the guard slot as 2713 // argument. 2714 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2715 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2716 2717 TargetLowering::ArgListTy Args; 2718 TargetLowering::ArgListEntry Entry; 2719 Entry.Node = GuardVal; 2720 Entry.Ty = FnTy->getParamType(0); 2721 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2722 Entry.IsInReg = true; 2723 Args.push_back(Entry); 2724 2725 TargetLowering::CallLoweringInfo CLI(DAG); 2726 CLI.setDebugLoc(getCurSDLoc()) 2727 .setChain(DAG.getEntryNode()) 2728 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2729 getValue(GuardCheckFn), std::move(Args)); 2730 2731 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2732 DAG.setRoot(Result.second); 2733 return; 2734 } 2735 2736 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2737 // Otherwise, emit a volatile load to retrieve the stack guard value. 2738 SDValue Chain = DAG.getEntryNode(); 2739 if (TLI.useLoadStackGuardNode()) { 2740 Guard = getLoadStackGuard(DAG, dl, Chain); 2741 } else { 2742 const Value *IRGuard = TLI.getSDagStackGuard(M); 2743 SDValue GuardPtr = getValue(IRGuard); 2744 2745 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2746 MachinePointerInfo(IRGuard, 0), Align, 2747 MachineMemOperand::MOVolatile); 2748 } 2749 2750 // Perform the comparison via a getsetcc. 2751 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2752 *DAG.getContext(), 2753 Guard.getValueType()), 2754 Guard, GuardVal, ISD::SETNE); 2755 2756 // If the guard/stackslot do not equal, branch to failure MBB. 2757 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2758 MVT::Other, GuardVal.getOperand(0), 2759 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2760 // Otherwise branch to success MBB. 2761 SDValue Br = DAG.getNode(ISD::BR, dl, 2762 MVT::Other, BrCond, 2763 DAG.getBasicBlock(SPD.getSuccessMBB())); 2764 2765 DAG.setRoot(Br); 2766 } 2767 2768 /// Codegen the failure basic block for a stack protector check. 2769 /// 2770 /// A failure stack protector machine basic block consists simply of a call to 2771 /// __stack_chk_fail(). 2772 /// 2773 /// For a high level explanation of how this fits into the stack protector 2774 /// generation see the comment on the declaration of class 2775 /// StackProtectorDescriptor. 2776 void 2777 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2778 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2779 TargetLowering::MakeLibCallOptions CallOptions; 2780 CallOptions.setDiscardResult(true); 2781 SDValue Chain = 2782 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2783 None, CallOptions, getCurSDLoc()).second; 2784 // On PS4/PS5, the "return address" must still be within the calling 2785 // function, even if it's at the very end, so emit an explicit TRAP here. 2786 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2787 if (TM.getTargetTriple().isPS()) 2788 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2789 // WebAssembly needs an unreachable instruction after a non-returning call, 2790 // because the function return type can be different from __stack_chk_fail's 2791 // return type (void). 2792 if (TM.getTargetTriple().isWasm()) 2793 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2794 2795 DAG.setRoot(Chain); 2796 } 2797 2798 /// visitBitTestHeader - This function emits necessary code to produce value 2799 /// suitable for "bit tests" 2800 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2801 MachineBasicBlock *SwitchBB) { 2802 SDLoc dl = getCurSDLoc(); 2803 2804 // Subtract the minimum value. 2805 SDValue SwitchOp = getValue(B.SValue); 2806 EVT VT = SwitchOp.getValueType(); 2807 SDValue RangeSub = 2808 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2809 2810 // Determine the type of the test operands. 2811 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2812 bool UsePtrType = false; 2813 if (!TLI.isTypeLegal(VT)) { 2814 UsePtrType = true; 2815 } else { 2816 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2817 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2818 // Switch table case range are encoded into series of masks. 2819 // Just use pointer type, it's guaranteed to fit. 2820 UsePtrType = true; 2821 break; 2822 } 2823 } 2824 SDValue Sub = RangeSub; 2825 if (UsePtrType) { 2826 VT = TLI.getPointerTy(DAG.getDataLayout()); 2827 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2828 } 2829 2830 B.RegVT = VT.getSimpleVT(); 2831 B.Reg = FuncInfo.CreateReg(B.RegVT); 2832 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2833 2834 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2835 2836 if (!B.FallthroughUnreachable) 2837 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2838 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2839 SwitchBB->normalizeSuccProbs(); 2840 2841 SDValue Root = CopyTo; 2842 if (!B.FallthroughUnreachable) { 2843 // Conditional branch to the default block. 2844 SDValue RangeCmp = DAG.getSetCC(dl, 2845 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2846 RangeSub.getValueType()), 2847 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2848 ISD::SETUGT); 2849 2850 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2851 DAG.getBasicBlock(B.Default)); 2852 } 2853 2854 // Avoid emitting unnecessary branches to the next block. 2855 if (MBB != NextBlock(SwitchBB)) 2856 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2857 2858 DAG.setRoot(Root); 2859 } 2860 2861 /// visitBitTestCase - this function produces one "bit test" 2862 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2863 MachineBasicBlock* NextMBB, 2864 BranchProbability BranchProbToNext, 2865 unsigned Reg, 2866 BitTestCase &B, 2867 MachineBasicBlock *SwitchBB) { 2868 SDLoc dl = getCurSDLoc(); 2869 MVT VT = BB.RegVT; 2870 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2871 SDValue Cmp; 2872 unsigned PopCount = countPopulation(B.Mask); 2873 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2874 if (PopCount == 1) { 2875 // Testing for a single bit; just compare the shift count with what it 2876 // would need to be to shift a 1 bit in that position. 2877 Cmp = DAG.getSetCC( 2878 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2879 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2880 ISD::SETEQ); 2881 } else if (PopCount == BB.Range) { 2882 // There is only one zero bit in the range, test for it directly. 2883 Cmp = DAG.getSetCC( 2884 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2885 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2886 ISD::SETNE); 2887 } else { 2888 // Make desired shift 2889 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2890 DAG.getConstant(1, dl, VT), ShiftOp); 2891 2892 // Emit bit tests and jumps 2893 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2894 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2895 Cmp = DAG.getSetCC( 2896 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2897 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2898 } 2899 2900 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2901 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2902 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2903 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2904 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2905 // one as they are relative probabilities (and thus work more like weights), 2906 // and hence we need to normalize them to let the sum of them become one. 2907 SwitchBB->normalizeSuccProbs(); 2908 2909 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2910 MVT::Other, getControlRoot(), 2911 Cmp, DAG.getBasicBlock(B.TargetBB)); 2912 2913 // Avoid emitting unnecessary branches to the next block. 2914 if (NextMBB != NextBlock(SwitchBB)) 2915 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2916 DAG.getBasicBlock(NextMBB)); 2917 2918 DAG.setRoot(BrAnd); 2919 } 2920 2921 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2922 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2923 2924 // Retrieve successors. Look through artificial IR level blocks like 2925 // catchswitch for successors. 2926 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2927 const BasicBlock *EHPadBB = I.getSuccessor(1); 2928 2929 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2930 // have to do anything here to lower funclet bundles. 2931 assert(!I.hasOperandBundlesOtherThan( 2932 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2933 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2934 LLVMContext::OB_cfguardtarget, 2935 LLVMContext::OB_clang_arc_attachedcall}) && 2936 "Cannot lower invokes with arbitrary operand bundles yet!"); 2937 2938 const Value *Callee(I.getCalledOperand()); 2939 const Function *Fn = dyn_cast<Function>(Callee); 2940 if (isa<InlineAsm>(Callee)) 2941 visitInlineAsm(I, EHPadBB); 2942 else if (Fn && Fn->isIntrinsic()) { 2943 switch (Fn->getIntrinsicID()) { 2944 default: 2945 llvm_unreachable("Cannot invoke this intrinsic"); 2946 case Intrinsic::donothing: 2947 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2948 case Intrinsic::seh_try_begin: 2949 case Intrinsic::seh_scope_begin: 2950 case Intrinsic::seh_try_end: 2951 case Intrinsic::seh_scope_end: 2952 break; 2953 case Intrinsic::experimental_patchpoint_void: 2954 case Intrinsic::experimental_patchpoint_i64: 2955 visitPatchpoint(I, EHPadBB); 2956 break; 2957 case Intrinsic::experimental_gc_statepoint: 2958 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2959 break; 2960 case Intrinsic::wasm_rethrow: { 2961 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2962 // special because it can be invoked, so we manually lower it to a DAG 2963 // node here. 2964 SmallVector<SDValue, 8> Ops; 2965 Ops.push_back(getRoot()); // inchain 2966 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2967 Ops.push_back( 2968 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2969 TLI.getPointerTy(DAG.getDataLayout()))); 2970 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2971 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2972 break; 2973 } 2974 } 2975 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2976 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2977 // Eventually we will support lowering the @llvm.experimental.deoptimize 2978 // intrinsic, and right now there are no plans to support other intrinsics 2979 // with deopt state. 2980 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2981 } else { 2982 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 2983 } 2984 2985 // If the value of the invoke is used outside of its defining block, make it 2986 // available as a virtual register. 2987 // We already took care of the exported value for the statepoint instruction 2988 // during call to the LowerStatepoint. 2989 if (!isa<GCStatepointInst>(I)) { 2990 CopyToExportRegsIfNeeded(&I); 2991 } 2992 2993 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2994 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2995 BranchProbability EHPadBBProb = 2996 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2997 : BranchProbability::getZero(); 2998 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2999 3000 // Update successor info. 3001 addSuccessorWithProb(InvokeMBB, Return); 3002 for (auto &UnwindDest : UnwindDests) { 3003 UnwindDest.first->setIsEHPad(); 3004 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3005 } 3006 InvokeMBB->normalizeSuccProbs(); 3007 3008 // Drop into normal successor. 3009 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3010 DAG.getBasicBlock(Return))); 3011 } 3012 3013 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3014 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3015 3016 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3017 // have to do anything here to lower funclet bundles. 3018 assert(!I.hasOperandBundlesOtherThan( 3019 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3020 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3021 3022 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3023 visitInlineAsm(I); 3024 CopyToExportRegsIfNeeded(&I); 3025 3026 // Retrieve successors. 3027 SmallPtrSet<BasicBlock *, 8> Dests; 3028 Dests.insert(I.getDefaultDest()); 3029 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3030 3031 // Update successor info. 3032 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3033 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3034 BasicBlock *Dest = I.getIndirectDest(i); 3035 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3036 Target->setIsInlineAsmBrIndirectTarget(); 3037 Target->setMachineBlockAddressTaken(); 3038 Target->setLabelMustBeEmitted(); 3039 // Don't add duplicate machine successors. 3040 if (Dests.insert(Dest).second) 3041 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3042 } 3043 CallBrMBB->normalizeSuccProbs(); 3044 3045 // Drop into default successor. 3046 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3047 MVT::Other, getControlRoot(), 3048 DAG.getBasicBlock(Return))); 3049 } 3050 3051 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3052 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3053 } 3054 3055 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3056 assert(FuncInfo.MBB->isEHPad() && 3057 "Call to landingpad not in landing pad!"); 3058 3059 // If there aren't registers to copy the values into (e.g., during SjLj 3060 // exceptions), then don't bother to create these DAG nodes. 3061 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3062 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3063 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3064 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3065 return; 3066 3067 // If landingpad's return type is token type, we don't create DAG nodes 3068 // for its exception pointer and selector value. The extraction of exception 3069 // pointer or selector value from token type landingpads is not currently 3070 // supported. 3071 if (LP.getType()->isTokenTy()) 3072 return; 3073 3074 SmallVector<EVT, 2> ValueVTs; 3075 SDLoc dl = getCurSDLoc(); 3076 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3077 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3078 3079 // Get the two live-in registers as SDValues. The physregs have already been 3080 // copied into virtual registers. 3081 SDValue Ops[2]; 3082 if (FuncInfo.ExceptionPointerVirtReg) { 3083 Ops[0] = DAG.getZExtOrTrunc( 3084 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3085 FuncInfo.ExceptionPointerVirtReg, 3086 TLI.getPointerTy(DAG.getDataLayout())), 3087 dl, ValueVTs[0]); 3088 } else { 3089 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3090 } 3091 Ops[1] = DAG.getZExtOrTrunc( 3092 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3093 FuncInfo.ExceptionSelectorVirtReg, 3094 TLI.getPointerTy(DAG.getDataLayout())), 3095 dl, ValueVTs[1]); 3096 3097 // Merge into one. 3098 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3099 DAG.getVTList(ValueVTs), Ops); 3100 setValue(&LP, Res); 3101 } 3102 3103 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3104 MachineBasicBlock *Last) { 3105 // Update JTCases. 3106 for (JumpTableBlock &JTB : SL->JTCases) 3107 if (JTB.first.HeaderBB == First) 3108 JTB.first.HeaderBB = Last; 3109 3110 // Update BitTestCases. 3111 for (BitTestBlock &BTB : SL->BitTestCases) 3112 if (BTB.Parent == First) 3113 BTB.Parent = Last; 3114 } 3115 3116 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3117 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3118 3119 // Update machine-CFG edges with unique successors. 3120 SmallSet<BasicBlock*, 32> Done; 3121 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3122 BasicBlock *BB = I.getSuccessor(i); 3123 bool Inserted = Done.insert(BB).second; 3124 if (!Inserted) 3125 continue; 3126 3127 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3128 addSuccessorWithProb(IndirectBrMBB, Succ); 3129 } 3130 IndirectBrMBB->normalizeSuccProbs(); 3131 3132 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3133 MVT::Other, getControlRoot(), 3134 getValue(I.getAddress()))); 3135 } 3136 3137 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3138 if (!DAG.getTarget().Options.TrapUnreachable) 3139 return; 3140 3141 // We may be able to ignore unreachable behind a noreturn call. 3142 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3143 const BasicBlock &BB = *I.getParent(); 3144 if (&I != &BB.front()) { 3145 BasicBlock::const_iterator PredI = 3146 std::prev(BasicBlock::const_iterator(&I)); 3147 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3148 if (Call->doesNotReturn()) 3149 return; 3150 } 3151 } 3152 } 3153 3154 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3155 } 3156 3157 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3158 SDNodeFlags Flags; 3159 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3160 Flags.copyFMF(*FPOp); 3161 3162 SDValue Op = getValue(I.getOperand(0)); 3163 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3164 Op, Flags); 3165 setValue(&I, UnNodeValue); 3166 } 3167 3168 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3169 SDNodeFlags Flags; 3170 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3171 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3172 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3173 } 3174 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3175 Flags.setExact(ExactOp->isExact()); 3176 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3177 Flags.copyFMF(*FPOp); 3178 3179 SDValue Op1 = getValue(I.getOperand(0)); 3180 SDValue Op2 = getValue(I.getOperand(1)); 3181 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3182 Op1, Op2, Flags); 3183 setValue(&I, BinNodeValue); 3184 } 3185 3186 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3187 SDValue Op1 = getValue(I.getOperand(0)); 3188 SDValue Op2 = getValue(I.getOperand(1)); 3189 3190 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3191 Op1.getValueType(), DAG.getDataLayout()); 3192 3193 // Coerce the shift amount to the right type if we can. This exposes the 3194 // truncate or zext to optimization early. 3195 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3196 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3197 "Unexpected shift type"); 3198 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3199 } 3200 3201 bool nuw = false; 3202 bool nsw = false; 3203 bool exact = false; 3204 3205 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3206 3207 if (const OverflowingBinaryOperator *OFBinOp = 3208 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3209 nuw = OFBinOp->hasNoUnsignedWrap(); 3210 nsw = OFBinOp->hasNoSignedWrap(); 3211 } 3212 if (const PossiblyExactOperator *ExactOp = 3213 dyn_cast<const PossiblyExactOperator>(&I)) 3214 exact = ExactOp->isExact(); 3215 } 3216 SDNodeFlags Flags; 3217 Flags.setExact(exact); 3218 Flags.setNoSignedWrap(nsw); 3219 Flags.setNoUnsignedWrap(nuw); 3220 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3221 Flags); 3222 setValue(&I, Res); 3223 } 3224 3225 void SelectionDAGBuilder::visitSDiv(const User &I) { 3226 SDValue Op1 = getValue(I.getOperand(0)); 3227 SDValue Op2 = getValue(I.getOperand(1)); 3228 3229 SDNodeFlags Flags; 3230 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3231 cast<PossiblyExactOperator>(&I)->isExact()); 3232 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3233 Op2, Flags)); 3234 } 3235 3236 void SelectionDAGBuilder::visitICmp(const User &I) { 3237 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3238 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3239 predicate = IC->getPredicate(); 3240 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3241 predicate = ICmpInst::Predicate(IC->getPredicate()); 3242 SDValue Op1 = getValue(I.getOperand(0)); 3243 SDValue Op2 = getValue(I.getOperand(1)); 3244 ISD::CondCode Opcode = getICmpCondCode(predicate); 3245 3246 auto &TLI = DAG.getTargetLoweringInfo(); 3247 EVT MemVT = 3248 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3249 3250 // If a pointer's DAG type is larger than its memory type then the DAG values 3251 // are zero-extended. This breaks signed comparisons so truncate back to the 3252 // underlying type before doing the compare. 3253 if (Op1.getValueType() != MemVT) { 3254 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3255 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3256 } 3257 3258 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3259 I.getType()); 3260 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3261 } 3262 3263 void SelectionDAGBuilder::visitFCmp(const User &I) { 3264 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3265 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3266 predicate = FC->getPredicate(); 3267 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3268 predicate = FCmpInst::Predicate(FC->getPredicate()); 3269 SDValue Op1 = getValue(I.getOperand(0)); 3270 SDValue Op2 = getValue(I.getOperand(1)); 3271 3272 ISD::CondCode Condition = getFCmpCondCode(predicate); 3273 auto *FPMO = cast<FPMathOperator>(&I); 3274 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3275 Condition = getFCmpCodeWithoutNaN(Condition); 3276 3277 SDNodeFlags Flags; 3278 Flags.copyFMF(*FPMO); 3279 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3280 3281 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3282 I.getType()); 3283 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3284 } 3285 3286 // Check if the condition of the select has one use or two users that are both 3287 // selects with the same condition. 3288 static bool hasOnlySelectUsers(const Value *Cond) { 3289 return llvm::all_of(Cond->users(), [](const Value *V) { 3290 return isa<SelectInst>(V); 3291 }); 3292 } 3293 3294 void SelectionDAGBuilder::visitSelect(const User &I) { 3295 SmallVector<EVT, 4> ValueVTs; 3296 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3297 ValueVTs); 3298 unsigned NumValues = ValueVTs.size(); 3299 if (NumValues == 0) return; 3300 3301 SmallVector<SDValue, 4> Values(NumValues); 3302 SDValue Cond = getValue(I.getOperand(0)); 3303 SDValue LHSVal = getValue(I.getOperand(1)); 3304 SDValue RHSVal = getValue(I.getOperand(2)); 3305 SmallVector<SDValue, 1> BaseOps(1, Cond); 3306 ISD::NodeType OpCode = 3307 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3308 3309 bool IsUnaryAbs = false; 3310 bool Negate = false; 3311 3312 SDNodeFlags Flags; 3313 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3314 Flags.copyFMF(*FPOp); 3315 3316 // Min/max matching is only viable if all output VTs are the same. 3317 if (all_equal(ValueVTs)) { 3318 EVT VT = ValueVTs[0]; 3319 LLVMContext &Ctx = *DAG.getContext(); 3320 auto &TLI = DAG.getTargetLoweringInfo(); 3321 3322 // We care about the legality of the operation after it has been type 3323 // legalized. 3324 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3325 VT = TLI.getTypeToTransformTo(Ctx, VT); 3326 3327 // If the vselect is legal, assume we want to leave this as a vector setcc + 3328 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3329 // min/max is legal on the scalar type. 3330 bool UseScalarMinMax = VT.isVector() && 3331 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3332 3333 Value *LHS, *RHS; 3334 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3335 ISD::NodeType Opc = ISD::DELETED_NODE; 3336 switch (SPR.Flavor) { 3337 case SPF_UMAX: Opc = ISD::UMAX; break; 3338 case SPF_UMIN: Opc = ISD::UMIN; break; 3339 case SPF_SMAX: Opc = ISD::SMAX; break; 3340 case SPF_SMIN: Opc = ISD::SMIN; break; 3341 case SPF_FMINNUM: 3342 switch (SPR.NaNBehavior) { 3343 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3344 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3345 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3346 case SPNB_RETURNS_ANY: { 3347 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3348 Opc = ISD::FMINNUM; 3349 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3350 Opc = ISD::FMINIMUM; 3351 else if (UseScalarMinMax) 3352 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3353 ISD::FMINNUM : ISD::FMINIMUM; 3354 break; 3355 } 3356 } 3357 break; 3358 case SPF_FMAXNUM: 3359 switch (SPR.NaNBehavior) { 3360 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3361 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3362 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3363 case SPNB_RETURNS_ANY: 3364 3365 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3366 Opc = ISD::FMAXNUM; 3367 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3368 Opc = ISD::FMAXIMUM; 3369 else if (UseScalarMinMax) 3370 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3371 ISD::FMAXNUM : ISD::FMAXIMUM; 3372 break; 3373 } 3374 break; 3375 case SPF_NABS: 3376 Negate = true; 3377 [[fallthrough]]; 3378 case SPF_ABS: 3379 IsUnaryAbs = true; 3380 Opc = ISD::ABS; 3381 break; 3382 default: break; 3383 } 3384 3385 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3386 (TLI.isOperationLegalOrCustom(Opc, VT) || 3387 (UseScalarMinMax && 3388 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3389 // If the underlying comparison instruction is used by any other 3390 // instruction, the consumed instructions won't be destroyed, so it is 3391 // not profitable to convert to a min/max. 3392 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3393 OpCode = Opc; 3394 LHSVal = getValue(LHS); 3395 RHSVal = getValue(RHS); 3396 BaseOps.clear(); 3397 } 3398 3399 if (IsUnaryAbs) { 3400 OpCode = Opc; 3401 LHSVal = getValue(LHS); 3402 BaseOps.clear(); 3403 } 3404 } 3405 3406 if (IsUnaryAbs) { 3407 for (unsigned i = 0; i != NumValues; ++i) { 3408 SDLoc dl = getCurSDLoc(); 3409 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3410 Values[i] = 3411 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3412 if (Negate) 3413 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3414 Values[i]); 3415 } 3416 } else { 3417 for (unsigned i = 0; i != NumValues; ++i) { 3418 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3419 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3420 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3421 Values[i] = DAG.getNode( 3422 OpCode, getCurSDLoc(), 3423 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3424 } 3425 } 3426 3427 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3428 DAG.getVTList(ValueVTs), Values)); 3429 } 3430 3431 void SelectionDAGBuilder::visitTrunc(const User &I) { 3432 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3433 SDValue N = getValue(I.getOperand(0)); 3434 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3435 I.getType()); 3436 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3437 } 3438 3439 void SelectionDAGBuilder::visitZExt(const User &I) { 3440 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3441 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3442 SDValue N = getValue(I.getOperand(0)); 3443 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3444 I.getType()); 3445 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3446 } 3447 3448 void SelectionDAGBuilder::visitSExt(const User &I) { 3449 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3450 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3451 SDValue N = getValue(I.getOperand(0)); 3452 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3453 I.getType()); 3454 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3455 } 3456 3457 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3458 // FPTrunc is never a no-op cast, no need to check 3459 SDValue N = getValue(I.getOperand(0)); 3460 SDLoc dl = getCurSDLoc(); 3461 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3462 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3463 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3464 DAG.getTargetConstant( 3465 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3466 } 3467 3468 void SelectionDAGBuilder::visitFPExt(const User &I) { 3469 // FPExt is never a no-op cast, no need to check 3470 SDValue N = getValue(I.getOperand(0)); 3471 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3472 I.getType()); 3473 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3474 } 3475 3476 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3477 // FPToUI is never a no-op cast, no need to check 3478 SDValue N = getValue(I.getOperand(0)); 3479 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3480 I.getType()); 3481 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3482 } 3483 3484 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3485 // FPToSI is never a no-op cast, no need to check 3486 SDValue N = getValue(I.getOperand(0)); 3487 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3488 I.getType()); 3489 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3490 } 3491 3492 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3493 // UIToFP is never a no-op cast, no need to check 3494 SDValue N = getValue(I.getOperand(0)); 3495 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3496 I.getType()); 3497 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3498 } 3499 3500 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3501 // SIToFP is never a no-op cast, no need to check 3502 SDValue N = getValue(I.getOperand(0)); 3503 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3504 I.getType()); 3505 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3506 } 3507 3508 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3509 // What to do depends on the size of the integer and the size of the pointer. 3510 // We can either truncate, zero extend, or no-op, accordingly. 3511 SDValue N = getValue(I.getOperand(0)); 3512 auto &TLI = DAG.getTargetLoweringInfo(); 3513 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3514 I.getType()); 3515 EVT PtrMemVT = 3516 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3517 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3518 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3519 setValue(&I, N); 3520 } 3521 3522 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3523 // What to do depends on the size of the integer and the size of the pointer. 3524 // We can either truncate, zero extend, or no-op, accordingly. 3525 SDValue N = getValue(I.getOperand(0)); 3526 auto &TLI = DAG.getTargetLoweringInfo(); 3527 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3528 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3529 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3530 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3531 setValue(&I, N); 3532 } 3533 3534 void SelectionDAGBuilder::visitBitCast(const User &I) { 3535 SDValue N = getValue(I.getOperand(0)); 3536 SDLoc dl = getCurSDLoc(); 3537 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3538 I.getType()); 3539 3540 // BitCast assures us that source and destination are the same size so this is 3541 // either a BITCAST or a no-op. 3542 if (DestVT != N.getValueType()) 3543 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3544 DestVT, N)); // convert types. 3545 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3546 // might fold any kind of constant expression to an integer constant and that 3547 // is not what we are looking for. Only recognize a bitcast of a genuine 3548 // constant integer as an opaque constant. 3549 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3550 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3551 /*isOpaque*/true)); 3552 else 3553 setValue(&I, N); // noop cast. 3554 } 3555 3556 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3557 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3558 const Value *SV = I.getOperand(0); 3559 SDValue N = getValue(SV); 3560 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3561 3562 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3563 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3564 3565 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3566 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3567 3568 setValue(&I, N); 3569 } 3570 3571 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3572 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3573 SDValue InVec = getValue(I.getOperand(0)); 3574 SDValue InVal = getValue(I.getOperand(1)); 3575 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3576 TLI.getVectorIdxTy(DAG.getDataLayout())); 3577 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3578 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3579 InVec, InVal, InIdx)); 3580 } 3581 3582 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3583 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3584 SDValue InVec = getValue(I.getOperand(0)); 3585 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3586 TLI.getVectorIdxTy(DAG.getDataLayout())); 3587 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3588 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3589 InVec, InIdx)); 3590 } 3591 3592 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3593 SDValue Src1 = getValue(I.getOperand(0)); 3594 SDValue Src2 = getValue(I.getOperand(1)); 3595 ArrayRef<int> Mask; 3596 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3597 Mask = SVI->getShuffleMask(); 3598 else 3599 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3600 SDLoc DL = getCurSDLoc(); 3601 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3602 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3603 EVT SrcVT = Src1.getValueType(); 3604 3605 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3606 VT.isScalableVector()) { 3607 // Canonical splat form of first element of first input vector. 3608 SDValue FirstElt = 3609 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3610 DAG.getVectorIdxConstant(0, DL)); 3611 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3612 return; 3613 } 3614 3615 // For now, we only handle splats for scalable vectors. 3616 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3617 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3618 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3619 3620 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3621 unsigned MaskNumElts = Mask.size(); 3622 3623 if (SrcNumElts == MaskNumElts) { 3624 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3625 return; 3626 } 3627 3628 // Normalize the shuffle vector since mask and vector length don't match. 3629 if (SrcNumElts < MaskNumElts) { 3630 // Mask is longer than the source vectors. We can use concatenate vector to 3631 // make the mask and vectors lengths match. 3632 3633 if (MaskNumElts % SrcNumElts == 0) { 3634 // Mask length is a multiple of the source vector length. 3635 // Check if the shuffle is some kind of concatenation of the input 3636 // vectors. 3637 unsigned NumConcat = MaskNumElts / SrcNumElts; 3638 bool IsConcat = true; 3639 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3640 for (unsigned i = 0; i != MaskNumElts; ++i) { 3641 int Idx = Mask[i]; 3642 if (Idx < 0) 3643 continue; 3644 // Ensure the indices in each SrcVT sized piece are sequential and that 3645 // the same source is used for the whole piece. 3646 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3647 (ConcatSrcs[i / SrcNumElts] >= 0 && 3648 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3649 IsConcat = false; 3650 break; 3651 } 3652 // Remember which source this index came from. 3653 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3654 } 3655 3656 // The shuffle is concatenating multiple vectors together. Just emit 3657 // a CONCAT_VECTORS operation. 3658 if (IsConcat) { 3659 SmallVector<SDValue, 8> ConcatOps; 3660 for (auto Src : ConcatSrcs) { 3661 if (Src < 0) 3662 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3663 else if (Src == 0) 3664 ConcatOps.push_back(Src1); 3665 else 3666 ConcatOps.push_back(Src2); 3667 } 3668 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3669 return; 3670 } 3671 } 3672 3673 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3674 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3675 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3676 PaddedMaskNumElts); 3677 3678 // Pad both vectors with undefs to make them the same length as the mask. 3679 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3680 3681 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3682 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3683 MOps1[0] = Src1; 3684 MOps2[0] = Src2; 3685 3686 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3687 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3688 3689 // Readjust mask for new input vector length. 3690 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3691 for (unsigned i = 0; i != MaskNumElts; ++i) { 3692 int Idx = Mask[i]; 3693 if (Idx >= (int)SrcNumElts) 3694 Idx -= SrcNumElts - PaddedMaskNumElts; 3695 MappedOps[i] = Idx; 3696 } 3697 3698 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3699 3700 // If the concatenated vector was padded, extract a subvector with the 3701 // correct number of elements. 3702 if (MaskNumElts != PaddedMaskNumElts) 3703 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3704 DAG.getVectorIdxConstant(0, DL)); 3705 3706 setValue(&I, Result); 3707 return; 3708 } 3709 3710 if (SrcNumElts > MaskNumElts) { 3711 // Analyze the access pattern of the vector to see if we can extract 3712 // two subvectors and do the shuffle. 3713 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3714 bool CanExtract = true; 3715 for (int Idx : Mask) { 3716 unsigned Input = 0; 3717 if (Idx < 0) 3718 continue; 3719 3720 if (Idx >= (int)SrcNumElts) { 3721 Input = 1; 3722 Idx -= SrcNumElts; 3723 } 3724 3725 // If all the indices come from the same MaskNumElts sized portion of 3726 // the sources we can use extract. Also make sure the extract wouldn't 3727 // extract past the end of the source. 3728 int NewStartIdx = alignDown(Idx, MaskNumElts); 3729 if (NewStartIdx + MaskNumElts > SrcNumElts || 3730 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3731 CanExtract = false; 3732 // Make sure we always update StartIdx as we use it to track if all 3733 // elements are undef. 3734 StartIdx[Input] = NewStartIdx; 3735 } 3736 3737 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3738 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3739 return; 3740 } 3741 if (CanExtract) { 3742 // Extract appropriate subvector and generate a vector shuffle 3743 for (unsigned Input = 0; Input < 2; ++Input) { 3744 SDValue &Src = Input == 0 ? Src1 : Src2; 3745 if (StartIdx[Input] < 0) 3746 Src = DAG.getUNDEF(VT); 3747 else { 3748 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3749 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3750 } 3751 } 3752 3753 // Calculate new mask. 3754 SmallVector<int, 8> MappedOps(Mask); 3755 for (int &Idx : MappedOps) { 3756 if (Idx >= (int)SrcNumElts) 3757 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3758 else if (Idx >= 0) 3759 Idx -= StartIdx[0]; 3760 } 3761 3762 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3763 return; 3764 } 3765 } 3766 3767 // We can't use either concat vectors or extract subvectors so fall back to 3768 // replacing the shuffle with extract and build vector. 3769 // to insert and build vector. 3770 EVT EltVT = VT.getVectorElementType(); 3771 SmallVector<SDValue,8> Ops; 3772 for (int Idx : Mask) { 3773 SDValue Res; 3774 3775 if (Idx < 0) { 3776 Res = DAG.getUNDEF(EltVT); 3777 } else { 3778 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3779 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3780 3781 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3782 DAG.getVectorIdxConstant(Idx, DL)); 3783 } 3784 3785 Ops.push_back(Res); 3786 } 3787 3788 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3789 } 3790 3791 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3792 ArrayRef<unsigned> Indices = I.getIndices(); 3793 const Value *Op0 = I.getOperand(0); 3794 const Value *Op1 = I.getOperand(1); 3795 Type *AggTy = I.getType(); 3796 Type *ValTy = Op1->getType(); 3797 bool IntoUndef = isa<UndefValue>(Op0); 3798 bool FromUndef = isa<UndefValue>(Op1); 3799 3800 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3801 3802 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3803 SmallVector<EVT, 4> AggValueVTs; 3804 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3805 SmallVector<EVT, 4> ValValueVTs; 3806 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3807 3808 unsigned NumAggValues = AggValueVTs.size(); 3809 unsigned NumValValues = ValValueVTs.size(); 3810 SmallVector<SDValue, 4> Values(NumAggValues); 3811 3812 // Ignore an insertvalue that produces an empty object 3813 if (!NumAggValues) { 3814 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3815 return; 3816 } 3817 3818 SDValue Agg = getValue(Op0); 3819 unsigned i = 0; 3820 // Copy the beginning value(s) from the original aggregate. 3821 for (; i != LinearIndex; ++i) 3822 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3823 SDValue(Agg.getNode(), Agg.getResNo() + i); 3824 // Copy values from the inserted value(s). 3825 if (NumValValues) { 3826 SDValue Val = getValue(Op1); 3827 for (; i != LinearIndex + NumValValues; ++i) 3828 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3829 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3830 } 3831 // Copy remaining value(s) from the original aggregate. 3832 for (; i != NumAggValues; ++i) 3833 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3834 SDValue(Agg.getNode(), Agg.getResNo() + i); 3835 3836 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3837 DAG.getVTList(AggValueVTs), Values)); 3838 } 3839 3840 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3841 ArrayRef<unsigned> Indices = I.getIndices(); 3842 const Value *Op0 = I.getOperand(0); 3843 Type *AggTy = Op0->getType(); 3844 Type *ValTy = I.getType(); 3845 bool OutOfUndef = isa<UndefValue>(Op0); 3846 3847 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3848 3849 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3850 SmallVector<EVT, 4> ValValueVTs; 3851 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3852 3853 unsigned NumValValues = ValValueVTs.size(); 3854 3855 // Ignore a extractvalue that produces an empty object 3856 if (!NumValValues) { 3857 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3858 return; 3859 } 3860 3861 SmallVector<SDValue, 4> Values(NumValValues); 3862 3863 SDValue Agg = getValue(Op0); 3864 // Copy out the selected value(s). 3865 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3866 Values[i - LinearIndex] = 3867 OutOfUndef ? 3868 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3869 SDValue(Agg.getNode(), Agg.getResNo() + i); 3870 3871 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3872 DAG.getVTList(ValValueVTs), Values)); 3873 } 3874 3875 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3876 Value *Op0 = I.getOperand(0); 3877 // Note that the pointer operand may be a vector of pointers. Take the scalar 3878 // element which holds a pointer. 3879 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3880 SDValue N = getValue(Op0); 3881 SDLoc dl = getCurSDLoc(); 3882 auto &TLI = DAG.getTargetLoweringInfo(); 3883 3884 // Normalize Vector GEP - all scalar operands should be converted to the 3885 // splat vector. 3886 bool IsVectorGEP = I.getType()->isVectorTy(); 3887 ElementCount VectorElementCount = 3888 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3889 : ElementCount::getFixed(0); 3890 3891 if (IsVectorGEP && !N.getValueType().isVector()) { 3892 LLVMContext &Context = *DAG.getContext(); 3893 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3894 if (VectorElementCount.isScalable()) 3895 N = DAG.getSplatVector(VT, dl, N); 3896 else 3897 N = DAG.getSplatBuildVector(VT, dl, N); 3898 } 3899 3900 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3901 GTI != E; ++GTI) { 3902 const Value *Idx = GTI.getOperand(); 3903 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3904 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3905 if (Field) { 3906 // N = N + Offset 3907 uint64_t Offset = 3908 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3909 3910 // In an inbounds GEP with an offset that is nonnegative even when 3911 // interpreted as signed, assume there is no unsigned overflow. 3912 SDNodeFlags Flags; 3913 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3914 Flags.setNoUnsignedWrap(true); 3915 3916 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3917 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3918 } 3919 } else { 3920 // IdxSize is the width of the arithmetic according to IR semantics. 3921 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3922 // (and fix up the result later). 3923 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3924 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3925 TypeSize ElementSize = 3926 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3927 // We intentionally mask away the high bits here; ElementSize may not 3928 // fit in IdxTy. 3929 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3930 bool ElementScalable = ElementSize.isScalable(); 3931 3932 // If this is a scalar constant or a splat vector of constants, 3933 // handle it quickly. 3934 const auto *C = dyn_cast<Constant>(Idx); 3935 if (C && isa<VectorType>(C->getType())) 3936 C = C->getSplatValue(); 3937 3938 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3939 if (CI && CI->isZero()) 3940 continue; 3941 if (CI && !ElementScalable) { 3942 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3943 LLVMContext &Context = *DAG.getContext(); 3944 SDValue OffsVal; 3945 if (IsVectorGEP) 3946 OffsVal = DAG.getConstant( 3947 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3948 else 3949 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3950 3951 // In an inbounds GEP with an offset that is nonnegative even when 3952 // interpreted as signed, assume there is no unsigned overflow. 3953 SDNodeFlags Flags; 3954 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3955 Flags.setNoUnsignedWrap(true); 3956 3957 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3958 3959 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3960 continue; 3961 } 3962 3963 // N = N + Idx * ElementMul; 3964 SDValue IdxN = getValue(Idx); 3965 3966 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3967 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3968 VectorElementCount); 3969 if (VectorElementCount.isScalable()) 3970 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3971 else 3972 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3973 } 3974 3975 // If the index is smaller or larger than intptr_t, truncate or extend 3976 // it. 3977 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3978 3979 if (ElementScalable) { 3980 EVT VScaleTy = N.getValueType().getScalarType(); 3981 SDValue VScale = DAG.getNode( 3982 ISD::VSCALE, dl, VScaleTy, 3983 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3984 if (IsVectorGEP) 3985 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3986 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3987 } else { 3988 // If this is a multiply by a power of two, turn it into a shl 3989 // immediately. This is a very common case. 3990 if (ElementMul != 1) { 3991 if (ElementMul.isPowerOf2()) { 3992 unsigned Amt = ElementMul.logBase2(); 3993 IdxN = DAG.getNode(ISD::SHL, dl, 3994 N.getValueType(), IdxN, 3995 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3996 } else { 3997 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3998 IdxN.getValueType()); 3999 IdxN = DAG.getNode(ISD::MUL, dl, 4000 N.getValueType(), IdxN, Scale); 4001 } 4002 } 4003 } 4004 4005 N = DAG.getNode(ISD::ADD, dl, 4006 N.getValueType(), N, IdxN); 4007 } 4008 } 4009 4010 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4011 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4012 if (IsVectorGEP) { 4013 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4014 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4015 } 4016 4017 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4018 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4019 4020 setValue(&I, N); 4021 } 4022 4023 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4024 // If this is a fixed sized alloca in the entry block of the function, 4025 // allocate it statically on the stack. 4026 if (FuncInfo.StaticAllocaMap.count(&I)) 4027 return; // getValue will auto-populate this. 4028 4029 SDLoc dl = getCurSDLoc(); 4030 Type *Ty = I.getAllocatedType(); 4031 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4032 auto &DL = DAG.getDataLayout(); 4033 TypeSize TySize = DL.getTypeAllocSize(Ty); 4034 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4035 4036 SDValue AllocSize = getValue(I.getArraySize()); 4037 4038 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 4039 if (AllocSize.getValueType() != IntPtr) 4040 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4041 4042 if (TySize.isScalable()) 4043 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4044 DAG.getVScale(dl, IntPtr, 4045 APInt(IntPtr.getScalarSizeInBits(), 4046 TySize.getKnownMinValue()))); 4047 else 4048 AllocSize = 4049 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4050 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4051 4052 // Handle alignment. If the requested alignment is less than or equal to 4053 // the stack alignment, ignore it. If the size is greater than or equal to 4054 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4055 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4056 if (*Alignment <= StackAlign) 4057 Alignment = None; 4058 4059 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4060 // Round the size of the allocation up to the stack alignment size 4061 // by add SA-1 to the size. This doesn't overflow because we're computing 4062 // an address inside an alloca. 4063 SDNodeFlags Flags; 4064 Flags.setNoUnsignedWrap(true); 4065 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4066 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4067 4068 // Mask out the low bits for alignment purposes. 4069 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4070 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4071 4072 SDValue Ops[] = { 4073 getRoot(), AllocSize, 4074 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4075 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4076 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4077 setValue(&I, DSA); 4078 DAG.setRoot(DSA.getValue(1)); 4079 4080 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4081 } 4082 4083 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4084 if (I.isAtomic()) 4085 return visitAtomicLoad(I); 4086 4087 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4088 const Value *SV = I.getOperand(0); 4089 if (TLI.supportSwiftError()) { 4090 // Swifterror values can come from either a function parameter with 4091 // swifterror attribute or an alloca with swifterror attribute. 4092 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4093 if (Arg->hasSwiftErrorAttr()) 4094 return visitLoadFromSwiftError(I); 4095 } 4096 4097 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4098 if (Alloca->isSwiftError()) 4099 return visitLoadFromSwiftError(I); 4100 } 4101 } 4102 4103 SDValue Ptr = getValue(SV); 4104 4105 Type *Ty = I.getType(); 4106 SmallVector<EVT, 4> ValueVTs, MemVTs; 4107 SmallVector<uint64_t, 4> Offsets; 4108 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4109 unsigned NumValues = ValueVTs.size(); 4110 if (NumValues == 0) 4111 return; 4112 4113 Align Alignment = I.getAlign(); 4114 AAMDNodes AAInfo = I.getAAMetadata(); 4115 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4116 bool isVolatile = I.isVolatile(); 4117 MachineMemOperand::Flags MMOFlags = 4118 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4119 4120 SDValue Root; 4121 bool ConstantMemory = false; 4122 if (isVolatile) 4123 // Serialize volatile loads with other side effects. 4124 Root = getRoot(); 4125 else if (NumValues > MaxParallelChains) 4126 Root = getMemoryRoot(); 4127 else if (AA && 4128 AA->pointsToConstantMemory(MemoryLocation( 4129 SV, 4130 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4131 AAInfo))) { 4132 // Do not serialize (non-volatile) loads of constant memory with anything. 4133 Root = DAG.getEntryNode(); 4134 ConstantMemory = true; 4135 MMOFlags |= MachineMemOperand::MOInvariant; 4136 } else { 4137 // Do not serialize non-volatile loads against each other. 4138 Root = DAG.getRoot(); 4139 } 4140 4141 if (isDereferenceableAndAlignedPointer(SV, Ty, Alignment, DAG.getDataLayout(), 4142 &I, nullptr, nullptr, LibInfo)) 4143 MMOFlags |= MachineMemOperand::MODereferenceable; 4144 4145 SDLoc dl = getCurSDLoc(); 4146 4147 if (isVolatile) 4148 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4149 4150 // An aggregate load cannot wrap around the address space, so offsets to its 4151 // parts don't wrap either. 4152 SDNodeFlags Flags; 4153 Flags.setNoUnsignedWrap(true); 4154 4155 SmallVector<SDValue, 4> Values(NumValues); 4156 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4157 EVT PtrVT = Ptr.getValueType(); 4158 4159 unsigned ChainI = 0; 4160 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4161 // Serializing loads here may result in excessive register pressure, and 4162 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4163 // could recover a bit by hoisting nodes upward in the chain by recognizing 4164 // they are side-effect free or do not alias. The optimizer should really 4165 // avoid this case by converting large object/array copies to llvm.memcpy 4166 // (MaxParallelChains should always remain as failsafe). 4167 if (ChainI == MaxParallelChains) { 4168 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4169 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4170 makeArrayRef(Chains.data(), ChainI)); 4171 Root = Chain; 4172 ChainI = 0; 4173 } 4174 SDValue A = DAG.getNode(ISD::ADD, dl, 4175 PtrVT, Ptr, 4176 DAG.getConstant(Offsets[i], dl, PtrVT), 4177 Flags); 4178 4179 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4180 MachinePointerInfo(SV, Offsets[i]), Alignment, 4181 MMOFlags, AAInfo, Ranges); 4182 Chains[ChainI] = L.getValue(1); 4183 4184 if (MemVTs[i] != ValueVTs[i]) 4185 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4186 4187 Values[i] = L; 4188 } 4189 4190 if (!ConstantMemory) { 4191 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4192 makeArrayRef(Chains.data(), ChainI)); 4193 if (isVolatile) 4194 DAG.setRoot(Chain); 4195 else 4196 PendingLoads.push_back(Chain); 4197 } 4198 4199 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4200 DAG.getVTList(ValueVTs), Values)); 4201 } 4202 4203 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4204 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4205 "call visitStoreToSwiftError when backend supports swifterror"); 4206 4207 SmallVector<EVT, 4> ValueVTs; 4208 SmallVector<uint64_t, 4> Offsets; 4209 const Value *SrcV = I.getOperand(0); 4210 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4211 SrcV->getType(), ValueVTs, &Offsets); 4212 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4213 "expect a single EVT for swifterror"); 4214 4215 SDValue Src = getValue(SrcV); 4216 // Create a virtual register, then update the virtual register. 4217 Register VReg = 4218 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4219 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4220 // Chain can be getRoot or getControlRoot. 4221 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4222 SDValue(Src.getNode(), Src.getResNo())); 4223 DAG.setRoot(CopyNode); 4224 } 4225 4226 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4227 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4228 "call visitLoadFromSwiftError when backend supports swifterror"); 4229 4230 assert(!I.isVolatile() && 4231 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4232 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4233 "Support volatile, non temporal, invariant for load_from_swift_error"); 4234 4235 const Value *SV = I.getOperand(0); 4236 Type *Ty = I.getType(); 4237 assert( 4238 (!AA || 4239 !AA->pointsToConstantMemory(MemoryLocation( 4240 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4241 I.getAAMetadata()))) && 4242 "load_from_swift_error should not be constant memory"); 4243 4244 SmallVector<EVT, 4> ValueVTs; 4245 SmallVector<uint64_t, 4> Offsets; 4246 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4247 ValueVTs, &Offsets); 4248 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4249 "expect a single EVT for swifterror"); 4250 4251 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4252 SDValue L = DAG.getCopyFromReg( 4253 getRoot(), getCurSDLoc(), 4254 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4255 4256 setValue(&I, L); 4257 } 4258 4259 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4260 if (I.isAtomic()) 4261 return visitAtomicStore(I); 4262 4263 const Value *SrcV = I.getOperand(0); 4264 const Value *PtrV = I.getOperand(1); 4265 4266 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4267 if (TLI.supportSwiftError()) { 4268 // Swifterror values can come from either a function parameter with 4269 // swifterror attribute or an alloca with swifterror attribute. 4270 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4271 if (Arg->hasSwiftErrorAttr()) 4272 return visitStoreToSwiftError(I); 4273 } 4274 4275 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4276 if (Alloca->isSwiftError()) 4277 return visitStoreToSwiftError(I); 4278 } 4279 } 4280 4281 SmallVector<EVT, 4> ValueVTs, MemVTs; 4282 SmallVector<uint64_t, 4> Offsets; 4283 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4284 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4285 unsigned NumValues = ValueVTs.size(); 4286 if (NumValues == 0) 4287 return; 4288 4289 // Get the lowered operands. Note that we do this after 4290 // checking if NumResults is zero, because with zero results 4291 // the operands won't have values in the map. 4292 SDValue Src = getValue(SrcV); 4293 SDValue Ptr = getValue(PtrV); 4294 4295 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4296 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4297 SDLoc dl = getCurSDLoc(); 4298 Align Alignment = I.getAlign(); 4299 AAMDNodes AAInfo = I.getAAMetadata(); 4300 4301 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4302 4303 // An aggregate load cannot wrap around the address space, so offsets to its 4304 // parts don't wrap either. 4305 SDNodeFlags Flags; 4306 Flags.setNoUnsignedWrap(true); 4307 4308 unsigned ChainI = 0; 4309 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4310 // See visitLoad comments. 4311 if (ChainI == MaxParallelChains) { 4312 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4313 makeArrayRef(Chains.data(), ChainI)); 4314 Root = Chain; 4315 ChainI = 0; 4316 } 4317 SDValue Add = 4318 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4319 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4320 if (MemVTs[i] != ValueVTs[i]) 4321 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4322 SDValue St = 4323 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4324 Alignment, MMOFlags, AAInfo); 4325 Chains[ChainI] = St; 4326 } 4327 4328 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4329 makeArrayRef(Chains.data(), ChainI)); 4330 setValue(&I, StoreNode); 4331 DAG.setRoot(StoreNode); 4332 } 4333 4334 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4335 bool IsCompressing) { 4336 SDLoc sdl = getCurSDLoc(); 4337 4338 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4339 MaybeAlign &Alignment) { 4340 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4341 Src0 = I.getArgOperand(0); 4342 Ptr = I.getArgOperand(1); 4343 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4344 Mask = I.getArgOperand(3); 4345 }; 4346 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4347 MaybeAlign &Alignment) { 4348 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4349 Src0 = I.getArgOperand(0); 4350 Ptr = I.getArgOperand(1); 4351 Mask = I.getArgOperand(2); 4352 Alignment = None; 4353 }; 4354 4355 Value *PtrOperand, *MaskOperand, *Src0Operand; 4356 MaybeAlign Alignment; 4357 if (IsCompressing) 4358 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4359 else 4360 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4361 4362 SDValue Ptr = getValue(PtrOperand); 4363 SDValue Src0 = getValue(Src0Operand); 4364 SDValue Mask = getValue(MaskOperand); 4365 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4366 4367 EVT VT = Src0.getValueType(); 4368 if (!Alignment) 4369 Alignment = DAG.getEVTAlign(VT); 4370 4371 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4372 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4373 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4374 SDValue StoreNode = 4375 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4376 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4377 DAG.setRoot(StoreNode); 4378 setValue(&I, StoreNode); 4379 } 4380 4381 // Get a uniform base for the Gather/Scatter intrinsic. 4382 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4383 // We try to represent it as a base pointer + vector of indices. 4384 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4385 // The first operand of the GEP may be a single pointer or a vector of pointers 4386 // Example: 4387 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4388 // or 4389 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4390 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4391 // 4392 // When the first GEP operand is a single pointer - it is the uniform base we 4393 // are looking for. If first operand of the GEP is a splat vector - we 4394 // extract the splat value and use it as a uniform base. 4395 // In all other cases the function returns 'false'. 4396 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4397 ISD::MemIndexType &IndexType, SDValue &Scale, 4398 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4399 uint64_t ElemSize) { 4400 SelectionDAG& DAG = SDB->DAG; 4401 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4402 const DataLayout &DL = DAG.getDataLayout(); 4403 4404 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4405 4406 // Handle splat constant pointer. 4407 if (auto *C = dyn_cast<Constant>(Ptr)) { 4408 C = C->getSplatValue(); 4409 if (!C) 4410 return false; 4411 4412 Base = SDB->getValue(C); 4413 4414 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4415 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4416 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4417 IndexType = ISD::SIGNED_SCALED; 4418 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4419 return true; 4420 } 4421 4422 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4423 if (!GEP || GEP->getParent() != CurBB) 4424 return false; 4425 4426 if (GEP->getNumOperands() != 2) 4427 return false; 4428 4429 const Value *BasePtr = GEP->getPointerOperand(); 4430 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4431 4432 // Make sure the base is scalar and the index is a vector. 4433 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4434 return false; 4435 4436 Base = SDB->getValue(BasePtr); 4437 Index = SDB->getValue(IndexVal); 4438 IndexType = ISD::SIGNED_SCALED; 4439 4440 // MGATHER/MSCATTER are only required to support scaling by one or by the 4441 // element size. Other scales may be produced using target-specific DAG 4442 // combines. 4443 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4444 if (ScaleVal != ElemSize && ScaleVal != 1) 4445 return false; 4446 4447 Scale = 4448 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4449 return true; 4450 } 4451 4452 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4453 SDLoc sdl = getCurSDLoc(); 4454 4455 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4456 const Value *Ptr = I.getArgOperand(1); 4457 SDValue Src0 = getValue(I.getArgOperand(0)); 4458 SDValue Mask = getValue(I.getArgOperand(3)); 4459 EVT VT = Src0.getValueType(); 4460 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4461 ->getMaybeAlignValue() 4462 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4463 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4464 4465 SDValue Base; 4466 SDValue Index; 4467 ISD::MemIndexType IndexType; 4468 SDValue Scale; 4469 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4470 I.getParent(), VT.getScalarStoreSize()); 4471 4472 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4473 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4474 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4475 // TODO: Make MachineMemOperands aware of scalable 4476 // vectors. 4477 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4478 if (!UniformBase) { 4479 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4480 Index = getValue(Ptr); 4481 IndexType = ISD::SIGNED_SCALED; 4482 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4483 } 4484 4485 EVT IdxVT = Index.getValueType(); 4486 EVT EltTy = IdxVT.getVectorElementType(); 4487 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4488 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4489 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4490 } 4491 4492 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4493 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4494 Ops, MMO, IndexType, false); 4495 DAG.setRoot(Scatter); 4496 setValue(&I, Scatter); 4497 } 4498 4499 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4500 SDLoc sdl = getCurSDLoc(); 4501 4502 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4503 MaybeAlign &Alignment) { 4504 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4505 Ptr = I.getArgOperand(0); 4506 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4507 Mask = I.getArgOperand(2); 4508 Src0 = I.getArgOperand(3); 4509 }; 4510 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4511 MaybeAlign &Alignment) { 4512 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4513 Ptr = I.getArgOperand(0); 4514 Alignment = None; 4515 Mask = I.getArgOperand(1); 4516 Src0 = I.getArgOperand(2); 4517 }; 4518 4519 Value *PtrOperand, *MaskOperand, *Src0Operand; 4520 MaybeAlign Alignment; 4521 if (IsExpanding) 4522 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4523 else 4524 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4525 4526 SDValue Ptr = getValue(PtrOperand); 4527 SDValue Src0 = getValue(Src0Operand); 4528 SDValue Mask = getValue(MaskOperand); 4529 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4530 4531 EVT VT = Src0.getValueType(); 4532 if (!Alignment) 4533 Alignment = DAG.getEVTAlign(VT); 4534 4535 AAMDNodes AAInfo = I.getAAMetadata(); 4536 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4537 4538 // Do not serialize masked loads of constant memory with anything. 4539 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4540 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4541 4542 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4543 4544 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4545 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4546 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4547 4548 SDValue Load = 4549 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4550 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4551 if (AddToChain) 4552 PendingLoads.push_back(Load.getValue(1)); 4553 setValue(&I, Load); 4554 } 4555 4556 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4557 SDLoc sdl = getCurSDLoc(); 4558 4559 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4560 const Value *Ptr = I.getArgOperand(0); 4561 SDValue Src0 = getValue(I.getArgOperand(3)); 4562 SDValue Mask = getValue(I.getArgOperand(2)); 4563 4564 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4565 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4566 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4567 ->getMaybeAlignValue() 4568 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4569 4570 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4571 4572 SDValue Root = DAG.getRoot(); 4573 SDValue Base; 4574 SDValue Index; 4575 ISD::MemIndexType IndexType; 4576 SDValue Scale; 4577 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4578 I.getParent(), VT.getScalarStoreSize()); 4579 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4580 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4581 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4582 // TODO: Make MachineMemOperands aware of scalable 4583 // vectors. 4584 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4585 4586 if (!UniformBase) { 4587 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4588 Index = getValue(Ptr); 4589 IndexType = ISD::SIGNED_SCALED; 4590 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4591 } 4592 4593 EVT IdxVT = Index.getValueType(); 4594 EVT EltTy = IdxVT.getVectorElementType(); 4595 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4596 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4597 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4598 } 4599 4600 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4601 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4602 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4603 4604 PendingLoads.push_back(Gather.getValue(1)); 4605 setValue(&I, Gather); 4606 } 4607 4608 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4609 SDLoc dl = getCurSDLoc(); 4610 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4611 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4612 SyncScope::ID SSID = I.getSyncScopeID(); 4613 4614 SDValue InChain = getRoot(); 4615 4616 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4617 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4618 4619 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4620 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4621 4622 MachineFunction &MF = DAG.getMachineFunction(); 4623 MachineMemOperand *MMO = MF.getMachineMemOperand( 4624 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4625 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4626 FailureOrdering); 4627 4628 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4629 dl, MemVT, VTs, InChain, 4630 getValue(I.getPointerOperand()), 4631 getValue(I.getCompareOperand()), 4632 getValue(I.getNewValOperand()), MMO); 4633 4634 SDValue OutChain = L.getValue(2); 4635 4636 setValue(&I, L); 4637 DAG.setRoot(OutChain); 4638 } 4639 4640 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4641 SDLoc dl = getCurSDLoc(); 4642 ISD::NodeType NT; 4643 switch (I.getOperation()) { 4644 default: llvm_unreachable("Unknown atomicrmw operation"); 4645 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4646 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4647 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4648 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4649 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4650 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4651 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4652 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4653 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4654 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4655 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4656 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4657 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4658 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4659 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4660 } 4661 AtomicOrdering Ordering = I.getOrdering(); 4662 SyncScope::ID SSID = I.getSyncScopeID(); 4663 4664 SDValue InChain = getRoot(); 4665 4666 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4667 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4668 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4669 4670 MachineFunction &MF = DAG.getMachineFunction(); 4671 MachineMemOperand *MMO = MF.getMachineMemOperand( 4672 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4673 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4674 4675 SDValue L = 4676 DAG.getAtomic(NT, dl, MemVT, InChain, 4677 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4678 MMO); 4679 4680 SDValue OutChain = L.getValue(1); 4681 4682 setValue(&I, L); 4683 DAG.setRoot(OutChain); 4684 } 4685 4686 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4687 SDLoc dl = getCurSDLoc(); 4688 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4689 SDValue Ops[3]; 4690 Ops[0] = getRoot(); 4691 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4692 TLI.getFenceOperandTy(DAG.getDataLayout())); 4693 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4694 TLI.getFenceOperandTy(DAG.getDataLayout())); 4695 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4696 setValue(&I, N); 4697 DAG.setRoot(N); 4698 } 4699 4700 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4701 SDLoc dl = getCurSDLoc(); 4702 AtomicOrdering Order = I.getOrdering(); 4703 SyncScope::ID SSID = I.getSyncScopeID(); 4704 4705 SDValue InChain = getRoot(); 4706 4707 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4708 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4709 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4710 4711 if (!TLI.supportsUnalignedAtomics() && 4712 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4713 report_fatal_error("Cannot generate unaligned atomic load"); 4714 4715 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4716 4717 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4718 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4719 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4720 4721 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4722 4723 SDValue Ptr = getValue(I.getPointerOperand()); 4724 4725 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4726 // TODO: Once this is better exercised by tests, it should be merged with 4727 // the normal path for loads to prevent future divergence. 4728 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4729 if (MemVT != VT) 4730 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4731 4732 setValue(&I, L); 4733 SDValue OutChain = L.getValue(1); 4734 if (!I.isUnordered()) 4735 DAG.setRoot(OutChain); 4736 else 4737 PendingLoads.push_back(OutChain); 4738 return; 4739 } 4740 4741 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4742 Ptr, MMO); 4743 4744 SDValue OutChain = L.getValue(1); 4745 if (MemVT != VT) 4746 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4747 4748 setValue(&I, L); 4749 DAG.setRoot(OutChain); 4750 } 4751 4752 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4753 SDLoc dl = getCurSDLoc(); 4754 4755 AtomicOrdering Ordering = I.getOrdering(); 4756 SyncScope::ID SSID = I.getSyncScopeID(); 4757 4758 SDValue InChain = getRoot(); 4759 4760 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4761 EVT MemVT = 4762 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4763 4764 if (!TLI.supportsUnalignedAtomics() && 4765 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4766 report_fatal_error("Cannot generate unaligned atomic store"); 4767 4768 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4769 4770 MachineFunction &MF = DAG.getMachineFunction(); 4771 MachineMemOperand *MMO = MF.getMachineMemOperand( 4772 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4773 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4774 4775 SDValue Val = getValue(I.getValueOperand()); 4776 if (Val.getValueType() != MemVT) 4777 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4778 SDValue Ptr = getValue(I.getPointerOperand()); 4779 4780 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4781 // TODO: Once this is better exercised by tests, it should be merged with 4782 // the normal path for stores to prevent future divergence. 4783 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4784 setValue(&I, S); 4785 DAG.setRoot(S); 4786 return; 4787 } 4788 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4789 Ptr, Val, MMO); 4790 4791 setValue(&I, OutChain); 4792 DAG.setRoot(OutChain); 4793 } 4794 4795 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4796 /// node. 4797 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4798 unsigned Intrinsic) { 4799 // Ignore the callsite's attributes. A specific call site may be marked with 4800 // readnone, but the lowering code will expect the chain based on the 4801 // definition. 4802 const Function *F = I.getCalledFunction(); 4803 bool HasChain = !F->doesNotAccessMemory(); 4804 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4805 4806 // Build the operand list. 4807 SmallVector<SDValue, 8> Ops; 4808 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4809 if (OnlyLoad) { 4810 // We don't need to serialize loads against other loads. 4811 Ops.push_back(DAG.getRoot()); 4812 } else { 4813 Ops.push_back(getRoot()); 4814 } 4815 } 4816 4817 // Info is set by getTgtMemIntrinsic 4818 TargetLowering::IntrinsicInfo Info; 4819 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4820 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4821 DAG.getMachineFunction(), 4822 Intrinsic); 4823 4824 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4825 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4826 Info.opc == ISD::INTRINSIC_W_CHAIN) 4827 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4828 TLI.getPointerTy(DAG.getDataLayout()))); 4829 4830 // Add all operands of the call to the operand list. 4831 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4832 const Value *Arg = I.getArgOperand(i); 4833 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4834 Ops.push_back(getValue(Arg)); 4835 continue; 4836 } 4837 4838 // Use TargetConstant instead of a regular constant for immarg. 4839 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4840 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4841 assert(CI->getBitWidth() <= 64 && 4842 "large intrinsic immediates not handled"); 4843 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4844 } else { 4845 Ops.push_back( 4846 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4847 } 4848 } 4849 4850 SmallVector<EVT, 4> ValueVTs; 4851 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4852 4853 if (HasChain) 4854 ValueVTs.push_back(MVT::Other); 4855 4856 SDVTList VTs = DAG.getVTList(ValueVTs); 4857 4858 // Propagate fast-math-flags from IR to node(s). 4859 SDNodeFlags Flags; 4860 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4861 Flags.copyFMF(*FPMO); 4862 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4863 4864 // Create the node. 4865 SDValue Result; 4866 if (IsTgtIntrinsic) { 4867 // This is target intrinsic that touches memory 4868 Result = 4869 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4870 MachinePointerInfo(Info.ptrVal, Info.offset), 4871 Info.align, Info.flags, Info.size, 4872 I.getAAMetadata()); 4873 } else if (!HasChain) { 4874 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4875 } else if (!I.getType()->isVoidTy()) { 4876 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4877 } else { 4878 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4879 } 4880 4881 if (HasChain) { 4882 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4883 if (OnlyLoad) 4884 PendingLoads.push_back(Chain); 4885 else 4886 DAG.setRoot(Chain); 4887 } 4888 4889 if (!I.getType()->isVoidTy()) { 4890 if (!isa<VectorType>(I.getType())) 4891 Result = lowerRangeToAssertZExt(DAG, I, Result); 4892 4893 MaybeAlign Alignment = I.getRetAlign(); 4894 if (!Alignment) 4895 Alignment = F->getAttributes().getRetAlignment(); 4896 // Insert `assertalign` node if there's an alignment. 4897 if (InsertAssertAlign && Alignment) { 4898 Result = 4899 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4900 } 4901 4902 setValue(&I, Result); 4903 } 4904 } 4905 4906 /// GetSignificand - Get the significand and build it into a floating-point 4907 /// number with exponent of 1: 4908 /// 4909 /// Op = (Op & 0x007fffff) | 0x3f800000; 4910 /// 4911 /// where Op is the hexadecimal representation of floating point value. 4912 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4913 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4914 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4915 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4916 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4917 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4918 } 4919 4920 /// GetExponent - Get the exponent: 4921 /// 4922 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4923 /// 4924 /// where Op is the hexadecimal representation of floating point value. 4925 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4926 const TargetLowering &TLI, const SDLoc &dl) { 4927 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4928 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4929 SDValue t1 = DAG.getNode( 4930 ISD::SRL, dl, MVT::i32, t0, 4931 DAG.getConstant(23, dl, 4932 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 4933 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4934 DAG.getConstant(127, dl, MVT::i32)); 4935 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4936 } 4937 4938 /// getF32Constant - Get 32-bit floating point constant. 4939 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4940 const SDLoc &dl) { 4941 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4942 MVT::f32); 4943 } 4944 4945 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4946 SelectionDAG &DAG) { 4947 // TODO: What fast-math-flags should be set on the floating-point nodes? 4948 4949 // IntegerPartOfX = ((int32_t)(t0); 4950 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4951 4952 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4953 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4954 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4955 4956 // IntegerPartOfX <<= 23; 4957 IntegerPartOfX = 4958 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4959 DAG.getConstant(23, dl, 4960 DAG.getTargetLoweringInfo().getShiftAmountTy( 4961 MVT::i32, DAG.getDataLayout()))); 4962 4963 SDValue TwoToFractionalPartOfX; 4964 if (LimitFloatPrecision <= 6) { 4965 // For floating-point precision of 6: 4966 // 4967 // TwoToFractionalPartOfX = 4968 // 0.997535578f + 4969 // (0.735607626f + 0.252464424f * x) * x; 4970 // 4971 // error 0.0144103317, which is 6 bits 4972 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4973 getF32Constant(DAG, 0x3e814304, dl)); 4974 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4975 getF32Constant(DAG, 0x3f3c50c8, dl)); 4976 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4977 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4978 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4979 } else if (LimitFloatPrecision <= 12) { 4980 // For floating-point precision of 12: 4981 // 4982 // TwoToFractionalPartOfX = 4983 // 0.999892986f + 4984 // (0.696457318f + 4985 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4986 // 4987 // error 0.000107046256, which is 13 to 14 bits 4988 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4989 getF32Constant(DAG, 0x3da235e3, dl)); 4990 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4991 getF32Constant(DAG, 0x3e65b8f3, dl)); 4992 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4993 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4994 getF32Constant(DAG, 0x3f324b07, dl)); 4995 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4996 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4997 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4998 } else { // LimitFloatPrecision <= 18 4999 // For floating-point precision of 18: 5000 // 5001 // TwoToFractionalPartOfX = 5002 // 0.999999982f + 5003 // (0.693148872f + 5004 // (0.240227044f + 5005 // (0.554906021e-1f + 5006 // (0.961591928e-2f + 5007 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5008 // error 2.47208000*10^(-7), which is better than 18 bits 5009 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5010 getF32Constant(DAG, 0x3924b03e, dl)); 5011 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5012 getF32Constant(DAG, 0x3ab24b87, dl)); 5013 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5014 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5015 getF32Constant(DAG, 0x3c1d8c17, dl)); 5016 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5017 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5018 getF32Constant(DAG, 0x3d634a1d, dl)); 5019 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5020 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5021 getF32Constant(DAG, 0x3e75fe14, dl)); 5022 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5023 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5024 getF32Constant(DAG, 0x3f317234, dl)); 5025 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5026 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5027 getF32Constant(DAG, 0x3f800000, dl)); 5028 } 5029 5030 // Add the exponent into the result in integer domain. 5031 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5032 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5033 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5034 } 5035 5036 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5037 /// limited-precision mode. 5038 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5039 const TargetLowering &TLI, SDNodeFlags Flags) { 5040 if (Op.getValueType() == MVT::f32 && 5041 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5042 5043 // Put the exponent in the right bit position for later addition to the 5044 // final result: 5045 // 5046 // t0 = Op * log2(e) 5047 5048 // TODO: What fast-math-flags should be set here? 5049 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5050 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5051 return getLimitedPrecisionExp2(t0, dl, DAG); 5052 } 5053 5054 // No special expansion. 5055 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5056 } 5057 5058 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5059 /// limited-precision mode. 5060 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5061 const TargetLowering &TLI, SDNodeFlags Flags) { 5062 // TODO: What fast-math-flags should be set on the floating-point nodes? 5063 5064 if (Op.getValueType() == MVT::f32 && 5065 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5066 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5067 5068 // Scale the exponent by log(2). 5069 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5070 SDValue LogOfExponent = 5071 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5072 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5073 5074 // Get the significand and build it into a floating-point number with 5075 // exponent of 1. 5076 SDValue X = GetSignificand(DAG, Op1, dl); 5077 5078 SDValue LogOfMantissa; 5079 if (LimitFloatPrecision <= 6) { 5080 // For floating-point precision of 6: 5081 // 5082 // LogofMantissa = 5083 // -1.1609546f + 5084 // (1.4034025f - 0.23903021f * x) * x; 5085 // 5086 // error 0.0034276066, which is better than 8 bits 5087 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5088 getF32Constant(DAG, 0xbe74c456, dl)); 5089 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5090 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5091 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5092 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5093 getF32Constant(DAG, 0x3f949a29, dl)); 5094 } else if (LimitFloatPrecision <= 12) { 5095 // For floating-point precision of 12: 5096 // 5097 // LogOfMantissa = 5098 // -1.7417939f + 5099 // (2.8212026f + 5100 // (-1.4699568f + 5101 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5102 // 5103 // error 0.000061011436, which is 14 bits 5104 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5105 getF32Constant(DAG, 0xbd67b6d6, dl)); 5106 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5107 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5108 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5109 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5110 getF32Constant(DAG, 0x3fbc278b, dl)); 5111 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5112 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5113 getF32Constant(DAG, 0x40348e95, dl)); 5114 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5115 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5116 getF32Constant(DAG, 0x3fdef31a, dl)); 5117 } else { // LimitFloatPrecision <= 18 5118 // For floating-point precision of 18: 5119 // 5120 // LogOfMantissa = 5121 // -2.1072184f + 5122 // (4.2372794f + 5123 // (-3.7029485f + 5124 // (2.2781945f + 5125 // (-0.87823314f + 5126 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5127 // 5128 // error 0.0000023660568, which is better than 18 bits 5129 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5130 getF32Constant(DAG, 0xbc91e5ac, dl)); 5131 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5132 getF32Constant(DAG, 0x3e4350aa, dl)); 5133 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5134 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5135 getF32Constant(DAG, 0x3f60d3e3, dl)); 5136 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5137 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5138 getF32Constant(DAG, 0x4011cdf0, dl)); 5139 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5140 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5141 getF32Constant(DAG, 0x406cfd1c, dl)); 5142 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5143 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5144 getF32Constant(DAG, 0x408797cb, dl)); 5145 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5146 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5147 getF32Constant(DAG, 0x4006dcab, dl)); 5148 } 5149 5150 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5151 } 5152 5153 // No special expansion. 5154 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5155 } 5156 5157 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5158 /// limited-precision mode. 5159 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5160 const TargetLowering &TLI, SDNodeFlags Flags) { 5161 // TODO: What fast-math-flags should be set on the floating-point nodes? 5162 5163 if (Op.getValueType() == MVT::f32 && 5164 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5165 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5166 5167 // Get the exponent. 5168 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5169 5170 // Get the significand and build it into a floating-point number with 5171 // exponent of 1. 5172 SDValue X = GetSignificand(DAG, Op1, dl); 5173 5174 // Different possible minimax approximations of significand in 5175 // floating-point for various degrees of accuracy over [1,2]. 5176 SDValue Log2ofMantissa; 5177 if (LimitFloatPrecision <= 6) { 5178 // For floating-point precision of 6: 5179 // 5180 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5181 // 5182 // error 0.0049451742, which is more than 7 bits 5183 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5184 getF32Constant(DAG, 0xbeb08fe0, dl)); 5185 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5186 getF32Constant(DAG, 0x40019463, dl)); 5187 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5188 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5189 getF32Constant(DAG, 0x3fd6633d, dl)); 5190 } else if (LimitFloatPrecision <= 12) { 5191 // For floating-point precision of 12: 5192 // 5193 // Log2ofMantissa = 5194 // -2.51285454f + 5195 // (4.07009056f + 5196 // (-2.12067489f + 5197 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5198 // 5199 // error 0.0000876136000, which is better than 13 bits 5200 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5201 getF32Constant(DAG, 0xbda7262e, dl)); 5202 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5203 getF32Constant(DAG, 0x3f25280b, dl)); 5204 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5205 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5206 getF32Constant(DAG, 0x4007b923, dl)); 5207 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5208 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5209 getF32Constant(DAG, 0x40823e2f, dl)); 5210 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5211 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5212 getF32Constant(DAG, 0x4020d29c, dl)); 5213 } else { // LimitFloatPrecision <= 18 5214 // For floating-point precision of 18: 5215 // 5216 // Log2ofMantissa = 5217 // -3.0400495f + 5218 // (6.1129976f + 5219 // (-5.3420409f + 5220 // (3.2865683f + 5221 // (-1.2669343f + 5222 // (0.27515199f - 5223 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5224 // 5225 // error 0.0000018516, which is better than 18 bits 5226 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5227 getF32Constant(DAG, 0xbcd2769e, dl)); 5228 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5229 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5230 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5231 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5232 getF32Constant(DAG, 0x3fa22ae7, dl)); 5233 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5234 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5235 getF32Constant(DAG, 0x40525723, dl)); 5236 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5237 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5238 getF32Constant(DAG, 0x40aaf200, dl)); 5239 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5240 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5241 getF32Constant(DAG, 0x40c39dad, dl)); 5242 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5243 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5244 getF32Constant(DAG, 0x4042902c, dl)); 5245 } 5246 5247 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5248 } 5249 5250 // No special expansion. 5251 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5252 } 5253 5254 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5255 /// limited-precision mode. 5256 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5257 const TargetLowering &TLI, SDNodeFlags Flags) { 5258 // TODO: What fast-math-flags should be set on the floating-point nodes? 5259 5260 if (Op.getValueType() == MVT::f32 && 5261 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5262 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5263 5264 // Scale the exponent by log10(2) [0.30102999f]. 5265 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5266 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5267 getF32Constant(DAG, 0x3e9a209a, dl)); 5268 5269 // Get the significand and build it into a floating-point number with 5270 // exponent of 1. 5271 SDValue X = GetSignificand(DAG, Op1, dl); 5272 5273 SDValue Log10ofMantissa; 5274 if (LimitFloatPrecision <= 6) { 5275 // For floating-point precision of 6: 5276 // 5277 // Log10ofMantissa = 5278 // -0.50419619f + 5279 // (0.60948995f - 0.10380950f * x) * x; 5280 // 5281 // error 0.0014886165, which is 6 bits 5282 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5283 getF32Constant(DAG, 0xbdd49a13, dl)); 5284 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5285 getF32Constant(DAG, 0x3f1c0789, dl)); 5286 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5287 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5288 getF32Constant(DAG, 0x3f011300, dl)); 5289 } else if (LimitFloatPrecision <= 12) { 5290 // For floating-point precision of 12: 5291 // 5292 // Log10ofMantissa = 5293 // -0.64831180f + 5294 // (0.91751397f + 5295 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5296 // 5297 // error 0.00019228036, which is better than 12 bits 5298 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5299 getF32Constant(DAG, 0x3d431f31, dl)); 5300 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5301 getF32Constant(DAG, 0x3ea21fb2, dl)); 5302 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5303 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5304 getF32Constant(DAG, 0x3f6ae232, dl)); 5305 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5306 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5307 getF32Constant(DAG, 0x3f25f7c3, dl)); 5308 } else { // LimitFloatPrecision <= 18 5309 // For floating-point precision of 18: 5310 // 5311 // Log10ofMantissa = 5312 // -0.84299375f + 5313 // (1.5327582f + 5314 // (-1.0688956f + 5315 // (0.49102474f + 5316 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5317 // 5318 // error 0.0000037995730, which is better than 18 bits 5319 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5320 getF32Constant(DAG, 0x3c5d51ce, dl)); 5321 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5322 getF32Constant(DAG, 0x3e00685a, dl)); 5323 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5324 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5325 getF32Constant(DAG, 0x3efb6798, dl)); 5326 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5327 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5328 getF32Constant(DAG, 0x3f88d192, dl)); 5329 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5330 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5331 getF32Constant(DAG, 0x3fc4316c, dl)); 5332 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5333 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5334 getF32Constant(DAG, 0x3f57ce70, dl)); 5335 } 5336 5337 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5338 } 5339 5340 // No special expansion. 5341 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5342 } 5343 5344 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5345 /// limited-precision mode. 5346 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5347 const TargetLowering &TLI, SDNodeFlags Flags) { 5348 if (Op.getValueType() == MVT::f32 && 5349 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5350 return getLimitedPrecisionExp2(Op, dl, DAG); 5351 5352 // No special expansion. 5353 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5354 } 5355 5356 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5357 /// limited-precision mode with x == 10.0f. 5358 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5359 SelectionDAG &DAG, const TargetLowering &TLI, 5360 SDNodeFlags Flags) { 5361 bool IsExp10 = false; 5362 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5363 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5364 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5365 APFloat Ten(10.0f); 5366 IsExp10 = LHSC->isExactlyValue(Ten); 5367 } 5368 } 5369 5370 // TODO: What fast-math-flags should be set on the FMUL node? 5371 if (IsExp10) { 5372 // Put the exponent in the right bit position for later addition to the 5373 // final result: 5374 // 5375 // #define LOG2OF10 3.3219281f 5376 // t0 = Op * LOG2OF10; 5377 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5378 getF32Constant(DAG, 0x40549a78, dl)); 5379 return getLimitedPrecisionExp2(t0, dl, DAG); 5380 } 5381 5382 // No special expansion. 5383 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5384 } 5385 5386 /// ExpandPowI - Expand a llvm.powi intrinsic. 5387 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5388 SelectionDAG &DAG) { 5389 // If RHS is a constant, we can expand this out to a multiplication tree if 5390 // it's beneficial on the target, otherwise we end up lowering to a call to 5391 // __powidf2 (for example). 5392 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5393 unsigned Val = RHSC->getSExtValue(); 5394 5395 // powi(x, 0) -> 1.0 5396 if (Val == 0) 5397 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5398 5399 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5400 Val, DAG.shouldOptForSize())) { 5401 // Get the exponent as a positive value. 5402 if ((int)Val < 0) 5403 Val = -Val; 5404 // We use the simple binary decomposition method to generate the multiply 5405 // sequence. There are more optimal ways to do this (for example, 5406 // powi(x,15) generates one more multiply than it should), but this has 5407 // the benefit of being both really simple and much better than a libcall. 5408 SDValue Res; // Logically starts equal to 1.0 5409 SDValue CurSquare = LHS; 5410 // TODO: Intrinsics should have fast-math-flags that propagate to these 5411 // nodes. 5412 while (Val) { 5413 if (Val & 1) { 5414 if (Res.getNode()) 5415 Res = 5416 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5417 else 5418 Res = CurSquare; // 1.0*CurSquare. 5419 } 5420 5421 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5422 CurSquare, CurSquare); 5423 Val >>= 1; 5424 } 5425 5426 // If the original was negative, invert the result, producing 1/(x*x*x). 5427 if (RHSC->getSExtValue() < 0) 5428 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5429 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5430 return Res; 5431 } 5432 } 5433 5434 // Otherwise, expand to a libcall. 5435 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5436 } 5437 5438 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5439 SDValue LHS, SDValue RHS, SDValue Scale, 5440 SelectionDAG &DAG, const TargetLowering &TLI) { 5441 EVT VT = LHS.getValueType(); 5442 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5443 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5444 LLVMContext &Ctx = *DAG.getContext(); 5445 5446 // If the type is legal but the operation isn't, this node might survive all 5447 // the way to operation legalization. If we end up there and we do not have 5448 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5449 // node. 5450 5451 // Coax the legalizer into expanding the node during type legalization instead 5452 // by bumping the size by one bit. This will force it to Promote, enabling the 5453 // early expansion and avoiding the need to expand later. 5454 5455 // We don't have to do this if Scale is 0; that can always be expanded, unless 5456 // it's a saturating signed operation. Those can experience true integer 5457 // division overflow, a case which we must avoid. 5458 5459 // FIXME: We wouldn't have to do this (or any of the early 5460 // expansion/promotion) if it was possible to expand a libcall of an 5461 // illegal type during operation legalization. But it's not, so things 5462 // get a bit hacky. 5463 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5464 if ((ScaleInt > 0 || (Saturating && Signed)) && 5465 (TLI.isTypeLegal(VT) || 5466 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5467 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5468 Opcode, VT, ScaleInt); 5469 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5470 EVT PromVT; 5471 if (VT.isScalarInteger()) 5472 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5473 else if (VT.isVector()) { 5474 PromVT = VT.getVectorElementType(); 5475 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5476 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5477 } else 5478 llvm_unreachable("Wrong VT for DIVFIX?"); 5479 if (Signed) { 5480 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5481 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5482 } else { 5483 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5484 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5485 } 5486 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5487 // For saturating operations, we need to shift up the LHS to get the 5488 // proper saturation width, and then shift down again afterwards. 5489 if (Saturating) 5490 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5491 DAG.getConstant(1, DL, ShiftTy)); 5492 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5493 if (Saturating) 5494 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5495 DAG.getConstant(1, DL, ShiftTy)); 5496 return DAG.getZExtOrTrunc(Res, DL, VT); 5497 } 5498 } 5499 5500 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5501 } 5502 5503 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5504 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5505 static void 5506 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5507 const SDValue &N) { 5508 switch (N.getOpcode()) { 5509 case ISD::CopyFromReg: { 5510 SDValue Op = N.getOperand(1); 5511 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5512 Op.getValueType().getSizeInBits()); 5513 return; 5514 } 5515 case ISD::BITCAST: 5516 case ISD::AssertZext: 5517 case ISD::AssertSext: 5518 case ISD::TRUNCATE: 5519 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5520 return; 5521 case ISD::BUILD_PAIR: 5522 case ISD::BUILD_VECTOR: 5523 case ISD::CONCAT_VECTORS: 5524 for (SDValue Op : N->op_values()) 5525 getUnderlyingArgRegs(Regs, Op); 5526 return; 5527 default: 5528 return; 5529 } 5530 } 5531 5532 /// If the DbgValueInst is a dbg_value of a function argument, create the 5533 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5534 /// instruction selection, they will be inserted to the entry BB. 5535 /// We don't currently support this for variadic dbg_values, as they shouldn't 5536 /// appear for function arguments or in the prologue. 5537 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5538 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5539 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5540 const Argument *Arg = dyn_cast<Argument>(V); 5541 if (!Arg) 5542 return false; 5543 5544 MachineFunction &MF = DAG.getMachineFunction(); 5545 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5546 5547 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5548 // we've been asked to pursue. 5549 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5550 bool Indirect) { 5551 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5552 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5553 // pointing at the VReg, which will be patched up later. 5554 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5555 auto MIB = BuildMI(MF, DL, Inst); 5556 MIB.addReg(Reg); 5557 MIB.addImm(0); 5558 MIB.addMetadata(Variable); 5559 auto *NewDIExpr = FragExpr; 5560 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5561 // the DIExpression. 5562 if (Indirect) 5563 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5564 MIB.addMetadata(NewDIExpr); 5565 return MIB; 5566 } else { 5567 // Create a completely standard DBG_VALUE. 5568 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5569 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5570 } 5571 }; 5572 5573 if (Kind == FuncArgumentDbgValueKind::Value) { 5574 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5575 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5576 // the entry block. 5577 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5578 if (!IsInEntryBlock) 5579 return false; 5580 5581 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5582 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5583 // variable that also is a param. 5584 // 5585 // Although, if we are at the top of the entry block already, we can still 5586 // emit using ArgDbgValue. This might catch some situations when the 5587 // dbg.value refers to an argument that isn't used in the entry block, so 5588 // any CopyToReg node would be optimized out and the only way to express 5589 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5590 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5591 // we should only emit as ArgDbgValue if the Variable is an argument to the 5592 // current function, and the dbg.value intrinsic is found in the entry 5593 // block. 5594 bool VariableIsFunctionInputArg = Variable->isParameter() && 5595 !DL->getInlinedAt(); 5596 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5597 if (!IsInPrologue && !VariableIsFunctionInputArg) 5598 return false; 5599 5600 // Here we assume that a function argument on IR level only can be used to 5601 // describe one input parameter on source level. If we for example have 5602 // source code like this 5603 // 5604 // struct A { long x, y; }; 5605 // void foo(struct A a, long b) { 5606 // ... 5607 // b = a.x; 5608 // ... 5609 // } 5610 // 5611 // and IR like this 5612 // 5613 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5614 // entry: 5615 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5616 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5617 // call void @llvm.dbg.value(metadata i32 %b, "b", 5618 // ... 5619 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5620 // ... 5621 // 5622 // then the last dbg.value is describing a parameter "b" using a value that 5623 // is an argument. But since we already has used %a1 to describe a parameter 5624 // we should not handle that last dbg.value here (that would result in an 5625 // incorrect hoisting of the DBG_VALUE to the function entry). 5626 // Notice that we allow one dbg.value per IR level argument, to accommodate 5627 // for the situation with fragments above. 5628 if (VariableIsFunctionInputArg) { 5629 unsigned ArgNo = Arg->getArgNo(); 5630 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5631 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5632 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5633 return false; 5634 FuncInfo.DescribedArgs.set(ArgNo); 5635 } 5636 } 5637 5638 bool IsIndirect = false; 5639 Optional<MachineOperand> Op; 5640 // Some arguments' frame index is recorded during argument lowering. 5641 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5642 if (FI != std::numeric_limits<int>::max()) 5643 Op = MachineOperand::CreateFI(FI); 5644 5645 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5646 if (!Op && N.getNode()) { 5647 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5648 Register Reg; 5649 if (ArgRegsAndSizes.size() == 1) 5650 Reg = ArgRegsAndSizes.front().first; 5651 5652 if (Reg && Reg.isVirtual()) { 5653 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5654 Register PR = RegInfo.getLiveInPhysReg(Reg); 5655 if (PR) 5656 Reg = PR; 5657 } 5658 if (Reg) { 5659 Op = MachineOperand::CreateReg(Reg, false); 5660 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5661 } 5662 } 5663 5664 if (!Op && N.getNode()) { 5665 // Check if frame index is available. 5666 SDValue LCandidate = peekThroughBitcasts(N); 5667 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5668 if (FrameIndexSDNode *FINode = 5669 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5670 Op = MachineOperand::CreateFI(FINode->getIndex()); 5671 } 5672 5673 if (!Op) { 5674 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5675 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5676 SplitRegs) { 5677 unsigned Offset = 0; 5678 for (const auto &RegAndSize : SplitRegs) { 5679 // If the expression is already a fragment, the current register 5680 // offset+size might extend beyond the fragment. In this case, only 5681 // the register bits that are inside the fragment are relevant. 5682 int RegFragmentSizeInBits = RegAndSize.second; 5683 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5684 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5685 // The register is entirely outside the expression fragment, 5686 // so is irrelevant for debug info. 5687 if (Offset >= ExprFragmentSizeInBits) 5688 break; 5689 // The register is partially outside the expression fragment, only 5690 // the low bits within the fragment are relevant for debug info. 5691 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5692 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5693 } 5694 } 5695 5696 auto FragmentExpr = DIExpression::createFragmentExpression( 5697 Expr, Offset, RegFragmentSizeInBits); 5698 Offset += RegAndSize.second; 5699 // If a valid fragment expression cannot be created, the variable's 5700 // correct value cannot be determined and so it is set as Undef. 5701 if (!FragmentExpr) { 5702 SDDbgValue *SDV = DAG.getConstantDbgValue( 5703 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5704 DAG.AddDbgValue(SDV, false); 5705 continue; 5706 } 5707 MachineInstr *NewMI = 5708 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5709 Kind != FuncArgumentDbgValueKind::Value); 5710 FuncInfo.ArgDbgValues.push_back(NewMI); 5711 } 5712 }; 5713 5714 // Check if ValueMap has reg number. 5715 DenseMap<const Value *, Register>::const_iterator 5716 VMI = FuncInfo.ValueMap.find(V); 5717 if (VMI != FuncInfo.ValueMap.end()) { 5718 const auto &TLI = DAG.getTargetLoweringInfo(); 5719 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5720 V->getType(), None); 5721 if (RFV.occupiesMultipleRegs()) { 5722 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5723 return true; 5724 } 5725 5726 Op = MachineOperand::CreateReg(VMI->second, false); 5727 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5728 } else if (ArgRegsAndSizes.size() > 1) { 5729 // This was split due to the calling convention, and no virtual register 5730 // mapping exists for the value. 5731 splitMultiRegDbgValue(ArgRegsAndSizes); 5732 return true; 5733 } 5734 } 5735 5736 if (!Op) 5737 return false; 5738 5739 assert(Variable->isValidLocationForIntrinsic(DL) && 5740 "Expected inlined-at fields to agree"); 5741 MachineInstr *NewMI = nullptr; 5742 5743 if (Op->isReg()) 5744 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5745 else 5746 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5747 Variable, Expr); 5748 5749 // Otherwise, use ArgDbgValues. 5750 FuncInfo.ArgDbgValues.push_back(NewMI); 5751 return true; 5752 } 5753 5754 /// Return the appropriate SDDbgValue based on N. 5755 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5756 DILocalVariable *Variable, 5757 DIExpression *Expr, 5758 const DebugLoc &dl, 5759 unsigned DbgSDNodeOrder) { 5760 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5761 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5762 // stack slot locations. 5763 // 5764 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5765 // debug values here after optimization: 5766 // 5767 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5768 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5769 // 5770 // Both describe the direct values of their associated variables. 5771 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5772 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5773 } 5774 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5775 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5776 } 5777 5778 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5779 switch (Intrinsic) { 5780 case Intrinsic::smul_fix: 5781 return ISD::SMULFIX; 5782 case Intrinsic::umul_fix: 5783 return ISD::UMULFIX; 5784 case Intrinsic::smul_fix_sat: 5785 return ISD::SMULFIXSAT; 5786 case Intrinsic::umul_fix_sat: 5787 return ISD::UMULFIXSAT; 5788 case Intrinsic::sdiv_fix: 5789 return ISD::SDIVFIX; 5790 case Intrinsic::udiv_fix: 5791 return ISD::UDIVFIX; 5792 case Intrinsic::sdiv_fix_sat: 5793 return ISD::SDIVFIXSAT; 5794 case Intrinsic::udiv_fix_sat: 5795 return ISD::UDIVFIXSAT; 5796 default: 5797 llvm_unreachable("Unhandled fixed point intrinsic"); 5798 } 5799 } 5800 5801 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5802 const char *FunctionName) { 5803 assert(FunctionName && "FunctionName must not be nullptr"); 5804 SDValue Callee = DAG.getExternalSymbol( 5805 FunctionName, 5806 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5807 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5808 } 5809 5810 /// Given a @llvm.call.preallocated.setup, return the corresponding 5811 /// preallocated call. 5812 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5813 assert(cast<CallBase>(PreallocatedSetup) 5814 ->getCalledFunction() 5815 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5816 "expected call_preallocated_setup Value"); 5817 for (const auto *U : PreallocatedSetup->users()) { 5818 auto *UseCall = cast<CallBase>(U); 5819 const Function *Fn = UseCall->getCalledFunction(); 5820 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5821 return UseCall; 5822 } 5823 } 5824 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5825 } 5826 5827 /// Lower the call to the specified intrinsic function. 5828 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5829 unsigned Intrinsic) { 5830 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5831 SDLoc sdl = getCurSDLoc(); 5832 DebugLoc dl = getCurDebugLoc(); 5833 SDValue Res; 5834 5835 SDNodeFlags Flags; 5836 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5837 Flags.copyFMF(*FPOp); 5838 5839 switch (Intrinsic) { 5840 default: 5841 // By default, turn this into a target intrinsic node. 5842 visitTargetIntrinsic(I, Intrinsic); 5843 return; 5844 case Intrinsic::vscale: { 5845 match(&I, m_VScale(DAG.getDataLayout())); 5846 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5847 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5848 return; 5849 } 5850 case Intrinsic::vastart: visitVAStart(I); return; 5851 case Intrinsic::vaend: visitVAEnd(I); return; 5852 case Intrinsic::vacopy: visitVACopy(I); return; 5853 case Intrinsic::returnaddress: 5854 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5855 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5856 getValue(I.getArgOperand(0)))); 5857 return; 5858 case Intrinsic::addressofreturnaddress: 5859 setValue(&I, 5860 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5861 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5862 return; 5863 case Intrinsic::sponentry: 5864 setValue(&I, 5865 DAG.getNode(ISD::SPONENTRY, sdl, 5866 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5867 return; 5868 case Intrinsic::frameaddress: 5869 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5870 TLI.getFrameIndexTy(DAG.getDataLayout()), 5871 getValue(I.getArgOperand(0)))); 5872 return; 5873 case Intrinsic::read_volatile_register: 5874 case Intrinsic::read_register: { 5875 Value *Reg = I.getArgOperand(0); 5876 SDValue Chain = getRoot(); 5877 SDValue RegName = 5878 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5879 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5880 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5881 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5882 setValue(&I, Res); 5883 DAG.setRoot(Res.getValue(1)); 5884 return; 5885 } 5886 case Intrinsic::write_register: { 5887 Value *Reg = I.getArgOperand(0); 5888 Value *RegValue = I.getArgOperand(1); 5889 SDValue Chain = getRoot(); 5890 SDValue RegName = 5891 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5892 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5893 RegName, getValue(RegValue))); 5894 return; 5895 } 5896 case Intrinsic::memcpy: { 5897 const auto &MCI = cast<MemCpyInst>(I); 5898 SDValue Op1 = getValue(I.getArgOperand(0)); 5899 SDValue Op2 = getValue(I.getArgOperand(1)); 5900 SDValue Op3 = getValue(I.getArgOperand(2)); 5901 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5902 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5903 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5904 Align Alignment = std::min(DstAlign, SrcAlign); 5905 bool isVol = MCI.isVolatile(); 5906 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5907 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5908 // node. 5909 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5910 SDValue MC = DAG.getMemcpy( 5911 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5912 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 5913 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5914 updateDAGForMaybeTailCall(MC); 5915 return; 5916 } 5917 case Intrinsic::memcpy_inline: { 5918 const auto &MCI = cast<MemCpyInlineInst>(I); 5919 SDValue Dst = getValue(I.getArgOperand(0)); 5920 SDValue Src = getValue(I.getArgOperand(1)); 5921 SDValue Size = getValue(I.getArgOperand(2)); 5922 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5923 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5924 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5925 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5926 Align Alignment = std::min(DstAlign, SrcAlign); 5927 bool isVol = MCI.isVolatile(); 5928 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5929 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5930 // node. 5931 SDValue MC = DAG.getMemcpy( 5932 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5933 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5934 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5935 updateDAGForMaybeTailCall(MC); 5936 return; 5937 } 5938 case Intrinsic::memset: { 5939 const auto &MSI = cast<MemSetInst>(I); 5940 SDValue Op1 = getValue(I.getArgOperand(0)); 5941 SDValue Op2 = getValue(I.getArgOperand(1)); 5942 SDValue Op3 = getValue(I.getArgOperand(2)); 5943 // @llvm.memset defines 0 and 1 to both mean no alignment. 5944 Align Alignment = MSI.getDestAlign().valueOrOne(); 5945 bool isVol = MSI.isVolatile(); 5946 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5947 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5948 SDValue MS = DAG.getMemset( 5949 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 5950 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 5951 updateDAGForMaybeTailCall(MS); 5952 return; 5953 } 5954 case Intrinsic::memset_inline: { 5955 const auto &MSII = cast<MemSetInlineInst>(I); 5956 SDValue Dst = getValue(I.getArgOperand(0)); 5957 SDValue Value = getValue(I.getArgOperand(1)); 5958 SDValue Size = getValue(I.getArgOperand(2)); 5959 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 5960 // @llvm.memset defines 0 and 1 to both mean no alignment. 5961 Align DstAlign = MSII.getDestAlign().valueOrOne(); 5962 bool isVol = MSII.isVolatile(); 5963 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5964 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5965 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 5966 /* AlwaysInline */ true, isTC, 5967 MachinePointerInfo(I.getArgOperand(0)), 5968 I.getAAMetadata()); 5969 updateDAGForMaybeTailCall(MC); 5970 return; 5971 } 5972 case Intrinsic::memmove: { 5973 const auto &MMI = cast<MemMoveInst>(I); 5974 SDValue Op1 = getValue(I.getArgOperand(0)); 5975 SDValue Op2 = getValue(I.getArgOperand(1)); 5976 SDValue Op3 = getValue(I.getArgOperand(2)); 5977 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5978 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5979 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5980 Align Alignment = std::min(DstAlign, SrcAlign); 5981 bool isVol = MMI.isVolatile(); 5982 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5983 // FIXME: Support passing different dest/src alignments to the memmove DAG 5984 // node. 5985 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5986 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5987 isTC, MachinePointerInfo(I.getArgOperand(0)), 5988 MachinePointerInfo(I.getArgOperand(1)), 5989 I.getAAMetadata(), AA); 5990 updateDAGForMaybeTailCall(MM); 5991 return; 5992 } 5993 case Intrinsic::memcpy_element_unordered_atomic: { 5994 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5995 SDValue Dst = getValue(MI.getRawDest()); 5996 SDValue Src = getValue(MI.getRawSource()); 5997 SDValue Length = getValue(MI.getLength()); 5998 5999 Type *LengthTy = MI.getLength()->getType(); 6000 unsigned ElemSz = MI.getElementSizeInBytes(); 6001 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6002 SDValue MC = 6003 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6004 isTC, MachinePointerInfo(MI.getRawDest()), 6005 MachinePointerInfo(MI.getRawSource())); 6006 updateDAGForMaybeTailCall(MC); 6007 return; 6008 } 6009 case Intrinsic::memmove_element_unordered_atomic: { 6010 auto &MI = cast<AtomicMemMoveInst>(I); 6011 SDValue Dst = getValue(MI.getRawDest()); 6012 SDValue Src = getValue(MI.getRawSource()); 6013 SDValue Length = getValue(MI.getLength()); 6014 6015 Type *LengthTy = MI.getLength()->getType(); 6016 unsigned ElemSz = MI.getElementSizeInBytes(); 6017 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6018 SDValue MC = 6019 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6020 isTC, MachinePointerInfo(MI.getRawDest()), 6021 MachinePointerInfo(MI.getRawSource())); 6022 updateDAGForMaybeTailCall(MC); 6023 return; 6024 } 6025 case Intrinsic::memset_element_unordered_atomic: { 6026 auto &MI = cast<AtomicMemSetInst>(I); 6027 SDValue Dst = getValue(MI.getRawDest()); 6028 SDValue Val = getValue(MI.getValue()); 6029 SDValue Length = getValue(MI.getLength()); 6030 6031 Type *LengthTy = MI.getLength()->getType(); 6032 unsigned ElemSz = MI.getElementSizeInBytes(); 6033 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6034 SDValue MC = 6035 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6036 isTC, MachinePointerInfo(MI.getRawDest())); 6037 updateDAGForMaybeTailCall(MC); 6038 return; 6039 } 6040 case Intrinsic::call_preallocated_setup: { 6041 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6042 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6043 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6044 getRoot(), SrcValue); 6045 setValue(&I, Res); 6046 DAG.setRoot(Res); 6047 return; 6048 } 6049 case Intrinsic::call_preallocated_arg: { 6050 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6051 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6052 SDValue Ops[3]; 6053 Ops[0] = getRoot(); 6054 Ops[1] = SrcValue; 6055 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6056 MVT::i32); // arg index 6057 SDValue Res = DAG.getNode( 6058 ISD::PREALLOCATED_ARG, sdl, 6059 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6060 setValue(&I, Res); 6061 DAG.setRoot(Res.getValue(1)); 6062 return; 6063 } 6064 case Intrinsic::dbg_addr: 6065 case Intrinsic::dbg_declare: { 6066 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6067 // they are non-variadic. 6068 const auto &DI = cast<DbgVariableIntrinsic>(I); 6069 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6070 DILocalVariable *Variable = DI.getVariable(); 6071 DIExpression *Expression = DI.getExpression(); 6072 dropDanglingDebugInfo(Variable, Expression); 6073 assert(Variable && "Missing variable"); 6074 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6075 << "\n"); 6076 // Check if address has undef value. 6077 const Value *Address = DI.getVariableLocationOp(0); 6078 if (!Address || isa<UndefValue>(Address) || 6079 (Address->use_empty() && !isa<Argument>(Address))) { 6080 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6081 << " (bad/undef/unused-arg address)\n"); 6082 return; 6083 } 6084 6085 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6086 6087 // Check if this variable can be described by a frame index, typically 6088 // either as a static alloca or a byval parameter. 6089 int FI = std::numeric_limits<int>::max(); 6090 if (const auto *AI = 6091 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6092 if (AI->isStaticAlloca()) { 6093 auto I = FuncInfo.StaticAllocaMap.find(AI); 6094 if (I != FuncInfo.StaticAllocaMap.end()) 6095 FI = I->second; 6096 } 6097 } else if (const auto *Arg = dyn_cast<Argument>( 6098 Address->stripInBoundsConstantOffsets())) { 6099 FI = FuncInfo.getArgumentFrameIndex(Arg); 6100 } 6101 6102 // llvm.dbg.addr is control dependent and always generates indirect 6103 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6104 // the MachineFunction variable table. 6105 if (FI != std::numeric_limits<int>::max()) { 6106 if (Intrinsic == Intrinsic::dbg_addr) { 6107 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6108 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6109 dl, SDNodeOrder); 6110 DAG.AddDbgValue(SDV, isParameter); 6111 } else { 6112 LLVM_DEBUG(dbgs() << "Skipping " << DI 6113 << " (variable info stashed in MF side table)\n"); 6114 } 6115 return; 6116 } 6117 6118 SDValue &N = NodeMap[Address]; 6119 if (!N.getNode() && isa<Argument>(Address)) 6120 // Check unused arguments map. 6121 N = UnusedArgNodeMap[Address]; 6122 SDDbgValue *SDV; 6123 if (N.getNode()) { 6124 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6125 Address = BCI->getOperand(0); 6126 // Parameters are handled specially. 6127 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6128 if (isParameter && FINode) { 6129 // Byval parameter. We have a frame index at this point. 6130 SDV = 6131 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6132 /*IsIndirect*/ true, dl, SDNodeOrder); 6133 } else if (isa<Argument>(Address)) { 6134 // Address is an argument, so try to emit its dbg value using 6135 // virtual register info from the FuncInfo.ValueMap. 6136 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6137 FuncArgumentDbgValueKind::Declare, N); 6138 return; 6139 } else { 6140 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6141 true, dl, SDNodeOrder); 6142 } 6143 DAG.AddDbgValue(SDV, isParameter); 6144 } else { 6145 // If Address is an argument then try to emit its dbg value using 6146 // virtual register info from the FuncInfo.ValueMap. 6147 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6148 FuncArgumentDbgValueKind::Declare, N)) { 6149 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6150 << " (could not emit func-arg dbg_value)\n"); 6151 } 6152 } 6153 return; 6154 } 6155 case Intrinsic::dbg_label: { 6156 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6157 DILabel *Label = DI.getLabel(); 6158 assert(Label && "Missing label"); 6159 6160 SDDbgLabel *SDV; 6161 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6162 DAG.AddDbgLabel(SDV); 6163 return; 6164 } 6165 case Intrinsic::dbg_value: { 6166 const DbgValueInst &DI = cast<DbgValueInst>(I); 6167 assert(DI.getVariable() && "Missing variable"); 6168 6169 DILocalVariable *Variable = DI.getVariable(); 6170 DIExpression *Expression = DI.getExpression(); 6171 dropDanglingDebugInfo(Variable, Expression); 6172 SmallVector<Value *, 4> Values(DI.getValues()); 6173 if (Values.empty()) 6174 return; 6175 6176 if (llvm::is_contained(Values, nullptr)) 6177 return; 6178 6179 bool IsVariadic = DI.hasArgList(); 6180 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6181 SDNodeOrder, IsVariadic)) 6182 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6183 return; 6184 } 6185 6186 case Intrinsic::eh_typeid_for: { 6187 // Find the type id for the given typeinfo. 6188 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6189 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6190 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6191 setValue(&I, Res); 6192 return; 6193 } 6194 6195 case Intrinsic::eh_return_i32: 6196 case Intrinsic::eh_return_i64: 6197 DAG.getMachineFunction().setCallsEHReturn(true); 6198 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6199 MVT::Other, 6200 getControlRoot(), 6201 getValue(I.getArgOperand(0)), 6202 getValue(I.getArgOperand(1)))); 6203 return; 6204 case Intrinsic::eh_unwind_init: 6205 DAG.getMachineFunction().setCallsUnwindInit(true); 6206 return; 6207 case Intrinsic::eh_dwarf_cfa: 6208 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6209 TLI.getPointerTy(DAG.getDataLayout()), 6210 getValue(I.getArgOperand(0)))); 6211 return; 6212 case Intrinsic::eh_sjlj_callsite: { 6213 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6214 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6215 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6216 6217 MMI.setCurrentCallSite(CI->getZExtValue()); 6218 return; 6219 } 6220 case Intrinsic::eh_sjlj_functioncontext: { 6221 // Get and store the index of the function context. 6222 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6223 AllocaInst *FnCtx = 6224 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6225 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6226 MFI.setFunctionContextIndex(FI); 6227 return; 6228 } 6229 case Intrinsic::eh_sjlj_setjmp: { 6230 SDValue Ops[2]; 6231 Ops[0] = getRoot(); 6232 Ops[1] = getValue(I.getArgOperand(0)); 6233 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6234 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6235 setValue(&I, Op.getValue(0)); 6236 DAG.setRoot(Op.getValue(1)); 6237 return; 6238 } 6239 case Intrinsic::eh_sjlj_longjmp: 6240 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6241 getRoot(), getValue(I.getArgOperand(0)))); 6242 return; 6243 case Intrinsic::eh_sjlj_setup_dispatch: 6244 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6245 getRoot())); 6246 return; 6247 case Intrinsic::masked_gather: 6248 visitMaskedGather(I); 6249 return; 6250 case Intrinsic::masked_load: 6251 visitMaskedLoad(I); 6252 return; 6253 case Intrinsic::masked_scatter: 6254 visitMaskedScatter(I); 6255 return; 6256 case Intrinsic::masked_store: 6257 visitMaskedStore(I); 6258 return; 6259 case Intrinsic::masked_expandload: 6260 visitMaskedLoad(I, true /* IsExpanding */); 6261 return; 6262 case Intrinsic::masked_compressstore: 6263 visitMaskedStore(I, true /* IsCompressing */); 6264 return; 6265 case Intrinsic::powi: 6266 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6267 getValue(I.getArgOperand(1)), DAG)); 6268 return; 6269 case Intrinsic::log: 6270 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6271 return; 6272 case Intrinsic::log2: 6273 setValue(&I, 6274 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6275 return; 6276 case Intrinsic::log10: 6277 setValue(&I, 6278 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6279 return; 6280 case Intrinsic::exp: 6281 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6282 return; 6283 case Intrinsic::exp2: 6284 setValue(&I, 6285 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6286 return; 6287 case Intrinsic::pow: 6288 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6289 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6290 return; 6291 case Intrinsic::sqrt: 6292 case Intrinsic::fabs: 6293 case Intrinsic::sin: 6294 case Intrinsic::cos: 6295 case Intrinsic::floor: 6296 case Intrinsic::ceil: 6297 case Intrinsic::trunc: 6298 case Intrinsic::rint: 6299 case Intrinsic::nearbyint: 6300 case Intrinsic::round: 6301 case Intrinsic::roundeven: 6302 case Intrinsic::canonicalize: { 6303 unsigned Opcode; 6304 switch (Intrinsic) { 6305 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6306 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6307 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6308 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6309 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6310 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6311 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6312 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6313 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6314 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6315 case Intrinsic::round: Opcode = ISD::FROUND; break; 6316 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6317 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6318 } 6319 6320 setValue(&I, DAG.getNode(Opcode, sdl, 6321 getValue(I.getArgOperand(0)).getValueType(), 6322 getValue(I.getArgOperand(0)), Flags)); 6323 return; 6324 } 6325 case Intrinsic::lround: 6326 case Intrinsic::llround: 6327 case Intrinsic::lrint: 6328 case Intrinsic::llrint: { 6329 unsigned Opcode; 6330 switch (Intrinsic) { 6331 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6332 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6333 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6334 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6335 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6336 } 6337 6338 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6339 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6340 getValue(I.getArgOperand(0)))); 6341 return; 6342 } 6343 case Intrinsic::minnum: 6344 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6345 getValue(I.getArgOperand(0)).getValueType(), 6346 getValue(I.getArgOperand(0)), 6347 getValue(I.getArgOperand(1)), Flags)); 6348 return; 6349 case Intrinsic::maxnum: 6350 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6351 getValue(I.getArgOperand(0)).getValueType(), 6352 getValue(I.getArgOperand(0)), 6353 getValue(I.getArgOperand(1)), Flags)); 6354 return; 6355 case Intrinsic::minimum: 6356 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6357 getValue(I.getArgOperand(0)).getValueType(), 6358 getValue(I.getArgOperand(0)), 6359 getValue(I.getArgOperand(1)), Flags)); 6360 return; 6361 case Intrinsic::maximum: 6362 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6363 getValue(I.getArgOperand(0)).getValueType(), 6364 getValue(I.getArgOperand(0)), 6365 getValue(I.getArgOperand(1)), Flags)); 6366 return; 6367 case Intrinsic::copysign: 6368 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6369 getValue(I.getArgOperand(0)).getValueType(), 6370 getValue(I.getArgOperand(0)), 6371 getValue(I.getArgOperand(1)), Flags)); 6372 return; 6373 case Intrinsic::arithmetic_fence: { 6374 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6375 getValue(I.getArgOperand(0)).getValueType(), 6376 getValue(I.getArgOperand(0)), Flags)); 6377 return; 6378 } 6379 case Intrinsic::fma: 6380 setValue(&I, DAG.getNode( 6381 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6382 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6383 getValue(I.getArgOperand(2)), Flags)); 6384 return; 6385 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6386 case Intrinsic::INTRINSIC: 6387 #include "llvm/IR/ConstrainedOps.def" 6388 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6389 return; 6390 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6391 #include "llvm/IR/VPIntrinsics.def" 6392 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6393 return; 6394 case Intrinsic::fptrunc_round: { 6395 // Get the last argument, the metadata and convert it to an integer in the 6396 // call 6397 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6398 Optional<RoundingMode> RoundMode = 6399 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6400 6401 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6402 6403 // Propagate fast-math-flags from IR to node(s). 6404 SDNodeFlags Flags; 6405 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6406 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6407 6408 SDValue Result; 6409 Result = DAG.getNode( 6410 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6411 DAG.getTargetConstant((int)*RoundMode, sdl, 6412 TLI.getPointerTy(DAG.getDataLayout()))); 6413 setValue(&I, Result); 6414 6415 return; 6416 } 6417 case Intrinsic::fmuladd: { 6418 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6419 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6420 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6421 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6422 getValue(I.getArgOperand(0)).getValueType(), 6423 getValue(I.getArgOperand(0)), 6424 getValue(I.getArgOperand(1)), 6425 getValue(I.getArgOperand(2)), Flags)); 6426 } else { 6427 // TODO: Intrinsic calls should have fast-math-flags. 6428 SDValue Mul = DAG.getNode( 6429 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6430 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6431 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6432 getValue(I.getArgOperand(0)).getValueType(), 6433 Mul, getValue(I.getArgOperand(2)), Flags); 6434 setValue(&I, Add); 6435 } 6436 return; 6437 } 6438 case Intrinsic::convert_to_fp16: 6439 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6440 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6441 getValue(I.getArgOperand(0)), 6442 DAG.getTargetConstant(0, sdl, 6443 MVT::i32)))); 6444 return; 6445 case Intrinsic::convert_from_fp16: 6446 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6447 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6448 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6449 getValue(I.getArgOperand(0))))); 6450 return; 6451 case Intrinsic::fptosi_sat: { 6452 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6453 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6454 getValue(I.getArgOperand(0)), 6455 DAG.getValueType(VT.getScalarType()))); 6456 return; 6457 } 6458 case Intrinsic::fptoui_sat: { 6459 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6460 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6461 getValue(I.getArgOperand(0)), 6462 DAG.getValueType(VT.getScalarType()))); 6463 return; 6464 } 6465 case Intrinsic::set_rounding: 6466 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6467 {getRoot(), getValue(I.getArgOperand(0))}); 6468 setValue(&I, Res); 6469 DAG.setRoot(Res.getValue(0)); 6470 return; 6471 case Intrinsic::is_fpclass: { 6472 const DataLayout DLayout = DAG.getDataLayout(); 6473 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6474 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6475 unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6476 MachineFunction &MF = DAG.getMachineFunction(); 6477 const Function &F = MF.getFunction(); 6478 SDValue Op = getValue(I.getArgOperand(0)); 6479 SDNodeFlags Flags; 6480 Flags.setNoFPExcept( 6481 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6482 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6483 // expansion can use illegal types. Making expansion early allows 6484 // legalizing these types prior to selection. 6485 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6486 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6487 setValue(&I, Result); 6488 return; 6489 } 6490 6491 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6492 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6493 setValue(&I, V); 6494 return; 6495 } 6496 case Intrinsic::pcmarker: { 6497 SDValue Tmp = getValue(I.getArgOperand(0)); 6498 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6499 return; 6500 } 6501 case Intrinsic::readcyclecounter: { 6502 SDValue Op = getRoot(); 6503 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6504 DAG.getVTList(MVT::i64, MVT::Other), Op); 6505 setValue(&I, Res); 6506 DAG.setRoot(Res.getValue(1)); 6507 return; 6508 } 6509 case Intrinsic::bitreverse: 6510 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6511 getValue(I.getArgOperand(0)).getValueType(), 6512 getValue(I.getArgOperand(0)))); 6513 return; 6514 case Intrinsic::bswap: 6515 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6516 getValue(I.getArgOperand(0)).getValueType(), 6517 getValue(I.getArgOperand(0)))); 6518 return; 6519 case Intrinsic::cttz: { 6520 SDValue Arg = getValue(I.getArgOperand(0)); 6521 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6522 EVT Ty = Arg.getValueType(); 6523 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6524 sdl, Ty, Arg)); 6525 return; 6526 } 6527 case Intrinsic::ctlz: { 6528 SDValue Arg = getValue(I.getArgOperand(0)); 6529 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6530 EVT Ty = Arg.getValueType(); 6531 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6532 sdl, Ty, Arg)); 6533 return; 6534 } 6535 case Intrinsic::ctpop: { 6536 SDValue Arg = getValue(I.getArgOperand(0)); 6537 EVT Ty = Arg.getValueType(); 6538 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6539 return; 6540 } 6541 case Intrinsic::fshl: 6542 case Intrinsic::fshr: { 6543 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6544 SDValue X = getValue(I.getArgOperand(0)); 6545 SDValue Y = getValue(I.getArgOperand(1)); 6546 SDValue Z = getValue(I.getArgOperand(2)); 6547 EVT VT = X.getValueType(); 6548 6549 if (X == Y) { 6550 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6551 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6552 } else { 6553 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6554 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6555 } 6556 return; 6557 } 6558 case Intrinsic::sadd_sat: { 6559 SDValue Op1 = getValue(I.getArgOperand(0)); 6560 SDValue Op2 = getValue(I.getArgOperand(1)); 6561 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6562 return; 6563 } 6564 case Intrinsic::uadd_sat: { 6565 SDValue Op1 = getValue(I.getArgOperand(0)); 6566 SDValue Op2 = getValue(I.getArgOperand(1)); 6567 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6568 return; 6569 } 6570 case Intrinsic::ssub_sat: { 6571 SDValue Op1 = getValue(I.getArgOperand(0)); 6572 SDValue Op2 = getValue(I.getArgOperand(1)); 6573 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6574 return; 6575 } 6576 case Intrinsic::usub_sat: { 6577 SDValue Op1 = getValue(I.getArgOperand(0)); 6578 SDValue Op2 = getValue(I.getArgOperand(1)); 6579 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6580 return; 6581 } 6582 case Intrinsic::sshl_sat: { 6583 SDValue Op1 = getValue(I.getArgOperand(0)); 6584 SDValue Op2 = getValue(I.getArgOperand(1)); 6585 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6586 return; 6587 } 6588 case Intrinsic::ushl_sat: { 6589 SDValue Op1 = getValue(I.getArgOperand(0)); 6590 SDValue Op2 = getValue(I.getArgOperand(1)); 6591 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6592 return; 6593 } 6594 case Intrinsic::smul_fix: 6595 case Intrinsic::umul_fix: 6596 case Intrinsic::smul_fix_sat: 6597 case Intrinsic::umul_fix_sat: { 6598 SDValue Op1 = getValue(I.getArgOperand(0)); 6599 SDValue Op2 = getValue(I.getArgOperand(1)); 6600 SDValue Op3 = getValue(I.getArgOperand(2)); 6601 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6602 Op1.getValueType(), Op1, Op2, Op3)); 6603 return; 6604 } 6605 case Intrinsic::sdiv_fix: 6606 case Intrinsic::udiv_fix: 6607 case Intrinsic::sdiv_fix_sat: 6608 case Intrinsic::udiv_fix_sat: { 6609 SDValue Op1 = getValue(I.getArgOperand(0)); 6610 SDValue Op2 = getValue(I.getArgOperand(1)); 6611 SDValue Op3 = getValue(I.getArgOperand(2)); 6612 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6613 Op1, Op2, Op3, DAG, TLI)); 6614 return; 6615 } 6616 case Intrinsic::smax: { 6617 SDValue Op1 = getValue(I.getArgOperand(0)); 6618 SDValue Op2 = getValue(I.getArgOperand(1)); 6619 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6620 return; 6621 } 6622 case Intrinsic::smin: { 6623 SDValue Op1 = getValue(I.getArgOperand(0)); 6624 SDValue Op2 = getValue(I.getArgOperand(1)); 6625 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6626 return; 6627 } 6628 case Intrinsic::umax: { 6629 SDValue Op1 = getValue(I.getArgOperand(0)); 6630 SDValue Op2 = getValue(I.getArgOperand(1)); 6631 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6632 return; 6633 } 6634 case Intrinsic::umin: { 6635 SDValue Op1 = getValue(I.getArgOperand(0)); 6636 SDValue Op2 = getValue(I.getArgOperand(1)); 6637 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6638 return; 6639 } 6640 case Intrinsic::abs: { 6641 // TODO: Preserve "int min is poison" arg in SDAG? 6642 SDValue Op1 = getValue(I.getArgOperand(0)); 6643 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6644 return; 6645 } 6646 case Intrinsic::stacksave: { 6647 SDValue Op = getRoot(); 6648 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6649 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6650 setValue(&I, Res); 6651 DAG.setRoot(Res.getValue(1)); 6652 return; 6653 } 6654 case Intrinsic::stackrestore: 6655 Res = getValue(I.getArgOperand(0)); 6656 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6657 return; 6658 case Intrinsic::get_dynamic_area_offset: { 6659 SDValue Op = getRoot(); 6660 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6661 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6662 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6663 // target. 6664 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6665 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6666 " intrinsic!"); 6667 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6668 Op); 6669 DAG.setRoot(Op); 6670 setValue(&I, Res); 6671 return; 6672 } 6673 case Intrinsic::stackguard: { 6674 MachineFunction &MF = DAG.getMachineFunction(); 6675 const Module &M = *MF.getFunction().getParent(); 6676 SDValue Chain = getRoot(); 6677 if (TLI.useLoadStackGuardNode()) { 6678 Res = getLoadStackGuard(DAG, sdl, Chain); 6679 } else { 6680 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6681 const Value *Global = TLI.getSDagStackGuard(M); 6682 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6683 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6684 MachinePointerInfo(Global, 0), Align, 6685 MachineMemOperand::MOVolatile); 6686 } 6687 if (TLI.useStackGuardXorFP()) 6688 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6689 DAG.setRoot(Chain); 6690 setValue(&I, Res); 6691 return; 6692 } 6693 case Intrinsic::stackprotector: { 6694 // Emit code into the DAG to store the stack guard onto the stack. 6695 MachineFunction &MF = DAG.getMachineFunction(); 6696 MachineFrameInfo &MFI = MF.getFrameInfo(); 6697 SDValue Src, Chain = getRoot(); 6698 6699 if (TLI.useLoadStackGuardNode()) 6700 Src = getLoadStackGuard(DAG, sdl, Chain); 6701 else 6702 Src = getValue(I.getArgOperand(0)); // The guard's value. 6703 6704 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6705 6706 int FI = FuncInfo.StaticAllocaMap[Slot]; 6707 MFI.setStackProtectorIndex(FI); 6708 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6709 6710 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6711 6712 // Store the stack protector onto the stack. 6713 Res = DAG.getStore( 6714 Chain, sdl, Src, FIN, 6715 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6716 MaybeAlign(), MachineMemOperand::MOVolatile); 6717 setValue(&I, Res); 6718 DAG.setRoot(Res); 6719 return; 6720 } 6721 case Intrinsic::objectsize: 6722 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6723 6724 case Intrinsic::is_constant: 6725 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6726 6727 case Intrinsic::annotation: 6728 case Intrinsic::ptr_annotation: 6729 case Intrinsic::launder_invariant_group: 6730 case Intrinsic::strip_invariant_group: 6731 // Drop the intrinsic, but forward the value 6732 setValue(&I, getValue(I.getOperand(0))); 6733 return; 6734 6735 case Intrinsic::assume: 6736 case Intrinsic::experimental_noalias_scope_decl: 6737 case Intrinsic::var_annotation: 6738 case Intrinsic::sideeffect: 6739 // Discard annotate attributes, noalias scope declarations, assumptions, and 6740 // artificial side-effects. 6741 return; 6742 6743 case Intrinsic::codeview_annotation: { 6744 // Emit a label associated with this metadata. 6745 MachineFunction &MF = DAG.getMachineFunction(); 6746 MCSymbol *Label = 6747 MF.getMMI().getContext().createTempSymbol("annotation", true); 6748 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6749 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6750 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6751 DAG.setRoot(Res); 6752 return; 6753 } 6754 6755 case Intrinsic::init_trampoline: { 6756 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6757 6758 SDValue Ops[6]; 6759 Ops[0] = getRoot(); 6760 Ops[1] = getValue(I.getArgOperand(0)); 6761 Ops[2] = getValue(I.getArgOperand(1)); 6762 Ops[3] = getValue(I.getArgOperand(2)); 6763 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6764 Ops[5] = DAG.getSrcValue(F); 6765 6766 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6767 6768 DAG.setRoot(Res); 6769 return; 6770 } 6771 case Intrinsic::adjust_trampoline: 6772 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6773 TLI.getPointerTy(DAG.getDataLayout()), 6774 getValue(I.getArgOperand(0)))); 6775 return; 6776 case Intrinsic::gcroot: { 6777 assert(DAG.getMachineFunction().getFunction().hasGC() && 6778 "only valid in functions with gc specified, enforced by Verifier"); 6779 assert(GFI && "implied by previous"); 6780 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6781 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6782 6783 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6784 GFI->addStackRoot(FI->getIndex(), TypeMap); 6785 return; 6786 } 6787 case Intrinsic::gcread: 6788 case Intrinsic::gcwrite: 6789 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6790 case Intrinsic::flt_rounds: 6791 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6792 setValue(&I, Res); 6793 DAG.setRoot(Res.getValue(1)); 6794 return; 6795 6796 case Intrinsic::expect: 6797 // Just replace __builtin_expect(exp, c) with EXP. 6798 setValue(&I, getValue(I.getArgOperand(0))); 6799 return; 6800 6801 case Intrinsic::ubsantrap: 6802 case Intrinsic::debugtrap: 6803 case Intrinsic::trap: { 6804 StringRef TrapFuncName = 6805 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6806 if (TrapFuncName.empty()) { 6807 switch (Intrinsic) { 6808 case Intrinsic::trap: 6809 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6810 break; 6811 case Intrinsic::debugtrap: 6812 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6813 break; 6814 case Intrinsic::ubsantrap: 6815 DAG.setRoot(DAG.getNode( 6816 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6817 DAG.getTargetConstant( 6818 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6819 MVT::i32))); 6820 break; 6821 default: llvm_unreachable("unknown trap intrinsic"); 6822 } 6823 return; 6824 } 6825 TargetLowering::ArgListTy Args; 6826 if (Intrinsic == Intrinsic::ubsantrap) { 6827 Args.push_back(TargetLoweringBase::ArgListEntry()); 6828 Args[0].Val = I.getArgOperand(0); 6829 Args[0].Node = getValue(Args[0].Val); 6830 Args[0].Ty = Args[0].Val->getType(); 6831 } 6832 6833 TargetLowering::CallLoweringInfo CLI(DAG); 6834 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6835 CallingConv::C, I.getType(), 6836 DAG.getExternalSymbol(TrapFuncName.data(), 6837 TLI.getPointerTy(DAG.getDataLayout())), 6838 std::move(Args)); 6839 6840 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6841 DAG.setRoot(Result.second); 6842 return; 6843 } 6844 6845 case Intrinsic::uadd_with_overflow: 6846 case Intrinsic::sadd_with_overflow: 6847 case Intrinsic::usub_with_overflow: 6848 case Intrinsic::ssub_with_overflow: 6849 case Intrinsic::umul_with_overflow: 6850 case Intrinsic::smul_with_overflow: { 6851 ISD::NodeType Op; 6852 switch (Intrinsic) { 6853 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6854 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6855 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6856 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6857 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6858 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6859 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6860 } 6861 SDValue Op1 = getValue(I.getArgOperand(0)); 6862 SDValue Op2 = getValue(I.getArgOperand(1)); 6863 6864 EVT ResultVT = Op1.getValueType(); 6865 EVT OverflowVT = MVT::i1; 6866 if (ResultVT.isVector()) 6867 OverflowVT = EVT::getVectorVT( 6868 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6869 6870 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6871 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6872 return; 6873 } 6874 case Intrinsic::prefetch: { 6875 SDValue Ops[5]; 6876 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6877 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6878 Ops[0] = DAG.getRoot(); 6879 Ops[1] = getValue(I.getArgOperand(0)); 6880 Ops[2] = getValue(I.getArgOperand(1)); 6881 Ops[3] = getValue(I.getArgOperand(2)); 6882 Ops[4] = getValue(I.getArgOperand(3)); 6883 SDValue Result = DAG.getMemIntrinsicNode( 6884 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6885 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6886 /* align */ None, Flags); 6887 6888 // Chain the prefetch in parallell with any pending loads, to stay out of 6889 // the way of later optimizations. 6890 PendingLoads.push_back(Result); 6891 Result = getRoot(); 6892 DAG.setRoot(Result); 6893 return; 6894 } 6895 case Intrinsic::lifetime_start: 6896 case Intrinsic::lifetime_end: { 6897 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6898 // Stack coloring is not enabled in O0, discard region information. 6899 if (TM.getOptLevel() == CodeGenOpt::None) 6900 return; 6901 6902 const int64_t ObjectSize = 6903 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6904 Value *const ObjectPtr = I.getArgOperand(1); 6905 SmallVector<const Value *, 4> Allocas; 6906 getUnderlyingObjects(ObjectPtr, Allocas); 6907 6908 for (const Value *Alloca : Allocas) { 6909 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6910 6911 // Could not find an Alloca. 6912 if (!LifetimeObject) 6913 continue; 6914 6915 // First check that the Alloca is static, otherwise it won't have a 6916 // valid frame index. 6917 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6918 if (SI == FuncInfo.StaticAllocaMap.end()) 6919 return; 6920 6921 const int FrameIndex = SI->second; 6922 int64_t Offset; 6923 if (GetPointerBaseWithConstantOffset( 6924 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6925 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6926 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6927 Offset); 6928 DAG.setRoot(Res); 6929 } 6930 return; 6931 } 6932 case Intrinsic::pseudoprobe: { 6933 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6934 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6935 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6936 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6937 DAG.setRoot(Res); 6938 return; 6939 } 6940 case Intrinsic::invariant_start: 6941 // Discard region information. 6942 setValue(&I, 6943 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6944 return; 6945 case Intrinsic::invariant_end: 6946 // Discard region information. 6947 return; 6948 case Intrinsic::clear_cache: 6949 /// FunctionName may be null. 6950 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6951 lowerCallToExternalSymbol(I, FunctionName); 6952 return; 6953 case Intrinsic::donothing: 6954 case Intrinsic::seh_try_begin: 6955 case Intrinsic::seh_scope_begin: 6956 case Intrinsic::seh_try_end: 6957 case Intrinsic::seh_scope_end: 6958 // ignore 6959 return; 6960 case Intrinsic::experimental_stackmap: 6961 visitStackmap(I); 6962 return; 6963 case Intrinsic::experimental_patchpoint_void: 6964 case Intrinsic::experimental_patchpoint_i64: 6965 visitPatchpoint(I); 6966 return; 6967 case Intrinsic::experimental_gc_statepoint: 6968 LowerStatepoint(cast<GCStatepointInst>(I)); 6969 return; 6970 case Intrinsic::experimental_gc_result: 6971 visitGCResult(cast<GCResultInst>(I)); 6972 return; 6973 case Intrinsic::experimental_gc_relocate: 6974 visitGCRelocate(cast<GCRelocateInst>(I)); 6975 return; 6976 case Intrinsic::instrprof_cover: 6977 llvm_unreachable("instrprof failed to lower a cover"); 6978 case Intrinsic::instrprof_increment: 6979 llvm_unreachable("instrprof failed to lower an increment"); 6980 case Intrinsic::instrprof_value_profile: 6981 llvm_unreachable("instrprof failed to lower a value profiling call"); 6982 case Intrinsic::localescape: { 6983 MachineFunction &MF = DAG.getMachineFunction(); 6984 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6985 6986 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6987 // is the same on all targets. 6988 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 6989 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6990 if (isa<ConstantPointerNull>(Arg)) 6991 continue; // Skip null pointers. They represent a hole in index space. 6992 AllocaInst *Slot = cast<AllocaInst>(Arg); 6993 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6994 "can only escape static allocas"); 6995 int FI = FuncInfo.StaticAllocaMap[Slot]; 6996 MCSymbol *FrameAllocSym = 6997 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6998 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6999 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7000 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7001 .addSym(FrameAllocSym) 7002 .addFrameIndex(FI); 7003 } 7004 7005 return; 7006 } 7007 7008 case Intrinsic::localrecover: { 7009 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7010 MachineFunction &MF = DAG.getMachineFunction(); 7011 7012 // Get the symbol that defines the frame offset. 7013 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7014 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7015 unsigned IdxVal = 7016 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7017 MCSymbol *FrameAllocSym = 7018 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7019 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7020 7021 Value *FP = I.getArgOperand(1); 7022 SDValue FPVal = getValue(FP); 7023 EVT PtrVT = FPVal.getValueType(); 7024 7025 // Create a MCSymbol for the label to avoid any target lowering 7026 // that would make this PC relative. 7027 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7028 SDValue OffsetVal = 7029 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7030 7031 // Add the offset to the FP. 7032 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7033 setValue(&I, Add); 7034 7035 return; 7036 } 7037 7038 case Intrinsic::eh_exceptionpointer: 7039 case Intrinsic::eh_exceptioncode: { 7040 // Get the exception pointer vreg, copy from it, and resize it to fit. 7041 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7042 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7043 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7044 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7045 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7046 if (Intrinsic == Intrinsic::eh_exceptioncode) 7047 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7048 setValue(&I, N); 7049 return; 7050 } 7051 case Intrinsic::xray_customevent: { 7052 // Here we want to make sure that the intrinsic behaves as if it has a 7053 // specific calling convention, and only for x86_64. 7054 // FIXME: Support other platforms later. 7055 const auto &Triple = DAG.getTarget().getTargetTriple(); 7056 if (Triple.getArch() != Triple::x86_64) 7057 return; 7058 7059 SmallVector<SDValue, 8> Ops; 7060 7061 // We want to say that we always want the arguments in registers. 7062 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7063 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7064 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7065 SDValue Chain = getRoot(); 7066 Ops.push_back(LogEntryVal); 7067 Ops.push_back(StrSizeVal); 7068 Ops.push_back(Chain); 7069 7070 // We need to enforce the calling convention for the callsite, so that 7071 // argument ordering is enforced correctly, and that register allocation can 7072 // see that some registers may be assumed clobbered and have to preserve 7073 // them across calls to the intrinsic. 7074 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7075 sdl, NodeTys, Ops); 7076 SDValue patchableNode = SDValue(MN, 0); 7077 DAG.setRoot(patchableNode); 7078 setValue(&I, patchableNode); 7079 return; 7080 } 7081 case Intrinsic::xray_typedevent: { 7082 // Here we want to make sure that the intrinsic behaves as if it has a 7083 // specific calling convention, and only for x86_64. 7084 // FIXME: Support other platforms later. 7085 const auto &Triple = DAG.getTarget().getTargetTriple(); 7086 if (Triple.getArch() != Triple::x86_64) 7087 return; 7088 7089 SmallVector<SDValue, 8> Ops; 7090 7091 // We want to say that we always want the arguments in registers. 7092 // It's unclear to me how manipulating the selection DAG here forces callers 7093 // to provide arguments in registers instead of on the stack. 7094 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7095 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7096 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7097 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7098 SDValue Chain = getRoot(); 7099 Ops.push_back(LogTypeId); 7100 Ops.push_back(LogEntryVal); 7101 Ops.push_back(StrSizeVal); 7102 Ops.push_back(Chain); 7103 7104 // We need to enforce the calling convention for the callsite, so that 7105 // argument ordering is enforced correctly, and that register allocation can 7106 // see that some registers may be assumed clobbered and have to preserve 7107 // them across calls to the intrinsic. 7108 MachineSDNode *MN = DAG.getMachineNode( 7109 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7110 SDValue patchableNode = SDValue(MN, 0); 7111 DAG.setRoot(patchableNode); 7112 setValue(&I, patchableNode); 7113 return; 7114 } 7115 case Intrinsic::experimental_deoptimize: 7116 LowerDeoptimizeCall(&I); 7117 return; 7118 case Intrinsic::experimental_stepvector: 7119 visitStepVector(I); 7120 return; 7121 case Intrinsic::vector_reduce_fadd: 7122 case Intrinsic::vector_reduce_fmul: 7123 case Intrinsic::vector_reduce_add: 7124 case Intrinsic::vector_reduce_mul: 7125 case Intrinsic::vector_reduce_and: 7126 case Intrinsic::vector_reduce_or: 7127 case Intrinsic::vector_reduce_xor: 7128 case Intrinsic::vector_reduce_smax: 7129 case Intrinsic::vector_reduce_smin: 7130 case Intrinsic::vector_reduce_umax: 7131 case Intrinsic::vector_reduce_umin: 7132 case Intrinsic::vector_reduce_fmax: 7133 case Intrinsic::vector_reduce_fmin: 7134 visitVectorReduce(I, Intrinsic); 7135 return; 7136 7137 case Intrinsic::icall_branch_funnel: { 7138 SmallVector<SDValue, 16> Ops; 7139 Ops.push_back(getValue(I.getArgOperand(0))); 7140 7141 int64_t Offset; 7142 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7143 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7144 if (!Base) 7145 report_fatal_error( 7146 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7147 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7148 7149 struct BranchFunnelTarget { 7150 int64_t Offset; 7151 SDValue Target; 7152 }; 7153 SmallVector<BranchFunnelTarget, 8> Targets; 7154 7155 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7156 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7157 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7158 if (ElemBase != Base) 7159 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7160 "to the same GlobalValue"); 7161 7162 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7163 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7164 if (!GA) 7165 report_fatal_error( 7166 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7167 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7168 GA->getGlobal(), sdl, Val.getValueType(), 7169 GA->getOffset())}); 7170 } 7171 llvm::sort(Targets, 7172 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7173 return T1.Offset < T2.Offset; 7174 }); 7175 7176 for (auto &T : Targets) { 7177 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7178 Ops.push_back(T.Target); 7179 } 7180 7181 Ops.push_back(DAG.getRoot()); // Chain 7182 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7183 MVT::Other, Ops), 7184 0); 7185 DAG.setRoot(N); 7186 setValue(&I, N); 7187 HasTailCall = true; 7188 return; 7189 } 7190 7191 case Intrinsic::wasm_landingpad_index: 7192 // Information this intrinsic contained has been transferred to 7193 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7194 // delete it now. 7195 return; 7196 7197 case Intrinsic::aarch64_settag: 7198 case Intrinsic::aarch64_settag_zero: { 7199 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7200 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7201 SDValue Val = TSI.EmitTargetCodeForSetTag( 7202 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7203 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7204 ZeroMemory); 7205 DAG.setRoot(Val); 7206 setValue(&I, Val); 7207 return; 7208 } 7209 case Intrinsic::ptrmask: { 7210 SDValue Ptr = getValue(I.getOperand(0)); 7211 SDValue Const = getValue(I.getOperand(1)); 7212 7213 EVT PtrVT = Ptr.getValueType(); 7214 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7215 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7216 return; 7217 } 7218 case Intrinsic::threadlocal_address: { 7219 setValue(&I, getValue(I.getOperand(0))); 7220 return; 7221 } 7222 case Intrinsic::get_active_lane_mask: { 7223 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7224 SDValue Index = getValue(I.getOperand(0)); 7225 EVT ElementVT = Index.getValueType(); 7226 7227 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7228 visitTargetIntrinsic(I, Intrinsic); 7229 return; 7230 } 7231 7232 SDValue TripCount = getValue(I.getOperand(1)); 7233 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7234 7235 SDValue VectorIndex, VectorTripCount; 7236 if (VecTy.isScalableVector()) { 7237 VectorIndex = DAG.getSplatVector(VecTy, sdl, Index); 7238 VectorTripCount = DAG.getSplatVector(VecTy, sdl, TripCount); 7239 } else { 7240 VectorIndex = DAG.getSplatBuildVector(VecTy, sdl, Index); 7241 VectorTripCount = DAG.getSplatBuildVector(VecTy, sdl, TripCount); 7242 } 7243 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7244 SDValue VectorInduction = DAG.getNode( 7245 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7246 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7247 VectorTripCount, ISD::CondCode::SETULT); 7248 setValue(&I, SetCC); 7249 return; 7250 } 7251 case Intrinsic::vector_insert: { 7252 SDValue Vec = getValue(I.getOperand(0)); 7253 SDValue SubVec = getValue(I.getOperand(1)); 7254 SDValue Index = getValue(I.getOperand(2)); 7255 7256 // The intrinsic's index type is i64, but the SDNode requires an index type 7257 // suitable for the target. Convert the index as required. 7258 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7259 if (Index.getValueType() != VectorIdxTy) 7260 Index = DAG.getVectorIdxConstant( 7261 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7262 7263 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7264 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7265 Index)); 7266 return; 7267 } 7268 case Intrinsic::vector_extract: { 7269 SDValue Vec = getValue(I.getOperand(0)); 7270 SDValue Index = getValue(I.getOperand(1)); 7271 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7272 7273 // The intrinsic's index type is i64, but the SDNode requires an index type 7274 // suitable for the target. Convert the index as required. 7275 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7276 if (Index.getValueType() != VectorIdxTy) 7277 Index = DAG.getVectorIdxConstant( 7278 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7279 7280 setValue(&I, 7281 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7282 return; 7283 } 7284 case Intrinsic::experimental_vector_reverse: 7285 visitVectorReverse(I); 7286 return; 7287 case Intrinsic::experimental_vector_splice: 7288 visitVectorSplice(I); 7289 return; 7290 } 7291 } 7292 7293 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7294 const ConstrainedFPIntrinsic &FPI) { 7295 SDLoc sdl = getCurSDLoc(); 7296 7297 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7298 SmallVector<EVT, 4> ValueVTs; 7299 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7300 ValueVTs.push_back(MVT::Other); // Out chain 7301 7302 // We do not need to serialize constrained FP intrinsics against 7303 // each other or against (nonvolatile) loads, so they can be 7304 // chained like loads. 7305 SDValue Chain = DAG.getRoot(); 7306 SmallVector<SDValue, 4> Opers; 7307 Opers.push_back(Chain); 7308 if (FPI.isUnaryOp()) { 7309 Opers.push_back(getValue(FPI.getArgOperand(0))); 7310 } else if (FPI.isTernaryOp()) { 7311 Opers.push_back(getValue(FPI.getArgOperand(0))); 7312 Opers.push_back(getValue(FPI.getArgOperand(1))); 7313 Opers.push_back(getValue(FPI.getArgOperand(2))); 7314 } else { 7315 Opers.push_back(getValue(FPI.getArgOperand(0))); 7316 Opers.push_back(getValue(FPI.getArgOperand(1))); 7317 } 7318 7319 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7320 assert(Result.getNode()->getNumValues() == 2); 7321 7322 // Push node to the appropriate list so that future instructions can be 7323 // chained up correctly. 7324 SDValue OutChain = Result.getValue(1); 7325 switch (EB) { 7326 case fp::ExceptionBehavior::ebIgnore: 7327 // The only reason why ebIgnore nodes still need to be chained is that 7328 // they might depend on the current rounding mode, and therefore must 7329 // not be moved across instruction that may change that mode. 7330 [[fallthrough]]; 7331 case fp::ExceptionBehavior::ebMayTrap: 7332 // These must not be moved across calls or instructions that may change 7333 // floating-point exception masks. 7334 PendingConstrainedFP.push_back(OutChain); 7335 break; 7336 case fp::ExceptionBehavior::ebStrict: 7337 // These must not be moved across calls or instructions that may change 7338 // floating-point exception masks or read floating-point exception flags. 7339 // In addition, they cannot be optimized out even if unused. 7340 PendingConstrainedFPStrict.push_back(OutChain); 7341 break; 7342 } 7343 }; 7344 7345 SDVTList VTs = DAG.getVTList(ValueVTs); 7346 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7347 7348 SDNodeFlags Flags; 7349 if (EB == fp::ExceptionBehavior::ebIgnore) 7350 Flags.setNoFPExcept(true); 7351 7352 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7353 Flags.copyFMF(*FPOp); 7354 7355 unsigned Opcode; 7356 switch (FPI.getIntrinsicID()) { 7357 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7358 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7359 case Intrinsic::INTRINSIC: \ 7360 Opcode = ISD::STRICT_##DAGN; \ 7361 break; 7362 #include "llvm/IR/ConstrainedOps.def" 7363 case Intrinsic::experimental_constrained_fmuladd: { 7364 Opcode = ISD::STRICT_FMA; 7365 // Break fmuladd into fmul and fadd. 7366 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7367 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7368 ValueVTs[0])) { 7369 Opers.pop_back(); 7370 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7371 pushOutChain(Mul, EB); 7372 Opcode = ISD::STRICT_FADD; 7373 Opers.clear(); 7374 Opers.push_back(Mul.getValue(1)); 7375 Opers.push_back(Mul.getValue(0)); 7376 Opers.push_back(getValue(FPI.getArgOperand(2))); 7377 } 7378 break; 7379 } 7380 } 7381 7382 // A few strict DAG nodes carry additional operands that are not 7383 // set up by the default code above. 7384 switch (Opcode) { 7385 default: break; 7386 case ISD::STRICT_FP_ROUND: 7387 Opers.push_back( 7388 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7389 break; 7390 case ISD::STRICT_FSETCC: 7391 case ISD::STRICT_FSETCCS: { 7392 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7393 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7394 if (TM.Options.NoNaNsFPMath) 7395 Condition = getFCmpCodeWithoutNaN(Condition); 7396 Opers.push_back(DAG.getCondCode(Condition)); 7397 break; 7398 } 7399 } 7400 7401 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7402 pushOutChain(Result, EB); 7403 7404 SDValue FPResult = Result.getValue(0); 7405 setValue(&FPI, FPResult); 7406 } 7407 7408 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7409 Optional<unsigned> ResOPC; 7410 switch (VPIntrin.getIntrinsicID()) { 7411 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7412 case Intrinsic::VPID: \ 7413 ResOPC = ISD::VPSD; \ 7414 break; 7415 #include "llvm/IR/VPIntrinsics.def" 7416 } 7417 7418 if (!ResOPC) 7419 llvm_unreachable( 7420 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7421 7422 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7423 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7424 if (VPIntrin.getFastMathFlags().allowReassoc()) 7425 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7426 : ISD::VP_REDUCE_FMUL; 7427 } 7428 7429 return *ResOPC; 7430 } 7431 7432 void SelectionDAGBuilder::visitVPLoadGather(const VPIntrinsic &VPIntrin, EVT VT, 7433 SmallVector<SDValue, 7> &OpValues, 7434 bool IsGather) { 7435 SDLoc DL = getCurSDLoc(); 7436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7437 Value *PtrOperand = VPIntrin.getArgOperand(0); 7438 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7439 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7440 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7441 SDValue LD; 7442 bool AddToChain = true; 7443 if (!IsGather) { 7444 // Do not serialize variable-length loads of constant memory with 7445 // anything. 7446 if (!Alignment) 7447 Alignment = DAG.getEVTAlign(VT); 7448 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7449 AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7450 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7451 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7452 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7453 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7454 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7455 MMO, false /*IsExpanding */); 7456 } else { 7457 if (!Alignment) 7458 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7459 unsigned AS = 7460 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7461 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7462 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7463 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7464 SDValue Base, Index, Scale; 7465 ISD::MemIndexType IndexType; 7466 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7467 this, VPIntrin.getParent(), 7468 VT.getScalarStoreSize()); 7469 if (!UniformBase) { 7470 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7471 Index = getValue(PtrOperand); 7472 IndexType = ISD::SIGNED_SCALED; 7473 Scale = 7474 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7475 } 7476 EVT IdxVT = Index.getValueType(); 7477 EVT EltTy = IdxVT.getVectorElementType(); 7478 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7479 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7480 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7481 } 7482 LD = DAG.getGatherVP( 7483 DAG.getVTList(VT, MVT::Other), VT, DL, 7484 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7485 IndexType); 7486 } 7487 if (AddToChain) 7488 PendingLoads.push_back(LD.getValue(1)); 7489 setValue(&VPIntrin, LD); 7490 } 7491 7492 void SelectionDAGBuilder::visitVPStoreScatter(const VPIntrinsic &VPIntrin, 7493 SmallVector<SDValue, 7> &OpValues, 7494 bool IsScatter) { 7495 SDLoc DL = getCurSDLoc(); 7496 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7497 Value *PtrOperand = VPIntrin.getArgOperand(1); 7498 EVT VT = OpValues[0].getValueType(); 7499 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7500 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7501 SDValue ST; 7502 if (!IsScatter) { 7503 if (!Alignment) 7504 Alignment = DAG.getEVTAlign(VT); 7505 SDValue Ptr = OpValues[1]; 7506 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7507 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7508 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7509 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7510 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7511 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7512 /* IsTruncating */ false, /*IsCompressing*/ false); 7513 } else { 7514 if (!Alignment) 7515 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7516 unsigned AS = 7517 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7518 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7519 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7520 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7521 SDValue Base, Index, Scale; 7522 ISD::MemIndexType IndexType; 7523 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7524 this, VPIntrin.getParent(), 7525 VT.getScalarStoreSize()); 7526 if (!UniformBase) { 7527 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7528 Index = getValue(PtrOperand); 7529 IndexType = ISD::SIGNED_SCALED; 7530 Scale = 7531 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7532 } 7533 EVT IdxVT = Index.getValueType(); 7534 EVT EltTy = IdxVT.getVectorElementType(); 7535 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7536 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7537 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7538 } 7539 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7540 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7541 OpValues[2], OpValues[3]}, 7542 MMO, IndexType); 7543 } 7544 DAG.setRoot(ST); 7545 setValue(&VPIntrin, ST); 7546 } 7547 7548 void SelectionDAGBuilder::visitVPStridedLoad( 7549 const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) { 7550 SDLoc DL = getCurSDLoc(); 7551 Value *PtrOperand = VPIntrin.getArgOperand(0); 7552 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7553 if (!Alignment) 7554 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7555 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7556 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7557 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7558 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7559 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7560 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7561 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7562 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7563 7564 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7565 OpValues[2], OpValues[3], MMO, 7566 false /*IsExpanding*/); 7567 7568 if (AddToChain) 7569 PendingLoads.push_back(LD.getValue(1)); 7570 setValue(&VPIntrin, LD); 7571 } 7572 7573 void SelectionDAGBuilder::visitVPStridedStore( 7574 const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) { 7575 SDLoc DL = getCurSDLoc(); 7576 Value *PtrOperand = VPIntrin.getArgOperand(1); 7577 EVT VT = OpValues[0].getValueType(); 7578 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7579 if (!Alignment) 7580 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7581 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7582 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7583 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7584 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7585 7586 SDValue ST = DAG.getStridedStoreVP( 7587 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7588 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7589 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7590 /*IsCompressing*/ false); 7591 7592 DAG.setRoot(ST); 7593 setValue(&VPIntrin, ST); 7594 } 7595 7596 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7597 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7598 SDLoc DL = getCurSDLoc(); 7599 7600 ISD::CondCode Condition; 7601 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7602 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7603 if (IsFP) { 7604 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7605 // flags, but calls that don't return floating-point types can't be 7606 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7607 Condition = getFCmpCondCode(CondCode); 7608 if (TM.Options.NoNaNsFPMath) 7609 Condition = getFCmpCodeWithoutNaN(Condition); 7610 } else { 7611 Condition = getICmpCondCode(CondCode); 7612 } 7613 7614 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7615 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7616 // #2 is the condition code 7617 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7618 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7619 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7620 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7621 "Unexpected target EVL type"); 7622 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7623 7624 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7625 VPIntrin.getType()); 7626 setValue(&VPIntrin, 7627 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7628 } 7629 7630 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7631 const VPIntrinsic &VPIntrin) { 7632 SDLoc DL = getCurSDLoc(); 7633 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7634 7635 auto IID = VPIntrin.getIntrinsicID(); 7636 7637 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7638 return visitVPCmp(*CmpI); 7639 7640 SmallVector<EVT, 4> ValueVTs; 7641 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7642 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7643 SDVTList VTs = DAG.getVTList(ValueVTs); 7644 7645 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7646 7647 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7648 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7649 "Unexpected target EVL type"); 7650 7651 // Request operands. 7652 SmallVector<SDValue, 7> OpValues; 7653 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7654 auto Op = getValue(VPIntrin.getArgOperand(I)); 7655 if (I == EVLParamPos) 7656 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7657 OpValues.push_back(Op); 7658 } 7659 7660 switch (Opcode) { 7661 default: { 7662 SDNodeFlags SDFlags; 7663 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7664 SDFlags.copyFMF(*FPMO); 7665 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7666 setValue(&VPIntrin, Result); 7667 break; 7668 } 7669 case ISD::VP_LOAD: 7670 case ISD::VP_GATHER: 7671 visitVPLoadGather(VPIntrin, ValueVTs[0], OpValues, 7672 Opcode == ISD::VP_GATHER); 7673 break; 7674 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7675 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7676 break; 7677 case ISD::VP_STORE: 7678 case ISD::VP_SCATTER: 7679 visitVPStoreScatter(VPIntrin, OpValues, Opcode == ISD::VP_SCATTER); 7680 break; 7681 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7682 visitVPStridedStore(VPIntrin, OpValues); 7683 break; 7684 } 7685 } 7686 7687 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7688 const BasicBlock *EHPadBB, 7689 MCSymbol *&BeginLabel) { 7690 MachineFunction &MF = DAG.getMachineFunction(); 7691 MachineModuleInfo &MMI = MF.getMMI(); 7692 7693 // Insert a label before the invoke call to mark the try range. This can be 7694 // used to detect deletion of the invoke via the MachineModuleInfo. 7695 BeginLabel = MMI.getContext().createTempSymbol(); 7696 7697 // For SjLj, keep track of which landing pads go with which invokes 7698 // so as to maintain the ordering of pads in the LSDA. 7699 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7700 if (CallSiteIndex) { 7701 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7702 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7703 7704 // Now that the call site is handled, stop tracking it. 7705 MMI.setCurrentCallSite(0); 7706 } 7707 7708 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7709 } 7710 7711 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7712 const BasicBlock *EHPadBB, 7713 MCSymbol *BeginLabel) { 7714 assert(BeginLabel && "BeginLabel should've been set"); 7715 7716 MachineFunction &MF = DAG.getMachineFunction(); 7717 MachineModuleInfo &MMI = MF.getMMI(); 7718 7719 // Insert a label at the end of the invoke call to mark the try range. This 7720 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7721 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7722 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7723 7724 // Inform MachineModuleInfo of range. 7725 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7726 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7727 // actually use outlined funclets and their LSDA info style. 7728 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7729 assert(II && "II should've been set"); 7730 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7731 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7732 } else if (!isScopedEHPersonality(Pers)) { 7733 assert(EHPadBB); 7734 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7735 } 7736 7737 return Chain; 7738 } 7739 7740 std::pair<SDValue, SDValue> 7741 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7742 const BasicBlock *EHPadBB) { 7743 MCSymbol *BeginLabel = nullptr; 7744 7745 if (EHPadBB) { 7746 // Both PendingLoads and PendingExports must be flushed here; 7747 // this call might not return. 7748 (void)getRoot(); 7749 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7750 CLI.setChain(getRoot()); 7751 } 7752 7753 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7754 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7755 7756 assert((CLI.IsTailCall || Result.second.getNode()) && 7757 "Non-null chain expected with non-tail call!"); 7758 assert((Result.second.getNode() || !Result.first.getNode()) && 7759 "Null value expected with tail call!"); 7760 7761 if (!Result.second.getNode()) { 7762 // As a special case, a null chain means that a tail call has been emitted 7763 // and the DAG root is already updated. 7764 HasTailCall = true; 7765 7766 // Since there's no actual continuation from this block, nothing can be 7767 // relying on us setting vregs for them. 7768 PendingExports.clear(); 7769 } else { 7770 DAG.setRoot(Result.second); 7771 } 7772 7773 if (EHPadBB) { 7774 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7775 BeginLabel)); 7776 } 7777 7778 return Result; 7779 } 7780 7781 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7782 bool isTailCall, 7783 bool isMustTailCall, 7784 const BasicBlock *EHPadBB) { 7785 auto &DL = DAG.getDataLayout(); 7786 FunctionType *FTy = CB.getFunctionType(); 7787 Type *RetTy = CB.getType(); 7788 7789 TargetLowering::ArgListTy Args; 7790 Args.reserve(CB.arg_size()); 7791 7792 const Value *SwiftErrorVal = nullptr; 7793 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7794 7795 if (isTailCall) { 7796 // Avoid emitting tail calls in functions with the disable-tail-calls 7797 // attribute. 7798 auto *Caller = CB.getParent()->getParent(); 7799 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7800 "true" && !isMustTailCall) 7801 isTailCall = false; 7802 7803 // We can't tail call inside a function with a swifterror argument. Lowering 7804 // does not support this yet. It would have to move into the swifterror 7805 // register before the call. 7806 if (TLI.supportSwiftError() && 7807 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7808 isTailCall = false; 7809 } 7810 7811 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7812 TargetLowering::ArgListEntry Entry; 7813 const Value *V = *I; 7814 7815 // Skip empty types 7816 if (V->getType()->isEmptyTy()) 7817 continue; 7818 7819 SDValue ArgNode = getValue(V); 7820 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7821 7822 Entry.setAttributes(&CB, I - CB.arg_begin()); 7823 7824 // Use swifterror virtual register as input to the call. 7825 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7826 SwiftErrorVal = V; 7827 // We find the virtual register for the actual swifterror argument. 7828 // Instead of using the Value, we use the virtual register instead. 7829 Entry.Node = 7830 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7831 EVT(TLI.getPointerTy(DL))); 7832 } 7833 7834 Args.push_back(Entry); 7835 7836 // If we have an explicit sret argument that is an Instruction, (i.e., it 7837 // might point to function-local memory), we can't meaningfully tail-call. 7838 if (Entry.IsSRet && isa<Instruction>(V)) 7839 isTailCall = false; 7840 } 7841 7842 // If call site has a cfguardtarget operand bundle, create and add an 7843 // additional ArgListEntry. 7844 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7845 TargetLowering::ArgListEntry Entry; 7846 Value *V = Bundle->Inputs[0]; 7847 SDValue ArgNode = getValue(V); 7848 Entry.Node = ArgNode; 7849 Entry.Ty = V->getType(); 7850 Entry.IsCFGuardTarget = true; 7851 Args.push_back(Entry); 7852 } 7853 7854 // Check if target-independent constraints permit a tail call here. 7855 // Target-dependent constraints are checked within TLI->LowerCallTo. 7856 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7857 isTailCall = false; 7858 7859 // Disable tail calls if there is an swifterror argument. Targets have not 7860 // been updated to support tail calls. 7861 if (TLI.supportSwiftError() && SwiftErrorVal) 7862 isTailCall = false; 7863 7864 ConstantInt *CFIType = nullptr; 7865 if (CB.isIndirectCall()) { 7866 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 7867 if (!TLI.supportKCFIBundles()) 7868 report_fatal_error( 7869 "Target doesn't support calls with kcfi operand bundles."); 7870 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 7871 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 7872 } 7873 } 7874 7875 TargetLowering::CallLoweringInfo CLI(DAG); 7876 CLI.setDebugLoc(getCurSDLoc()) 7877 .setChain(getRoot()) 7878 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7879 .setTailCall(isTailCall) 7880 .setConvergent(CB.isConvergent()) 7881 .setIsPreallocated( 7882 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 7883 .setCFIType(CFIType); 7884 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7885 7886 if (Result.first.getNode()) { 7887 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7888 setValue(&CB, Result.first); 7889 } 7890 7891 // The last element of CLI.InVals has the SDValue for swifterror return. 7892 // Here we copy it to a virtual register and update SwiftErrorMap for 7893 // book-keeping. 7894 if (SwiftErrorVal && TLI.supportSwiftError()) { 7895 // Get the last element of InVals. 7896 SDValue Src = CLI.InVals.back(); 7897 Register VReg = 7898 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7899 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7900 DAG.setRoot(CopyNode); 7901 } 7902 } 7903 7904 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7905 SelectionDAGBuilder &Builder) { 7906 // Check to see if this load can be trivially constant folded, e.g. if the 7907 // input is from a string literal. 7908 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7909 // Cast pointer to the type we really want to load. 7910 Type *LoadTy = 7911 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7912 if (LoadVT.isVector()) 7913 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7914 7915 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7916 PointerType::getUnqual(LoadTy)); 7917 7918 if (const Constant *LoadCst = 7919 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 7920 LoadTy, Builder.DAG.getDataLayout())) 7921 return Builder.getValue(LoadCst); 7922 } 7923 7924 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7925 // still constant memory, the input chain can be the entry node. 7926 SDValue Root; 7927 bool ConstantMemory = false; 7928 7929 // Do not serialize (non-volatile) loads of constant memory with anything. 7930 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7931 Root = Builder.DAG.getEntryNode(); 7932 ConstantMemory = true; 7933 } else { 7934 // Do not serialize non-volatile loads against each other. 7935 Root = Builder.DAG.getRoot(); 7936 } 7937 7938 SDValue Ptr = Builder.getValue(PtrVal); 7939 SDValue LoadVal = 7940 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7941 MachinePointerInfo(PtrVal), Align(1)); 7942 7943 if (!ConstantMemory) 7944 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7945 return LoadVal; 7946 } 7947 7948 /// Record the value for an instruction that produces an integer result, 7949 /// converting the type where necessary. 7950 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7951 SDValue Value, 7952 bool IsSigned) { 7953 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7954 I.getType(), true); 7955 if (IsSigned) 7956 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7957 else 7958 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7959 setValue(&I, Value); 7960 } 7961 7962 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7963 /// true and lower it. Otherwise return false, and it will be lowered like a 7964 /// normal call. 7965 /// The caller already checked that \p I calls the appropriate LibFunc with a 7966 /// correct prototype. 7967 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7968 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7969 const Value *Size = I.getArgOperand(2); 7970 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 7971 if (CSize && CSize->getZExtValue() == 0) { 7972 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7973 I.getType(), true); 7974 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7975 return true; 7976 } 7977 7978 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7979 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7980 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7981 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7982 if (Res.first.getNode()) { 7983 processIntegerCallValue(I, Res.first, true); 7984 PendingLoads.push_back(Res.second); 7985 return true; 7986 } 7987 7988 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7989 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7990 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7991 return false; 7992 7993 // If the target has a fast compare for the given size, it will return a 7994 // preferred load type for that size. Require that the load VT is legal and 7995 // that the target supports unaligned loads of that type. Otherwise, return 7996 // INVALID. 7997 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7998 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7999 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8000 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8001 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8002 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8003 // TODO: Check alignment of src and dest ptrs. 8004 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8005 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8006 if (!TLI.isTypeLegal(LVT) || 8007 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8008 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8009 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8010 } 8011 8012 return LVT; 8013 }; 8014 8015 // This turns into unaligned loads. We only do this if the target natively 8016 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8017 // we'll only produce a small number of byte loads. 8018 MVT LoadVT; 8019 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8020 switch (NumBitsToCompare) { 8021 default: 8022 return false; 8023 case 16: 8024 LoadVT = MVT::i16; 8025 break; 8026 case 32: 8027 LoadVT = MVT::i32; 8028 break; 8029 case 64: 8030 case 128: 8031 case 256: 8032 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8033 break; 8034 } 8035 8036 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8037 return false; 8038 8039 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8040 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8041 8042 // Bitcast to a wide integer type if the loads are vectors. 8043 if (LoadVT.isVector()) { 8044 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8045 LoadL = DAG.getBitcast(CmpVT, LoadL); 8046 LoadR = DAG.getBitcast(CmpVT, LoadR); 8047 } 8048 8049 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8050 processIntegerCallValue(I, Cmp, false); 8051 return true; 8052 } 8053 8054 /// See if we can lower a memchr call into an optimized form. If so, return 8055 /// true and lower it. Otherwise return false, and it will be lowered like a 8056 /// normal call. 8057 /// The caller already checked that \p I calls the appropriate LibFunc with a 8058 /// correct prototype. 8059 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8060 const Value *Src = I.getArgOperand(0); 8061 const Value *Char = I.getArgOperand(1); 8062 const Value *Length = I.getArgOperand(2); 8063 8064 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8065 std::pair<SDValue, SDValue> Res = 8066 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8067 getValue(Src), getValue(Char), getValue(Length), 8068 MachinePointerInfo(Src)); 8069 if (Res.first.getNode()) { 8070 setValue(&I, Res.first); 8071 PendingLoads.push_back(Res.second); 8072 return true; 8073 } 8074 8075 return false; 8076 } 8077 8078 /// See if we can lower a mempcpy call into an optimized form. If so, return 8079 /// true and lower it. Otherwise return false, and it will be lowered like a 8080 /// normal call. 8081 /// The caller already checked that \p I calls the appropriate LibFunc with a 8082 /// correct prototype. 8083 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8084 SDValue Dst = getValue(I.getArgOperand(0)); 8085 SDValue Src = getValue(I.getArgOperand(1)); 8086 SDValue Size = getValue(I.getArgOperand(2)); 8087 8088 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8089 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8090 // DAG::getMemcpy needs Alignment to be defined. 8091 Align Alignment = std::min(DstAlign, SrcAlign); 8092 8093 bool isVol = false; 8094 SDLoc sdl = getCurSDLoc(); 8095 8096 // In the mempcpy context we need to pass in a false value for isTailCall 8097 // because the return pointer needs to be adjusted by the size of 8098 // the copied memory. 8099 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 8100 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 8101 /*isTailCall=*/false, 8102 MachinePointerInfo(I.getArgOperand(0)), 8103 MachinePointerInfo(I.getArgOperand(1)), 8104 I.getAAMetadata()); 8105 assert(MC.getNode() != nullptr && 8106 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8107 DAG.setRoot(MC); 8108 8109 // Check if Size needs to be truncated or extended. 8110 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8111 8112 // Adjust return pointer to point just past the last dst byte. 8113 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8114 Dst, Size); 8115 setValue(&I, DstPlusSize); 8116 return true; 8117 } 8118 8119 /// See if we can lower a strcpy call into an optimized form. If so, return 8120 /// true and lower it, otherwise return false and it will be lowered like a 8121 /// normal call. 8122 /// The caller already checked that \p I calls the appropriate LibFunc with a 8123 /// correct prototype. 8124 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8125 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8126 8127 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8128 std::pair<SDValue, SDValue> Res = 8129 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8130 getValue(Arg0), getValue(Arg1), 8131 MachinePointerInfo(Arg0), 8132 MachinePointerInfo(Arg1), isStpcpy); 8133 if (Res.first.getNode()) { 8134 setValue(&I, Res.first); 8135 DAG.setRoot(Res.second); 8136 return true; 8137 } 8138 8139 return false; 8140 } 8141 8142 /// See if we can lower a strcmp call into an optimized form. If so, return 8143 /// true and lower it, otherwise return false and it will be lowered like a 8144 /// normal call. 8145 /// The caller already checked that \p I calls the appropriate LibFunc with a 8146 /// correct prototype. 8147 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8148 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8149 8150 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8151 std::pair<SDValue, SDValue> Res = 8152 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8153 getValue(Arg0), getValue(Arg1), 8154 MachinePointerInfo(Arg0), 8155 MachinePointerInfo(Arg1)); 8156 if (Res.first.getNode()) { 8157 processIntegerCallValue(I, Res.first, true); 8158 PendingLoads.push_back(Res.second); 8159 return true; 8160 } 8161 8162 return false; 8163 } 8164 8165 /// See if we can lower a strlen call into an optimized form. If so, return 8166 /// true and lower it, otherwise return false and it will be lowered like a 8167 /// normal call. 8168 /// The caller already checked that \p I calls the appropriate LibFunc with a 8169 /// correct prototype. 8170 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8171 const Value *Arg0 = I.getArgOperand(0); 8172 8173 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8174 std::pair<SDValue, SDValue> Res = 8175 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8176 getValue(Arg0), MachinePointerInfo(Arg0)); 8177 if (Res.first.getNode()) { 8178 processIntegerCallValue(I, Res.first, false); 8179 PendingLoads.push_back(Res.second); 8180 return true; 8181 } 8182 8183 return false; 8184 } 8185 8186 /// See if we can lower a strnlen call into an optimized form. If so, return 8187 /// true and lower it, otherwise return false and it will be lowered like a 8188 /// normal call. 8189 /// The caller already checked that \p I calls the appropriate LibFunc with a 8190 /// correct prototype. 8191 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8192 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8193 8194 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8195 std::pair<SDValue, SDValue> Res = 8196 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8197 getValue(Arg0), getValue(Arg1), 8198 MachinePointerInfo(Arg0)); 8199 if (Res.first.getNode()) { 8200 processIntegerCallValue(I, Res.first, false); 8201 PendingLoads.push_back(Res.second); 8202 return true; 8203 } 8204 8205 return false; 8206 } 8207 8208 /// See if we can lower a unary floating-point operation into an SDNode with 8209 /// the specified Opcode. If so, return true and lower it, otherwise return 8210 /// false and it will be lowered like a normal call. 8211 /// The caller already checked that \p I calls the appropriate LibFunc with a 8212 /// correct prototype. 8213 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8214 unsigned Opcode) { 8215 // We already checked this call's prototype; verify it doesn't modify errno. 8216 if (!I.onlyReadsMemory()) 8217 return false; 8218 8219 SDNodeFlags Flags; 8220 Flags.copyFMF(cast<FPMathOperator>(I)); 8221 8222 SDValue Tmp = getValue(I.getArgOperand(0)); 8223 setValue(&I, 8224 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8225 return true; 8226 } 8227 8228 /// See if we can lower a binary floating-point operation into an SDNode with 8229 /// the specified Opcode. If so, return true and lower it. Otherwise return 8230 /// false, and it will be lowered like a normal call. 8231 /// The caller already checked that \p I calls the appropriate LibFunc with a 8232 /// correct prototype. 8233 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8234 unsigned Opcode) { 8235 // We already checked this call's prototype; verify it doesn't modify errno. 8236 if (!I.onlyReadsMemory()) 8237 return false; 8238 8239 SDNodeFlags Flags; 8240 Flags.copyFMF(cast<FPMathOperator>(I)); 8241 8242 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8243 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8244 EVT VT = Tmp0.getValueType(); 8245 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8246 return true; 8247 } 8248 8249 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8250 // Handle inline assembly differently. 8251 if (I.isInlineAsm()) { 8252 visitInlineAsm(I); 8253 return; 8254 } 8255 8256 if (Function *F = I.getCalledFunction()) { 8257 diagnoseDontCall(I); 8258 8259 if (F->isDeclaration()) { 8260 // Is this an LLVM intrinsic or a target-specific intrinsic? 8261 unsigned IID = F->getIntrinsicID(); 8262 if (!IID) 8263 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8264 IID = II->getIntrinsicID(F); 8265 8266 if (IID) { 8267 visitIntrinsicCall(I, IID); 8268 return; 8269 } 8270 } 8271 8272 // Check for well-known libc/libm calls. If the function is internal, it 8273 // can't be a library call. Don't do the check if marked as nobuiltin for 8274 // some reason or the call site requires strict floating point semantics. 8275 LibFunc Func; 8276 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8277 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8278 LibInfo->hasOptimizedCodeGen(Func)) { 8279 switch (Func) { 8280 default: break; 8281 case LibFunc_bcmp: 8282 if (visitMemCmpBCmpCall(I)) 8283 return; 8284 break; 8285 case LibFunc_copysign: 8286 case LibFunc_copysignf: 8287 case LibFunc_copysignl: 8288 // We already checked this call's prototype; verify it doesn't modify 8289 // errno. 8290 if (I.onlyReadsMemory()) { 8291 SDValue LHS = getValue(I.getArgOperand(0)); 8292 SDValue RHS = getValue(I.getArgOperand(1)); 8293 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8294 LHS.getValueType(), LHS, RHS)); 8295 return; 8296 } 8297 break; 8298 case LibFunc_fabs: 8299 case LibFunc_fabsf: 8300 case LibFunc_fabsl: 8301 if (visitUnaryFloatCall(I, ISD::FABS)) 8302 return; 8303 break; 8304 case LibFunc_fmin: 8305 case LibFunc_fminf: 8306 case LibFunc_fminl: 8307 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8308 return; 8309 break; 8310 case LibFunc_fmax: 8311 case LibFunc_fmaxf: 8312 case LibFunc_fmaxl: 8313 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8314 return; 8315 break; 8316 case LibFunc_sin: 8317 case LibFunc_sinf: 8318 case LibFunc_sinl: 8319 if (visitUnaryFloatCall(I, ISD::FSIN)) 8320 return; 8321 break; 8322 case LibFunc_cos: 8323 case LibFunc_cosf: 8324 case LibFunc_cosl: 8325 if (visitUnaryFloatCall(I, ISD::FCOS)) 8326 return; 8327 break; 8328 case LibFunc_sqrt: 8329 case LibFunc_sqrtf: 8330 case LibFunc_sqrtl: 8331 case LibFunc_sqrt_finite: 8332 case LibFunc_sqrtf_finite: 8333 case LibFunc_sqrtl_finite: 8334 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8335 return; 8336 break; 8337 case LibFunc_floor: 8338 case LibFunc_floorf: 8339 case LibFunc_floorl: 8340 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8341 return; 8342 break; 8343 case LibFunc_nearbyint: 8344 case LibFunc_nearbyintf: 8345 case LibFunc_nearbyintl: 8346 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8347 return; 8348 break; 8349 case LibFunc_ceil: 8350 case LibFunc_ceilf: 8351 case LibFunc_ceill: 8352 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8353 return; 8354 break; 8355 case LibFunc_rint: 8356 case LibFunc_rintf: 8357 case LibFunc_rintl: 8358 if (visitUnaryFloatCall(I, ISD::FRINT)) 8359 return; 8360 break; 8361 case LibFunc_round: 8362 case LibFunc_roundf: 8363 case LibFunc_roundl: 8364 if (visitUnaryFloatCall(I, ISD::FROUND)) 8365 return; 8366 break; 8367 case LibFunc_trunc: 8368 case LibFunc_truncf: 8369 case LibFunc_truncl: 8370 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8371 return; 8372 break; 8373 case LibFunc_log2: 8374 case LibFunc_log2f: 8375 case LibFunc_log2l: 8376 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8377 return; 8378 break; 8379 case LibFunc_exp2: 8380 case LibFunc_exp2f: 8381 case LibFunc_exp2l: 8382 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8383 return; 8384 break; 8385 case LibFunc_memcmp: 8386 if (visitMemCmpBCmpCall(I)) 8387 return; 8388 break; 8389 case LibFunc_mempcpy: 8390 if (visitMemPCpyCall(I)) 8391 return; 8392 break; 8393 case LibFunc_memchr: 8394 if (visitMemChrCall(I)) 8395 return; 8396 break; 8397 case LibFunc_strcpy: 8398 if (visitStrCpyCall(I, false)) 8399 return; 8400 break; 8401 case LibFunc_stpcpy: 8402 if (visitStrCpyCall(I, true)) 8403 return; 8404 break; 8405 case LibFunc_strcmp: 8406 if (visitStrCmpCall(I)) 8407 return; 8408 break; 8409 case LibFunc_strlen: 8410 if (visitStrLenCall(I)) 8411 return; 8412 break; 8413 case LibFunc_strnlen: 8414 if (visitStrNLenCall(I)) 8415 return; 8416 break; 8417 } 8418 } 8419 } 8420 8421 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8422 // have to do anything here to lower funclet bundles. 8423 // CFGuardTarget bundles are lowered in LowerCallTo. 8424 assert(!I.hasOperandBundlesOtherThan( 8425 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8426 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8427 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8428 "Cannot lower calls with arbitrary operand bundles!"); 8429 8430 SDValue Callee = getValue(I.getCalledOperand()); 8431 8432 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8433 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8434 else 8435 // Check if we can potentially perform a tail call. More detailed checking 8436 // is be done within LowerCallTo, after more information about the call is 8437 // known. 8438 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8439 } 8440 8441 namespace { 8442 8443 /// AsmOperandInfo - This contains information for each constraint that we are 8444 /// lowering. 8445 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8446 public: 8447 /// CallOperand - If this is the result output operand or a clobber 8448 /// this is null, otherwise it is the incoming operand to the CallInst. 8449 /// This gets modified as the asm is processed. 8450 SDValue CallOperand; 8451 8452 /// AssignedRegs - If this is a register or register class operand, this 8453 /// contains the set of register corresponding to the operand. 8454 RegsForValue AssignedRegs; 8455 8456 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8457 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8458 } 8459 8460 /// Whether or not this operand accesses memory 8461 bool hasMemory(const TargetLowering &TLI) const { 8462 // Indirect operand accesses access memory. 8463 if (isIndirect) 8464 return true; 8465 8466 for (const auto &Code : Codes) 8467 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8468 return true; 8469 8470 return false; 8471 } 8472 }; 8473 8474 8475 } // end anonymous namespace 8476 8477 /// Make sure that the output operand \p OpInfo and its corresponding input 8478 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8479 /// out). 8480 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8481 SDISelAsmOperandInfo &MatchingOpInfo, 8482 SelectionDAG &DAG) { 8483 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8484 return; 8485 8486 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8487 const auto &TLI = DAG.getTargetLoweringInfo(); 8488 8489 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8490 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8491 OpInfo.ConstraintVT); 8492 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8493 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8494 MatchingOpInfo.ConstraintVT); 8495 if ((OpInfo.ConstraintVT.isInteger() != 8496 MatchingOpInfo.ConstraintVT.isInteger()) || 8497 (MatchRC.second != InputRC.second)) { 8498 // FIXME: error out in a more elegant fashion 8499 report_fatal_error("Unsupported asm: input constraint" 8500 " with a matching output constraint of" 8501 " incompatible type!"); 8502 } 8503 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8504 } 8505 8506 /// Get a direct memory input to behave well as an indirect operand. 8507 /// This may introduce stores, hence the need for a \p Chain. 8508 /// \return The (possibly updated) chain. 8509 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8510 SDISelAsmOperandInfo &OpInfo, 8511 SelectionDAG &DAG) { 8512 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8513 8514 // If we don't have an indirect input, put it in the constpool if we can, 8515 // otherwise spill it to a stack slot. 8516 // TODO: This isn't quite right. We need to handle these according to 8517 // the addressing mode that the constraint wants. Also, this may take 8518 // an additional register for the computation and we don't want that 8519 // either. 8520 8521 // If the operand is a float, integer, or vector constant, spill to a 8522 // constant pool entry to get its address. 8523 const Value *OpVal = OpInfo.CallOperandVal; 8524 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8525 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8526 OpInfo.CallOperand = DAG.getConstantPool( 8527 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8528 return Chain; 8529 } 8530 8531 // Otherwise, create a stack slot and emit a store to it before the asm. 8532 Type *Ty = OpVal->getType(); 8533 auto &DL = DAG.getDataLayout(); 8534 uint64_t TySize = DL.getTypeAllocSize(Ty); 8535 MachineFunction &MF = DAG.getMachineFunction(); 8536 int SSFI = MF.getFrameInfo().CreateStackObject( 8537 TySize, DL.getPrefTypeAlign(Ty), false); 8538 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8539 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8540 MachinePointerInfo::getFixedStack(MF, SSFI), 8541 TLI.getMemValueType(DL, Ty)); 8542 OpInfo.CallOperand = StackSlot; 8543 8544 return Chain; 8545 } 8546 8547 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8548 /// specified operand. We prefer to assign virtual registers, to allow the 8549 /// register allocator to handle the assignment process. However, if the asm 8550 /// uses features that we can't model on machineinstrs, we have SDISel do the 8551 /// allocation. This produces generally horrible, but correct, code. 8552 /// 8553 /// OpInfo describes the operand 8554 /// RefOpInfo describes the matching operand if any, the operand otherwise 8555 static llvm::Optional<unsigned> 8556 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8557 SDISelAsmOperandInfo &OpInfo, 8558 SDISelAsmOperandInfo &RefOpInfo) { 8559 LLVMContext &Context = *DAG.getContext(); 8560 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8561 8562 MachineFunction &MF = DAG.getMachineFunction(); 8563 SmallVector<unsigned, 4> Regs; 8564 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8565 8566 // No work to do for memory/address operands. 8567 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8568 OpInfo.ConstraintType == TargetLowering::C_Address) 8569 return None; 8570 8571 // If this is a constraint for a single physreg, or a constraint for a 8572 // register class, find it. 8573 unsigned AssignedReg; 8574 const TargetRegisterClass *RC; 8575 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8576 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8577 // RC is unset only on failure. Return immediately. 8578 if (!RC) 8579 return None; 8580 8581 // Get the actual register value type. This is important, because the user 8582 // may have asked for (e.g.) the AX register in i32 type. We need to 8583 // remember that AX is actually i16 to get the right extension. 8584 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8585 8586 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8587 // If this is an FP operand in an integer register (or visa versa), or more 8588 // generally if the operand value disagrees with the register class we plan 8589 // to stick it in, fix the operand type. 8590 // 8591 // If this is an input value, the bitcast to the new type is done now. 8592 // Bitcast for output value is done at the end of visitInlineAsm(). 8593 if ((OpInfo.Type == InlineAsm::isOutput || 8594 OpInfo.Type == InlineAsm::isInput) && 8595 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8596 // Try to convert to the first EVT that the reg class contains. If the 8597 // types are identical size, use a bitcast to convert (e.g. two differing 8598 // vector types). Note: output bitcast is done at the end of 8599 // visitInlineAsm(). 8600 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8601 // Exclude indirect inputs while they are unsupported because the code 8602 // to perform the load is missing and thus OpInfo.CallOperand still 8603 // refers to the input address rather than the pointed-to value. 8604 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8605 OpInfo.CallOperand = 8606 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8607 OpInfo.ConstraintVT = RegVT; 8608 // If the operand is an FP value and we want it in integer registers, 8609 // use the corresponding integer type. This turns an f64 value into 8610 // i64, which can be passed with two i32 values on a 32-bit machine. 8611 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8612 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8613 if (OpInfo.Type == InlineAsm::isInput) 8614 OpInfo.CallOperand = 8615 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8616 OpInfo.ConstraintVT = VT; 8617 } 8618 } 8619 } 8620 8621 // No need to allocate a matching input constraint since the constraint it's 8622 // matching to has already been allocated. 8623 if (OpInfo.isMatchingInputConstraint()) 8624 return None; 8625 8626 EVT ValueVT = OpInfo.ConstraintVT; 8627 if (OpInfo.ConstraintVT == MVT::Other) 8628 ValueVT = RegVT; 8629 8630 // Initialize NumRegs. 8631 unsigned NumRegs = 1; 8632 if (OpInfo.ConstraintVT != MVT::Other) 8633 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8634 8635 // If this is a constraint for a specific physical register, like {r17}, 8636 // assign it now. 8637 8638 // If this associated to a specific register, initialize iterator to correct 8639 // place. If virtual, make sure we have enough registers 8640 8641 // Initialize iterator if necessary 8642 TargetRegisterClass::iterator I = RC->begin(); 8643 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8644 8645 // Do not check for single registers. 8646 if (AssignedReg) { 8647 I = std::find(I, RC->end(), AssignedReg); 8648 if (I == RC->end()) { 8649 // RC does not contain the selected register, which indicates a 8650 // mismatch between the register and the required type/bitwidth. 8651 return {AssignedReg}; 8652 } 8653 } 8654 8655 for (; NumRegs; --NumRegs, ++I) { 8656 assert(I != RC->end() && "Ran out of registers to allocate!"); 8657 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8658 Regs.push_back(R); 8659 } 8660 8661 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8662 return None; 8663 } 8664 8665 static unsigned 8666 findMatchingInlineAsmOperand(unsigned OperandNo, 8667 const std::vector<SDValue> &AsmNodeOperands) { 8668 // Scan until we find the definition we already emitted of this operand. 8669 unsigned CurOp = InlineAsm::Op_FirstOperand; 8670 for (; OperandNo; --OperandNo) { 8671 // Advance to the next operand. 8672 unsigned OpFlag = 8673 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8674 assert((InlineAsm::isRegDefKind(OpFlag) || 8675 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8676 InlineAsm::isMemKind(OpFlag)) && 8677 "Skipped past definitions?"); 8678 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8679 } 8680 return CurOp; 8681 } 8682 8683 namespace { 8684 8685 class ExtraFlags { 8686 unsigned Flags = 0; 8687 8688 public: 8689 explicit ExtraFlags(const CallBase &Call) { 8690 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8691 if (IA->hasSideEffects()) 8692 Flags |= InlineAsm::Extra_HasSideEffects; 8693 if (IA->isAlignStack()) 8694 Flags |= InlineAsm::Extra_IsAlignStack; 8695 if (Call.isConvergent()) 8696 Flags |= InlineAsm::Extra_IsConvergent; 8697 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8698 } 8699 8700 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8701 // Ideally, we would only check against memory constraints. However, the 8702 // meaning of an Other constraint can be target-specific and we can't easily 8703 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8704 // for Other constraints as well. 8705 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8706 OpInfo.ConstraintType == TargetLowering::C_Other) { 8707 if (OpInfo.Type == InlineAsm::isInput) 8708 Flags |= InlineAsm::Extra_MayLoad; 8709 else if (OpInfo.Type == InlineAsm::isOutput) 8710 Flags |= InlineAsm::Extra_MayStore; 8711 else if (OpInfo.Type == InlineAsm::isClobber) 8712 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8713 } 8714 } 8715 8716 unsigned get() const { return Flags; } 8717 }; 8718 8719 } // end anonymous namespace 8720 8721 /// visitInlineAsm - Handle a call to an InlineAsm object. 8722 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8723 const BasicBlock *EHPadBB) { 8724 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8725 8726 /// ConstraintOperands - Information about all of the constraints. 8727 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8728 8729 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8730 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8731 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8732 8733 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8734 // AsmDialect, MayLoad, MayStore). 8735 bool HasSideEffect = IA->hasSideEffects(); 8736 ExtraFlags ExtraInfo(Call); 8737 8738 for (auto &T : TargetConstraints) { 8739 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8740 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8741 8742 if (OpInfo.CallOperandVal) 8743 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8744 8745 if (!HasSideEffect) 8746 HasSideEffect = OpInfo.hasMemory(TLI); 8747 8748 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8749 // FIXME: Could we compute this on OpInfo rather than T? 8750 8751 // Compute the constraint code and ConstraintType to use. 8752 TLI.ComputeConstraintToUse(T, SDValue()); 8753 8754 if (T.ConstraintType == TargetLowering::C_Immediate && 8755 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8756 // We've delayed emitting a diagnostic like the "n" constraint because 8757 // inlining could cause an integer showing up. 8758 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8759 "' expects an integer constant " 8760 "expression"); 8761 8762 ExtraInfo.update(T); 8763 } 8764 8765 // We won't need to flush pending loads if this asm doesn't touch 8766 // memory and is nonvolatile. 8767 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8768 8769 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8770 if (EmitEHLabels) { 8771 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8772 } 8773 bool IsCallBr = isa<CallBrInst>(Call); 8774 8775 if (IsCallBr || EmitEHLabels) { 8776 // If this is a callbr or invoke we need to flush pending exports since 8777 // inlineasm_br and invoke are terminators. 8778 // We need to do this before nodes are glued to the inlineasm_br node. 8779 Chain = getControlRoot(); 8780 } 8781 8782 MCSymbol *BeginLabel = nullptr; 8783 if (EmitEHLabels) { 8784 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8785 } 8786 8787 // Second pass over the constraints: compute which constraint option to use. 8788 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8789 // If this is an output operand with a matching input operand, look up the 8790 // matching input. If their types mismatch, e.g. one is an integer, the 8791 // other is floating point, or their sizes are different, flag it as an 8792 // error. 8793 if (OpInfo.hasMatchingInput()) { 8794 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8795 patchMatchingInput(OpInfo, Input, DAG); 8796 } 8797 8798 // Compute the constraint code and ConstraintType to use. 8799 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8800 8801 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 8802 OpInfo.Type == InlineAsm::isClobber) || 8803 OpInfo.ConstraintType == TargetLowering::C_Address) 8804 continue; 8805 8806 // If this is a memory input, and if the operand is not indirect, do what we 8807 // need to provide an address for the memory input. 8808 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8809 !OpInfo.isIndirect) { 8810 assert((OpInfo.isMultipleAlternative || 8811 (OpInfo.Type == InlineAsm::isInput)) && 8812 "Can only indirectify direct input operands!"); 8813 8814 // Memory operands really want the address of the value. 8815 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8816 8817 // There is no longer a Value* corresponding to this operand. 8818 OpInfo.CallOperandVal = nullptr; 8819 8820 // It is now an indirect operand. 8821 OpInfo.isIndirect = true; 8822 } 8823 8824 } 8825 8826 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8827 std::vector<SDValue> AsmNodeOperands; 8828 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8829 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8830 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8831 8832 // If we have a !srcloc metadata node associated with it, we want to attach 8833 // this to the ultimately generated inline asm machineinstr. To do this, we 8834 // pass in the third operand as this (potentially null) inline asm MDNode. 8835 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8836 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8837 8838 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8839 // bits as operand 3. 8840 AsmNodeOperands.push_back(DAG.getTargetConstant( 8841 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8842 8843 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8844 // this, assign virtual and physical registers for inputs and otput. 8845 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8846 // Assign Registers. 8847 SDISelAsmOperandInfo &RefOpInfo = 8848 OpInfo.isMatchingInputConstraint() 8849 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8850 : OpInfo; 8851 const auto RegError = 8852 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8853 if (RegError) { 8854 const MachineFunction &MF = DAG.getMachineFunction(); 8855 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8856 const char *RegName = TRI.getName(RegError.value()); 8857 emitInlineAsmError(Call, "register '" + Twine(RegName) + 8858 "' allocated for constraint '" + 8859 Twine(OpInfo.ConstraintCode) + 8860 "' does not match required type"); 8861 return; 8862 } 8863 8864 auto DetectWriteToReservedRegister = [&]() { 8865 const MachineFunction &MF = DAG.getMachineFunction(); 8866 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8867 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8868 if (Register::isPhysicalRegister(Reg) && 8869 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8870 const char *RegName = TRI.getName(Reg); 8871 emitInlineAsmError(Call, "write to reserved register '" + 8872 Twine(RegName) + "'"); 8873 return true; 8874 } 8875 } 8876 return false; 8877 }; 8878 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 8879 (OpInfo.Type == InlineAsm::isInput && 8880 !OpInfo.isMatchingInputConstraint())) && 8881 "Only address as input operand is allowed."); 8882 8883 switch (OpInfo.Type) { 8884 case InlineAsm::isOutput: 8885 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8886 unsigned ConstraintID = 8887 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8888 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8889 "Failed to convert memory constraint code to constraint id."); 8890 8891 // Add information to the INLINEASM node to know about this output. 8892 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8893 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8894 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8895 MVT::i32)); 8896 AsmNodeOperands.push_back(OpInfo.CallOperand); 8897 } else { 8898 // Otherwise, this outputs to a register (directly for C_Register / 8899 // C_RegisterClass, and a target-defined fashion for 8900 // C_Immediate/C_Other). Find a register that we can use. 8901 if (OpInfo.AssignedRegs.Regs.empty()) { 8902 emitInlineAsmError( 8903 Call, "couldn't allocate output register for constraint '" + 8904 Twine(OpInfo.ConstraintCode) + "'"); 8905 return; 8906 } 8907 8908 if (DetectWriteToReservedRegister()) 8909 return; 8910 8911 // Add information to the INLINEASM node to know that this register is 8912 // set. 8913 OpInfo.AssignedRegs.AddInlineAsmOperands( 8914 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8915 : InlineAsm::Kind_RegDef, 8916 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8917 } 8918 break; 8919 8920 case InlineAsm::isInput: 8921 case InlineAsm::isLabel: { 8922 SDValue InOperandVal = OpInfo.CallOperand; 8923 8924 if (OpInfo.isMatchingInputConstraint()) { 8925 // If this is required to match an output register we have already set, 8926 // just use its register. 8927 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8928 AsmNodeOperands); 8929 unsigned OpFlag = 8930 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8931 if (InlineAsm::isRegDefKind(OpFlag) || 8932 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8933 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8934 if (OpInfo.isIndirect) { 8935 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8936 emitInlineAsmError(Call, "inline asm not supported yet: " 8937 "don't know how to handle tied " 8938 "indirect register inputs"); 8939 return; 8940 } 8941 8942 SmallVector<unsigned, 4> Regs; 8943 MachineFunction &MF = DAG.getMachineFunction(); 8944 MachineRegisterInfo &MRI = MF.getRegInfo(); 8945 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8946 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 8947 Register TiedReg = R->getReg(); 8948 MVT RegVT = R->getSimpleValueType(0); 8949 const TargetRegisterClass *RC = 8950 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 8951 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 8952 : TRI.getMinimalPhysRegClass(TiedReg); 8953 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8954 for (unsigned i = 0; i != NumRegs; ++i) 8955 Regs.push_back(MRI.createVirtualRegister(RC)); 8956 8957 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8958 8959 SDLoc dl = getCurSDLoc(); 8960 // Use the produced MatchedRegs object to 8961 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8962 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8963 true, OpInfo.getMatchedOperand(), dl, 8964 DAG, AsmNodeOperands); 8965 break; 8966 } 8967 8968 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8969 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8970 "Unexpected number of operands"); 8971 // Add information to the INLINEASM node to know about this input. 8972 // See InlineAsm.h isUseOperandTiedToDef. 8973 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8974 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8975 OpInfo.getMatchedOperand()); 8976 AsmNodeOperands.push_back(DAG.getTargetConstant( 8977 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8978 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8979 break; 8980 } 8981 8982 // Treat indirect 'X' constraint as memory. 8983 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8984 OpInfo.isIndirect) 8985 OpInfo.ConstraintType = TargetLowering::C_Memory; 8986 8987 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8988 OpInfo.ConstraintType == TargetLowering::C_Other) { 8989 std::vector<SDValue> Ops; 8990 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8991 Ops, DAG); 8992 if (Ops.empty()) { 8993 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8994 if (isa<ConstantSDNode>(InOperandVal)) { 8995 emitInlineAsmError(Call, "value out of range for constraint '" + 8996 Twine(OpInfo.ConstraintCode) + "'"); 8997 return; 8998 } 8999 9000 emitInlineAsmError(Call, 9001 "invalid operand for inline asm constraint '" + 9002 Twine(OpInfo.ConstraintCode) + "'"); 9003 return; 9004 } 9005 9006 // Add information to the INLINEASM node to know about this input. 9007 unsigned ResOpType = 9008 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9009 AsmNodeOperands.push_back(DAG.getTargetConstant( 9010 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9011 llvm::append_range(AsmNodeOperands, Ops); 9012 break; 9013 } 9014 9015 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9016 OpInfo.ConstraintType == TargetLowering::C_Address) { 9017 assert((OpInfo.isIndirect || 9018 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9019 "Operand must be indirect to be a mem!"); 9020 assert(InOperandVal.getValueType() == 9021 TLI.getPointerTy(DAG.getDataLayout()) && 9022 "Memory operands expect pointer values"); 9023 9024 unsigned ConstraintID = 9025 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9026 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9027 "Failed to convert memory constraint code to constraint id."); 9028 9029 // Add information to the INLINEASM node to know about this input. 9030 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9031 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9032 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9033 getCurSDLoc(), 9034 MVT::i32)); 9035 AsmNodeOperands.push_back(InOperandVal); 9036 break; 9037 } 9038 9039 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9040 OpInfo.ConstraintType == TargetLowering::C_Register) && 9041 "Unknown constraint type!"); 9042 9043 // TODO: Support this. 9044 if (OpInfo.isIndirect) { 9045 emitInlineAsmError( 9046 Call, "Don't know how to handle indirect register inputs yet " 9047 "for constraint '" + 9048 Twine(OpInfo.ConstraintCode) + "'"); 9049 return; 9050 } 9051 9052 // Copy the input into the appropriate registers. 9053 if (OpInfo.AssignedRegs.Regs.empty()) { 9054 emitInlineAsmError(Call, 9055 "couldn't allocate input reg for constraint '" + 9056 Twine(OpInfo.ConstraintCode) + "'"); 9057 return; 9058 } 9059 9060 if (DetectWriteToReservedRegister()) 9061 return; 9062 9063 SDLoc dl = getCurSDLoc(); 9064 9065 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 9066 &Call); 9067 9068 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9069 dl, DAG, AsmNodeOperands); 9070 break; 9071 } 9072 case InlineAsm::isClobber: 9073 // Add the clobbered value to the operand list, so that the register 9074 // allocator is aware that the physreg got clobbered. 9075 if (!OpInfo.AssignedRegs.Regs.empty()) 9076 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9077 false, 0, getCurSDLoc(), DAG, 9078 AsmNodeOperands); 9079 break; 9080 } 9081 } 9082 9083 // Finish up input operands. Set the input chain and add the flag last. 9084 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9085 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 9086 9087 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9088 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9089 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9090 Flag = Chain.getValue(1); 9091 9092 // Do additional work to generate outputs. 9093 9094 SmallVector<EVT, 1> ResultVTs; 9095 SmallVector<SDValue, 1> ResultValues; 9096 SmallVector<SDValue, 8> OutChains; 9097 9098 llvm::Type *CallResultType = Call.getType(); 9099 ArrayRef<Type *> ResultTypes; 9100 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9101 ResultTypes = StructResult->elements(); 9102 else if (!CallResultType->isVoidTy()) 9103 ResultTypes = makeArrayRef(CallResultType); 9104 9105 auto CurResultType = ResultTypes.begin(); 9106 auto handleRegAssign = [&](SDValue V) { 9107 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9108 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9109 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9110 ++CurResultType; 9111 // If the type of the inline asm call site return value is different but has 9112 // same size as the type of the asm output bitcast it. One example of this 9113 // is for vectors with different width / number of elements. This can 9114 // happen for register classes that can contain multiple different value 9115 // types. The preg or vreg allocated may not have the same VT as was 9116 // expected. 9117 // 9118 // This can also happen for a return value that disagrees with the register 9119 // class it is put in, eg. a double in a general-purpose register on a 9120 // 32-bit machine. 9121 if (ResultVT != V.getValueType() && 9122 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9123 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9124 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9125 V.getValueType().isInteger()) { 9126 // If a result value was tied to an input value, the computed result 9127 // may have a wider width than the expected result. Extract the 9128 // relevant portion. 9129 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9130 } 9131 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9132 ResultVTs.push_back(ResultVT); 9133 ResultValues.push_back(V); 9134 }; 9135 9136 // Deal with output operands. 9137 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9138 if (OpInfo.Type == InlineAsm::isOutput) { 9139 SDValue Val; 9140 // Skip trivial output operands. 9141 if (OpInfo.AssignedRegs.Regs.empty()) 9142 continue; 9143 9144 switch (OpInfo.ConstraintType) { 9145 case TargetLowering::C_Register: 9146 case TargetLowering::C_RegisterClass: 9147 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9148 Chain, &Flag, &Call); 9149 break; 9150 case TargetLowering::C_Immediate: 9151 case TargetLowering::C_Other: 9152 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 9153 OpInfo, DAG); 9154 break; 9155 case TargetLowering::C_Memory: 9156 break; // Already handled. 9157 case TargetLowering::C_Address: 9158 break; // Silence warning. 9159 case TargetLowering::C_Unknown: 9160 assert(false && "Unexpected unknown constraint"); 9161 } 9162 9163 // Indirect output manifest as stores. Record output chains. 9164 if (OpInfo.isIndirect) { 9165 const Value *Ptr = OpInfo.CallOperandVal; 9166 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9167 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9168 MachinePointerInfo(Ptr)); 9169 OutChains.push_back(Store); 9170 } else { 9171 // generate CopyFromRegs to associated registers. 9172 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9173 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9174 for (const SDValue &V : Val->op_values()) 9175 handleRegAssign(V); 9176 } else 9177 handleRegAssign(Val); 9178 } 9179 } 9180 } 9181 9182 // Set results. 9183 if (!ResultValues.empty()) { 9184 assert(CurResultType == ResultTypes.end() && 9185 "Mismatch in number of ResultTypes"); 9186 assert(ResultValues.size() == ResultTypes.size() && 9187 "Mismatch in number of output operands in asm result"); 9188 9189 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9190 DAG.getVTList(ResultVTs), ResultValues); 9191 setValue(&Call, V); 9192 } 9193 9194 // Collect store chains. 9195 if (!OutChains.empty()) 9196 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9197 9198 if (EmitEHLabels) { 9199 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9200 } 9201 9202 // Only Update Root if inline assembly has a memory effect. 9203 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9204 EmitEHLabels) 9205 DAG.setRoot(Chain); 9206 } 9207 9208 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9209 const Twine &Message) { 9210 LLVMContext &Ctx = *DAG.getContext(); 9211 Ctx.emitError(&Call, Message); 9212 9213 // Make sure we leave the DAG in a valid state 9214 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9215 SmallVector<EVT, 1> ValueVTs; 9216 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9217 9218 if (ValueVTs.empty()) 9219 return; 9220 9221 SmallVector<SDValue, 1> Ops; 9222 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9223 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9224 9225 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9226 } 9227 9228 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9229 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9230 MVT::Other, getRoot(), 9231 getValue(I.getArgOperand(0)), 9232 DAG.getSrcValue(I.getArgOperand(0)))); 9233 } 9234 9235 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9236 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9237 const DataLayout &DL = DAG.getDataLayout(); 9238 SDValue V = DAG.getVAArg( 9239 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9240 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9241 DL.getABITypeAlign(I.getType()).value()); 9242 DAG.setRoot(V.getValue(1)); 9243 9244 if (I.getType()->isPointerTy()) 9245 V = DAG.getPtrExtOrTrunc( 9246 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9247 setValue(&I, V); 9248 } 9249 9250 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9251 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9252 MVT::Other, getRoot(), 9253 getValue(I.getArgOperand(0)), 9254 DAG.getSrcValue(I.getArgOperand(0)))); 9255 } 9256 9257 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9258 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9259 MVT::Other, getRoot(), 9260 getValue(I.getArgOperand(0)), 9261 getValue(I.getArgOperand(1)), 9262 DAG.getSrcValue(I.getArgOperand(0)), 9263 DAG.getSrcValue(I.getArgOperand(1)))); 9264 } 9265 9266 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9267 const Instruction &I, 9268 SDValue Op) { 9269 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9270 if (!Range) 9271 return Op; 9272 9273 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9274 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9275 return Op; 9276 9277 APInt Lo = CR.getUnsignedMin(); 9278 if (!Lo.isMinValue()) 9279 return Op; 9280 9281 APInt Hi = CR.getUnsignedMax(); 9282 unsigned Bits = std::max(Hi.getActiveBits(), 9283 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9284 9285 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9286 9287 SDLoc SL = getCurSDLoc(); 9288 9289 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9290 DAG.getValueType(SmallVT)); 9291 unsigned NumVals = Op.getNode()->getNumValues(); 9292 if (NumVals == 1) 9293 return ZExt; 9294 9295 SmallVector<SDValue, 4> Ops; 9296 9297 Ops.push_back(ZExt); 9298 for (unsigned I = 1; I != NumVals; ++I) 9299 Ops.push_back(Op.getValue(I)); 9300 9301 return DAG.getMergeValues(Ops, SL); 9302 } 9303 9304 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9305 /// the call being lowered. 9306 /// 9307 /// This is a helper for lowering intrinsics that follow a target calling 9308 /// convention or require stack pointer adjustment. Only a subset of the 9309 /// intrinsic's operands need to participate in the calling convention. 9310 void SelectionDAGBuilder::populateCallLoweringInfo( 9311 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9312 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9313 bool IsPatchPoint) { 9314 TargetLowering::ArgListTy Args; 9315 Args.reserve(NumArgs); 9316 9317 // Populate the argument list. 9318 // Attributes for args start at offset 1, after the return attribute. 9319 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9320 ArgI != ArgE; ++ArgI) { 9321 const Value *V = Call->getOperand(ArgI); 9322 9323 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9324 9325 TargetLowering::ArgListEntry Entry; 9326 Entry.Node = getValue(V); 9327 Entry.Ty = V->getType(); 9328 Entry.setAttributes(Call, ArgI); 9329 Args.push_back(Entry); 9330 } 9331 9332 CLI.setDebugLoc(getCurSDLoc()) 9333 .setChain(getRoot()) 9334 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9335 .setDiscardResult(Call->use_empty()) 9336 .setIsPatchPoint(IsPatchPoint) 9337 .setIsPreallocated( 9338 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9339 } 9340 9341 /// Add a stack map intrinsic call's live variable operands to a stackmap 9342 /// or patchpoint target node's operand list. 9343 /// 9344 /// Constants are converted to TargetConstants purely as an optimization to 9345 /// avoid constant materialization and register allocation. 9346 /// 9347 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9348 /// generate addess computation nodes, and so FinalizeISel can convert the 9349 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9350 /// address materialization and register allocation, but may also be required 9351 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9352 /// alloca in the entry block, then the runtime may assume that the alloca's 9353 /// StackMap location can be read immediately after compilation and that the 9354 /// location is valid at any point during execution (this is similar to the 9355 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9356 /// only available in a register, then the runtime would need to trap when 9357 /// execution reaches the StackMap in order to read the alloca's location. 9358 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9359 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9360 SelectionDAGBuilder &Builder) { 9361 SelectionDAG &DAG = Builder.DAG; 9362 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9363 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9364 9365 // Things on the stack are pointer-typed, meaning that they are already 9366 // legal and can be emitted directly to target nodes. 9367 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9368 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9369 } else { 9370 // Otherwise emit a target independent node to be legalised. 9371 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9372 } 9373 } 9374 } 9375 9376 /// Lower llvm.experimental.stackmap. 9377 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9378 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9379 // [live variables...]) 9380 9381 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9382 9383 SDValue Chain, InFlag, Callee; 9384 SmallVector<SDValue, 32> Ops; 9385 9386 SDLoc DL = getCurSDLoc(); 9387 Callee = getValue(CI.getCalledOperand()); 9388 9389 // The stackmap intrinsic only records the live variables (the arguments 9390 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9391 // intrinsic, this won't be lowered to a function call. This means we don't 9392 // have to worry about calling conventions and target specific lowering code. 9393 // Instead we perform the call lowering right here. 9394 // 9395 // chain, flag = CALLSEQ_START(chain, 0, 0) 9396 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9397 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9398 // 9399 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9400 InFlag = Chain.getValue(1); 9401 9402 // Add the STACKMAP operands, starting with DAG house-keeping. 9403 Ops.push_back(Chain); 9404 Ops.push_back(InFlag); 9405 9406 // Add the <id>, <numShadowBytes> operands. 9407 // 9408 // These do not require legalisation, and can be emitted directly to target 9409 // constant nodes. 9410 SDValue ID = getValue(CI.getArgOperand(0)); 9411 assert(ID.getValueType() == MVT::i64); 9412 SDValue IDConst = DAG.getTargetConstant( 9413 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9414 Ops.push_back(IDConst); 9415 9416 SDValue Shad = getValue(CI.getArgOperand(1)); 9417 assert(Shad.getValueType() == MVT::i32); 9418 SDValue ShadConst = DAG.getTargetConstant( 9419 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9420 Ops.push_back(ShadConst); 9421 9422 // Add the live variables. 9423 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9424 9425 // Create the STACKMAP node. 9426 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9427 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9428 InFlag = Chain.getValue(1); 9429 9430 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL); 9431 9432 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9433 9434 // Set the root to the target-lowered call chain. 9435 DAG.setRoot(Chain); 9436 9437 // Inform the Frame Information that we have a stackmap in this function. 9438 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9439 } 9440 9441 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9442 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9443 const BasicBlock *EHPadBB) { 9444 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9445 // i32 <numBytes>, 9446 // i8* <target>, 9447 // i32 <numArgs>, 9448 // [Args...], 9449 // [live variables...]) 9450 9451 CallingConv::ID CC = CB.getCallingConv(); 9452 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9453 bool HasDef = !CB.getType()->isVoidTy(); 9454 SDLoc dl = getCurSDLoc(); 9455 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9456 9457 // Handle immediate and symbolic callees. 9458 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9459 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9460 /*isTarget=*/true); 9461 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9462 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9463 SDLoc(SymbolicCallee), 9464 SymbolicCallee->getValueType(0)); 9465 9466 // Get the real number of arguments participating in the call <numArgs> 9467 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9468 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9469 9470 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9471 // Intrinsics include all meta-operands up to but not including CC. 9472 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9473 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9474 "Not enough arguments provided to the patchpoint intrinsic"); 9475 9476 // For AnyRegCC the arguments are lowered later on manually. 9477 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9478 Type *ReturnTy = 9479 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9480 9481 TargetLowering::CallLoweringInfo CLI(DAG); 9482 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9483 ReturnTy, true); 9484 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9485 9486 SDNode *CallEnd = Result.second.getNode(); 9487 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9488 CallEnd = CallEnd->getOperand(0).getNode(); 9489 9490 /// Get a call instruction from the call sequence chain. 9491 /// Tail calls are not allowed. 9492 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9493 "Expected a callseq node."); 9494 SDNode *Call = CallEnd->getOperand(0).getNode(); 9495 bool HasGlue = Call->getGluedNode(); 9496 9497 // Replace the target specific call node with the patchable intrinsic. 9498 SmallVector<SDValue, 8> Ops; 9499 9500 // Push the chain. 9501 Ops.push_back(*(Call->op_begin())); 9502 9503 // Optionally, push the glue (if any). 9504 if (HasGlue) 9505 Ops.push_back(*(Call->op_end() - 1)); 9506 9507 // Push the register mask info. 9508 if (HasGlue) 9509 Ops.push_back(*(Call->op_end() - 2)); 9510 else 9511 Ops.push_back(*(Call->op_end() - 1)); 9512 9513 // Add the <id> and <numBytes> constants. 9514 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9515 Ops.push_back(DAG.getTargetConstant( 9516 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9517 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9518 Ops.push_back(DAG.getTargetConstant( 9519 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9520 MVT::i32)); 9521 9522 // Add the callee. 9523 Ops.push_back(Callee); 9524 9525 // Adjust <numArgs> to account for any arguments that have been passed on the 9526 // stack instead. 9527 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9528 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9529 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9530 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9531 9532 // Add the calling convention 9533 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9534 9535 // Add the arguments we omitted previously. The register allocator should 9536 // place these in any free register. 9537 if (IsAnyRegCC) 9538 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9539 Ops.push_back(getValue(CB.getArgOperand(i))); 9540 9541 // Push the arguments from the call instruction. 9542 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9543 Ops.append(Call->op_begin() + 2, e); 9544 9545 // Push live variables for the stack map. 9546 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9547 9548 SDVTList NodeTys; 9549 if (IsAnyRegCC && HasDef) { 9550 // Create the return types based on the intrinsic definition 9551 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9552 SmallVector<EVT, 3> ValueVTs; 9553 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9554 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9555 9556 // There is always a chain and a glue type at the end 9557 ValueVTs.push_back(MVT::Other); 9558 ValueVTs.push_back(MVT::Glue); 9559 NodeTys = DAG.getVTList(ValueVTs); 9560 } else 9561 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9562 9563 // Replace the target specific call node with a PATCHPOINT node. 9564 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9565 9566 // Update the NodeMap. 9567 if (HasDef) { 9568 if (IsAnyRegCC) 9569 setValue(&CB, SDValue(PPV.getNode(), 0)); 9570 else 9571 setValue(&CB, Result.first); 9572 } 9573 9574 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9575 // call sequence. Furthermore the location of the chain and glue can change 9576 // when the AnyReg calling convention is used and the intrinsic returns a 9577 // value. 9578 if (IsAnyRegCC && HasDef) { 9579 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9580 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9581 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9582 } else 9583 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9584 DAG.DeleteNode(Call); 9585 9586 // Inform the Frame Information that we have a patchpoint in this function. 9587 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9588 } 9589 9590 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9591 unsigned Intrinsic) { 9592 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9593 SDValue Op1 = getValue(I.getArgOperand(0)); 9594 SDValue Op2; 9595 if (I.arg_size() > 1) 9596 Op2 = getValue(I.getArgOperand(1)); 9597 SDLoc dl = getCurSDLoc(); 9598 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9599 SDValue Res; 9600 SDNodeFlags SDFlags; 9601 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9602 SDFlags.copyFMF(*FPMO); 9603 9604 switch (Intrinsic) { 9605 case Intrinsic::vector_reduce_fadd: 9606 if (SDFlags.hasAllowReassociation()) 9607 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9608 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9609 SDFlags); 9610 else 9611 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9612 break; 9613 case Intrinsic::vector_reduce_fmul: 9614 if (SDFlags.hasAllowReassociation()) 9615 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9616 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9617 SDFlags); 9618 else 9619 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9620 break; 9621 case Intrinsic::vector_reduce_add: 9622 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9623 break; 9624 case Intrinsic::vector_reduce_mul: 9625 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9626 break; 9627 case Intrinsic::vector_reduce_and: 9628 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9629 break; 9630 case Intrinsic::vector_reduce_or: 9631 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9632 break; 9633 case Intrinsic::vector_reduce_xor: 9634 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9635 break; 9636 case Intrinsic::vector_reduce_smax: 9637 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9638 break; 9639 case Intrinsic::vector_reduce_smin: 9640 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9641 break; 9642 case Intrinsic::vector_reduce_umax: 9643 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9644 break; 9645 case Intrinsic::vector_reduce_umin: 9646 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9647 break; 9648 case Intrinsic::vector_reduce_fmax: 9649 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9650 break; 9651 case Intrinsic::vector_reduce_fmin: 9652 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9653 break; 9654 default: 9655 llvm_unreachable("Unhandled vector reduce intrinsic"); 9656 } 9657 setValue(&I, Res); 9658 } 9659 9660 /// Returns an AttributeList representing the attributes applied to the return 9661 /// value of the given call. 9662 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9663 SmallVector<Attribute::AttrKind, 2> Attrs; 9664 if (CLI.RetSExt) 9665 Attrs.push_back(Attribute::SExt); 9666 if (CLI.RetZExt) 9667 Attrs.push_back(Attribute::ZExt); 9668 if (CLI.IsInReg) 9669 Attrs.push_back(Attribute::InReg); 9670 9671 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9672 Attrs); 9673 } 9674 9675 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9676 /// implementation, which just calls LowerCall. 9677 /// FIXME: When all targets are 9678 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9679 std::pair<SDValue, SDValue> 9680 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9681 // Handle the incoming return values from the call. 9682 CLI.Ins.clear(); 9683 Type *OrigRetTy = CLI.RetTy; 9684 SmallVector<EVT, 4> RetTys; 9685 SmallVector<uint64_t, 4> Offsets; 9686 auto &DL = CLI.DAG.getDataLayout(); 9687 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9688 9689 if (CLI.IsPostTypeLegalization) { 9690 // If we are lowering a libcall after legalization, split the return type. 9691 SmallVector<EVT, 4> OldRetTys; 9692 SmallVector<uint64_t, 4> OldOffsets; 9693 RetTys.swap(OldRetTys); 9694 Offsets.swap(OldOffsets); 9695 9696 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9697 EVT RetVT = OldRetTys[i]; 9698 uint64_t Offset = OldOffsets[i]; 9699 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9700 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9701 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9702 RetTys.append(NumRegs, RegisterVT); 9703 for (unsigned j = 0; j != NumRegs; ++j) 9704 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9705 } 9706 } 9707 9708 SmallVector<ISD::OutputArg, 4> Outs; 9709 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9710 9711 bool CanLowerReturn = 9712 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9713 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9714 9715 SDValue DemoteStackSlot; 9716 int DemoteStackIdx = -100; 9717 if (!CanLowerReturn) { 9718 // FIXME: equivalent assert? 9719 // assert(!CS.hasInAllocaArgument() && 9720 // "sret demotion is incompatible with inalloca"); 9721 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9722 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9723 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9724 DemoteStackIdx = 9725 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9726 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9727 DL.getAllocaAddrSpace()); 9728 9729 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9730 ArgListEntry Entry; 9731 Entry.Node = DemoteStackSlot; 9732 Entry.Ty = StackSlotPtrType; 9733 Entry.IsSExt = false; 9734 Entry.IsZExt = false; 9735 Entry.IsInReg = false; 9736 Entry.IsSRet = true; 9737 Entry.IsNest = false; 9738 Entry.IsByVal = false; 9739 Entry.IsByRef = false; 9740 Entry.IsReturned = false; 9741 Entry.IsSwiftSelf = false; 9742 Entry.IsSwiftAsync = false; 9743 Entry.IsSwiftError = false; 9744 Entry.IsCFGuardTarget = false; 9745 Entry.Alignment = Alignment; 9746 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9747 CLI.NumFixedArgs += 1; 9748 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9749 9750 // sret demotion isn't compatible with tail-calls, since the sret argument 9751 // points into the callers stack frame. 9752 CLI.IsTailCall = false; 9753 } else { 9754 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9755 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9756 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9757 ISD::ArgFlagsTy Flags; 9758 if (NeedsRegBlock) { 9759 Flags.setInConsecutiveRegs(); 9760 if (I == RetTys.size() - 1) 9761 Flags.setInConsecutiveRegsLast(); 9762 } 9763 EVT VT = RetTys[I]; 9764 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9765 CLI.CallConv, VT); 9766 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9767 CLI.CallConv, VT); 9768 for (unsigned i = 0; i != NumRegs; ++i) { 9769 ISD::InputArg MyFlags; 9770 MyFlags.Flags = Flags; 9771 MyFlags.VT = RegisterVT; 9772 MyFlags.ArgVT = VT; 9773 MyFlags.Used = CLI.IsReturnValueUsed; 9774 if (CLI.RetTy->isPointerTy()) { 9775 MyFlags.Flags.setPointer(); 9776 MyFlags.Flags.setPointerAddrSpace( 9777 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9778 } 9779 if (CLI.RetSExt) 9780 MyFlags.Flags.setSExt(); 9781 if (CLI.RetZExt) 9782 MyFlags.Flags.setZExt(); 9783 if (CLI.IsInReg) 9784 MyFlags.Flags.setInReg(); 9785 CLI.Ins.push_back(MyFlags); 9786 } 9787 } 9788 } 9789 9790 // We push in swifterror return as the last element of CLI.Ins. 9791 ArgListTy &Args = CLI.getArgs(); 9792 if (supportSwiftError()) { 9793 for (const ArgListEntry &Arg : Args) { 9794 if (Arg.IsSwiftError) { 9795 ISD::InputArg MyFlags; 9796 MyFlags.VT = getPointerTy(DL); 9797 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9798 MyFlags.Flags.setSwiftError(); 9799 CLI.Ins.push_back(MyFlags); 9800 } 9801 } 9802 } 9803 9804 // Handle all of the outgoing arguments. 9805 CLI.Outs.clear(); 9806 CLI.OutVals.clear(); 9807 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9808 SmallVector<EVT, 4> ValueVTs; 9809 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9810 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9811 Type *FinalType = Args[i].Ty; 9812 if (Args[i].IsByVal) 9813 FinalType = Args[i].IndirectType; 9814 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9815 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 9816 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9817 ++Value) { 9818 EVT VT = ValueVTs[Value]; 9819 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9820 SDValue Op = SDValue(Args[i].Node.getNode(), 9821 Args[i].Node.getResNo() + Value); 9822 ISD::ArgFlagsTy Flags; 9823 9824 // Certain targets (such as MIPS), may have a different ABI alignment 9825 // for a type depending on the context. Give the target a chance to 9826 // specify the alignment it wants. 9827 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9828 Flags.setOrigAlign(OriginalAlignment); 9829 9830 if (Args[i].Ty->isPointerTy()) { 9831 Flags.setPointer(); 9832 Flags.setPointerAddrSpace( 9833 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9834 } 9835 if (Args[i].IsZExt) 9836 Flags.setZExt(); 9837 if (Args[i].IsSExt) 9838 Flags.setSExt(); 9839 if (Args[i].IsInReg) { 9840 // If we are using vectorcall calling convention, a structure that is 9841 // passed InReg - is surely an HVA 9842 if (CLI.CallConv == CallingConv::X86_VectorCall && 9843 isa<StructType>(FinalType)) { 9844 // The first value of a structure is marked 9845 if (0 == Value) 9846 Flags.setHvaStart(); 9847 Flags.setHva(); 9848 } 9849 // Set InReg Flag 9850 Flags.setInReg(); 9851 } 9852 if (Args[i].IsSRet) 9853 Flags.setSRet(); 9854 if (Args[i].IsSwiftSelf) 9855 Flags.setSwiftSelf(); 9856 if (Args[i].IsSwiftAsync) 9857 Flags.setSwiftAsync(); 9858 if (Args[i].IsSwiftError) 9859 Flags.setSwiftError(); 9860 if (Args[i].IsCFGuardTarget) 9861 Flags.setCFGuardTarget(); 9862 if (Args[i].IsByVal) 9863 Flags.setByVal(); 9864 if (Args[i].IsByRef) 9865 Flags.setByRef(); 9866 if (Args[i].IsPreallocated) { 9867 Flags.setPreallocated(); 9868 // Set the byval flag for CCAssignFn callbacks that don't know about 9869 // preallocated. This way we can know how many bytes we should've 9870 // allocated and how many bytes a callee cleanup function will pop. If 9871 // we port preallocated to more targets, we'll have to add custom 9872 // preallocated handling in the various CC lowering callbacks. 9873 Flags.setByVal(); 9874 } 9875 if (Args[i].IsInAlloca) { 9876 Flags.setInAlloca(); 9877 // Set the byval flag for CCAssignFn callbacks that don't know about 9878 // inalloca. This way we can know how many bytes we should've allocated 9879 // and how many bytes a callee cleanup function will pop. If we port 9880 // inalloca to more targets, we'll have to add custom inalloca handling 9881 // in the various CC lowering callbacks. 9882 Flags.setByVal(); 9883 } 9884 Align MemAlign; 9885 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9886 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 9887 Flags.setByValSize(FrameSize); 9888 9889 // info is not there but there are cases it cannot get right. 9890 if (auto MA = Args[i].Alignment) 9891 MemAlign = *MA; 9892 else 9893 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 9894 } else if (auto MA = Args[i].Alignment) { 9895 MemAlign = *MA; 9896 } else { 9897 MemAlign = OriginalAlignment; 9898 } 9899 Flags.setMemAlign(MemAlign); 9900 if (Args[i].IsNest) 9901 Flags.setNest(); 9902 if (NeedsRegBlock) 9903 Flags.setInConsecutiveRegs(); 9904 9905 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9906 CLI.CallConv, VT); 9907 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9908 CLI.CallConv, VT); 9909 SmallVector<SDValue, 4> Parts(NumParts); 9910 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9911 9912 if (Args[i].IsSExt) 9913 ExtendKind = ISD::SIGN_EXTEND; 9914 else if (Args[i].IsZExt) 9915 ExtendKind = ISD::ZERO_EXTEND; 9916 9917 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9918 // for now. 9919 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9920 CanLowerReturn) { 9921 assert((CLI.RetTy == Args[i].Ty || 9922 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9923 CLI.RetTy->getPointerAddressSpace() == 9924 Args[i].Ty->getPointerAddressSpace())) && 9925 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9926 // Before passing 'returned' to the target lowering code, ensure that 9927 // either the register MVT and the actual EVT are the same size or that 9928 // the return value and argument are extended in the same way; in these 9929 // cases it's safe to pass the argument register value unchanged as the 9930 // return register value (although it's at the target's option whether 9931 // to do so) 9932 // TODO: allow code generation to take advantage of partially preserved 9933 // registers rather than clobbering the entire register when the 9934 // parameter extension method is not compatible with the return 9935 // extension method 9936 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9937 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9938 CLI.RetZExt == Args[i].IsZExt)) 9939 Flags.setReturned(); 9940 } 9941 9942 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9943 CLI.CallConv, ExtendKind); 9944 9945 for (unsigned j = 0; j != NumParts; ++j) { 9946 // if it isn't first piece, alignment must be 1 9947 // For scalable vectors the scalable part is currently handled 9948 // by individual targets, so we just use the known minimum size here. 9949 ISD::OutputArg MyFlags( 9950 Flags, Parts[j].getValueType().getSimpleVT(), VT, 9951 i < CLI.NumFixedArgs, i, 9952 j * Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9953 if (NumParts > 1 && j == 0) 9954 MyFlags.Flags.setSplit(); 9955 else if (j != 0) { 9956 MyFlags.Flags.setOrigAlign(Align(1)); 9957 if (j == NumParts - 1) 9958 MyFlags.Flags.setSplitEnd(); 9959 } 9960 9961 CLI.Outs.push_back(MyFlags); 9962 CLI.OutVals.push_back(Parts[j]); 9963 } 9964 9965 if (NeedsRegBlock && Value == NumValues - 1) 9966 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9967 } 9968 } 9969 9970 SmallVector<SDValue, 4> InVals; 9971 CLI.Chain = LowerCall(CLI, InVals); 9972 9973 // Update CLI.InVals to use outside of this function. 9974 CLI.InVals = InVals; 9975 9976 // Verify that the target's LowerCall behaved as expected. 9977 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9978 "LowerCall didn't return a valid chain!"); 9979 assert((!CLI.IsTailCall || InVals.empty()) && 9980 "LowerCall emitted a return value for a tail call!"); 9981 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9982 "LowerCall didn't emit the correct number of values!"); 9983 9984 // For a tail call, the return value is merely live-out and there aren't 9985 // any nodes in the DAG representing it. Return a special value to 9986 // indicate that a tail call has been emitted and no more Instructions 9987 // should be processed in the current block. 9988 if (CLI.IsTailCall) { 9989 CLI.DAG.setRoot(CLI.Chain); 9990 return std::make_pair(SDValue(), SDValue()); 9991 } 9992 9993 #ifndef NDEBUG 9994 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9995 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9996 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9997 "LowerCall emitted a value with the wrong type!"); 9998 } 9999 #endif 10000 10001 SmallVector<SDValue, 4> ReturnValues; 10002 if (!CanLowerReturn) { 10003 // The instruction result is the result of loading from the 10004 // hidden sret parameter. 10005 SmallVector<EVT, 1> PVTs; 10006 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10007 10008 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10009 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10010 EVT PtrVT = PVTs[0]; 10011 10012 unsigned NumValues = RetTys.size(); 10013 ReturnValues.resize(NumValues); 10014 SmallVector<SDValue, 4> Chains(NumValues); 10015 10016 // An aggregate return value cannot wrap around the address space, so 10017 // offsets to its parts don't wrap either. 10018 SDNodeFlags Flags; 10019 Flags.setNoUnsignedWrap(true); 10020 10021 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10022 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10023 for (unsigned i = 0; i < NumValues; ++i) { 10024 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10025 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10026 PtrVT), Flags); 10027 SDValue L = CLI.DAG.getLoad( 10028 RetTys[i], CLI.DL, CLI.Chain, Add, 10029 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10030 DemoteStackIdx, Offsets[i]), 10031 HiddenSRetAlign); 10032 ReturnValues[i] = L; 10033 Chains[i] = L.getValue(1); 10034 } 10035 10036 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10037 } else { 10038 // Collect the legal value parts into potentially illegal values 10039 // that correspond to the original function's return values. 10040 Optional<ISD::NodeType> AssertOp; 10041 if (CLI.RetSExt) 10042 AssertOp = ISD::AssertSext; 10043 else if (CLI.RetZExt) 10044 AssertOp = ISD::AssertZext; 10045 unsigned CurReg = 0; 10046 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10047 EVT VT = RetTys[I]; 10048 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10049 CLI.CallConv, VT); 10050 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10051 CLI.CallConv, VT); 10052 10053 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10054 NumRegs, RegisterVT, VT, nullptr, 10055 CLI.CallConv, AssertOp)); 10056 CurReg += NumRegs; 10057 } 10058 10059 // For a function returning void, there is no return value. We can't create 10060 // such a node, so we just return a null return value in that case. In 10061 // that case, nothing will actually look at the value. 10062 if (ReturnValues.empty()) 10063 return std::make_pair(SDValue(), CLI.Chain); 10064 } 10065 10066 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10067 CLI.DAG.getVTList(RetTys), ReturnValues); 10068 return std::make_pair(Res, CLI.Chain); 10069 } 10070 10071 /// Places new result values for the node in Results (their number 10072 /// and types must exactly match those of the original return values of 10073 /// the node), or leaves Results empty, which indicates that the node is not 10074 /// to be custom lowered after all. 10075 void TargetLowering::LowerOperationWrapper(SDNode *N, 10076 SmallVectorImpl<SDValue> &Results, 10077 SelectionDAG &DAG) const { 10078 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10079 10080 if (!Res.getNode()) 10081 return; 10082 10083 // If the original node has one result, take the return value from 10084 // LowerOperation as is. It might not be result number 0. 10085 if (N->getNumValues() == 1) { 10086 Results.push_back(Res); 10087 return; 10088 } 10089 10090 // If the original node has multiple results, then the return node should 10091 // have the same number of results. 10092 assert((N->getNumValues() == Res->getNumValues()) && 10093 "Lowering returned the wrong number of results!"); 10094 10095 // Places new result values base on N result number. 10096 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10097 Results.push_back(Res.getValue(I)); 10098 } 10099 10100 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10101 llvm_unreachable("LowerOperation not implemented for this target!"); 10102 } 10103 10104 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10105 unsigned Reg, 10106 ISD::NodeType ExtendType) { 10107 SDValue Op = getNonRegisterValue(V); 10108 assert((Op.getOpcode() != ISD::CopyFromReg || 10109 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10110 "Copy from a reg to the same reg!"); 10111 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10112 10113 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10114 // If this is an InlineAsm we have to match the registers required, not the 10115 // notional registers required by the type. 10116 10117 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10118 None); // This is not an ABI copy. 10119 SDValue Chain = DAG.getEntryNode(); 10120 10121 if (ExtendType == ISD::ANY_EXTEND) { 10122 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10123 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10124 ExtendType = PreferredExtendIt->second; 10125 } 10126 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10127 PendingExports.push_back(Chain); 10128 } 10129 10130 #include "llvm/CodeGen/SelectionDAGISel.h" 10131 10132 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10133 /// entry block, return true. This includes arguments used by switches, since 10134 /// the switch may expand into multiple basic blocks. 10135 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10136 // With FastISel active, we may be splitting blocks, so force creation 10137 // of virtual registers for all non-dead arguments. 10138 if (FastISel) 10139 return A->use_empty(); 10140 10141 const BasicBlock &Entry = A->getParent()->front(); 10142 for (const User *U : A->users()) 10143 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10144 return false; // Use not in entry block. 10145 10146 return true; 10147 } 10148 10149 using ArgCopyElisionMapTy = 10150 DenseMap<const Argument *, 10151 std::pair<const AllocaInst *, const StoreInst *>>; 10152 10153 /// Scan the entry block of the function in FuncInfo for arguments that look 10154 /// like copies into a local alloca. Record any copied arguments in 10155 /// ArgCopyElisionCandidates. 10156 static void 10157 findArgumentCopyElisionCandidates(const DataLayout &DL, 10158 FunctionLoweringInfo *FuncInfo, 10159 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10160 // Record the state of every static alloca used in the entry block. Argument 10161 // allocas are all used in the entry block, so we need approximately as many 10162 // entries as we have arguments. 10163 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10164 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10165 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10166 StaticAllocas.reserve(NumArgs * 2); 10167 10168 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10169 if (!V) 10170 return nullptr; 10171 V = V->stripPointerCasts(); 10172 const auto *AI = dyn_cast<AllocaInst>(V); 10173 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10174 return nullptr; 10175 auto Iter = StaticAllocas.insert({AI, Unknown}); 10176 return &Iter.first->second; 10177 }; 10178 10179 // Look for stores of arguments to static allocas. Look through bitcasts and 10180 // GEPs to handle type coercions, as long as the alloca is fully initialized 10181 // by the store. Any non-store use of an alloca escapes it and any subsequent 10182 // unanalyzed store might write it. 10183 // FIXME: Handle structs initialized with multiple stores. 10184 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10185 // Look for stores, and handle non-store uses conservatively. 10186 const auto *SI = dyn_cast<StoreInst>(&I); 10187 if (!SI) { 10188 // We will look through cast uses, so ignore them completely. 10189 if (I.isCast()) 10190 continue; 10191 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10192 // to allocas. 10193 if (I.isDebugOrPseudoInst()) 10194 continue; 10195 // This is an unknown instruction. Assume it escapes or writes to all 10196 // static alloca operands. 10197 for (const Use &U : I.operands()) { 10198 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10199 *Info = StaticAllocaInfo::Clobbered; 10200 } 10201 continue; 10202 } 10203 10204 // If the stored value is a static alloca, mark it as escaped. 10205 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10206 *Info = StaticAllocaInfo::Clobbered; 10207 10208 // Check if the destination is a static alloca. 10209 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10210 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10211 if (!Info) 10212 continue; 10213 const AllocaInst *AI = cast<AllocaInst>(Dst); 10214 10215 // Skip allocas that have been initialized or clobbered. 10216 if (*Info != StaticAllocaInfo::Unknown) 10217 continue; 10218 10219 // Check if the stored value is an argument, and that this store fully 10220 // initializes the alloca. 10221 // If the argument type has padding bits we can't directly forward a pointer 10222 // as the upper bits may contain garbage. 10223 // Don't elide copies from the same argument twice. 10224 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10225 const auto *Arg = dyn_cast<Argument>(Val); 10226 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10227 Arg->getType()->isEmptyTy() || 10228 DL.getTypeStoreSize(Arg->getType()) != 10229 DL.getTypeAllocSize(AI->getAllocatedType()) || 10230 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10231 ArgCopyElisionCandidates.count(Arg)) { 10232 *Info = StaticAllocaInfo::Clobbered; 10233 continue; 10234 } 10235 10236 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10237 << '\n'); 10238 10239 // Mark this alloca and store for argument copy elision. 10240 *Info = StaticAllocaInfo::Elidable; 10241 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10242 10243 // Stop scanning if we've seen all arguments. This will happen early in -O0 10244 // builds, which is useful, because -O0 builds have large entry blocks and 10245 // many allocas. 10246 if (ArgCopyElisionCandidates.size() == NumArgs) 10247 break; 10248 } 10249 } 10250 10251 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10252 /// ArgVal is a load from a suitable fixed stack object. 10253 static void tryToElideArgumentCopy( 10254 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10255 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10256 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10257 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10258 SDValue ArgVal, bool &ArgHasUses) { 10259 // Check if this is a load from a fixed stack object. 10260 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10261 if (!LNode) 10262 return; 10263 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10264 if (!FINode) 10265 return; 10266 10267 // Check that the fixed stack object is the right size and alignment. 10268 // Look at the alignment that the user wrote on the alloca instead of looking 10269 // at the stack object. 10270 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10271 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10272 const AllocaInst *AI = ArgCopyIter->second.first; 10273 int FixedIndex = FINode->getIndex(); 10274 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10275 int OldIndex = AllocaIndex; 10276 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10277 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10278 LLVM_DEBUG( 10279 dbgs() << " argument copy elision failed due to bad fixed stack " 10280 "object size\n"); 10281 return; 10282 } 10283 Align RequiredAlignment = AI->getAlign(); 10284 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10285 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10286 "greater than stack argument alignment (" 10287 << DebugStr(RequiredAlignment) << " vs " 10288 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10289 return; 10290 } 10291 10292 // Perform the elision. Delete the old stack object and replace its only use 10293 // in the variable info map. Mark the stack object as mutable. 10294 LLVM_DEBUG({ 10295 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10296 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10297 << '\n'; 10298 }); 10299 MFI.RemoveStackObject(OldIndex); 10300 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10301 AllocaIndex = FixedIndex; 10302 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10303 Chains.push_back(ArgVal.getValue(1)); 10304 10305 // Avoid emitting code for the store implementing the copy. 10306 const StoreInst *SI = ArgCopyIter->second.second; 10307 ElidedArgCopyInstrs.insert(SI); 10308 10309 // Check for uses of the argument again so that we can avoid exporting ArgVal 10310 // if it is't used by anything other than the store. 10311 for (const Value *U : Arg.users()) { 10312 if (U != SI) { 10313 ArgHasUses = true; 10314 break; 10315 } 10316 } 10317 } 10318 10319 void SelectionDAGISel::LowerArguments(const Function &F) { 10320 SelectionDAG &DAG = SDB->DAG; 10321 SDLoc dl = SDB->getCurSDLoc(); 10322 const DataLayout &DL = DAG.getDataLayout(); 10323 SmallVector<ISD::InputArg, 16> Ins; 10324 10325 // In Naked functions we aren't going to save any registers. 10326 if (F.hasFnAttribute(Attribute::Naked)) 10327 return; 10328 10329 if (!FuncInfo->CanLowerReturn) { 10330 // Put in an sret pointer parameter before all the other parameters. 10331 SmallVector<EVT, 1> ValueVTs; 10332 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10333 F.getReturnType()->getPointerTo( 10334 DAG.getDataLayout().getAllocaAddrSpace()), 10335 ValueVTs); 10336 10337 // NOTE: Assuming that a pointer will never break down to more than one VT 10338 // or one register. 10339 ISD::ArgFlagsTy Flags; 10340 Flags.setSRet(); 10341 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10342 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10343 ISD::InputArg::NoArgIndex, 0); 10344 Ins.push_back(RetArg); 10345 } 10346 10347 // Look for stores of arguments to static allocas. Mark such arguments with a 10348 // flag to ask the target to give us the memory location of that argument if 10349 // available. 10350 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10351 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10352 ArgCopyElisionCandidates); 10353 10354 // Set up the incoming argument description vector. 10355 for (const Argument &Arg : F.args()) { 10356 unsigned ArgNo = Arg.getArgNo(); 10357 SmallVector<EVT, 4> ValueVTs; 10358 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10359 bool isArgValueUsed = !Arg.use_empty(); 10360 unsigned PartBase = 0; 10361 Type *FinalType = Arg.getType(); 10362 if (Arg.hasAttribute(Attribute::ByVal)) 10363 FinalType = Arg.getParamByValType(); 10364 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10365 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10366 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10367 Value != NumValues; ++Value) { 10368 EVT VT = ValueVTs[Value]; 10369 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10370 ISD::ArgFlagsTy Flags; 10371 10372 10373 if (Arg.getType()->isPointerTy()) { 10374 Flags.setPointer(); 10375 Flags.setPointerAddrSpace( 10376 cast<PointerType>(Arg.getType())->getAddressSpace()); 10377 } 10378 if (Arg.hasAttribute(Attribute::ZExt)) 10379 Flags.setZExt(); 10380 if (Arg.hasAttribute(Attribute::SExt)) 10381 Flags.setSExt(); 10382 if (Arg.hasAttribute(Attribute::InReg)) { 10383 // If we are using vectorcall calling convention, a structure that is 10384 // passed InReg - is surely an HVA 10385 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10386 isa<StructType>(Arg.getType())) { 10387 // The first value of a structure is marked 10388 if (0 == Value) 10389 Flags.setHvaStart(); 10390 Flags.setHva(); 10391 } 10392 // Set InReg Flag 10393 Flags.setInReg(); 10394 } 10395 if (Arg.hasAttribute(Attribute::StructRet)) 10396 Flags.setSRet(); 10397 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10398 Flags.setSwiftSelf(); 10399 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10400 Flags.setSwiftAsync(); 10401 if (Arg.hasAttribute(Attribute::SwiftError)) 10402 Flags.setSwiftError(); 10403 if (Arg.hasAttribute(Attribute::ByVal)) 10404 Flags.setByVal(); 10405 if (Arg.hasAttribute(Attribute::ByRef)) 10406 Flags.setByRef(); 10407 if (Arg.hasAttribute(Attribute::InAlloca)) { 10408 Flags.setInAlloca(); 10409 // Set the byval flag for CCAssignFn callbacks that don't know about 10410 // inalloca. This way we can know how many bytes we should've allocated 10411 // and how many bytes a callee cleanup function will pop. If we port 10412 // inalloca to more targets, we'll have to add custom inalloca handling 10413 // in the various CC lowering callbacks. 10414 Flags.setByVal(); 10415 } 10416 if (Arg.hasAttribute(Attribute::Preallocated)) { 10417 Flags.setPreallocated(); 10418 // Set the byval flag for CCAssignFn callbacks that don't know about 10419 // preallocated. This way we can know how many bytes we should've 10420 // allocated and how many bytes a callee cleanup function will pop. If 10421 // we port preallocated to more targets, we'll have to add custom 10422 // preallocated handling in the various CC lowering callbacks. 10423 Flags.setByVal(); 10424 } 10425 10426 // Certain targets (such as MIPS), may have a different ABI alignment 10427 // for a type depending on the context. Give the target a chance to 10428 // specify the alignment it wants. 10429 const Align OriginalAlignment( 10430 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10431 Flags.setOrigAlign(OriginalAlignment); 10432 10433 Align MemAlign; 10434 Type *ArgMemTy = nullptr; 10435 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10436 Flags.isByRef()) { 10437 if (!ArgMemTy) 10438 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10439 10440 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10441 10442 // For in-memory arguments, size and alignment should be passed from FE. 10443 // BE will guess if this info is not there but there are cases it cannot 10444 // get right. 10445 if (auto ParamAlign = Arg.getParamStackAlign()) 10446 MemAlign = *ParamAlign; 10447 else if ((ParamAlign = Arg.getParamAlign())) 10448 MemAlign = *ParamAlign; 10449 else 10450 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10451 if (Flags.isByRef()) 10452 Flags.setByRefSize(MemSize); 10453 else 10454 Flags.setByValSize(MemSize); 10455 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10456 MemAlign = *ParamAlign; 10457 } else { 10458 MemAlign = OriginalAlignment; 10459 } 10460 Flags.setMemAlign(MemAlign); 10461 10462 if (Arg.hasAttribute(Attribute::Nest)) 10463 Flags.setNest(); 10464 if (NeedsRegBlock) 10465 Flags.setInConsecutiveRegs(); 10466 if (ArgCopyElisionCandidates.count(&Arg)) 10467 Flags.setCopyElisionCandidate(); 10468 if (Arg.hasAttribute(Attribute::Returned)) 10469 Flags.setReturned(); 10470 10471 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10472 *CurDAG->getContext(), F.getCallingConv(), VT); 10473 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10474 *CurDAG->getContext(), F.getCallingConv(), VT); 10475 for (unsigned i = 0; i != NumRegs; ++i) { 10476 // For scalable vectors, use the minimum size; individual targets 10477 // are responsible for handling scalable vector arguments and 10478 // return values. 10479 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10480 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10481 if (NumRegs > 1 && i == 0) 10482 MyFlags.Flags.setSplit(); 10483 // if it isn't first piece, alignment must be 1 10484 else if (i > 0) { 10485 MyFlags.Flags.setOrigAlign(Align(1)); 10486 if (i == NumRegs - 1) 10487 MyFlags.Flags.setSplitEnd(); 10488 } 10489 Ins.push_back(MyFlags); 10490 } 10491 if (NeedsRegBlock && Value == NumValues - 1) 10492 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10493 PartBase += VT.getStoreSize().getKnownMinSize(); 10494 } 10495 } 10496 10497 // Call the target to set up the argument values. 10498 SmallVector<SDValue, 8> InVals; 10499 SDValue NewRoot = TLI->LowerFormalArguments( 10500 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10501 10502 // Verify that the target's LowerFormalArguments behaved as expected. 10503 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10504 "LowerFormalArguments didn't return a valid chain!"); 10505 assert(InVals.size() == Ins.size() && 10506 "LowerFormalArguments didn't emit the correct number of values!"); 10507 LLVM_DEBUG({ 10508 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10509 assert(InVals[i].getNode() && 10510 "LowerFormalArguments emitted a null value!"); 10511 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10512 "LowerFormalArguments emitted a value with the wrong type!"); 10513 } 10514 }); 10515 10516 // Update the DAG with the new chain value resulting from argument lowering. 10517 DAG.setRoot(NewRoot); 10518 10519 // Set up the argument values. 10520 unsigned i = 0; 10521 if (!FuncInfo->CanLowerReturn) { 10522 // Create a virtual register for the sret pointer, and put in a copy 10523 // from the sret argument into it. 10524 SmallVector<EVT, 1> ValueVTs; 10525 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10526 F.getReturnType()->getPointerTo( 10527 DAG.getDataLayout().getAllocaAddrSpace()), 10528 ValueVTs); 10529 MVT VT = ValueVTs[0].getSimpleVT(); 10530 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10531 Optional<ISD::NodeType> AssertOp; 10532 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10533 nullptr, F.getCallingConv(), AssertOp); 10534 10535 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10536 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10537 Register SRetReg = 10538 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10539 FuncInfo->DemoteRegister = SRetReg; 10540 NewRoot = 10541 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10542 DAG.setRoot(NewRoot); 10543 10544 // i indexes lowered arguments. Bump it past the hidden sret argument. 10545 ++i; 10546 } 10547 10548 SmallVector<SDValue, 4> Chains; 10549 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10550 for (const Argument &Arg : F.args()) { 10551 SmallVector<SDValue, 4> ArgValues; 10552 SmallVector<EVT, 4> ValueVTs; 10553 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10554 unsigned NumValues = ValueVTs.size(); 10555 if (NumValues == 0) 10556 continue; 10557 10558 bool ArgHasUses = !Arg.use_empty(); 10559 10560 // Elide the copying store if the target loaded this argument from a 10561 // suitable fixed stack object. 10562 if (Ins[i].Flags.isCopyElisionCandidate()) { 10563 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10564 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10565 InVals[i], ArgHasUses); 10566 } 10567 10568 // If this argument is unused then remember its value. It is used to generate 10569 // debugging information. 10570 bool isSwiftErrorArg = 10571 TLI->supportSwiftError() && 10572 Arg.hasAttribute(Attribute::SwiftError); 10573 if (!ArgHasUses && !isSwiftErrorArg) { 10574 SDB->setUnusedArgValue(&Arg, InVals[i]); 10575 10576 // Also remember any frame index for use in FastISel. 10577 if (FrameIndexSDNode *FI = 10578 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10579 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10580 } 10581 10582 for (unsigned Val = 0; Val != NumValues; ++Val) { 10583 EVT VT = ValueVTs[Val]; 10584 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10585 F.getCallingConv(), VT); 10586 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10587 *CurDAG->getContext(), F.getCallingConv(), VT); 10588 10589 // Even an apparent 'unused' swifterror argument needs to be returned. So 10590 // we do generate a copy for it that can be used on return from the 10591 // function. 10592 if (ArgHasUses || isSwiftErrorArg) { 10593 Optional<ISD::NodeType> AssertOp; 10594 if (Arg.hasAttribute(Attribute::SExt)) 10595 AssertOp = ISD::AssertSext; 10596 else if (Arg.hasAttribute(Attribute::ZExt)) 10597 AssertOp = ISD::AssertZext; 10598 10599 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10600 PartVT, VT, nullptr, 10601 F.getCallingConv(), AssertOp)); 10602 } 10603 10604 i += NumParts; 10605 } 10606 10607 // We don't need to do anything else for unused arguments. 10608 if (ArgValues.empty()) 10609 continue; 10610 10611 // Note down frame index. 10612 if (FrameIndexSDNode *FI = 10613 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10614 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10615 10616 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10617 SDB->getCurSDLoc()); 10618 10619 SDB->setValue(&Arg, Res); 10620 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10621 // We want to associate the argument with the frame index, among 10622 // involved operands, that correspond to the lowest address. The 10623 // getCopyFromParts function, called earlier, is swapping the order of 10624 // the operands to BUILD_PAIR depending on endianness. The result of 10625 // that swapping is that the least significant bits of the argument will 10626 // be in the first operand of the BUILD_PAIR node, and the most 10627 // significant bits will be in the second operand. 10628 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10629 if (LoadSDNode *LNode = 10630 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10631 if (FrameIndexSDNode *FI = 10632 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10633 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10634 } 10635 10636 // Analyses past this point are naive and don't expect an assertion. 10637 if (Res.getOpcode() == ISD::AssertZext) 10638 Res = Res.getOperand(0); 10639 10640 // Update the SwiftErrorVRegDefMap. 10641 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10642 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10643 if (Register::isVirtualRegister(Reg)) 10644 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10645 Reg); 10646 } 10647 10648 // If this argument is live outside of the entry block, insert a copy from 10649 // wherever we got it to the vreg that other BB's will reference it as. 10650 if (Res.getOpcode() == ISD::CopyFromReg) { 10651 // If we can, though, try to skip creating an unnecessary vreg. 10652 // FIXME: This isn't very clean... it would be nice to make this more 10653 // general. 10654 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10655 if (Register::isVirtualRegister(Reg)) { 10656 FuncInfo->ValueMap[&Arg] = Reg; 10657 continue; 10658 } 10659 } 10660 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10661 FuncInfo->InitializeRegForValue(&Arg); 10662 SDB->CopyToExportRegsIfNeeded(&Arg); 10663 } 10664 } 10665 10666 if (!Chains.empty()) { 10667 Chains.push_back(NewRoot); 10668 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10669 } 10670 10671 DAG.setRoot(NewRoot); 10672 10673 assert(i == InVals.size() && "Argument register count mismatch!"); 10674 10675 // If any argument copy elisions occurred and we have debug info, update the 10676 // stale frame indices used in the dbg.declare variable info table. 10677 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10678 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10679 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10680 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10681 if (I != ArgCopyElisionFrameIndexMap.end()) 10682 VI.Slot = I->second; 10683 } 10684 } 10685 10686 // Finally, if the target has anything special to do, allow it to do so. 10687 emitFunctionEntryCode(); 10688 } 10689 10690 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10691 /// ensure constants are generated when needed. Remember the virtual registers 10692 /// that need to be added to the Machine PHI nodes as input. We cannot just 10693 /// directly add them, because expansion might result in multiple MBB's for one 10694 /// BB. As such, the start of the BB might correspond to a different MBB than 10695 /// the end. 10696 void 10697 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10698 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10699 const Instruction *TI = LLVMBB->getTerminator(); 10700 10701 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10702 10703 // Check PHI nodes in successors that expect a value to be available from this 10704 // block. 10705 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10706 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10707 if (!isa<PHINode>(SuccBB->begin())) continue; 10708 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10709 10710 // If this terminator has multiple identical successors (common for 10711 // switches), only handle each succ once. 10712 if (!SuccsHandled.insert(SuccMBB).second) 10713 continue; 10714 10715 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10716 10717 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10718 // nodes and Machine PHI nodes, but the incoming operands have not been 10719 // emitted yet. 10720 for (const PHINode &PN : SuccBB->phis()) { 10721 // Ignore dead phi's. 10722 if (PN.use_empty()) 10723 continue; 10724 10725 // Skip empty types 10726 if (PN.getType()->isEmptyTy()) 10727 continue; 10728 10729 unsigned Reg; 10730 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10731 10732 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10733 unsigned &RegOut = ConstantsOut[C]; 10734 if (RegOut == 0) { 10735 RegOut = FuncInfo.CreateRegs(C); 10736 // We need to zero/sign extend ConstantInt phi operands to match 10737 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 10738 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 10739 if (auto *CI = dyn_cast<ConstantInt>(C)) 10740 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 10741 : ISD::ZERO_EXTEND; 10742 CopyValueToVirtualRegister(C, RegOut, ExtendType); 10743 } 10744 Reg = RegOut; 10745 } else { 10746 DenseMap<const Value *, Register>::iterator I = 10747 FuncInfo.ValueMap.find(PHIOp); 10748 if (I != FuncInfo.ValueMap.end()) 10749 Reg = I->second; 10750 else { 10751 assert(isa<AllocaInst>(PHIOp) && 10752 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10753 "Didn't codegen value into a register!??"); 10754 Reg = FuncInfo.CreateRegs(PHIOp); 10755 CopyValueToVirtualRegister(PHIOp, Reg); 10756 } 10757 } 10758 10759 // Remember that this register needs to added to the machine PHI node as 10760 // the input for this MBB. 10761 SmallVector<EVT, 4> ValueVTs; 10762 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10763 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10764 EVT VT = ValueVTs[vti]; 10765 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10766 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10767 FuncInfo.PHINodesToUpdate.push_back( 10768 std::make_pair(&*MBBI++, Reg + i)); 10769 Reg += NumRegisters; 10770 } 10771 } 10772 } 10773 10774 ConstantsOut.clear(); 10775 } 10776 10777 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10778 MachineFunction::iterator I(MBB); 10779 if (++I == FuncInfo.MF->end()) 10780 return nullptr; 10781 return &*I; 10782 } 10783 10784 /// During lowering new call nodes can be created (such as memset, etc.). 10785 /// Those will become new roots of the current DAG, but complications arise 10786 /// when they are tail calls. In such cases, the call lowering will update 10787 /// the root, but the builder still needs to know that a tail call has been 10788 /// lowered in order to avoid generating an additional return. 10789 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10790 // If the node is null, we do have a tail call. 10791 if (MaybeTC.getNode() != nullptr) 10792 DAG.setRoot(MaybeTC); 10793 else 10794 HasTailCall = true; 10795 } 10796 10797 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10798 MachineBasicBlock *SwitchMBB, 10799 MachineBasicBlock *DefaultMBB) { 10800 MachineFunction *CurMF = FuncInfo.MF; 10801 MachineBasicBlock *NextMBB = nullptr; 10802 MachineFunction::iterator BBI(W.MBB); 10803 if (++BBI != FuncInfo.MF->end()) 10804 NextMBB = &*BBI; 10805 10806 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10807 10808 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10809 10810 if (Size == 2 && W.MBB == SwitchMBB) { 10811 // If any two of the cases has the same destination, and if one value 10812 // is the same as the other, but has one bit unset that the other has set, 10813 // use bit manipulation to do two compares at once. For example: 10814 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10815 // TODO: This could be extended to merge any 2 cases in switches with 3 10816 // cases. 10817 // TODO: Handle cases where W.CaseBB != SwitchBB. 10818 CaseCluster &Small = *W.FirstCluster; 10819 CaseCluster &Big = *W.LastCluster; 10820 10821 if (Small.Low == Small.High && Big.Low == Big.High && 10822 Small.MBB == Big.MBB) { 10823 const APInt &SmallValue = Small.Low->getValue(); 10824 const APInt &BigValue = Big.Low->getValue(); 10825 10826 // Check that there is only one bit different. 10827 APInt CommonBit = BigValue ^ SmallValue; 10828 if (CommonBit.isPowerOf2()) { 10829 SDValue CondLHS = getValue(Cond); 10830 EVT VT = CondLHS.getValueType(); 10831 SDLoc DL = getCurSDLoc(); 10832 10833 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10834 DAG.getConstant(CommonBit, DL, VT)); 10835 SDValue Cond = DAG.getSetCC( 10836 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10837 ISD::SETEQ); 10838 10839 // Update successor info. 10840 // Both Small and Big will jump to Small.BB, so we sum up the 10841 // probabilities. 10842 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10843 if (BPI) 10844 addSuccessorWithProb( 10845 SwitchMBB, DefaultMBB, 10846 // The default destination is the first successor in IR. 10847 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10848 else 10849 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10850 10851 // Insert the true branch. 10852 SDValue BrCond = 10853 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10854 DAG.getBasicBlock(Small.MBB)); 10855 // Insert the false branch. 10856 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10857 DAG.getBasicBlock(DefaultMBB)); 10858 10859 DAG.setRoot(BrCond); 10860 return; 10861 } 10862 } 10863 } 10864 10865 if (TM.getOptLevel() != CodeGenOpt::None) { 10866 // Here, we order cases by probability so the most likely case will be 10867 // checked first. However, two clusters can have the same probability in 10868 // which case their relative ordering is non-deterministic. So we use Low 10869 // as a tie-breaker as clusters are guaranteed to never overlap. 10870 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10871 [](const CaseCluster &a, const CaseCluster &b) { 10872 return a.Prob != b.Prob ? 10873 a.Prob > b.Prob : 10874 a.Low->getValue().slt(b.Low->getValue()); 10875 }); 10876 10877 // Rearrange the case blocks so that the last one falls through if possible 10878 // without changing the order of probabilities. 10879 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10880 --I; 10881 if (I->Prob > W.LastCluster->Prob) 10882 break; 10883 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10884 std::swap(*I, *W.LastCluster); 10885 break; 10886 } 10887 } 10888 } 10889 10890 // Compute total probability. 10891 BranchProbability DefaultProb = W.DefaultProb; 10892 BranchProbability UnhandledProbs = DefaultProb; 10893 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10894 UnhandledProbs += I->Prob; 10895 10896 MachineBasicBlock *CurMBB = W.MBB; 10897 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10898 bool FallthroughUnreachable = false; 10899 MachineBasicBlock *Fallthrough; 10900 if (I == W.LastCluster) { 10901 // For the last cluster, fall through to the default destination. 10902 Fallthrough = DefaultMBB; 10903 FallthroughUnreachable = isa<UnreachableInst>( 10904 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10905 } else { 10906 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10907 CurMF->insert(BBI, Fallthrough); 10908 // Put Cond in a virtual register to make it available from the new blocks. 10909 ExportFromCurrentBlock(Cond); 10910 } 10911 UnhandledProbs -= I->Prob; 10912 10913 switch (I->Kind) { 10914 case CC_JumpTable: { 10915 // FIXME: Optimize away range check based on pivot comparisons. 10916 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10917 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10918 10919 // The jump block hasn't been inserted yet; insert it here. 10920 MachineBasicBlock *JumpMBB = JT->MBB; 10921 CurMF->insert(BBI, JumpMBB); 10922 10923 auto JumpProb = I->Prob; 10924 auto FallthroughProb = UnhandledProbs; 10925 10926 // If the default statement is a target of the jump table, we evenly 10927 // distribute the default probability to successors of CurMBB. Also 10928 // update the probability on the edge from JumpMBB to Fallthrough. 10929 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10930 SE = JumpMBB->succ_end(); 10931 SI != SE; ++SI) { 10932 if (*SI == DefaultMBB) { 10933 JumpProb += DefaultProb / 2; 10934 FallthroughProb -= DefaultProb / 2; 10935 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10936 JumpMBB->normalizeSuccProbs(); 10937 break; 10938 } 10939 } 10940 10941 if (FallthroughUnreachable) 10942 JTH->FallthroughUnreachable = true; 10943 10944 if (!JTH->FallthroughUnreachable) 10945 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10946 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10947 CurMBB->normalizeSuccProbs(); 10948 10949 // The jump table header will be inserted in our current block, do the 10950 // range check, and fall through to our fallthrough block. 10951 JTH->HeaderBB = CurMBB; 10952 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10953 10954 // If we're in the right place, emit the jump table header right now. 10955 if (CurMBB == SwitchMBB) { 10956 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10957 JTH->Emitted = true; 10958 } 10959 break; 10960 } 10961 case CC_BitTests: { 10962 // FIXME: Optimize away range check based on pivot comparisons. 10963 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10964 10965 // The bit test blocks haven't been inserted yet; insert them here. 10966 for (BitTestCase &BTC : BTB->Cases) 10967 CurMF->insert(BBI, BTC.ThisBB); 10968 10969 // Fill in fields of the BitTestBlock. 10970 BTB->Parent = CurMBB; 10971 BTB->Default = Fallthrough; 10972 10973 BTB->DefaultProb = UnhandledProbs; 10974 // If the cases in bit test don't form a contiguous range, we evenly 10975 // distribute the probability on the edge to Fallthrough to two 10976 // successors of CurMBB. 10977 if (!BTB->ContiguousRange) { 10978 BTB->Prob += DefaultProb / 2; 10979 BTB->DefaultProb -= DefaultProb / 2; 10980 } 10981 10982 if (FallthroughUnreachable) 10983 BTB->FallthroughUnreachable = true; 10984 10985 // If we're in the right place, emit the bit test header right now. 10986 if (CurMBB == SwitchMBB) { 10987 visitBitTestHeader(*BTB, SwitchMBB); 10988 BTB->Emitted = true; 10989 } 10990 break; 10991 } 10992 case CC_Range: { 10993 const Value *RHS, *LHS, *MHS; 10994 ISD::CondCode CC; 10995 if (I->Low == I->High) { 10996 // Check Cond == I->Low. 10997 CC = ISD::SETEQ; 10998 LHS = Cond; 10999 RHS=I->Low; 11000 MHS = nullptr; 11001 } else { 11002 // Check I->Low <= Cond <= I->High. 11003 CC = ISD::SETLE; 11004 LHS = I->Low; 11005 MHS = Cond; 11006 RHS = I->High; 11007 } 11008 11009 // If Fallthrough is unreachable, fold away the comparison. 11010 if (FallthroughUnreachable) 11011 CC = ISD::SETTRUE; 11012 11013 // The false probability is the sum of all unhandled cases. 11014 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11015 getCurSDLoc(), I->Prob, UnhandledProbs); 11016 11017 if (CurMBB == SwitchMBB) 11018 visitSwitchCase(CB, SwitchMBB); 11019 else 11020 SL->SwitchCases.push_back(CB); 11021 11022 break; 11023 } 11024 } 11025 CurMBB = Fallthrough; 11026 } 11027 } 11028 11029 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11030 CaseClusterIt First, 11031 CaseClusterIt Last) { 11032 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11033 if (X.Prob != CC.Prob) 11034 return X.Prob > CC.Prob; 11035 11036 // Ties are broken by comparing the case value. 11037 return X.Low->getValue().slt(CC.Low->getValue()); 11038 }); 11039 } 11040 11041 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11042 const SwitchWorkListItem &W, 11043 Value *Cond, 11044 MachineBasicBlock *SwitchMBB) { 11045 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11046 "Clusters not sorted?"); 11047 11048 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11049 11050 // Balance the tree based on branch probabilities to create a near-optimal (in 11051 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11052 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11053 CaseClusterIt LastLeft = W.FirstCluster; 11054 CaseClusterIt FirstRight = W.LastCluster; 11055 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11056 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11057 11058 // Move LastLeft and FirstRight towards each other from opposite directions to 11059 // find a partitioning of the clusters which balances the probability on both 11060 // sides. If LeftProb and RightProb are equal, alternate which side is 11061 // taken to ensure 0-probability nodes are distributed evenly. 11062 unsigned I = 0; 11063 while (LastLeft + 1 < FirstRight) { 11064 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11065 LeftProb += (++LastLeft)->Prob; 11066 else 11067 RightProb += (--FirstRight)->Prob; 11068 I++; 11069 } 11070 11071 while (true) { 11072 // Our binary search tree differs from a typical BST in that ours can have up 11073 // to three values in each leaf. The pivot selection above doesn't take that 11074 // into account, which means the tree might require more nodes and be less 11075 // efficient. We compensate for this here. 11076 11077 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11078 unsigned NumRight = W.LastCluster - FirstRight + 1; 11079 11080 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11081 // If one side has less than 3 clusters, and the other has more than 3, 11082 // consider taking a cluster from the other side. 11083 11084 if (NumLeft < NumRight) { 11085 // Consider moving the first cluster on the right to the left side. 11086 CaseCluster &CC = *FirstRight; 11087 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11088 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11089 if (LeftSideRank <= RightSideRank) { 11090 // Moving the cluster to the left does not demote it. 11091 ++LastLeft; 11092 ++FirstRight; 11093 continue; 11094 } 11095 } else { 11096 assert(NumRight < NumLeft); 11097 // Consider moving the last element on the left to the right side. 11098 CaseCluster &CC = *LastLeft; 11099 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11100 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11101 if (RightSideRank <= LeftSideRank) { 11102 // Moving the cluster to the right does not demot it. 11103 --LastLeft; 11104 --FirstRight; 11105 continue; 11106 } 11107 } 11108 } 11109 break; 11110 } 11111 11112 assert(LastLeft + 1 == FirstRight); 11113 assert(LastLeft >= W.FirstCluster); 11114 assert(FirstRight <= W.LastCluster); 11115 11116 // Use the first element on the right as pivot since we will make less-than 11117 // comparisons against it. 11118 CaseClusterIt PivotCluster = FirstRight; 11119 assert(PivotCluster > W.FirstCluster); 11120 assert(PivotCluster <= W.LastCluster); 11121 11122 CaseClusterIt FirstLeft = W.FirstCluster; 11123 CaseClusterIt LastRight = W.LastCluster; 11124 11125 const ConstantInt *Pivot = PivotCluster->Low; 11126 11127 // New blocks will be inserted immediately after the current one. 11128 MachineFunction::iterator BBI(W.MBB); 11129 ++BBI; 11130 11131 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11132 // we can branch to its destination directly if it's squeezed exactly in 11133 // between the known lower bound and Pivot - 1. 11134 MachineBasicBlock *LeftMBB; 11135 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11136 FirstLeft->Low == W.GE && 11137 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11138 LeftMBB = FirstLeft->MBB; 11139 } else { 11140 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11141 FuncInfo.MF->insert(BBI, LeftMBB); 11142 WorkList.push_back( 11143 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11144 // Put Cond in a virtual register to make it available from the new blocks. 11145 ExportFromCurrentBlock(Cond); 11146 } 11147 11148 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11149 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11150 // directly if RHS.High equals the current upper bound. 11151 MachineBasicBlock *RightMBB; 11152 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11153 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11154 RightMBB = FirstRight->MBB; 11155 } else { 11156 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11157 FuncInfo.MF->insert(BBI, RightMBB); 11158 WorkList.push_back( 11159 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11160 // Put Cond in a virtual register to make it available from the new blocks. 11161 ExportFromCurrentBlock(Cond); 11162 } 11163 11164 // Create the CaseBlock record that will be used to lower the branch. 11165 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11166 getCurSDLoc(), LeftProb, RightProb); 11167 11168 if (W.MBB == SwitchMBB) 11169 visitSwitchCase(CB, SwitchMBB); 11170 else 11171 SL->SwitchCases.push_back(CB); 11172 } 11173 11174 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11175 // from the swith statement. 11176 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11177 BranchProbability PeeledCaseProb) { 11178 if (PeeledCaseProb == BranchProbability::getOne()) 11179 return BranchProbability::getZero(); 11180 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11181 11182 uint32_t Numerator = CaseProb.getNumerator(); 11183 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11184 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11185 } 11186 11187 // Try to peel the top probability case if it exceeds the threshold. 11188 // Return current MachineBasicBlock for the switch statement if the peeling 11189 // does not occur. 11190 // If the peeling is performed, return the newly created MachineBasicBlock 11191 // for the peeled switch statement. Also update Clusters to remove the peeled 11192 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11193 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11194 const SwitchInst &SI, CaseClusterVector &Clusters, 11195 BranchProbability &PeeledCaseProb) { 11196 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11197 // Don't perform if there is only one cluster or optimizing for size. 11198 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11199 TM.getOptLevel() == CodeGenOpt::None || 11200 SwitchMBB->getParent()->getFunction().hasMinSize()) 11201 return SwitchMBB; 11202 11203 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11204 unsigned PeeledCaseIndex = 0; 11205 bool SwitchPeeled = false; 11206 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11207 CaseCluster &CC = Clusters[Index]; 11208 if (CC.Prob < TopCaseProb) 11209 continue; 11210 TopCaseProb = CC.Prob; 11211 PeeledCaseIndex = Index; 11212 SwitchPeeled = true; 11213 } 11214 if (!SwitchPeeled) 11215 return SwitchMBB; 11216 11217 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11218 << TopCaseProb << "\n"); 11219 11220 // Record the MBB for the peeled switch statement. 11221 MachineFunction::iterator BBI(SwitchMBB); 11222 ++BBI; 11223 MachineBasicBlock *PeeledSwitchMBB = 11224 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11225 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11226 11227 ExportFromCurrentBlock(SI.getCondition()); 11228 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11229 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11230 nullptr, nullptr, TopCaseProb.getCompl()}; 11231 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11232 11233 Clusters.erase(PeeledCaseIt); 11234 for (CaseCluster &CC : Clusters) { 11235 LLVM_DEBUG( 11236 dbgs() << "Scale the probablity for one cluster, before scaling: " 11237 << CC.Prob << "\n"); 11238 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11239 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11240 } 11241 PeeledCaseProb = TopCaseProb; 11242 return PeeledSwitchMBB; 11243 } 11244 11245 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11246 // Extract cases from the switch. 11247 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11248 CaseClusterVector Clusters; 11249 Clusters.reserve(SI.getNumCases()); 11250 for (auto I : SI.cases()) { 11251 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11252 const ConstantInt *CaseVal = I.getCaseValue(); 11253 BranchProbability Prob = 11254 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11255 : BranchProbability(1, SI.getNumCases() + 1); 11256 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11257 } 11258 11259 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11260 11261 // Cluster adjacent cases with the same destination. We do this at all 11262 // optimization levels because it's cheap to do and will make codegen faster 11263 // if there are many clusters. 11264 sortAndRangeify(Clusters); 11265 11266 // The branch probablity of the peeled case. 11267 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11268 MachineBasicBlock *PeeledSwitchMBB = 11269 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11270 11271 // If there is only the default destination, jump there directly. 11272 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11273 if (Clusters.empty()) { 11274 assert(PeeledSwitchMBB == SwitchMBB); 11275 SwitchMBB->addSuccessor(DefaultMBB); 11276 if (DefaultMBB != NextBlock(SwitchMBB)) { 11277 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11278 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11279 } 11280 return; 11281 } 11282 11283 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11284 SL->findBitTestClusters(Clusters, &SI); 11285 11286 LLVM_DEBUG({ 11287 dbgs() << "Case clusters: "; 11288 for (const CaseCluster &C : Clusters) { 11289 if (C.Kind == CC_JumpTable) 11290 dbgs() << "JT:"; 11291 if (C.Kind == CC_BitTests) 11292 dbgs() << "BT:"; 11293 11294 C.Low->getValue().print(dbgs(), true); 11295 if (C.Low != C.High) { 11296 dbgs() << '-'; 11297 C.High->getValue().print(dbgs(), true); 11298 } 11299 dbgs() << ' '; 11300 } 11301 dbgs() << '\n'; 11302 }); 11303 11304 assert(!Clusters.empty()); 11305 SwitchWorkList WorkList; 11306 CaseClusterIt First = Clusters.begin(); 11307 CaseClusterIt Last = Clusters.end() - 1; 11308 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11309 // Scale the branchprobability for DefaultMBB if the peel occurs and 11310 // DefaultMBB is not replaced. 11311 if (PeeledCaseProb != BranchProbability::getZero() && 11312 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11313 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11314 WorkList.push_back( 11315 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11316 11317 while (!WorkList.empty()) { 11318 SwitchWorkListItem W = WorkList.pop_back_val(); 11319 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11320 11321 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11322 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11323 // For optimized builds, lower large range as a balanced binary tree. 11324 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11325 continue; 11326 } 11327 11328 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11329 } 11330 } 11331 11332 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11333 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11334 auto DL = getCurSDLoc(); 11335 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11336 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11337 } 11338 11339 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11340 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11341 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11342 11343 SDLoc DL = getCurSDLoc(); 11344 SDValue V = getValue(I.getOperand(0)); 11345 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11346 11347 if (VT.isScalableVector()) { 11348 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11349 return; 11350 } 11351 11352 // Use VECTOR_SHUFFLE for the fixed-length vector 11353 // to maintain existing behavior. 11354 SmallVector<int, 8> Mask; 11355 unsigned NumElts = VT.getVectorMinNumElements(); 11356 for (unsigned i = 0; i != NumElts; ++i) 11357 Mask.push_back(NumElts - 1 - i); 11358 11359 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11360 } 11361 11362 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11363 SmallVector<EVT, 4> ValueVTs; 11364 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11365 ValueVTs); 11366 unsigned NumValues = ValueVTs.size(); 11367 if (NumValues == 0) return; 11368 11369 SmallVector<SDValue, 4> Values(NumValues); 11370 SDValue Op = getValue(I.getOperand(0)); 11371 11372 for (unsigned i = 0; i != NumValues; ++i) 11373 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11374 SDValue(Op.getNode(), Op.getResNo() + i)); 11375 11376 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11377 DAG.getVTList(ValueVTs), Values)); 11378 } 11379 11380 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11381 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11382 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11383 11384 SDLoc DL = getCurSDLoc(); 11385 SDValue V1 = getValue(I.getOperand(0)); 11386 SDValue V2 = getValue(I.getOperand(1)); 11387 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11388 11389 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11390 if (VT.isScalableVector()) { 11391 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11392 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11393 DAG.getConstant(Imm, DL, IdxVT))); 11394 return; 11395 } 11396 11397 unsigned NumElts = VT.getVectorNumElements(); 11398 11399 uint64_t Idx = (NumElts + Imm) % NumElts; 11400 11401 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11402 SmallVector<int, 8> Mask; 11403 for (unsigned i = 0; i < NumElts; ++i) 11404 Mask.push_back(Idx + i); 11405 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11406 } 11407