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 AssumptionCache *ac, 1030 const TargetLibraryInfo *li) { 1031 AA = aa; 1032 AC = ac; 1033 GFI = gfi; 1034 LibInfo = li; 1035 Context = DAG.getContext(); 1036 LPadToCallSiteMap.clear(); 1037 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1038 } 1039 1040 void SelectionDAGBuilder::clear() { 1041 NodeMap.clear(); 1042 UnusedArgNodeMap.clear(); 1043 PendingLoads.clear(); 1044 PendingExports.clear(); 1045 PendingConstrainedFP.clear(); 1046 PendingConstrainedFPStrict.clear(); 1047 CurInst = nullptr; 1048 HasTailCall = false; 1049 SDNodeOrder = LowestSDNodeOrder; 1050 StatepointLowering.clear(); 1051 } 1052 1053 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1054 DanglingDebugInfoMap.clear(); 1055 } 1056 1057 // Update DAG root to include dependencies on Pending chains. 1058 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1059 SDValue Root = DAG.getRoot(); 1060 1061 if (Pending.empty()) 1062 return Root; 1063 1064 // Add current root to PendingChains, unless we already indirectly 1065 // depend on it. 1066 if (Root.getOpcode() != ISD::EntryToken) { 1067 unsigned i = 0, e = Pending.size(); 1068 for (; i != e; ++i) { 1069 assert(Pending[i].getNode()->getNumOperands() > 1); 1070 if (Pending[i].getNode()->getOperand(0) == Root) 1071 break; // Don't add the root if we already indirectly depend on it. 1072 } 1073 1074 if (i == e) 1075 Pending.push_back(Root); 1076 } 1077 1078 if (Pending.size() == 1) 1079 Root = Pending[0]; 1080 else 1081 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1082 1083 DAG.setRoot(Root); 1084 Pending.clear(); 1085 return Root; 1086 } 1087 1088 SDValue SelectionDAGBuilder::getMemoryRoot() { 1089 return updateRoot(PendingLoads); 1090 } 1091 1092 SDValue SelectionDAGBuilder::getRoot() { 1093 // Chain up all pending constrained intrinsics together with all 1094 // pending loads, by simply appending them to PendingLoads and 1095 // then calling getMemoryRoot(). 1096 PendingLoads.reserve(PendingLoads.size() + 1097 PendingConstrainedFP.size() + 1098 PendingConstrainedFPStrict.size()); 1099 PendingLoads.append(PendingConstrainedFP.begin(), 1100 PendingConstrainedFP.end()); 1101 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1102 PendingConstrainedFPStrict.end()); 1103 PendingConstrainedFP.clear(); 1104 PendingConstrainedFPStrict.clear(); 1105 return getMemoryRoot(); 1106 } 1107 1108 SDValue SelectionDAGBuilder::getControlRoot() { 1109 // We need to emit pending fpexcept.strict constrained intrinsics, 1110 // so append them to the PendingExports list. 1111 PendingExports.append(PendingConstrainedFPStrict.begin(), 1112 PendingConstrainedFPStrict.end()); 1113 PendingConstrainedFPStrict.clear(); 1114 return updateRoot(PendingExports); 1115 } 1116 1117 void SelectionDAGBuilder::visit(const Instruction &I) { 1118 // Set up outgoing PHI node register values before emitting the terminator. 1119 if (I.isTerminator()) { 1120 HandlePHINodesInSuccessorBlocks(I.getParent()); 1121 } 1122 1123 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1124 if (!isa<DbgInfoIntrinsic>(I)) 1125 ++SDNodeOrder; 1126 1127 CurInst = &I; 1128 1129 // Set inserted listener only if required. 1130 bool NodeInserted = false; 1131 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1132 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1133 if (PCSectionsMD) { 1134 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1135 DAG, [&](SDNode *) { NodeInserted = true; }); 1136 } 1137 1138 visit(I.getOpcode(), I); 1139 1140 if (!I.isTerminator() && !HasTailCall && 1141 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1142 CopyToExportRegsIfNeeded(&I); 1143 1144 // Handle metadata. 1145 if (PCSectionsMD) { 1146 auto It = NodeMap.find(&I); 1147 if (It != NodeMap.end()) { 1148 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1149 } else if (NodeInserted) { 1150 // This should not happen; if it does, don't let it go unnoticed so we can 1151 // fix it. Relevant visit*() function is probably missing a setValue(). 1152 errs() << "warning: loosing !pcsections metadata [" 1153 << I.getModule()->getName() << "]\n"; 1154 LLVM_DEBUG(I.dump()); 1155 assert(false); 1156 } 1157 } 1158 1159 CurInst = nullptr; 1160 } 1161 1162 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1163 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1164 } 1165 1166 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1167 // Note: this doesn't use InstVisitor, because it has to work with 1168 // ConstantExpr's in addition to instructions. 1169 switch (Opcode) { 1170 default: llvm_unreachable("Unknown instruction type encountered!"); 1171 // Build the switch statement using the Instruction.def file. 1172 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1173 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1174 #include "llvm/IR/Instruction.def" 1175 } 1176 } 1177 1178 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1179 DebugLoc DL, unsigned Order) { 1180 // We treat variadic dbg_values differently at this stage. 1181 if (DI->hasArgList()) { 1182 // For variadic dbg_values we will now insert an undef. 1183 // FIXME: We can potentially recover these! 1184 SmallVector<SDDbgOperand, 2> Locs; 1185 for (const Value *V : DI->getValues()) { 1186 auto Undef = UndefValue::get(V->getType()); 1187 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1188 } 1189 SDDbgValue *SDV = DAG.getDbgValueList( 1190 DI->getVariable(), DI->getExpression(), Locs, {}, 1191 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1192 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1193 } else { 1194 // TODO: Dangling debug info will eventually either be resolved or produce 1195 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1196 // between the original dbg.value location and its resolved DBG_VALUE, 1197 // which we should ideally fill with an extra Undef DBG_VALUE. 1198 assert(DI->getNumVariableLocationOps() == 1 && 1199 "DbgValueInst without an ArgList should have a single location " 1200 "operand."); 1201 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1202 } 1203 } 1204 1205 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1206 const DIExpression *Expr) { 1207 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1208 const DbgValueInst *DI = DDI.getDI(); 1209 DIVariable *DanglingVariable = DI->getVariable(); 1210 DIExpression *DanglingExpr = DI->getExpression(); 1211 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1212 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1213 return true; 1214 } 1215 return false; 1216 }; 1217 1218 for (auto &DDIMI : DanglingDebugInfoMap) { 1219 DanglingDebugInfoVector &DDIV = DDIMI.second; 1220 1221 // If debug info is to be dropped, run it through final checks to see 1222 // whether it can be salvaged. 1223 for (auto &DDI : DDIV) 1224 if (isMatchingDbgValue(DDI)) 1225 salvageUnresolvedDbgValue(DDI); 1226 1227 erase_if(DDIV, isMatchingDbgValue); 1228 } 1229 } 1230 1231 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1232 // generate the debug data structures now that we've seen its definition. 1233 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1234 SDValue Val) { 1235 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1236 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1237 return; 1238 1239 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1240 for (auto &DDI : DDIV) { 1241 const DbgValueInst *DI = DDI.getDI(); 1242 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1243 assert(DI && "Ill-formed DanglingDebugInfo"); 1244 DebugLoc dl = DDI.getdl(); 1245 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1246 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1247 DILocalVariable *Variable = DI->getVariable(); 1248 DIExpression *Expr = DI->getExpression(); 1249 assert(Variable->isValidLocationForIntrinsic(dl) && 1250 "Expected inlined-at fields to agree"); 1251 SDDbgValue *SDV; 1252 if (Val.getNode()) { 1253 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1254 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1255 // we couldn't resolve it directly when examining the DbgValue intrinsic 1256 // in the first place we should not be more successful here). Unless we 1257 // have some test case that prove this to be correct we should avoid 1258 // calling EmitFuncArgumentDbgValue here. 1259 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, 1260 FuncArgumentDbgValueKind::Value, Val)) { 1261 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1262 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1263 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1264 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1265 // inserted after the definition of Val when emitting the instructions 1266 // after ISel. An alternative could be to teach 1267 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1268 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1269 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1270 << ValSDNodeOrder << "\n"); 1271 SDV = getDbgValue(Val, Variable, Expr, dl, 1272 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1273 DAG.AddDbgValue(SDV, false); 1274 } else 1275 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1276 << "in EmitFuncArgumentDbgValue\n"); 1277 } else { 1278 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1279 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1280 auto SDV = 1281 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1282 DAG.AddDbgValue(SDV, false); 1283 } 1284 } 1285 DDIV.clear(); 1286 } 1287 1288 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1289 // TODO: For the variadic implementation, instead of only checking the fail 1290 // state of `handleDebugValue`, we need know specifically which values were 1291 // invalid, so that we attempt to salvage only those values when processing 1292 // a DIArgList. 1293 assert(!DDI.getDI()->hasArgList() && 1294 "Not implemented for variadic dbg_values"); 1295 Value *V = DDI.getDI()->getValue(0); 1296 DILocalVariable *Var = DDI.getDI()->getVariable(); 1297 DIExpression *Expr = DDI.getDI()->getExpression(); 1298 DebugLoc DL = DDI.getdl(); 1299 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1300 unsigned SDOrder = DDI.getSDNodeOrder(); 1301 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1302 // that DW_OP_stack_value is desired. 1303 assert(isa<DbgValueInst>(DDI.getDI())); 1304 bool StackValue = true; 1305 1306 // Can this Value can be encoded without any further work? 1307 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1308 return; 1309 1310 // Attempt to salvage back through as many instructions as possible. Bail if 1311 // a non-instruction is seen, such as a constant expression or global 1312 // variable. FIXME: Further work could recover those too. 1313 while (isa<Instruction>(V)) { 1314 Instruction &VAsInst = *cast<Instruction>(V); 1315 // Temporary "0", awaiting real implementation. 1316 SmallVector<uint64_t, 16> Ops; 1317 SmallVector<Value *, 4> AdditionalValues; 1318 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1319 AdditionalValues); 1320 // If we cannot salvage any further, and haven't yet found a suitable debug 1321 // expression, bail out. 1322 if (!V) 1323 break; 1324 1325 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1326 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1327 // here for variadic dbg_values, remove that condition. 1328 if (!AdditionalValues.empty()) 1329 break; 1330 1331 // New value and expr now represent this debuginfo. 1332 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1333 1334 // Some kind of simplification occurred: check whether the operand of the 1335 // salvaged debug expression can be encoded in this DAG. 1336 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1337 /*IsVariadic=*/false)) { 1338 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1339 << *DDI.getDI() << "\nBy stripping back to:\n " << *V); 1340 return; 1341 } 1342 } 1343 1344 // This was the final opportunity to salvage this debug information, and it 1345 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1346 // any earlier variable location. 1347 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1348 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1349 DAG.AddDbgValue(SDV, false); 1350 1351 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << *DDI.getDI() 1352 << "\n"); 1353 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1354 << "\n"); 1355 } 1356 1357 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1358 DILocalVariable *Var, 1359 DIExpression *Expr, DebugLoc dl, 1360 DebugLoc InstDL, unsigned Order, 1361 bool IsVariadic) { 1362 if (Values.empty()) 1363 return true; 1364 SmallVector<SDDbgOperand> LocationOps; 1365 SmallVector<SDNode *> Dependencies; 1366 for (const Value *V : Values) { 1367 // Constant value. 1368 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1369 isa<ConstantPointerNull>(V)) { 1370 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1371 continue; 1372 } 1373 1374 // Look through IntToPtr constants. 1375 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1376 if (CE->getOpcode() == Instruction::IntToPtr) { 1377 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1378 continue; 1379 } 1380 1381 // If the Value is a frame index, we can create a FrameIndex debug value 1382 // without relying on the DAG at all. 1383 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1384 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1385 if (SI != FuncInfo.StaticAllocaMap.end()) { 1386 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1387 continue; 1388 } 1389 } 1390 1391 // Do not use getValue() in here; we don't want to generate code at 1392 // this point if it hasn't been done yet. 1393 SDValue N = NodeMap[V]; 1394 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1395 N = UnusedArgNodeMap[V]; 1396 if (N.getNode()) { 1397 // Only emit func arg dbg value for non-variadic dbg.values for now. 1398 if (!IsVariadic && 1399 EmitFuncArgumentDbgValue(V, Var, Expr, dl, 1400 FuncArgumentDbgValueKind::Value, N)) 1401 return true; 1402 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1403 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1404 // describe stack slot locations. 1405 // 1406 // Consider "int x = 0; int *px = &x;". There are two kinds of 1407 // interesting debug values here after optimization: 1408 // 1409 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1410 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1411 // 1412 // Both describe the direct values of their associated variables. 1413 Dependencies.push_back(N.getNode()); 1414 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1415 continue; 1416 } 1417 LocationOps.emplace_back( 1418 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1419 continue; 1420 } 1421 1422 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1423 // Special rules apply for the first dbg.values of parameter variables in a 1424 // function. Identify them by the fact they reference Argument Values, that 1425 // they're parameters, and they are parameters of the current function. We 1426 // need to let them dangle until they get an SDNode. 1427 bool IsParamOfFunc = 1428 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1429 if (IsParamOfFunc) 1430 return false; 1431 1432 // The value is not used in this block yet (or it would have an SDNode). 1433 // We still want the value to appear for the user if possible -- if it has 1434 // an associated VReg, we can refer to that instead. 1435 auto VMI = FuncInfo.ValueMap.find(V); 1436 if (VMI != FuncInfo.ValueMap.end()) { 1437 unsigned Reg = VMI->second; 1438 // If this is a PHI node, it may be split up into several MI PHI nodes 1439 // (in FunctionLoweringInfo::set). 1440 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1441 V->getType(), None); 1442 if (RFV.occupiesMultipleRegs()) { 1443 // FIXME: We could potentially support variadic dbg_values here. 1444 if (IsVariadic) 1445 return false; 1446 unsigned Offset = 0; 1447 unsigned BitsToDescribe = 0; 1448 if (auto VarSize = Var->getSizeInBits()) 1449 BitsToDescribe = *VarSize; 1450 if (auto Fragment = Expr->getFragmentInfo()) 1451 BitsToDescribe = Fragment->SizeInBits; 1452 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1453 // Bail out if all bits are described already. 1454 if (Offset >= BitsToDescribe) 1455 break; 1456 // TODO: handle scalable vectors. 1457 unsigned RegisterSize = RegAndSize.second; 1458 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1459 ? BitsToDescribe - Offset 1460 : RegisterSize; 1461 auto FragmentExpr = DIExpression::createFragmentExpression( 1462 Expr, Offset, FragmentSize); 1463 if (!FragmentExpr) 1464 continue; 1465 SDDbgValue *SDV = DAG.getVRegDbgValue( 1466 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1467 DAG.AddDbgValue(SDV, false); 1468 Offset += RegisterSize; 1469 } 1470 return true; 1471 } 1472 // We can use simple vreg locations for variadic dbg_values as well. 1473 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1474 continue; 1475 } 1476 // We failed to create a SDDbgOperand for V. 1477 return false; 1478 } 1479 1480 // We have created a SDDbgOperand for each Value in Values. 1481 // Should use Order instead of SDNodeOrder? 1482 assert(!LocationOps.empty()); 1483 SDDbgValue *SDV = 1484 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1485 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1486 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1487 return true; 1488 } 1489 1490 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1491 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1492 for (auto &Pair : DanglingDebugInfoMap) 1493 for (auto &DDI : Pair.second) 1494 salvageUnresolvedDbgValue(DDI); 1495 clearDanglingDebugInfo(); 1496 } 1497 1498 /// getCopyFromRegs - If there was virtual register allocated for the value V 1499 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1500 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1501 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1502 SDValue Result; 1503 1504 if (It != FuncInfo.ValueMap.end()) { 1505 Register InReg = It->second; 1506 1507 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1508 DAG.getDataLayout(), InReg, Ty, 1509 None); // This is not an ABI copy. 1510 SDValue Chain = DAG.getEntryNode(); 1511 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1512 V); 1513 resolveDanglingDebugInfo(V, Result); 1514 } 1515 1516 return Result; 1517 } 1518 1519 /// getValue - Return an SDValue for the given Value. 1520 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1521 // If we already have an SDValue for this value, use it. It's important 1522 // to do this first, so that we don't create a CopyFromReg if we already 1523 // have a regular SDValue. 1524 SDValue &N = NodeMap[V]; 1525 if (N.getNode()) return N; 1526 1527 // If there's a virtual register allocated and initialized for this 1528 // value, use it. 1529 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1530 return copyFromReg; 1531 1532 // Otherwise create a new SDValue and remember it. 1533 SDValue Val = getValueImpl(V); 1534 NodeMap[V] = Val; 1535 resolveDanglingDebugInfo(V, Val); 1536 return Val; 1537 } 1538 1539 /// getNonRegisterValue - Return an SDValue for the given Value, but 1540 /// don't look in FuncInfo.ValueMap for a virtual register. 1541 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1542 // If we already have an SDValue for this value, use it. 1543 SDValue &N = NodeMap[V]; 1544 if (N.getNode()) { 1545 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1546 // Remove the debug location from the node as the node is about to be used 1547 // in a location which may differ from the original debug location. This 1548 // is relevant to Constant and ConstantFP nodes because they can appear 1549 // as constant expressions inside PHI nodes. 1550 N->setDebugLoc(DebugLoc()); 1551 } 1552 return N; 1553 } 1554 1555 // Otherwise create a new SDValue and remember it. 1556 SDValue Val = getValueImpl(V); 1557 NodeMap[V] = Val; 1558 resolveDanglingDebugInfo(V, Val); 1559 return Val; 1560 } 1561 1562 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1563 /// Create an SDValue for the given value. 1564 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1565 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1566 1567 if (const Constant *C = dyn_cast<Constant>(V)) { 1568 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1569 1570 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1571 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1572 1573 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1574 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1575 1576 if (isa<ConstantPointerNull>(C)) { 1577 unsigned AS = V->getType()->getPointerAddressSpace(); 1578 return DAG.getConstant(0, getCurSDLoc(), 1579 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1580 } 1581 1582 if (match(C, m_VScale(DAG.getDataLayout()))) 1583 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1584 1585 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1586 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1587 1588 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1589 return DAG.getUNDEF(VT); 1590 1591 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1592 visit(CE->getOpcode(), *CE); 1593 SDValue N1 = NodeMap[V]; 1594 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1595 return N1; 1596 } 1597 1598 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1599 SmallVector<SDValue, 4> Constants; 1600 for (const Use &U : C->operands()) { 1601 SDNode *Val = getValue(U).getNode(); 1602 // If the operand is an empty aggregate, there are no values. 1603 if (!Val) continue; 1604 // Add each leaf value from the operand to the Constants list 1605 // to form a flattened list of all the values. 1606 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1607 Constants.push_back(SDValue(Val, i)); 1608 } 1609 1610 return DAG.getMergeValues(Constants, getCurSDLoc()); 1611 } 1612 1613 if (const ConstantDataSequential *CDS = 1614 dyn_cast<ConstantDataSequential>(C)) { 1615 SmallVector<SDValue, 4> Ops; 1616 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1617 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1618 // Add each leaf value from the operand to the Constants list 1619 // to form a flattened list of all the values. 1620 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1621 Ops.push_back(SDValue(Val, i)); 1622 } 1623 1624 if (isa<ArrayType>(CDS->getType())) 1625 return DAG.getMergeValues(Ops, getCurSDLoc()); 1626 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1627 } 1628 1629 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1630 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1631 "Unknown struct or array constant!"); 1632 1633 SmallVector<EVT, 4> ValueVTs; 1634 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1635 unsigned NumElts = ValueVTs.size(); 1636 if (NumElts == 0) 1637 return SDValue(); // empty struct 1638 SmallVector<SDValue, 4> Constants(NumElts); 1639 for (unsigned i = 0; i != NumElts; ++i) { 1640 EVT EltVT = ValueVTs[i]; 1641 if (isa<UndefValue>(C)) 1642 Constants[i] = DAG.getUNDEF(EltVT); 1643 else if (EltVT.isFloatingPoint()) 1644 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1645 else 1646 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1647 } 1648 1649 return DAG.getMergeValues(Constants, getCurSDLoc()); 1650 } 1651 1652 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1653 return DAG.getBlockAddress(BA, VT); 1654 1655 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1656 return getValue(Equiv->getGlobalValue()); 1657 1658 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1659 return getValue(NC->getGlobalValue()); 1660 1661 VectorType *VecTy = cast<VectorType>(V->getType()); 1662 1663 // Now that we know the number and type of the elements, get that number of 1664 // elements into the Ops array based on what kind of constant it is. 1665 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1666 SmallVector<SDValue, 16> Ops; 1667 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1668 for (unsigned i = 0; i != NumElements; ++i) 1669 Ops.push_back(getValue(CV->getOperand(i))); 1670 1671 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1672 } 1673 1674 if (isa<ConstantAggregateZero>(C)) { 1675 EVT EltVT = 1676 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1677 1678 SDValue Op; 1679 if (EltVT.isFloatingPoint()) 1680 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1681 else 1682 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1683 1684 if (isa<ScalableVectorType>(VecTy)) 1685 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1686 1687 SmallVector<SDValue, 16> Ops; 1688 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1689 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1690 } 1691 1692 llvm_unreachable("Unknown vector constant"); 1693 } 1694 1695 // If this is a static alloca, generate it as the frameindex instead of 1696 // computation. 1697 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1698 DenseMap<const AllocaInst*, int>::iterator SI = 1699 FuncInfo.StaticAllocaMap.find(AI); 1700 if (SI != FuncInfo.StaticAllocaMap.end()) 1701 return DAG.getFrameIndex(SI->second, 1702 TLI.getFrameIndexTy(DAG.getDataLayout())); 1703 } 1704 1705 // If this is an instruction which fast-isel has deferred, select it now. 1706 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1707 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1708 1709 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1710 Inst->getType(), None); 1711 SDValue Chain = DAG.getEntryNode(); 1712 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1713 } 1714 1715 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1716 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1717 1718 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1719 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1720 1721 llvm_unreachable("Can't get register for value!"); 1722 } 1723 1724 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1725 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1726 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1727 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1728 bool IsSEH = isAsynchronousEHPersonality(Pers); 1729 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1730 if (!IsSEH) 1731 CatchPadMBB->setIsEHScopeEntry(); 1732 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1733 if (IsMSVCCXX || IsCoreCLR) 1734 CatchPadMBB->setIsEHFuncletEntry(); 1735 } 1736 1737 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1738 // Update machine-CFG edge. 1739 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1740 FuncInfo.MBB->addSuccessor(TargetMBB); 1741 TargetMBB->setIsEHCatchretTarget(true); 1742 DAG.getMachineFunction().setHasEHCatchret(true); 1743 1744 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1745 bool IsSEH = isAsynchronousEHPersonality(Pers); 1746 if (IsSEH) { 1747 // If this is not a fall-through branch or optimizations are switched off, 1748 // emit the branch. 1749 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1750 TM.getOptLevel() == CodeGenOpt::None) 1751 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1752 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1753 return; 1754 } 1755 1756 // Figure out the funclet membership for the catchret's successor. 1757 // This will be used by the FuncletLayout pass to determine how to order the 1758 // BB's. 1759 // A 'catchret' returns to the outer scope's color. 1760 Value *ParentPad = I.getCatchSwitchParentPad(); 1761 const BasicBlock *SuccessorColor; 1762 if (isa<ConstantTokenNone>(ParentPad)) 1763 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1764 else 1765 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1766 assert(SuccessorColor && "No parent funclet for catchret!"); 1767 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1768 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1769 1770 // Create the terminator node. 1771 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1772 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1773 DAG.getBasicBlock(SuccessorColorMBB)); 1774 DAG.setRoot(Ret); 1775 } 1776 1777 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1778 // Don't emit any special code for the cleanuppad instruction. It just marks 1779 // the start of an EH scope/funclet. 1780 FuncInfo.MBB->setIsEHScopeEntry(); 1781 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1782 if (Pers != EHPersonality::Wasm_CXX) { 1783 FuncInfo.MBB->setIsEHFuncletEntry(); 1784 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1785 } 1786 } 1787 1788 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1789 // not match, it is OK to add only the first unwind destination catchpad to the 1790 // successors, because there will be at least one invoke instruction within the 1791 // catch scope that points to the next unwind destination, if one exists, so 1792 // CFGSort cannot mess up with BB sorting order. 1793 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1794 // call within them, and catchpads only consisting of 'catch (...)' have a 1795 // '__cxa_end_catch' call within them, both of which generate invokes in case 1796 // the next unwind destination exists, i.e., the next unwind destination is not 1797 // the caller.) 1798 // 1799 // Having at most one EH pad successor is also simpler and helps later 1800 // transformations. 1801 // 1802 // For example, 1803 // current: 1804 // invoke void @foo to ... unwind label %catch.dispatch 1805 // catch.dispatch: 1806 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1807 // catch.start: 1808 // ... 1809 // ... in this BB or some other child BB dominated by this BB there will be an 1810 // invoke that points to 'next' BB as an unwind destination 1811 // 1812 // next: ; We don't need to add this to 'current' BB's successor 1813 // ... 1814 static void findWasmUnwindDestinations( 1815 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1816 BranchProbability Prob, 1817 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1818 &UnwindDests) { 1819 while (EHPadBB) { 1820 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1821 if (isa<CleanupPadInst>(Pad)) { 1822 // Stop on cleanup pads. 1823 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1824 UnwindDests.back().first->setIsEHScopeEntry(); 1825 break; 1826 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1827 // Add the catchpad handlers to the possible destinations. We don't 1828 // continue to the unwind destination of the catchswitch for wasm. 1829 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1830 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1831 UnwindDests.back().first->setIsEHScopeEntry(); 1832 } 1833 break; 1834 } else { 1835 continue; 1836 } 1837 } 1838 } 1839 1840 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1841 /// many places it could ultimately go. In the IR, we have a single unwind 1842 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1843 /// This function skips over imaginary basic blocks that hold catchswitch 1844 /// instructions, and finds all the "real" machine 1845 /// basic block destinations. As those destinations may not be successors of 1846 /// EHPadBB, here we also calculate the edge probability to those destinations. 1847 /// The passed-in Prob is the edge probability to EHPadBB. 1848 static void findUnwindDestinations( 1849 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1850 BranchProbability Prob, 1851 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1852 &UnwindDests) { 1853 EHPersonality Personality = 1854 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1855 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1856 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1857 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1858 bool IsSEH = isAsynchronousEHPersonality(Personality); 1859 1860 if (IsWasmCXX) { 1861 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1862 assert(UnwindDests.size() <= 1 && 1863 "There should be at most one unwind destination for wasm"); 1864 return; 1865 } 1866 1867 while (EHPadBB) { 1868 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1869 BasicBlock *NewEHPadBB = nullptr; 1870 if (isa<LandingPadInst>(Pad)) { 1871 // Stop on landingpads. They are not funclets. 1872 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1873 break; 1874 } else if (isa<CleanupPadInst>(Pad)) { 1875 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1876 // personalities. 1877 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1878 UnwindDests.back().first->setIsEHScopeEntry(); 1879 UnwindDests.back().first->setIsEHFuncletEntry(); 1880 break; 1881 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1882 // Add the catchpad handlers to the possible destinations. 1883 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1884 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1885 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1886 if (IsMSVCCXX || IsCoreCLR) 1887 UnwindDests.back().first->setIsEHFuncletEntry(); 1888 if (!IsSEH) 1889 UnwindDests.back().first->setIsEHScopeEntry(); 1890 } 1891 NewEHPadBB = CatchSwitch->getUnwindDest(); 1892 } else { 1893 continue; 1894 } 1895 1896 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1897 if (BPI && NewEHPadBB) 1898 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1899 EHPadBB = NewEHPadBB; 1900 } 1901 } 1902 1903 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1904 // Update successor info. 1905 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1906 auto UnwindDest = I.getUnwindDest(); 1907 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1908 BranchProbability UnwindDestProb = 1909 (BPI && UnwindDest) 1910 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1911 : BranchProbability::getZero(); 1912 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1913 for (auto &UnwindDest : UnwindDests) { 1914 UnwindDest.first->setIsEHPad(); 1915 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1916 } 1917 FuncInfo.MBB->normalizeSuccProbs(); 1918 1919 // Create the terminator node. 1920 SDValue Ret = 1921 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1922 DAG.setRoot(Ret); 1923 } 1924 1925 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1926 report_fatal_error("visitCatchSwitch not yet implemented!"); 1927 } 1928 1929 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1930 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1931 auto &DL = DAG.getDataLayout(); 1932 SDValue Chain = getControlRoot(); 1933 SmallVector<ISD::OutputArg, 8> Outs; 1934 SmallVector<SDValue, 8> OutVals; 1935 1936 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1937 // lower 1938 // 1939 // %val = call <ty> @llvm.experimental.deoptimize() 1940 // ret <ty> %val 1941 // 1942 // differently. 1943 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1944 LowerDeoptimizingReturn(); 1945 return; 1946 } 1947 1948 if (!FuncInfo.CanLowerReturn) { 1949 unsigned DemoteReg = FuncInfo.DemoteRegister; 1950 const Function *F = I.getParent()->getParent(); 1951 1952 // Emit a store of the return value through the virtual register. 1953 // Leave Outs empty so that LowerReturn won't try to load return 1954 // registers the usual way. 1955 SmallVector<EVT, 1> PtrValueVTs; 1956 ComputeValueVTs(TLI, DL, 1957 F->getReturnType()->getPointerTo( 1958 DAG.getDataLayout().getAllocaAddrSpace()), 1959 PtrValueVTs); 1960 1961 SDValue RetPtr = 1962 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 1963 SDValue RetOp = getValue(I.getOperand(0)); 1964 1965 SmallVector<EVT, 4> ValueVTs, MemVTs; 1966 SmallVector<uint64_t, 4> Offsets; 1967 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1968 &Offsets); 1969 unsigned NumValues = ValueVTs.size(); 1970 1971 SmallVector<SDValue, 4> Chains(NumValues); 1972 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1973 for (unsigned i = 0; i != NumValues; ++i) { 1974 // An aggregate return value cannot wrap around the address space, so 1975 // offsets to its parts don't wrap either. 1976 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1977 TypeSize::Fixed(Offsets[i])); 1978 1979 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1980 if (MemVTs[i] != ValueVTs[i]) 1981 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1982 Chains[i] = DAG.getStore( 1983 Chain, getCurSDLoc(), Val, 1984 // FIXME: better loc info would be nice. 1985 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1986 commonAlignment(BaseAlign, Offsets[i])); 1987 } 1988 1989 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1990 MVT::Other, Chains); 1991 } else if (I.getNumOperands() != 0) { 1992 SmallVector<EVT, 4> ValueVTs; 1993 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1994 unsigned NumValues = ValueVTs.size(); 1995 if (NumValues) { 1996 SDValue RetOp = getValue(I.getOperand(0)); 1997 1998 const Function *F = I.getParent()->getParent(); 1999 2000 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2001 I.getOperand(0)->getType(), F->getCallingConv(), 2002 /*IsVarArg*/ false, DL); 2003 2004 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2005 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2006 ExtendKind = ISD::SIGN_EXTEND; 2007 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2008 ExtendKind = ISD::ZERO_EXTEND; 2009 2010 LLVMContext &Context = F->getContext(); 2011 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2012 2013 for (unsigned j = 0; j != NumValues; ++j) { 2014 EVT VT = ValueVTs[j]; 2015 2016 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2017 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2018 2019 CallingConv::ID CC = F->getCallingConv(); 2020 2021 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2022 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2023 SmallVector<SDValue, 4> Parts(NumParts); 2024 getCopyToParts(DAG, getCurSDLoc(), 2025 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2026 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2027 2028 // 'inreg' on function refers to return value 2029 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2030 if (RetInReg) 2031 Flags.setInReg(); 2032 2033 if (I.getOperand(0)->getType()->isPointerTy()) { 2034 Flags.setPointer(); 2035 Flags.setPointerAddrSpace( 2036 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2037 } 2038 2039 if (NeedsRegBlock) { 2040 Flags.setInConsecutiveRegs(); 2041 if (j == NumValues - 1) 2042 Flags.setInConsecutiveRegsLast(); 2043 } 2044 2045 // Propagate extension type if any 2046 if (ExtendKind == ISD::SIGN_EXTEND) 2047 Flags.setSExt(); 2048 else if (ExtendKind == ISD::ZERO_EXTEND) 2049 Flags.setZExt(); 2050 2051 for (unsigned i = 0; i < NumParts; ++i) { 2052 Outs.push_back(ISD::OutputArg(Flags, 2053 Parts[i].getValueType().getSimpleVT(), 2054 VT, /*isfixed=*/true, 0, 0)); 2055 OutVals.push_back(Parts[i]); 2056 } 2057 } 2058 } 2059 } 2060 2061 // Push in swifterror virtual register as the last element of Outs. This makes 2062 // sure swifterror virtual register will be returned in the swifterror 2063 // physical register. 2064 const Function *F = I.getParent()->getParent(); 2065 if (TLI.supportSwiftError() && 2066 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2067 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2068 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2069 Flags.setSwiftError(); 2070 Outs.push_back(ISD::OutputArg( 2071 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2072 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2073 // Create SDNode for the swifterror virtual register. 2074 OutVals.push_back( 2075 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2076 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2077 EVT(TLI.getPointerTy(DL)))); 2078 } 2079 2080 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2081 CallingConv::ID CallConv = 2082 DAG.getMachineFunction().getFunction().getCallingConv(); 2083 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2084 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2085 2086 // Verify that the target's LowerReturn behaved as expected. 2087 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2088 "LowerReturn didn't return a valid chain!"); 2089 2090 // Update the DAG with the new chain value resulting from return lowering. 2091 DAG.setRoot(Chain); 2092 } 2093 2094 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2095 /// created for it, emit nodes to copy the value into the virtual 2096 /// registers. 2097 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2098 // Skip empty types 2099 if (V->getType()->isEmptyTy()) 2100 return; 2101 2102 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2103 if (VMI != FuncInfo.ValueMap.end()) { 2104 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2105 CopyValueToVirtualRegister(V, VMI->second); 2106 } 2107 } 2108 2109 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2110 /// the current basic block, add it to ValueMap now so that we'll get a 2111 /// CopyTo/FromReg. 2112 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2113 // No need to export constants. 2114 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2115 2116 // Already exported? 2117 if (FuncInfo.isExportedInst(V)) return; 2118 2119 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2120 CopyValueToVirtualRegister(V, Reg); 2121 } 2122 2123 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2124 const BasicBlock *FromBB) { 2125 // The operands of the setcc have to be in this block. We don't know 2126 // how to export them from some other block. 2127 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2128 // Can export from current BB. 2129 if (VI->getParent() == FromBB) 2130 return true; 2131 2132 // Is already exported, noop. 2133 return FuncInfo.isExportedInst(V); 2134 } 2135 2136 // If this is an argument, we can export it if the BB is the entry block or 2137 // if it is already exported. 2138 if (isa<Argument>(V)) { 2139 if (FromBB->isEntryBlock()) 2140 return true; 2141 2142 // Otherwise, can only export this if it is already exported. 2143 return FuncInfo.isExportedInst(V); 2144 } 2145 2146 // Otherwise, constants can always be exported. 2147 return true; 2148 } 2149 2150 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2151 BranchProbability 2152 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2153 const MachineBasicBlock *Dst) const { 2154 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2155 const BasicBlock *SrcBB = Src->getBasicBlock(); 2156 const BasicBlock *DstBB = Dst->getBasicBlock(); 2157 if (!BPI) { 2158 // If BPI is not available, set the default probability as 1 / N, where N is 2159 // the number of successors. 2160 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2161 return BranchProbability(1, SuccSize); 2162 } 2163 return BPI->getEdgeProbability(SrcBB, DstBB); 2164 } 2165 2166 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2167 MachineBasicBlock *Dst, 2168 BranchProbability Prob) { 2169 if (!FuncInfo.BPI) 2170 Src->addSuccessorWithoutProb(Dst); 2171 else { 2172 if (Prob.isUnknown()) 2173 Prob = getEdgeProbability(Src, Dst); 2174 Src->addSuccessor(Dst, Prob); 2175 } 2176 } 2177 2178 static bool InBlock(const Value *V, const BasicBlock *BB) { 2179 if (const Instruction *I = dyn_cast<Instruction>(V)) 2180 return I->getParent() == BB; 2181 return true; 2182 } 2183 2184 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2185 /// This function emits a branch and is used at the leaves of an OR or an 2186 /// AND operator tree. 2187 void 2188 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2189 MachineBasicBlock *TBB, 2190 MachineBasicBlock *FBB, 2191 MachineBasicBlock *CurBB, 2192 MachineBasicBlock *SwitchBB, 2193 BranchProbability TProb, 2194 BranchProbability FProb, 2195 bool InvertCond) { 2196 const BasicBlock *BB = CurBB->getBasicBlock(); 2197 2198 // If the leaf of the tree is a comparison, merge the condition into 2199 // the caseblock. 2200 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2201 // The operands of the cmp have to be in this block. We don't know 2202 // how to export them from some other block. If this is the first block 2203 // of the sequence, no exporting is needed. 2204 if (CurBB == SwitchBB || 2205 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2206 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2207 ISD::CondCode Condition; 2208 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2209 ICmpInst::Predicate Pred = 2210 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2211 Condition = getICmpCondCode(Pred); 2212 } else { 2213 const FCmpInst *FC = cast<FCmpInst>(Cond); 2214 FCmpInst::Predicate Pred = 2215 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2216 Condition = getFCmpCondCode(Pred); 2217 if (TM.Options.NoNaNsFPMath) 2218 Condition = getFCmpCodeWithoutNaN(Condition); 2219 } 2220 2221 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2222 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2223 SL->SwitchCases.push_back(CB); 2224 return; 2225 } 2226 } 2227 2228 // Create a CaseBlock record representing this branch. 2229 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2230 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2231 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2232 SL->SwitchCases.push_back(CB); 2233 } 2234 2235 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2236 MachineBasicBlock *TBB, 2237 MachineBasicBlock *FBB, 2238 MachineBasicBlock *CurBB, 2239 MachineBasicBlock *SwitchBB, 2240 Instruction::BinaryOps Opc, 2241 BranchProbability TProb, 2242 BranchProbability FProb, 2243 bool InvertCond) { 2244 // Skip over not part of the tree and remember to invert op and operands at 2245 // next level. 2246 Value *NotCond; 2247 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2248 InBlock(NotCond, CurBB->getBasicBlock())) { 2249 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2250 !InvertCond); 2251 return; 2252 } 2253 2254 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2255 const Value *BOpOp0, *BOpOp1; 2256 // Compute the effective opcode for Cond, taking into account whether it needs 2257 // to be inverted, e.g. 2258 // and (not (or A, B)), C 2259 // gets lowered as 2260 // and (and (not A, not B), C) 2261 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2262 if (BOp) { 2263 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2264 ? Instruction::And 2265 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2266 ? Instruction::Or 2267 : (Instruction::BinaryOps)0); 2268 if (InvertCond) { 2269 if (BOpc == Instruction::And) 2270 BOpc = Instruction::Or; 2271 else if (BOpc == Instruction::Or) 2272 BOpc = Instruction::And; 2273 } 2274 } 2275 2276 // If this node is not part of the or/and tree, emit it as a branch. 2277 // Note that all nodes in the tree should have same opcode. 2278 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2279 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2280 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2281 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2282 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2283 TProb, FProb, InvertCond); 2284 return; 2285 } 2286 2287 // Create TmpBB after CurBB. 2288 MachineFunction::iterator BBI(CurBB); 2289 MachineFunction &MF = DAG.getMachineFunction(); 2290 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2291 CurBB->getParent()->insert(++BBI, TmpBB); 2292 2293 if (Opc == Instruction::Or) { 2294 // Codegen X | Y as: 2295 // BB1: 2296 // jmp_if_X TBB 2297 // jmp TmpBB 2298 // TmpBB: 2299 // jmp_if_Y TBB 2300 // jmp FBB 2301 // 2302 2303 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2304 // The requirement is that 2305 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2306 // = TrueProb for original BB. 2307 // Assuming the original probabilities are A and B, one choice is to set 2308 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2309 // A/(1+B) and 2B/(1+B). This choice assumes that 2310 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2311 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2312 // TmpBB, but the math is more complicated. 2313 2314 auto NewTrueProb = TProb / 2; 2315 auto NewFalseProb = TProb / 2 + FProb; 2316 // Emit the LHS condition. 2317 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2318 NewFalseProb, InvertCond); 2319 2320 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2321 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2322 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2323 // Emit the RHS condition into TmpBB. 2324 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2325 Probs[1], InvertCond); 2326 } else { 2327 assert(Opc == Instruction::And && "Unknown merge op!"); 2328 // Codegen X & Y as: 2329 // BB1: 2330 // jmp_if_X TmpBB 2331 // jmp FBB 2332 // TmpBB: 2333 // jmp_if_Y TBB 2334 // jmp FBB 2335 // 2336 // This requires creation of TmpBB after CurBB. 2337 2338 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2339 // The requirement is that 2340 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2341 // = FalseProb for original BB. 2342 // Assuming the original probabilities are A and B, one choice is to set 2343 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2344 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2345 // TrueProb for BB1 * FalseProb for TmpBB. 2346 2347 auto NewTrueProb = TProb + FProb / 2; 2348 auto NewFalseProb = FProb / 2; 2349 // Emit the LHS condition. 2350 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2351 NewFalseProb, InvertCond); 2352 2353 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2354 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2355 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2356 // Emit the RHS condition into TmpBB. 2357 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2358 Probs[1], InvertCond); 2359 } 2360 } 2361 2362 /// If the set of cases should be emitted as a series of branches, return true. 2363 /// If we should emit this as a bunch of and/or'd together conditions, return 2364 /// false. 2365 bool 2366 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2367 if (Cases.size() != 2) return true; 2368 2369 // If this is two comparisons of the same values or'd or and'd together, they 2370 // will get folded into a single comparison, so don't emit two blocks. 2371 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2372 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2373 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2374 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2375 return false; 2376 } 2377 2378 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2379 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2380 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2381 Cases[0].CC == Cases[1].CC && 2382 isa<Constant>(Cases[0].CmpRHS) && 2383 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2384 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2385 return false; 2386 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2387 return false; 2388 } 2389 2390 return true; 2391 } 2392 2393 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2394 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2395 2396 // Update machine-CFG edges. 2397 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2398 2399 if (I.isUnconditional()) { 2400 // Update machine-CFG edges. 2401 BrMBB->addSuccessor(Succ0MBB); 2402 2403 // If this is not a fall-through branch or optimizations are switched off, 2404 // emit the branch. 2405 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2406 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2407 MVT::Other, getControlRoot(), 2408 DAG.getBasicBlock(Succ0MBB))); 2409 2410 return; 2411 } 2412 2413 // If this condition is one of the special cases we handle, do special stuff 2414 // now. 2415 const Value *CondVal = I.getCondition(); 2416 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2417 2418 // If this is a series of conditions that are or'd or and'd together, emit 2419 // this as a sequence of branches instead of setcc's with and/or operations. 2420 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2421 // unpredictable branches, and vector extracts because those jumps are likely 2422 // expensive for any target), this should improve performance. 2423 // For example, instead of something like: 2424 // cmp A, B 2425 // C = seteq 2426 // cmp D, E 2427 // F = setle 2428 // or C, F 2429 // jnz foo 2430 // Emit: 2431 // cmp A, B 2432 // je foo 2433 // cmp D, E 2434 // jle foo 2435 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2436 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2437 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2438 Value *Vec; 2439 const Value *BOp0, *BOp1; 2440 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2441 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2442 Opcode = Instruction::And; 2443 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2444 Opcode = Instruction::Or; 2445 2446 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2447 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2448 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2449 getEdgeProbability(BrMBB, Succ0MBB), 2450 getEdgeProbability(BrMBB, Succ1MBB), 2451 /*InvertCond=*/false); 2452 // If the compares in later blocks need to use values not currently 2453 // exported from this block, export them now. This block should always 2454 // be the first entry. 2455 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2456 2457 // Allow some cases to be rejected. 2458 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2459 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2460 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2461 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2462 } 2463 2464 // Emit the branch for this block. 2465 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2466 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2467 return; 2468 } 2469 2470 // Okay, we decided not to do this, remove any inserted MBB's and clear 2471 // SwitchCases. 2472 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2473 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2474 2475 SL->SwitchCases.clear(); 2476 } 2477 } 2478 2479 // Create a CaseBlock record representing this branch. 2480 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2481 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2482 2483 // Use visitSwitchCase to actually insert the fast branch sequence for this 2484 // cond branch. 2485 visitSwitchCase(CB, BrMBB); 2486 } 2487 2488 /// visitSwitchCase - Emits the necessary code to represent a single node in 2489 /// the binary search tree resulting from lowering a switch instruction. 2490 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2491 MachineBasicBlock *SwitchBB) { 2492 SDValue Cond; 2493 SDValue CondLHS = getValue(CB.CmpLHS); 2494 SDLoc dl = CB.DL; 2495 2496 if (CB.CC == ISD::SETTRUE) { 2497 // Branch or fall through to TrueBB. 2498 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2499 SwitchBB->normalizeSuccProbs(); 2500 if (CB.TrueBB != NextBlock(SwitchBB)) { 2501 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2502 DAG.getBasicBlock(CB.TrueBB))); 2503 } 2504 return; 2505 } 2506 2507 auto &TLI = DAG.getTargetLoweringInfo(); 2508 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2509 2510 // Build the setcc now. 2511 if (!CB.CmpMHS) { 2512 // Fold "(X == true)" to X and "(X == false)" to !X to 2513 // handle common cases produced by branch lowering. 2514 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2515 CB.CC == ISD::SETEQ) 2516 Cond = CondLHS; 2517 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2518 CB.CC == ISD::SETEQ) { 2519 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2520 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2521 } else { 2522 SDValue CondRHS = getValue(CB.CmpRHS); 2523 2524 // If a pointer's DAG type is larger than its memory type then the DAG 2525 // values are zero-extended. This breaks signed comparisons so truncate 2526 // back to the underlying type before doing the compare. 2527 if (CondLHS.getValueType() != MemVT) { 2528 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2529 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2530 } 2531 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2532 } 2533 } else { 2534 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2535 2536 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2537 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2538 2539 SDValue CmpOp = getValue(CB.CmpMHS); 2540 EVT VT = CmpOp.getValueType(); 2541 2542 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2543 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2544 ISD::SETLE); 2545 } else { 2546 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2547 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2548 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2549 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2550 } 2551 } 2552 2553 // Update successor info 2554 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2555 // TrueBB and FalseBB are always different unless the incoming IR is 2556 // degenerate. This only happens when running llc on weird IR. 2557 if (CB.TrueBB != CB.FalseBB) 2558 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2559 SwitchBB->normalizeSuccProbs(); 2560 2561 // If the lhs block is the next block, invert the condition so that we can 2562 // fall through to the lhs instead of the rhs block. 2563 if (CB.TrueBB == NextBlock(SwitchBB)) { 2564 std::swap(CB.TrueBB, CB.FalseBB); 2565 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2566 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2567 } 2568 2569 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2570 MVT::Other, getControlRoot(), Cond, 2571 DAG.getBasicBlock(CB.TrueBB)); 2572 2573 setValue(CurInst, BrCond); 2574 2575 // Insert the false branch. Do this even if it's a fall through branch, 2576 // this makes it easier to do DAG optimizations which require inverting 2577 // the branch condition. 2578 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2579 DAG.getBasicBlock(CB.FalseBB)); 2580 2581 DAG.setRoot(BrCond); 2582 } 2583 2584 /// visitJumpTable - Emit JumpTable node in the current MBB 2585 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2586 // Emit the code for the jump table 2587 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2588 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2589 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2590 JT.Reg, PTy); 2591 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2592 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2593 MVT::Other, Index.getValue(1), 2594 Table, Index); 2595 DAG.setRoot(BrJumpTable); 2596 } 2597 2598 /// visitJumpTableHeader - This function emits necessary code to produce index 2599 /// in the JumpTable from switch case. 2600 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2601 JumpTableHeader &JTH, 2602 MachineBasicBlock *SwitchBB) { 2603 SDLoc dl = getCurSDLoc(); 2604 2605 // Subtract the lowest switch case value from the value being switched on. 2606 SDValue SwitchOp = getValue(JTH.SValue); 2607 EVT VT = SwitchOp.getValueType(); 2608 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2609 DAG.getConstant(JTH.First, dl, VT)); 2610 2611 // The SDNode we just created, which holds the value being switched on minus 2612 // the smallest case value, needs to be copied to a virtual register so it 2613 // can be used as an index into the jump table in a subsequent basic block. 2614 // This value may be smaller or larger than the target's pointer type, and 2615 // therefore require extension or truncating. 2616 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2617 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2618 2619 unsigned JumpTableReg = 2620 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2621 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2622 JumpTableReg, SwitchOp); 2623 JT.Reg = JumpTableReg; 2624 2625 if (!JTH.FallthroughUnreachable) { 2626 // Emit the range check for the jump table, and branch to the default block 2627 // for the switch statement if the value being switched on exceeds the 2628 // largest case in the switch. 2629 SDValue CMP = DAG.getSetCC( 2630 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2631 Sub.getValueType()), 2632 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2633 2634 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2635 MVT::Other, CopyTo, CMP, 2636 DAG.getBasicBlock(JT.Default)); 2637 2638 // Avoid emitting unnecessary branches to the next block. 2639 if (JT.MBB != NextBlock(SwitchBB)) 2640 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2641 DAG.getBasicBlock(JT.MBB)); 2642 2643 DAG.setRoot(BrCond); 2644 } else { 2645 // Avoid emitting unnecessary branches to the next block. 2646 if (JT.MBB != NextBlock(SwitchBB)) 2647 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2648 DAG.getBasicBlock(JT.MBB))); 2649 else 2650 DAG.setRoot(CopyTo); 2651 } 2652 } 2653 2654 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2655 /// variable if there exists one. 2656 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2657 SDValue &Chain) { 2658 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2659 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2660 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2661 MachineFunction &MF = DAG.getMachineFunction(); 2662 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2663 MachineSDNode *Node = 2664 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2665 if (Global) { 2666 MachinePointerInfo MPInfo(Global); 2667 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2668 MachineMemOperand::MODereferenceable; 2669 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2670 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2671 DAG.setNodeMemRefs(Node, {MemRef}); 2672 } 2673 if (PtrTy != PtrMemTy) 2674 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2675 return SDValue(Node, 0); 2676 } 2677 2678 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2679 /// tail spliced into a stack protector check success bb. 2680 /// 2681 /// For a high level explanation of how this fits into the stack protector 2682 /// generation see the comment on the declaration of class 2683 /// StackProtectorDescriptor. 2684 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2685 MachineBasicBlock *ParentBB) { 2686 2687 // First create the loads to the guard/stack slot for the comparison. 2688 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2689 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2690 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2691 2692 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2693 int FI = MFI.getStackProtectorIndex(); 2694 2695 SDValue Guard; 2696 SDLoc dl = getCurSDLoc(); 2697 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2698 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2699 Align Align = 2700 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2701 2702 // Generate code to load the content of the guard slot. 2703 SDValue GuardVal = DAG.getLoad( 2704 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2705 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2706 MachineMemOperand::MOVolatile); 2707 2708 if (TLI.useStackGuardXorFP()) 2709 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2710 2711 // Retrieve guard check function, nullptr if instrumentation is inlined. 2712 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2713 // The target provides a guard check function to validate the guard value. 2714 // Generate a call to that function with the content of the guard slot as 2715 // argument. 2716 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2717 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2718 2719 TargetLowering::ArgListTy Args; 2720 TargetLowering::ArgListEntry Entry; 2721 Entry.Node = GuardVal; 2722 Entry.Ty = FnTy->getParamType(0); 2723 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2724 Entry.IsInReg = true; 2725 Args.push_back(Entry); 2726 2727 TargetLowering::CallLoweringInfo CLI(DAG); 2728 CLI.setDebugLoc(getCurSDLoc()) 2729 .setChain(DAG.getEntryNode()) 2730 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2731 getValue(GuardCheckFn), std::move(Args)); 2732 2733 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2734 DAG.setRoot(Result.second); 2735 return; 2736 } 2737 2738 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2739 // Otherwise, emit a volatile load to retrieve the stack guard value. 2740 SDValue Chain = DAG.getEntryNode(); 2741 if (TLI.useLoadStackGuardNode()) { 2742 Guard = getLoadStackGuard(DAG, dl, Chain); 2743 } else { 2744 const Value *IRGuard = TLI.getSDagStackGuard(M); 2745 SDValue GuardPtr = getValue(IRGuard); 2746 2747 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2748 MachinePointerInfo(IRGuard, 0), Align, 2749 MachineMemOperand::MOVolatile); 2750 } 2751 2752 // Perform the comparison via a getsetcc. 2753 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2754 *DAG.getContext(), 2755 Guard.getValueType()), 2756 Guard, GuardVal, ISD::SETNE); 2757 2758 // If the guard/stackslot do not equal, branch to failure MBB. 2759 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2760 MVT::Other, GuardVal.getOperand(0), 2761 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2762 // Otherwise branch to success MBB. 2763 SDValue Br = DAG.getNode(ISD::BR, dl, 2764 MVT::Other, BrCond, 2765 DAG.getBasicBlock(SPD.getSuccessMBB())); 2766 2767 DAG.setRoot(Br); 2768 } 2769 2770 /// Codegen the failure basic block for a stack protector check. 2771 /// 2772 /// A failure stack protector machine basic block consists simply of a call to 2773 /// __stack_chk_fail(). 2774 /// 2775 /// For a high level explanation of how this fits into the stack protector 2776 /// generation see the comment on the declaration of class 2777 /// StackProtectorDescriptor. 2778 void 2779 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2780 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2781 TargetLowering::MakeLibCallOptions CallOptions; 2782 CallOptions.setDiscardResult(true); 2783 SDValue Chain = 2784 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2785 None, CallOptions, getCurSDLoc()).second; 2786 // On PS4/PS5, the "return address" must still be within the calling 2787 // function, even if it's at the very end, so emit an explicit TRAP here. 2788 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2789 if (TM.getTargetTriple().isPS()) 2790 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2791 // WebAssembly needs an unreachable instruction after a non-returning call, 2792 // because the function return type can be different from __stack_chk_fail's 2793 // return type (void). 2794 if (TM.getTargetTriple().isWasm()) 2795 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2796 2797 DAG.setRoot(Chain); 2798 } 2799 2800 /// visitBitTestHeader - This function emits necessary code to produce value 2801 /// suitable for "bit tests" 2802 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2803 MachineBasicBlock *SwitchBB) { 2804 SDLoc dl = getCurSDLoc(); 2805 2806 // Subtract the minimum value. 2807 SDValue SwitchOp = getValue(B.SValue); 2808 EVT VT = SwitchOp.getValueType(); 2809 SDValue RangeSub = 2810 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2811 2812 // Determine the type of the test operands. 2813 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2814 bool UsePtrType = false; 2815 if (!TLI.isTypeLegal(VT)) { 2816 UsePtrType = true; 2817 } else { 2818 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2819 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2820 // Switch table case range are encoded into series of masks. 2821 // Just use pointer type, it's guaranteed to fit. 2822 UsePtrType = true; 2823 break; 2824 } 2825 } 2826 SDValue Sub = RangeSub; 2827 if (UsePtrType) { 2828 VT = TLI.getPointerTy(DAG.getDataLayout()); 2829 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2830 } 2831 2832 B.RegVT = VT.getSimpleVT(); 2833 B.Reg = FuncInfo.CreateReg(B.RegVT); 2834 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2835 2836 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2837 2838 if (!B.FallthroughUnreachable) 2839 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2840 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2841 SwitchBB->normalizeSuccProbs(); 2842 2843 SDValue Root = CopyTo; 2844 if (!B.FallthroughUnreachable) { 2845 // Conditional branch to the default block. 2846 SDValue RangeCmp = DAG.getSetCC(dl, 2847 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2848 RangeSub.getValueType()), 2849 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2850 ISD::SETUGT); 2851 2852 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2853 DAG.getBasicBlock(B.Default)); 2854 } 2855 2856 // Avoid emitting unnecessary branches to the next block. 2857 if (MBB != NextBlock(SwitchBB)) 2858 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2859 2860 DAG.setRoot(Root); 2861 } 2862 2863 /// visitBitTestCase - this function produces one "bit test" 2864 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2865 MachineBasicBlock* NextMBB, 2866 BranchProbability BranchProbToNext, 2867 unsigned Reg, 2868 BitTestCase &B, 2869 MachineBasicBlock *SwitchBB) { 2870 SDLoc dl = getCurSDLoc(); 2871 MVT VT = BB.RegVT; 2872 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2873 SDValue Cmp; 2874 unsigned PopCount = countPopulation(B.Mask); 2875 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2876 if (PopCount == 1) { 2877 // Testing for a single bit; just compare the shift count with what it 2878 // would need to be to shift a 1 bit in that position. 2879 Cmp = DAG.getSetCC( 2880 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2881 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2882 ISD::SETEQ); 2883 } else if (PopCount == BB.Range) { 2884 // There is only one zero bit in the range, test for it directly. 2885 Cmp = DAG.getSetCC( 2886 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2887 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2888 ISD::SETNE); 2889 } else { 2890 // Make desired shift 2891 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2892 DAG.getConstant(1, dl, VT), ShiftOp); 2893 2894 // Emit bit tests and jumps 2895 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2896 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2897 Cmp = DAG.getSetCC( 2898 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2899 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2900 } 2901 2902 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2903 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2904 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2905 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2906 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2907 // one as they are relative probabilities (and thus work more like weights), 2908 // and hence we need to normalize them to let the sum of them become one. 2909 SwitchBB->normalizeSuccProbs(); 2910 2911 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2912 MVT::Other, getControlRoot(), 2913 Cmp, DAG.getBasicBlock(B.TargetBB)); 2914 2915 // Avoid emitting unnecessary branches to the next block. 2916 if (NextMBB != NextBlock(SwitchBB)) 2917 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2918 DAG.getBasicBlock(NextMBB)); 2919 2920 DAG.setRoot(BrAnd); 2921 } 2922 2923 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2924 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2925 2926 // Retrieve successors. Look through artificial IR level blocks like 2927 // catchswitch for successors. 2928 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2929 const BasicBlock *EHPadBB = I.getSuccessor(1); 2930 2931 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2932 // have to do anything here to lower funclet bundles. 2933 assert(!I.hasOperandBundlesOtherThan( 2934 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2935 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2936 LLVMContext::OB_cfguardtarget, 2937 LLVMContext::OB_clang_arc_attachedcall}) && 2938 "Cannot lower invokes with arbitrary operand bundles yet!"); 2939 2940 const Value *Callee(I.getCalledOperand()); 2941 const Function *Fn = dyn_cast<Function>(Callee); 2942 if (isa<InlineAsm>(Callee)) 2943 visitInlineAsm(I, EHPadBB); 2944 else if (Fn && Fn->isIntrinsic()) { 2945 switch (Fn->getIntrinsicID()) { 2946 default: 2947 llvm_unreachable("Cannot invoke this intrinsic"); 2948 case Intrinsic::donothing: 2949 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2950 case Intrinsic::seh_try_begin: 2951 case Intrinsic::seh_scope_begin: 2952 case Intrinsic::seh_try_end: 2953 case Intrinsic::seh_scope_end: 2954 break; 2955 case Intrinsic::experimental_patchpoint_void: 2956 case Intrinsic::experimental_patchpoint_i64: 2957 visitPatchpoint(I, EHPadBB); 2958 break; 2959 case Intrinsic::experimental_gc_statepoint: 2960 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2961 break; 2962 case Intrinsic::wasm_rethrow: { 2963 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2964 // special because it can be invoked, so we manually lower it to a DAG 2965 // node here. 2966 SmallVector<SDValue, 8> Ops; 2967 Ops.push_back(getRoot()); // inchain 2968 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2969 Ops.push_back( 2970 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2971 TLI.getPointerTy(DAG.getDataLayout()))); 2972 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2973 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2974 break; 2975 } 2976 } 2977 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2978 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2979 // Eventually we will support lowering the @llvm.experimental.deoptimize 2980 // intrinsic, and right now there are no plans to support other intrinsics 2981 // with deopt state. 2982 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2983 } else { 2984 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 2985 } 2986 2987 // If the value of the invoke is used outside of its defining block, make it 2988 // available as a virtual register. 2989 // We already took care of the exported value for the statepoint instruction 2990 // during call to the LowerStatepoint. 2991 if (!isa<GCStatepointInst>(I)) { 2992 CopyToExportRegsIfNeeded(&I); 2993 } 2994 2995 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2996 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2997 BranchProbability EHPadBBProb = 2998 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2999 : BranchProbability::getZero(); 3000 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3001 3002 // Update successor info. 3003 addSuccessorWithProb(InvokeMBB, Return); 3004 for (auto &UnwindDest : UnwindDests) { 3005 UnwindDest.first->setIsEHPad(); 3006 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3007 } 3008 InvokeMBB->normalizeSuccProbs(); 3009 3010 // Drop into normal successor. 3011 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3012 DAG.getBasicBlock(Return))); 3013 } 3014 3015 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3016 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3017 3018 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3019 // have to do anything here to lower funclet bundles. 3020 assert(!I.hasOperandBundlesOtherThan( 3021 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3022 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3023 3024 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3025 visitInlineAsm(I); 3026 CopyToExportRegsIfNeeded(&I); 3027 3028 // Retrieve successors. 3029 SmallPtrSet<BasicBlock *, 8> Dests; 3030 Dests.insert(I.getDefaultDest()); 3031 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3032 3033 // Update successor info. 3034 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3035 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3036 BasicBlock *Dest = I.getIndirectDest(i); 3037 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3038 Target->setIsInlineAsmBrIndirectTarget(); 3039 Target->setMachineBlockAddressTaken(); 3040 Target->setLabelMustBeEmitted(); 3041 // Don't add duplicate machine successors. 3042 if (Dests.insert(Dest).second) 3043 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3044 } 3045 CallBrMBB->normalizeSuccProbs(); 3046 3047 // Drop into default successor. 3048 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3049 MVT::Other, getControlRoot(), 3050 DAG.getBasicBlock(Return))); 3051 } 3052 3053 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3054 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3055 } 3056 3057 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3058 assert(FuncInfo.MBB->isEHPad() && 3059 "Call to landingpad not in landing pad!"); 3060 3061 // If there aren't registers to copy the values into (e.g., during SjLj 3062 // exceptions), then don't bother to create these DAG nodes. 3063 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3064 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3065 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3066 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3067 return; 3068 3069 // If landingpad's return type is token type, we don't create DAG nodes 3070 // for its exception pointer and selector value. The extraction of exception 3071 // pointer or selector value from token type landingpads is not currently 3072 // supported. 3073 if (LP.getType()->isTokenTy()) 3074 return; 3075 3076 SmallVector<EVT, 2> ValueVTs; 3077 SDLoc dl = getCurSDLoc(); 3078 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3079 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3080 3081 // Get the two live-in registers as SDValues. The physregs have already been 3082 // copied into virtual registers. 3083 SDValue Ops[2]; 3084 if (FuncInfo.ExceptionPointerVirtReg) { 3085 Ops[0] = DAG.getZExtOrTrunc( 3086 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3087 FuncInfo.ExceptionPointerVirtReg, 3088 TLI.getPointerTy(DAG.getDataLayout())), 3089 dl, ValueVTs[0]); 3090 } else { 3091 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3092 } 3093 Ops[1] = DAG.getZExtOrTrunc( 3094 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3095 FuncInfo.ExceptionSelectorVirtReg, 3096 TLI.getPointerTy(DAG.getDataLayout())), 3097 dl, ValueVTs[1]); 3098 3099 // Merge into one. 3100 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3101 DAG.getVTList(ValueVTs), Ops); 3102 setValue(&LP, Res); 3103 } 3104 3105 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3106 MachineBasicBlock *Last) { 3107 // Update JTCases. 3108 for (JumpTableBlock &JTB : SL->JTCases) 3109 if (JTB.first.HeaderBB == First) 3110 JTB.first.HeaderBB = Last; 3111 3112 // Update BitTestCases. 3113 for (BitTestBlock &BTB : SL->BitTestCases) 3114 if (BTB.Parent == First) 3115 BTB.Parent = Last; 3116 } 3117 3118 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3119 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3120 3121 // Update machine-CFG edges with unique successors. 3122 SmallSet<BasicBlock*, 32> Done; 3123 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3124 BasicBlock *BB = I.getSuccessor(i); 3125 bool Inserted = Done.insert(BB).second; 3126 if (!Inserted) 3127 continue; 3128 3129 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3130 addSuccessorWithProb(IndirectBrMBB, Succ); 3131 } 3132 IndirectBrMBB->normalizeSuccProbs(); 3133 3134 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3135 MVT::Other, getControlRoot(), 3136 getValue(I.getAddress()))); 3137 } 3138 3139 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3140 if (!DAG.getTarget().Options.TrapUnreachable) 3141 return; 3142 3143 // We may be able to ignore unreachable behind a noreturn call. 3144 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3145 const BasicBlock &BB = *I.getParent(); 3146 if (&I != &BB.front()) { 3147 BasicBlock::const_iterator PredI = 3148 std::prev(BasicBlock::const_iterator(&I)); 3149 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3150 if (Call->doesNotReturn()) 3151 return; 3152 } 3153 } 3154 } 3155 3156 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3157 } 3158 3159 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3160 SDNodeFlags Flags; 3161 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3162 Flags.copyFMF(*FPOp); 3163 3164 SDValue Op = getValue(I.getOperand(0)); 3165 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3166 Op, Flags); 3167 setValue(&I, UnNodeValue); 3168 } 3169 3170 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3171 SDNodeFlags Flags; 3172 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3173 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3174 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3175 } 3176 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3177 Flags.setExact(ExactOp->isExact()); 3178 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3179 Flags.copyFMF(*FPOp); 3180 3181 SDValue Op1 = getValue(I.getOperand(0)); 3182 SDValue Op2 = getValue(I.getOperand(1)); 3183 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3184 Op1, Op2, Flags); 3185 setValue(&I, BinNodeValue); 3186 } 3187 3188 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3189 SDValue Op1 = getValue(I.getOperand(0)); 3190 SDValue Op2 = getValue(I.getOperand(1)); 3191 3192 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3193 Op1.getValueType(), DAG.getDataLayout()); 3194 3195 // Coerce the shift amount to the right type if we can. This exposes the 3196 // truncate or zext to optimization early. 3197 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3198 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3199 "Unexpected shift type"); 3200 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3201 } 3202 3203 bool nuw = false; 3204 bool nsw = false; 3205 bool exact = false; 3206 3207 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3208 3209 if (const OverflowingBinaryOperator *OFBinOp = 3210 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3211 nuw = OFBinOp->hasNoUnsignedWrap(); 3212 nsw = OFBinOp->hasNoSignedWrap(); 3213 } 3214 if (const PossiblyExactOperator *ExactOp = 3215 dyn_cast<const PossiblyExactOperator>(&I)) 3216 exact = ExactOp->isExact(); 3217 } 3218 SDNodeFlags Flags; 3219 Flags.setExact(exact); 3220 Flags.setNoSignedWrap(nsw); 3221 Flags.setNoUnsignedWrap(nuw); 3222 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3223 Flags); 3224 setValue(&I, Res); 3225 } 3226 3227 void SelectionDAGBuilder::visitSDiv(const User &I) { 3228 SDValue Op1 = getValue(I.getOperand(0)); 3229 SDValue Op2 = getValue(I.getOperand(1)); 3230 3231 SDNodeFlags Flags; 3232 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3233 cast<PossiblyExactOperator>(&I)->isExact()); 3234 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3235 Op2, Flags)); 3236 } 3237 3238 void SelectionDAGBuilder::visitICmp(const User &I) { 3239 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3240 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3241 predicate = IC->getPredicate(); 3242 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3243 predicate = ICmpInst::Predicate(IC->getPredicate()); 3244 SDValue Op1 = getValue(I.getOperand(0)); 3245 SDValue Op2 = getValue(I.getOperand(1)); 3246 ISD::CondCode Opcode = getICmpCondCode(predicate); 3247 3248 auto &TLI = DAG.getTargetLoweringInfo(); 3249 EVT MemVT = 3250 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3251 3252 // If a pointer's DAG type is larger than its memory type then the DAG values 3253 // are zero-extended. This breaks signed comparisons so truncate back to the 3254 // underlying type before doing the compare. 3255 if (Op1.getValueType() != MemVT) { 3256 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3257 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3258 } 3259 3260 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3261 I.getType()); 3262 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3263 } 3264 3265 void SelectionDAGBuilder::visitFCmp(const User &I) { 3266 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3267 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3268 predicate = FC->getPredicate(); 3269 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3270 predicate = FCmpInst::Predicate(FC->getPredicate()); 3271 SDValue Op1 = getValue(I.getOperand(0)); 3272 SDValue Op2 = getValue(I.getOperand(1)); 3273 3274 ISD::CondCode Condition = getFCmpCondCode(predicate); 3275 auto *FPMO = cast<FPMathOperator>(&I); 3276 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3277 Condition = getFCmpCodeWithoutNaN(Condition); 3278 3279 SDNodeFlags Flags; 3280 Flags.copyFMF(*FPMO); 3281 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3282 3283 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3284 I.getType()); 3285 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3286 } 3287 3288 // Check if the condition of the select has one use or two users that are both 3289 // selects with the same condition. 3290 static bool hasOnlySelectUsers(const Value *Cond) { 3291 return llvm::all_of(Cond->users(), [](const Value *V) { 3292 return isa<SelectInst>(V); 3293 }); 3294 } 3295 3296 void SelectionDAGBuilder::visitSelect(const User &I) { 3297 SmallVector<EVT, 4> ValueVTs; 3298 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3299 ValueVTs); 3300 unsigned NumValues = ValueVTs.size(); 3301 if (NumValues == 0) return; 3302 3303 SmallVector<SDValue, 4> Values(NumValues); 3304 SDValue Cond = getValue(I.getOperand(0)); 3305 SDValue LHSVal = getValue(I.getOperand(1)); 3306 SDValue RHSVal = getValue(I.getOperand(2)); 3307 SmallVector<SDValue, 1> BaseOps(1, Cond); 3308 ISD::NodeType OpCode = 3309 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3310 3311 bool IsUnaryAbs = false; 3312 bool Negate = false; 3313 3314 SDNodeFlags Flags; 3315 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3316 Flags.copyFMF(*FPOp); 3317 3318 // Min/max matching is only viable if all output VTs are the same. 3319 if (all_equal(ValueVTs)) { 3320 EVT VT = ValueVTs[0]; 3321 LLVMContext &Ctx = *DAG.getContext(); 3322 auto &TLI = DAG.getTargetLoweringInfo(); 3323 3324 // We care about the legality of the operation after it has been type 3325 // legalized. 3326 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3327 VT = TLI.getTypeToTransformTo(Ctx, VT); 3328 3329 // If the vselect is legal, assume we want to leave this as a vector setcc + 3330 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3331 // min/max is legal on the scalar type. 3332 bool UseScalarMinMax = VT.isVector() && 3333 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3334 3335 Value *LHS, *RHS; 3336 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3337 ISD::NodeType Opc = ISD::DELETED_NODE; 3338 switch (SPR.Flavor) { 3339 case SPF_UMAX: Opc = ISD::UMAX; break; 3340 case SPF_UMIN: Opc = ISD::UMIN; break; 3341 case SPF_SMAX: Opc = ISD::SMAX; break; 3342 case SPF_SMIN: Opc = ISD::SMIN; break; 3343 case SPF_FMINNUM: 3344 switch (SPR.NaNBehavior) { 3345 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3346 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3347 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3348 case SPNB_RETURNS_ANY: { 3349 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3350 Opc = ISD::FMINNUM; 3351 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3352 Opc = ISD::FMINIMUM; 3353 else if (UseScalarMinMax) 3354 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3355 ISD::FMINNUM : ISD::FMINIMUM; 3356 break; 3357 } 3358 } 3359 break; 3360 case SPF_FMAXNUM: 3361 switch (SPR.NaNBehavior) { 3362 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3363 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3364 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3365 case SPNB_RETURNS_ANY: 3366 3367 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3368 Opc = ISD::FMAXNUM; 3369 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3370 Opc = ISD::FMAXIMUM; 3371 else if (UseScalarMinMax) 3372 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3373 ISD::FMAXNUM : ISD::FMAXIMUM; 3374 break; 3375 } 3376 break; 3377 case SPF_NABS: 3378 Negate = true; 3379 [[fallthrough]]; 3380 case SPF_ABS: 3381 IsUnaryAbs = true; 3382 Opc = ISD::ABS; 3383 break; 3384 default: break; 3385 } 3386 3387 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3388 (TLI.isOperationLegalOrCustom(Opc, VT) || 3389 (UseScalarMinMax && 3390 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3391 // If the underlying comparison instruction is used by any other 3392 // instruction, the consumed instructions won't be destroyed, so it is 3393 // not profitable to convert to a min/max. 3394 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3395 OpCode = Opc; 3396 LHSVal = getValue(LHS); 3397 RHSVal = getValue(RHS); 3398 BaseOps.clear(); 3399 } 3400 3401 if (IsUnaryAbs) { 3402 OpCode = Opc; 3403 LHSVal = getValue(LHS); 3404 BaseOps.clear(); 3405 } 3406 } 3407 3408 if (IsUnaryAbs) { 3409 for (unsigned i = 0; i != NumValues; ++i) { 3410 SDLoc dl = getCurSDLoc(); 3411 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3412 Values[i] = 3413 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3414 if (Negate) 3415 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3416 Values[i]); 3417 } 3418 } else { 3419 for (unsigned i = 0; i != NumValues; ++i) { 3420 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3421 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3422 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3423 Values[i] = DAG.getNode( 3424 OpCode, getCurSDLoc(), 3425 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3426 } 3427 } 3428 3429 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3430 DAG.getVTList(ValueVTs), Values)); 3431 } 3432 3433 void SelectionDAGBuilder::visitTrunc(const User &I) { 3434 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3435 SDValue N = getValue(I.getOperand(0)); 3436 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3437 I.getType()); 3438 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3439 } 3440 3441 void SelectionDAGBuilder::visitZExt(const User &I) { 3442 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3443 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3444 SDValue N = getValue(I.getOperand(0)); 3445 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3446 I.getType()); 3447 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3448 } 3449 3450 void SelectionDAGBuilder::visitSExt(const User &I) { 3451 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3452 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3453 SDValue N = getValue(I.getOperand(0)); 3454 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3455 I.getType()); 3456 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3457 } 3458 3459 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3460 // FPTrunc is never a no-op cast, no need to check 3461 SDValue N = getValue(I.getOperand(0)); 3462 SDLoc dl = getCurSDLoc(); 3463 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3464 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3465 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3466 DAG.getTargetConstant( 3467 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3468 } 3469 3470 void SelectionDAGBuilder::visitFPExt(const User &I) { 3471 // FPExt is never a no-op cast, no need to check 3472 SDValue N = getValue(I.getOperand(0)); 3473 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3474 I.getType()); 3475 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3476 } 3477 3478 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3479 // FPToUI is never a no-op cast, no need to check 3480 SDValue N = getValue(I.getOperand(0)); 3481 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3482 I.getType()); 3483 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3484 } 3485 3486 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3487 // FPToSI is never a no-op cast, no need to check 3488 SDValue N = getValue(I.getOperand(0)); 3489 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3490 I.getType()); 3491 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3492 } 3493 3494 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3495 // UIToFP is never a no-op cast, no need to check 3496 SDValue N = getValue(I.getOperand(0)); 3497 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3498 I.getType()); 3499 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3500 } 3501 3502 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3503 // SIToFP is never a no-op cast, no need to check 3504 SDValue N = getValue(I.getOperand(0)); 3505 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3506 I.getType()); 3507 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3508 } 3509 3510 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3511 // What to do depends on the size of the integer and the size of the pointer. 3512 // We can either truncate, zero extend, or no-op, accordingly. 3513 SDValue N = getValue(I.getOperand(0)); 3514 auto &TLI = DAG.getTargetLoweringInfo(); 3515 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3516 I.getType()); 3517 EVT PtrMemVT = 3518 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3519 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3520 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3521 setValue(&I, N); 3522 } 3523 3524 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3525 // What to do depends on the size of the integer and the size of the pointer. 3526 // We can either truncate, zero extend, or no-op, accordingly. 3527 SDValue N = getValue(I.getOperand(0)); 3528 auto &TLI = DAG.getTargetLoweringInfo(); 3529 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3530 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3531 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3532 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3533 setValue(&I, N); 3534 } 3535 3536 void SelectionDAGBuilder::visitBitCast(const User &I) { 3537 SDValue N = getValue(I.getOperand(0)); 3538 SDLoc dl = getCurSDLoc(); 3539 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3540 I.getType()); 3541 3542 // BitCast assures us that source and destination are the same size so this is 3543 // either a BITCAST or a no-op. 3544 if (DestVT != N.getValueType()) 3545 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3546 DestVT, N)); // convert types. 3547 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3548 // might fold any kind of constant expression to an integer constant and that 3549 // is not what we are looking for. Only recognize a bitcast of a genuine 3550 // constant integer as an opaque constant. 3551 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3552 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3553 /*isOpaque*/true)); 3554 else 3555 setValue(&I, N); // noop cast. 3556 } 3557 3558 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3559 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3560 const Value *SV = I.getOperand(0); 3561 SDValue N = getValue(SV); 3562 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3563 3564 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3565 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3566 3567 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3568 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3569 3570 setValue(&I, N); 3571 } 3572 3573 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3574 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3575 SDValue InVec = getValue(I.getOperand(0)); 3576 SDValue InVal = getValue(I.getOperand(1)); 3577 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3578 TLI.getVectorIdxTy(DAG.getDataLayout())); 3579 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3580 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3581 InVec, InVal, InIdx)); 3582 } 3583 3584 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3585 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3586 SDValue InVec = getValue(I.getOperand(0)); 3587 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3588 TLI.getVectorIdxTy(DAG.getDataLayout())); 3589 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3590 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3591 InVec, InIdx)); 3592 } 3593 3594 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3595 SDValue Src1 = getValue(I.getOperand(0)); 3596 SDValue Src2 = getValue(I.getOperand(1)); 3597 ArrayRef<int> Mask; 3598 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3599 Mask = SVI->getShuffleMask(); 3600 else 3601 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3602 SDLoc DL = getCurSDLoc(); 3603 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3604 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3605 EVT SrcVT = Src1.getValueType(); 3606 3607 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3608 VT.isScalableVector()) { 3609 // Canonical splat form of first element of first input vector. 3610 SDValue FirstElt = 3611 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3612 DAG.getVectorIdxConstant(0, DL)); 3613 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3614 return; 3615 } 3616 3617 // For now, we only handle splats for scalable vectors. 3618 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3619 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3620 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3621 3622 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3623 unsigned MaskNumElts = Mask.size(); 3624 3625 if (SrcNumElts == MaskNumElts) { 3626 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3627 return; 3628 } 3629 3630 // Normalize the shuffle vector since mask and vector length don't match. 3631 if (SrcNumElts < MaskNumElts) { 3632 // Mask is longer than the source vectors. We can use concatenate vector to 3633 // make the mask and vectors lengths match. 3634 3635 if (MaskNumElts % SrcNumElts == 0) { 3636 // Mask length is a multiple of the source vector length. 3637 // Check if the shuffle is some kind of concatenation of the input 3638 // vectors. 3639 unsigned NumConcat = MaskNumElts / SrcNumElts; 3640 bool IsConcat = true; 3641 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3642 for (unsigned i = 0; i != MaskNumElts; ++i) { 3643 int Idx = Mask[i]; 3644 if (Idx < 0) 3645 continue; 3646 // Ensure the indices in each SrcVT sized piece are sequential and that 3647 // the same source is used for the whole piece. 3648 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3649 (ConcatSrcs[i / SrcNumElts] >= 0 && 3650 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3651 IsConcat = false; 3652 break; 3653 } 3654 // Remember which source this index came from. 3655 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3656 } 3657 3658 // The shuffle is concatenating multiple vectors together. Just emit 3659 // a CONCAT_VECTORS operation. 3660 if (IsConcat) { 3661 SmallVector<SDValue, 8> ConcatOps; 3662 for (auto Src : ConcatSrcs) { 3663 if (Src < 0) 3664 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3665 else if (Src == 0) 3666 ConcatOps.push_back(Src1); 3667 else 3668 ConcatOps.push_back(Src2); 3669 } 3670 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3671 return; 3672 } 3673 } 3674 3675 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3676 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3677 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3678 PaddedMaskNumElts); 3679 3680 // Pad both vectors with undefs to make them the same length as the mask. 3681 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3682 3683 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3684 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3685 MOps1[0] = Src1; 3686 MOps2[0] = Src2; 3687 3688 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3689 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3690 3691 // Readjust mask for new input vector length. 3692 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3693 for (unsigned i = 0; i != MaskNumElts; ++i) { 3694 int Idx = Mask[i]; 3695 if (Idx >= (int)SrcNumElts) 3696 Idx -= SrcNumElts - PaddedMaskNumElts; 3697 MappedOps[i] = Idx; 3698 } 3699 3700 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3701 3702 // If the concatenated vector was padded, extract a subvector with the 3703 // correct number of elements. 3704 if (MaskNumElts != PaddedMaskNumElts) 3705 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3706 DAG.getVectorIdxConstant(0, DL)); 3707 3708 setValue(&I, Result); 3709 return; 3710 } 3711 3712 if (SrcNumElts > MaskNumElts) { 3713 // Analyze the access pattern of the vector to see if we can extract 3714 // two subvectors and do the shuffle. 3715 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3716 bool CanExtract = true; 3717 for (int Idx : Mask) { 3718 unsigned Input = 0; 3719 if (Idx < 0) 3720 continue; 3721 3722 if (Idx >= (int)SrcNumElts) { 3723 Input = 1; 3724 Idx -= SrcNumElts; 3725 } 3726 3727 // If all the indices come from the same MaskNumElts sized portion of 3728 // the sources we can use extract. Also make sure the extract wouldn't 3729 // extract past the end of the source. 3730 int NewStartIdx = alignDown(Idx, MaskNumElts); 3731 if (NewStartIdx + MaskNumElts > SrcNumElts || 3732 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3733 CanExtract = false; 3734 // Make sure we always update StartIdx as we use it to track if all 3735 // elements are undef. 3736 StartIdx[Input] = NewStartIdx; 3737 } 3738 3739 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3740 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3741 return; 3742 } 3743 if (CanExtract) { 3744 // Extract appropriate subvector and generate a vector shuffle 3745 for (unsigned Input = 0; Input < 2; ++Input) { 3746 SDValue &Src = Input == 0 ? Src1 : Src2; 3747 if (StartIdx[Input] < 0) 3748 Src = DAG.getUNDEF(VT); 3749 else { 3750 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3751 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3752 } 3753 } 3754 3755 // Calculate new mask. 3756 SmallVector<int, 8> MappedOps(Mask); 3757 for (int &Idx : MappedOps) { 3758 if (Idx >= (int)SrcNumElts) 3759 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3760 else if (Idx >= 0) 3761 Idx -= StartIdx[0]; 3762 } 3763 3764 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3765 return; 3766 } 3767 } 3768 3769 // We can't use either concat vectors or extract subvectors so fall back to 3770 // replacing the shuffle with extract and build vector. 3771 // to insert and build vector. 3772 EVT EltVT = VT.getVectorElementType(); 3773 SmallVector<SDValue,8> Ops; 3774 for (int Idx : Mask) { 3775 SDValue Res; 3776 3777 if (Idx < 0) { 3778 Res = DAG.getUNDEF(EltVT); 3779 } else { 3780 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3781 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3782 3783 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3784 DAG.getVectorIdxConstant(Idx, DL)); 3785 } 3786 3787 Ops.push_back(Res); 3788 } 3789 3790 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3791 } 3792 3793 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3794 ArrayRef<unsigned> Indices = I.getIndices(); 3795 const Value *Op0 = I.getOperand(0); 3796 const Value *Op1 = I.getOperand(1); 3797 Type *AggTy = I.getType(); 3798 Type *ValTy = Op1->getType(); 3799 bool IntoUndef = isa<UndefValue>(Op0); 3800 bool FromUndef = isa<UndefValue>(Op1); 3801 3802 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3803 3804 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3805 SmallVector<EVT, 4> AggValueVTs; 3806 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3807 SmallVector<EVT, 4> ValValueVTs; 3808 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3809 3810 unsigned NumAggValues = AggValueVTs.size(); 3811 unsigned NumValValues = ValValueVTs.size(); 3812 SmallVector<SDValue, 4> Values(NumAggValues); 3813 3814 // Ignore an insertvalue that produces an empty object 3815 if (!NumAggValues) { 3816 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3817 return; 3818 } 3819 3820 SDValue Agg = getValue(Op0); 3821 unsigned i = 0; 3822 // Copy the beginning value(s) from the original aggregate. 3823 for (; i != LinearIndex; ++i) 3824 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3825 SDValue(Agg.getNode(), Agg.getResNo() + i); 3826 // Copy values from the inserted value(s). 3827 if (NumValValues) { 3828 SDValue Val = getValue(Op1); 3829 for (; i != LinearIndex + NumValValues; ++i) 3830 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3831 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3832 } 3833 // Copy remaining value(s) from the original aggregate. 3834 for (; i != NumAggValues; ++i) 3835 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3836 SDValue(Agg.getNode(), Agg.getResNo() + i); 3837 3838 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3839 DAG.getVTList(AggValueVTs), Values)); 3840 } 3841 3842 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3843 ArrayRef<unsigned> Indices = I.getIndices(); 3844 const Value *Op0 = I.getOperand(0); 3845 Type *AggTy = Op0->getType(); 3846 Type *ValTy = I.getType(); 3847 bool OutOfUndef = isa<UndefValue>(Op0); 3848 3849 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3850 3851 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3852 SmallVector<EVT, 4> ValValueVTs; 3853 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3854 3855 unsigned NumValValues = ValValueVTs.size(); 3856 3857 // Ignore a extractvalue that produces an empty object 3858 if (!NumValValues) { 3859 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3860 return; 3861 } 3862 3863 SmallVector<SDValue, 4> Values(NumValValues); 3864 3865 SDValue Agg = getValue(Op0); 3866 // Copy out the selected value(s). 3867 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3868 Values[i - LinearIndex] = 3869 OutOfUndef ? 3870 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3871 SDValue(Agg.getNode(), Agg.getResNo() + i); 3872 3873 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3874 DAG.getVTList(ValValueVTs), Values)); 3875 } 3876 3877 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3878 Value *Op0 = I.getOperand(0); 3879 // Note that the pointer operand may be a vector of pointers. Take the scalar 3880 // element which holds a pointer. 3881 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3882 SDValue N = getValue(Op0); 3883 SDLoc dl = getCurSDLoc(); 3884 auto &TLI = DAG.getTargetLoweringInfo(); 3885 3886 // Normalize Vector GEP - all scalar operands should be converted to the 3887 // splat vector. 3888 bool IsVectorGEP = I.getType()->isVectorTy(); 3889 ElementCount VectorElementCount = 3890 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3891 : ElementCount::getFixed(0); 3892 3893 if (IsVectorGEP && !N.getValueType().isVector()) { 3894 LLVMContext &Context = *DAG.getContext(); 3895 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3896 if (VectorElementCount.isScalable()) 3897 N = DAG.getSplatVector(VT, dl, N); 3898 else 3899 N = DAG.getSplatBuildVector(VT, dl, N); 3900 } 3901 3902 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3903 GTI != E; ++GTI) { 3904 const Value *Idx = GTI.getOperand(); 3905 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3906 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3907 if (Field) { 3908 // N = N + Offset 3909 uint64_t Offset = 3910 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3911 3912 // In an inbounds GEP with an offset that is nonnegative even when 3913 // interpreted as signed, assume there is no unsigned overflow. 3914 SDNodeFlags Flags; 3915 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3916 Flags.setNoUnsignedWrap(true); 3917 3918 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3919 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3920 } 3921 } else { 3922 // IdxSize is the width of the arithmetic according to IR semantics. 3923 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3924 // (and fix up the result later). 3925 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3926 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3927 TypeSize ElementSize = 3928 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3929 // We intentionally mask away the high bits here; ElementSize may not 3930 // fit in IdxTy. 3931 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3932 bool ElementScalable = ElementSize.isScalable(); 3933 3934 // If this is a scalar constant or a splat vector of constants, 3935 // handle it quickly. 3936 const auto *C = dyn_cast<Constant>(Idx); 3937 if (C && isa<VectorType>(C->getType())) 3938 C = C->getSplatValue(); 3939 3940 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3941 if (CI && CI->isZero()) 3942 continue; 3943 if (CI && !ElementScalable) { 3944 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3945 LLVMContext &Context = *DAG.getContext(); 3946 SDValue OffsVal; 3947 if (IsVectorGEP) 3948 OffsVal = DAG.getConstant( 3949 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3950 else 3951 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3952 3953 // In an inbounds GEP with an offset that is nonnegative even when 3954 // interpreted as signed, assume there is no unsigned overflow. 3955 SDNodeFlags Flags; 3956 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3957 Flags.setNoUnsignedWrap(true); 3958 3959 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3960 3961 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3962 continue; 3963 } 3964 3965 // N = N + Idx * ElementMul; 3966 SDValue IdxN = getValue(Idx); 3967 3968 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3969 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3970 VectorElementCount); 3971 if (VectorElementCount.isScalable()) 3972 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3973 else 3974 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3975 } 3976 3977 // If the index is smaller or larger than intptr_t, truncate or extend 3978 // it. 3979 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3980 3981 if (ElementScalable) { 3982 EVT VScaleTy = N.getValueType().getScalarType(); 3983 SDValue VScale = DAG.getNode( 3984 ISD::VSCALE, dl, VScaleTy, 3985 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3986 if (IsVectorGEP) 3987 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3988 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3989 } else { 3990 // If this is a multiply by a power of two, turn it into a shl 3991 // immediately. This is a very common case. 3992 if (ElementMul != 1) { 3993 if (ElementMul.isPowerOf2()) { 3994 unsigned Amt = ElementMul.logBase2(); 3995 IdxN = DAG.getNode(ISD::SHL, dl, 3996 N.getValueType(), IdxN, 3997 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3998 } else { 3999 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4000 IdxN.getValueType()); 4001 IdxN = DAG.getNode(ISD::MUL, dl, 4002 N.getValueType(), IdxN, Scale); 4003 } 4004 } 4005 } 4006 4007 N = DAG.getNode(ISD::ADD, dl, 4008 N.getValueType(), N, IdxN); 4009 } 4010 } 4011 4012 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4013 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4014 if (IsVectorGEP) { 4015 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4016 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4017 } 4018 4019 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4020 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4021 4022 setValue(&I, N); 4023 } 4024 4025 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4026 // If this is a fixed sized alloca in the entry block of the function, 4027 // allocate it statically on the stack. 4028 if (FuncInfo.StaticAllocaMap.count(&I)) 4029 return; // getValue will auto-populate this. 4030 4031 SDLoc dl = getCurSDLoc(); 4032 Type *Ty = I.getAllocatedType(); 4033 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4034 auto &DL = DAG.getDataLayout(); 4035 TypeSize TySize = DL.getTypeAllocSize(Ty); 4036 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4037 4038 SDValue AllocSize = getValue(I.getArraySize()); 4039 4040 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 4041 if (AllocSize.getValueType() != IntPtr) 4042 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4043 4044 if (TySize.isScalable()) 4045 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4046 DAG.getVScale(dl, IntPtr, 4047 APInt(IntPtr.getScalarSizeInBits(), 4048 TySize.getKnownMinValue()))); 4049 else 4050 AllocSize = 4051 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4052 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4053 4054 // Handle alignment. If the requested alignment is less than or equal to 4055 // the stack alignment, ignore it. If the size is greater than or equal to 4056 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4057 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4058 if (*Alignment <= StackAlign) 4059 Alignment = None; 4060 4061 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4062 // Round the size of the allocation up to the stack alignment size 4063 // by add SA-1 to the size. This doesn't overflow because we're computing 4064 // an address inside an alloca. 4065 SDNodeFlags Flags; 4066 Flags.setNoUnsignedWrap(true); 4067 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4068 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4069 4070 // Mask out the low bits for alignment purposes. 4071 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4072 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4073 4074 SDValue Ops[] = { 4075 getRoot(), AllocSize, 4076 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4077 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4078 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4079 setValue(&I, DSA); 4080 DAG.setRoot(DSA.getValue(1)); 4081 4082 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4083 } 4084 4085 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4086 if (I.isAtomic()) 4087 return visitAtomicLoad(I); 4088 4089 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4090 const Value *SV = I.getOperand(0); 4091 if (TLI.supportSwiftError()) { 4092 // Swifterror values can come from either a function parameter with 4093 // swifterror attribute or an alloca with swifterror attribute. 4094 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4095 if (Arg->hasSwiftErrorAttr()) 4096 return visitLoadFromSwiftError(I); 4097 } 4098 4099 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4100 if (Alloca->isSwiftError()) 4101 return visitLoadFromSwiftError(I); 4102 } 4103 } 4104 4105 SDValue Ptr = getValue(SV); 4106 4107 Type *Ty = I.getType(); 4108 SmallVector<EVT, 4> ValueVTs, MemVTs; 4109 SmallVector<uint64_t, 4> Offsets; 4110 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4111 unsigned NumValues = ValueVTs.size(); 4112 if (NumValues == 0) 4113 return; 4114 4115 Align Alignment = I.getAlign(); 4116 AAMDNodes AAInfo = I.getAAMetadata(); 4117 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4118 bool isVolatile = I.isVolatile(); 4119 MachineMemOperand::Flags MMOFlags = 4120 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4121 4122 SDValue Root; 4123 bool ConstantMemory = false; 4124 if (isVolatile) 4125 // Serialize volatile loads with other side effects. 4126 Root = getRoot(); 4127 else if (NumValues > MaxParallelChains) 4128 Root = getMemoryRoot(); 4129 else if (AA && 4130 AA->pointsToConstantMemory(MemoryLocation( 4131 SV, 4132 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4133 AAInfo))) { 4134 // Do not serialize (non-volatile) loads of constant memory with anything. 4135 Root = DAG.getEntryNode(); 4136 ConstantMemory = true; 4137 MMOFlags |= MachineMemOperand::MOInvariant; 4138 } else { 4139 // Do not serialize non-volatile loads against each other. 4140 Root = DAG.getRoot(); 4141 } 4142 4143 if (isDereferenceableAndAlignedPointer(SV, Ty, Alignment, DAG.getDataLayout(), 4144 &I, AC, nullptr, LibInfo)) 4145 MMOFlags |= MachineMemOperand::MODereferenceable; 4146 4147 SDLoc dl = getCurSDLoc(); 4148 4149 if (isVolatile) 4150 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4151 4152 // An aggregate load cannot wrap around the address space, so offsets to its 4153 // parts don't wrap either. 4154 SDNodeFlags Flags; 4155 Flags.setNoUnsignedWrap(true); 4156 4157 SmallVector<SDValue, 4> Values(NumValues); 4158 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4159 EVT PtrVT = Ptr.getValueType(); 4160 4161 unsigned ChainI = 0; 4162 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4163 // Serializing loads here may result in excessive register pressure, and 4164 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4165 // could recover a bit by hoisting nodes upward in the chain by recognizing 4166 // they are side-effect free or do not alias. The optimizer should really 4167 // avoid this case by converting large object/array copies to llvm.memcpy 4168 // (MaxParallelChains should always remain as failsafe). 4169 if (ChainI == MaxParallelChains) { 4170 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4171 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4172 makeArrayRef(Chains.data(), ChainI)); 4173 Root = Chain; 4174 ChainI = 0; 4175 } 4176 SDValue A = DAG.getNode(ISD::ADD, dl, 4177 PtrVT, Ptr, 4178 DAG.getConstant(Offsets[i], dl, PtrVT), 4179 Flags); 4180 4181 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4182 MachinePointerInfo(SV, Offsets[i]), Alignment, 4183 MMOFlags, AAInfo, Ranges); 4184 Chains[ChainI] = L.getValue(1); 4185 4186 if (MemVTs[i] != ValueVTs[i]) 4187 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4188 4189 Values[i] = L; 4190 } 4191 4192 if (!ConstantMemory) { 4193 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4194 makeArrayRef(Chains.data(), ChainI)); 4195 if (isVolatile) 4196 DAG.setRoot(Chain); 4197 else 4198 PendingLoads.push_back(Chain); 4199 } 4200 4201 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4202 DAG.getVTList(ValueVTs), Values)); 4203 } 4204 4205 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4206 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4207 "call visitStoreToSwiftError when backend supports swifterror"); 4208 4209 SmallVector<EVT, 4> ValueVTs; 4210 SmallVector<uint64_t, 4> Offsets; 4211 const Value *SrcV = I.getOperand(0); 4212 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4213 SrcV->getType(), ValueVTs, &Offsets); 4214 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4215 "expect a single EVT for swifterror"); 4216 4217 SDValue Src = getValue(SrcV); 4218 // Create a virtual register, then update the virtual register. 4219 Register VReg = 4220 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4221 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4222 // Chain can be getRoot or getControlRoot. 4223 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4224 SDValue(Src.getNode(), Src.getResNo())); 4225 DAG.setRoot(CopyNode); 4226 } 4227 4228 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4229 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4230 "call visitLoadFromSwiftError when backend supports swifterror"); 4231 4232 assert(!I.isVolatile() && 4233 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4234 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4235 "Support volatile, non temporal, invariant for load_from_swift_error"); 4236 4237 const Value *SV = I.getOperand(0); 4238 Type *Ty = I.getType(); 4239 assert( 4240 (!AA || 4241 !AA->pointsToConstantMemory(MemoryLocation( 4242 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4243 I.getAAMetadata()))) && 4244 "load_from_swift_error should not be constant memory"); 4245 4246 SmallVector<EVT, 4> ValueVTs; 4247 SmallVector<uint64_t, 4> Offsets; 4248 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4249 ValueVTs, &Offsets); 4250 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4251 "expect a single EVT for swifterror"); 4252 4253 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4254 SDValue L = DAG.getCopyFromReg( 4255 getRoot(), getCurSDLoc(), 4256 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4257 4258 setValue(&I, L); 4259 } 4260 4261 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4262 if (I.isAtomic()) 4263 return visitAtomicStore(I); 4264 4265 const Value *SrcV = I.getOperand(0); 4266 const Value *PtrV = I.getOperand(1); 4267 4268 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4269 if (TLI.supportSwiftError()) { 4270 // Swifterror values can come from either a function parameter with 4271 // swifterror attribute or an alloca with swifterror attribute. 4272 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4273 if (Arg->hasSwiftErrorAttr()) 4274 return visitStoreToSwiftError(I); 4275 } 4276 4277 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4278 if (Alloca->isSwiftError()) 4279 return visitStoreToSwiftError(I); 4280 } 4281 } 4282 4283 SmallVector<EVT, 4> ValueVTs, MemVTs; 4284 SmallVector<uint64_t, 4> Offsets; 4285 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4286 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4287 unsigned NumValues = ValueVTs.size(); 4288 if (NumValues == 0) 4289 return; 4290 4291 // Get the lowered operands. Note that we do this after 4292 // checking if NumResults is zero, because with zero results 4293 // the operands won't have values in the map. 4294 SDValue Src = getValue(SrcV); 4295 SDValue Ptr = getValue(PtrV); 4296 4297 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4298 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4299 SDLoc dl = getCurSDLoc(); 4300 Align Alignment = I.getAlign(); 4301 AAMDNodes AAInfo = I.getAAMetadata(); 4302 4303 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4304 4305 // An aggregate load cannot wrap around the address space, so offsets to its 4306 // parts don't wrap either. 4307 SDNodeFlags Flags; 4308 Flags.setNoUnsignedWrap(true); 4309 4310 unsigned ChainI = 0; 4311 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4312 // See visitLoad comments. 4313 if (ChainI == MaxParallelChains) { 4314 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4315 makeArrayRef(Chains.data(), ChainI)); 4316 Root = Chain; 4317 ChainI = 0; 4318 } 4319 SDValue Add = 4320 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4321 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4322 if (MemVTs[i] != ValueVTs[i]) 4323 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4324 SDValue St = 4325 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4326 Alignment, MMOFlags, AAInfo); 4327 Chains[ChainI] = St; 4328 } 4329 4330 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4331 makeArrayRef(Chains.data(), ChainI)); 4332 setValue(&I, StoreNode); 4333 DAG.setRoot(StoreNode); 4334 } 4335 4336 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4337 bool IsCompressing) { 4338 SDLoc sdl = getCurSDLoc(); 4339 4340 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4341 MaybeAlign &Alignment) { 4342 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4343 Src0 = I.getArgOperand(0); 4344 Ptr = I.getArgOperand(1); 4345 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4346 Mask = I.getArgOperand(3); 4347 }; 4348 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4349 MaybeAlign &Alignment) { 4350 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4351 Src0 = I.getArgOperand(0); 4352 Ptr = I.getArgOperand(1); 4353 Mask = I.getArgOperand(2); 4354 Alignment = None; 4355 }; 4356 4357 Value *PtrOperand, *MaskOperand, *Src0Operand; 4358 MaybeAlign Alignment; 4359 if (IsCompressing) 4360 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4361 else 4362 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4363 4364 SDValue Ptr = getValue(PtrOperand); 4365 SDValue Src0 = getValue(Src0Operand); 4366 SDValue Mask = getValue(MaskOperand); 4367 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4368 4369 EVT VT = Src0.getValueType(); 4370 if (!Alignment) 4371 Alignment = DAG.getEVTAlign(VT); 4372 4373 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4374 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4375 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4376 SDValue StoreNode = 4377 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4378 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4379 DAG.setRoot(StoreNode); 4380 setValue(&I, StoreNode); 4381 } 4382 4383 // Get a uniform base for the Gather/Scatter intrinsic. 4384 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4385 // We try to represent it as a base pointer + vector of indices. 4386 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4387 // The first operand of the GEP may be a single pointer or a vector of pointers 4388 // Example: 4389 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4390 // or 4391 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4392 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4393 // 4394 // When the first GEP operand is a single pointer - it is the uniform base we 4395 // are looking for. If first operand of the GEP is a splat vector - we 4396 // extract the splat value and use it as a uniform base. 4397 // In all other cases the function returns 'false'. 4398 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4399 ISD::MemIndexType &IndexType, SDValue &Scale, 4400 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4401 uint64_t ElemSize) { 4402 SelectionDAG& DAG = SDB->DAG; 4403 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4404 const DataLayout &DL = DAG.getDataLayout(); 4405 4406 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4407 4408 // Handle splat constant pointer. 4409 if (auto *C = dyn_cast<Constant>(Ptr)) { 4410 C = C->getSplatValue(); 4411 if (!C) 4412 return false; 4413 4414 Base = SDB->getValue(C); 4415 4416 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4417 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4418 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4419 IndexType = ISD::SIGNED_SCALED; 4420 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4421 return true; 4422 } 4423 4424 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4425 if (!GEP || GEP->getParent() != CurBB) 4426 return false; 4427 4428 if (GEP->getNumOperands() != 2) 4429 return false; 4430 4431 const Value *BasePtr = GEP->getPointerOperand(); 4432 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4433 4434 // Make sure the base is scalar and the index is a vector. 4435 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4436 return false; 4437 4438 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4439 4440 // Target may not support the required addressing mode. 4441 if (ScaleVal != 1 && 4442 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4443 return false; 4444 4445 Base = SDB->getValue(BasePtr); 4446 Index = SDB->getValue(IndexVal); 4447 IndexType = ISD::SIGNED_SCALED; 4448 4449 Scale = 4450 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4451 return true; 4452 } 4453 4454 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4455 SDLoc sdl = getCurSDLoc(); 4456 4457 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4458 const Value *Ptr = I.getArgOperand(1); 4459 SDValue Src0 = getValue(I.getArgOperand(0)); 4460 SDValue Mask = getValue(I.getArgOperand(3)); 4461 EVT VT = Src0.getValueType(); 4462 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4463 ->getMaybeAlignValue() 4464 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4465 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4466 4467 SDValue Base; 4468 SDValue Index; 4469 ISD::MemIndexType IndexType; 4470 SDValue Scale; 4471 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4472 I.getParent(), VT.getScalarStoreSize()); 4473 4474 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4475 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4476 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4477 // TODO: Make MachineMemOperands aware of scalable 4478 // vectors. 4479 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4480 if (!UniformBase) { 4481 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4482 Index = getValue(Ptr); 4483 IndexType = ISD::SIGNED_SCALED; 4484 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4485 } 4486 4487 EVT IdxVT = Index.getValueType(); 4488 EVT EltTy = IdxVT.getVectorElementType(); 4489 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4490 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4491 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4492 } 4493 4494 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4495 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4496 Ops, MMO, IndexType, false); 4497 DAG.setRoot(Scatter); 4498 setValue(&I, Scatter); 4499 } 4500 4501 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4502 SDLoc sdl = getCurSDLoc(); 4503 4504 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4505 MaybeAlign &Alignment) { 4506 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4507 Ptr = I.getArgOperand(0); 4508 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4509 Mask = I.getArgOperand(2); 4510 Src0 = I.getArgOperand(3); 4511 }; 4512 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4513 MaybeAlign &Alignment) { 4514 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4515 Ptr = I.getArgOperand(0); 4516 Alignment = None; 4517 Mask = I.getArgOperand(1); 4518 Src0 = I.getArgOperand(2); 4519 }; 4520 4521 Value *PtrOperand, *MaskOperand, *Src0Operand; 4522 MaybeAlign Alignment; 4523 if (IsExpanding) 4524 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4525 else 4526 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4527 4528 SDValue Ptr = getValue(PtrOperand); 4529 SDValue Src0 = getValue(Src0Operand); 4530 SDValue Mask = getValue(MaskOperand); 4531 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4532 4533 EVT VT = Src0.getValueType(); 4534 if (!Alignment) 4535 Alignment = DAG.getEVTAlign(VT); 4536 4537 AAMDNodes AAInfo = I.getAAMetadata(); 4538 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4539 4540 // Do not serialize masked loads of constant memory with anything. 4541 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4542 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4543 4544 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4545 4546 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4547 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4548 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4549 4550 SDValue Load = 4551 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4552 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4553 if (AddToChain) 4554 PendingLoads.push_back(Load.getValue(1)); 4555 setValue(&I, Load); 4556 } 4557 4558 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4559 SDLoc sdl = getCurSDLoc(); 4560 4561 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4562 const Value *Ptr = I.getArgOperand(0); 4563 SDValue Src0 = getValue(I.getArgOperand(3)); 4564 SDValue Mask = getValue(I.getArgOperand(2)); 4565 4566 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4567 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4568 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4569 ->getMaybeAlignValue() 4570 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4571 4572 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4573 4574 SDValue Root = DAG.getRoot(); 4575 SDValue Base; 4576 SDValue Index; 4577 ISD::MemIndexType IndexType; 4578 SDValue Scale; 4579 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4580 I.getParent(), VT.getScalarStoreSize()); 4581 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4582 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4583 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4584 // TODO: Make MachineMemOperands aware of scalable 4585 // vectors. 4586 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4587 4588 if (!UniformBase) { 4589 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4590 Index = getValue(Ptr); 4591 IndexType = ISD::SIGNED_SCALED; 4592 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4593 } 4594 4595 EVT IdxVT = Index.getValueType(); 4596 EVT EltTy = IdxVT.getVectorElementType(); 4597 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4598 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4599 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4600 } 4601 4602 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4603 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4604 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4605 4606 PendingLoads.push_back(Gather.getValue(1)); 4607 setValue(&I, Gather); 4608 } 4609 4610 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4611 SDLoc dl = getCurSDLoc(); 4612 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4613 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4614 SyncScope::ID SSID = I.getSyncScopeID(); 4615 4616 SDValue InChain = getRoot(); 4617 4618 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4619 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4620 4621 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4622 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4623 4624 MachineFunction &MF = DAG.getMachineFunction(); 4625 MachineMemOperand *MMO = MF.getMachineMemOperand( 4626 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4627 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4628 FailureOrdering); 4629 4630 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4631 dl, MemVT, VTs, InChain, 4632 getValue(I.getPointerOperand()), 4633 getValue(I.getCompareOperand()), 4634 getValue(I.getNewValOperand()), MMO); 4635 4636 SDValue OutChain = L.getValue(2); 4637 4638 setValue(&I, L); 4639 DAG.setRoot(OutChain); 4640 } 4641 4642 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4643 SDLoc dl = getCurSDLoc(); 4644 ISD::NodeType NT; 4645 switch (I.getOperation()) { 4646 default: llvm_unreachable("Unknown atomicrmw operation"); 4647 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4648 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4649 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4650 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4651 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4652 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4653 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4654 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4655 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4656 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4657 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4658 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4659 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4660 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4661 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4662 } 4663 AtomicOrdering Ordering = I.getOrdering(); 4664 SyncScope::ID SSID = I.getSyncScopeID(); 4665 4666 SDValue InChain = getRoot(); 4667 4668 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4669 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4670 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4671 4672 MachineFunction &MF = DAG.getMachineFunction(); 4673 MachineMemOperand *MMO = MF.getMachineMemOperand( 4674 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4675 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4676 4677 SDValue L = 4678 DAG.getAtomic(NT, dl, MemVT, InChain, 4679 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4680 MMO); 4681 4682 SDValue OutChain = L.getValue(1); 4683 4684 setValue(&I, L); 4685 DAG.setRoot(OutChain); 4686 } 4687 4688 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4689 SDLoc dl = getCurSDLoc(); 4690 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4691 SDValue Ops[3]; 4692 Ops[0] = getRoot(); 4693 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4694 TLI.getFenceOperandTy(DAG.getDataLayout())); 4695 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4696 TLI.getFenceOperandTy(DAG.getDataLayout())); 4697 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4698 setValue(&I, N); 4699 DAG.setRoot(N); 4700 } 4701 4702 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4703 SDLoc dl = getCurSDLoc(); 4704 AtomicOrdering Order = I.getOrdering(); 4705 SyncScope::ID SSID = I.getSyncScopeID(); 4706 4707 SDValue InChain = getRoot(); 4708 4709 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4710 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4711 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4712 4713 if (!TLI.supportsUnalignedAtomics() && 4714 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4715 report_fatal_error("Cannot generate unaligned atomic load"); 4716 4717 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4718 4719 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4720 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4721 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4722 4723 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4724 4725 SDValue Ptr = getValue(I.getPointerOperand()); 4726 4727 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4728 // TODO: Once this is better exercised by tests, it should be merged with 4729 // the normal path for loads to prevent future divergence. 4730 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4731 if (MemVT != VT) 4732 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4733 4734 setValue(&I, L); 4735 SDValue OutChain = L.getValue(1); 4736 if (!I.isUnordered()) 4737 DAG.setRoot(OutChain); 4738 else 4739 PendingLoads.push_back(OutChain); 4740 return; 4741 } 4742 4743 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4744 Ptr, MMO); 4745 4746 SDValue OutChain = L.getValue(1); 4747 if (MemVT != VT) 4748 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4749 4750 setValue(&I, L); 4751 DAG.setRoot(OutChain); 4752 } 4753 4754 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4755 SDLoc dl = getCurSDLoc(); 4756 4757 AtomicOrdering Ordering = I.getOrdering(); 4758 SyncScope::ID SSID = I.getSyncScopeID(); 4759 4760 SDValue InChain = getRoot(); 4761 4762 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4763 EVT MemVT = 4764 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4765 4766 if (!TLI.supportsUnalignedAtomics() && 4767 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4768 report_fatal_error("Cannot generate unaligned atomic store"); 4769 4770 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4771 4772 MachineFunction &MF = DAG.getMachineFunction(); 4773 MachineMemOperand *MMO = MF.getMachineMemOperand( 4774 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4775 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4776 4777 SDValue Val = getValue(I.getValueOperand()); 4778 if (Val.getValueType() != MemVT) 4779 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4780 SDValue Ptr = getValue(I.getPointerOperand()); 4781 4782 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4783 // TODO: Once this is better exercised by tests, it should be merged with 4784 // the normal path for stores to prevent future divergence. 4785 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4786 setValue(&I, S); 4787 DAG.setRoot(S); 4788 return; 4789 } 4790 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4791 Ptr, Val, MMO); 4792 4793 setValue(&I, OutChain); 4794 DAG.setRoot(OutChain); 4795 } 4796 4797 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4798 /// node. 4799 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4800 unsigned Intrinsic) { 4801 // Ignore the callsite's attributes. A specific call site may be marked with 4802 // readnone, but the lowering code will expect the chain based on the 4803 // definition. 4804 const Function *F = I.getCalledFunction(); 4805 bool HasChain = !F->doesNotAccessMemory(); 4806 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4807 4808 // Build the operand list. 4809 SmallVector<SDValue, 8> Ops; 4810 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4811 if (OnlyLoad) { 4812 // We don't need to serialize loads against other loads. 4813 Ops.push_back(DAG.getRoot()); 4814 } else { 4815 Ops.push_back(getRoot()); 4816 } 4817 } 4818 4819 // Info is set by getTgtMemIntrinsic 4820 TargetLowering::IntrinsicInfo Info; 4821 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4822 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4823 DAG.getMachineFunction(), 4824 Intrinsic); 4825 4826 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4827 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4828 Info.opc == ISD::INTRINSIC_W_CHAIN) 4829 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4830 TLI.getPointerTy(DAG.getDataLayout()))); 4831 4832 // Add all operands of the call to the operand list. 4833 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4834 const Value *Arg = I.getArgOperand(i); 4835 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4836 Ops.push_back(getValue(Arg)); 4837 continue; 4838 } 4839 4840 // Use TargetConstant instead of a regular constant for immarg. 4841 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4842 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4843 assert(CI->getBitWidth() <= 64 && 4844 "large intrinsic immediates not handled"); 4845 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4846 } else { 4847 Ops.push_back( 4848 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4849 } 4850 } 4851 4852 SmallVector<EVT, 4> ValueVTs; 4853 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4854 4855 if (HasChain) 4856 ValueVTs.push_back(MVT::Other); 4857 4858 SDVTList VTs = DAG.getVTList(ValueVTs); 4859 4860 // Propagate fast-math-flags from IR to node(s). 4861 SDNodeFlags Flags; 4862 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4863 Flags.copyFMF(*FPMO); 4864 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4865 4866 // Create the node. 4867 SDValue Result; 4868 if (IsTgtIntrinsic) { 4869 // This is target intrinsic that touches memory 4870 Result = 4871 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4872 MachinePointerInfo(Info.ptrVal, Info.offset), 4873 Info.align, Info.flags, Info.size, 4874 I.getAAMetadata()); 4875 } else if (!HasChain) { 4876 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4877 } else if (!I.getType()->isVoidTy()) { 4878 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4879 } else { 4880 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4881 } 4882 4883 if (HasChain) { 4884 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4885 if (OnlyLoad) 4886 PendingLoads.push_back(Chain); 4887 else 4888 DAG.setRoot(Chain); 4889 } 4890 4891 if (!I.getType()->isVoidTy()) { 4892 if (!isa<VectorType>(I.getType())) 4893 Result = lowerRangeToAssertZExt(DAG, I, Result); 4894 4895 MaybeAlign Alignment = I.getRetAlign(); 4896 if (!Alignment) 4897 Alignment = F->getAttributes().getRetAlignment(); 4898 // Insert `assertalign` node if there's an alignment. 4899 if (InsertAssertAlign && Alignment) { 4900 Result = 4901 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4902 } 4903 4904 setValue(&I, Result); 4905 } 4906 } 4907 4908 /// GetSignificand - Get the significand and build it into a floating-point 4909 /// number with exponent of 1: 4910 /// 4911 /// Op = (Op & 0x007fffff) | 0x3f800000; 4912 /// 4913 /// where Op is the hexadecimal representation of floating point value. 4914 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4915 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4916 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4917 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4918 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4919 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4920 } 4921 4922 /// GetExponent - Get the exponent: 4923 /// 4924 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4925 /// 4926 /// where Op is the hexadecimal representation of floating point value. 4927 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4928 const TargetLowering &TLI, const SDLoc &dl) { 4929 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4930 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4931 SDValue t1 = DAG.getNode( 4932 ISD::SRL, dl, MVT::i32, t0, 4933 DAG.getConstant(23, dl, 4934 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 4935 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4936 DAG.getConstant(127, dl, MVT::i32)); 4937 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4938 } 4939 4940 /// getF32Constant - Get 32-bit floating point constant. 4941 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4942 const SDLoc &dl) { 4943 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4944 MVT::f32); 4945 } 4946 4947 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4948 SelectionDAG &DAG) { 4949 // TODO: What fast-math-flags should be set on the floating-point nodes? 4950 4951 // IntegerPartOfX = ((int32_t)(t0); 4952 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4953 4954 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4955 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4956 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4957 4958 // IntegerPartOfX <<= 23; 4959 IntegerPartOfX = 4960 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4961 DAG.getConstant(23, dl, 4962 DAG.getTargetLoweringInfo().getShiftAmountTy( 4963 MVT::i32, DAG.getDataLayout()))); 4964 4965 SDValue TwoToFractionalPartOfX; 4966 if (LimitFloatPrecision <= 6) { 4967 // For floating-point precision of 6: 4968 // 4969 // TwoToFractionalPartOfX = 4970 // 0.997535578f + 4971 // (0.735607626f + 0.252464424f * x) * x; 4972 // 4973 // error 0.0144103317, which is 6 bits 4974 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4975 getF32Constant(DAG, 0x3e814304, dl)); 4976 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4977 getF32Constant(DAG, 0x3f3c50c8, dl)); 4978 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4979 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4980 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4981 } else if (LimitFloatPrecision <= 12) { 4982 // For floating-point precision of 12: 4983 // 4984 // TwoToFractionalPartOfX = 4985 // 0.999892986f + 4986 // (0.696457318f + 4987 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4988 // 4989 // error 0.000107046256, which is 13 to 14 bits 4990 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4991 getF32Constant(DAG, 0x3da235e3, dl)); 4992 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4993 getF32Constant(DAG, 0x3e65b8f3, dl)); 4994 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4995 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4996 getF32Constant(DAG, 0x3f324b07, dl)); 4997 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4998 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4999 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5000 } else { // LimitFloatPrecision <= 18 5001 // For floating-point precision of 18: 5002 // 5003 // TwoToFractionalPartOfX = 5004 // 0.999999982f + 5005 // (0.693148872f + 5006 // (0.240227044f + 5007 // (0.554906021e-1f + 5008 // (0.961591928e-2f + 5009 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5010 // error 2.47208000*10^(-7), which is better than 18 bits 5011 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5012 getF32Constant(DAG, 0x3924b03e, dl)); 5013 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5014 getF32Constant(DAG, 0x3ab24b87, dl)); 5015 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5016 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5017 getF32Constant(DAG, 0x3c1d8c17, dl)); 5018 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5019 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5020 getF32Constant(DAG, 0x3d634a1d, dl)); 5021 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5022 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5023 getF32Constant(DAG, 0x3e75fe14, dl)); 5024 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5025 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5026 getF32Constant(DAG, 0x3f317234, dl)); 5027 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5028 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5029 getF32Constant(DAG, 0x3f800000, dl)); 5030 } 5031 5032 // Add the exponent into the result in integer domain. 5033 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5034 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5035 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5036 } 5037 5038 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5039 /// limited-precision mode. 5040 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5041 const TargetLowering &TLI, SDNodeFlags Flags) { 5042 if (Op.getValueType() == MVT::f32 && 5043 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5044 5045 // Put the exponent in the right bit position for later addition to the 5046 // final result: 5047 // 5048 // t0 = Op * log2(e) 5049 5050 // TODO: What fast-math-flags should be set here? 5051 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5052 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5053 return getLimitedPrecisionExp2(t0, dl, DAG); 5054 } 5055 5056 // No special expansion. 5057 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5058 } 5059 5060 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5061 /// limited-precision mode. 5062 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5063 const TargetLowering &TLI, SDNodeFlags Flags) { 5064 // TODO: What fast-math-flags should be set on the floating-point nodes? 5065 5066 if (Op.getValueType() == MVT::f32 && 5067 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5068 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5069 5070 // Scale the exponent by log(2). 5071 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5072 SDValue LogOfExponent = 5073 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5074 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5075 5076 // Get the significand and build it into a floating-point number with 5077 // exponent of 1. 5078 SDValue X = GetSignificand(DAG, Op1, dl); 5079 5080 SDValue LogOfMantissa; 5081 if (LimitFloatPrecision <= 6) { 5082 // For floating-point precision of 6: 5083 // 5084 // LogofMantissa = 5085 // -1.1609546f + 5086 // (1.4034025f - 0.23903021f * x) * x; 5087 // 5088 // error 0.0034276066, which is better than 8 bits 5089 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5090 getF32Constant(DAG, 0xbe74c456, dl)); 5091 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5092 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5093 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5094 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5095 getF32Constant(DAG, 0x3f949a29, dl)); 5096 } else if (LimitFloatPrecision <= 12) { 5097 // For floating-point precision of 12: 5098 // 5099 // LogOfMantissa = 5100 // -1.7417939f + 5101 // (2.8212026f + 5102 // (-1.4699568f + 5103 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5104 // 5105 // error 0.000061011436, which is 14 bits 5106 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5107 getF32Constant(DAG, 0xbd67b6d6, dl)); 5108 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5109 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5110 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5111 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5112 getF32Constant(DAG, 0x3fbc278b, dl)); 5113 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5114 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5115 getF32Constant(DAG, 0x40348e95, dl)); 5116 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5117 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5118 getF32Constant(DAG, 0x3fdef31a, dl)); 5119 } else { // LimitFloatPrecision <= 18 5120 // For floating-point precision of 18: 5121 // 5122 // LogOfMantissa = 5123 // -2.1072184f + 5124 // (4.2372794f + 5125 // (-3.7029485f + 5126 // (2.2781945f + 5127 // (-0.87823314f + 5128 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5129 // 5130 // error 0.0000023660568, which is better than 18 bits 5131 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5132 getF32Constant(DAG, 0xbc91e5ac, dl)); 5133 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5134 getF32Constant(DAG, 0x3e4350aa, dl)); 5135 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5136 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5137 getF32Constant(DAG, 0x3f60d3e3, dl)); 5138 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5139 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5140 getF32Constant(DAG, 0x4011cdf0, dl)); 5141 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5142 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5143 getF32Constant(DAG, 0x406cfd1c, dl)); 5144 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5145 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5146 getF32Constant(DAG, 0x408797cb, dl)); 5147 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5148 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5149 getF32Constant(DAG, 0x4006dcab, dl)); 5150 } 5151 5152 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5153 } 5154 5155 // No special expansion. 5156 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5157 } 5158 5159 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5160 /// limited-precision mode. 5161 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5162 const TargetLowering &TLI, SDNodeFlags Flags) { 5163 // TODO: What fast-math-flags should be set on the floating-point nodes? 5164 5165 if (Op.getValueType() == MVT::f32 && 5166 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5167 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5168 5169 // Get the exponent. 5170 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5171 5172 // Get the significand and build it into a floating-point number with 5173 // exponent of 1. 5174 SDValue X = GetSignificand(DAG, Op1, dl); 5175 5176 // Different possible minimax approximations of significand in 5177 // floating-point for various degrees of accuracy over [1,2]. 5178 SDValue Log2ofMantissa; 5179 if (LimitFloatPrecision <= 6) { 5180 // For floating-point precision of 6: 5181 // 5182 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5183 // 5184 // error 0.0049451742, which is more than 7 bits 5185 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5186 getF32Constant(DAG, 0xbeb08fe0, dl)); 5187 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5188 getF32Constant(DAG, 0x40019463, dl)); 5189 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5190 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5191 getF32Constant(DAG, 0x3fd6633d, dl)); 5192 } else if (LimitFloatPrecision <= 12) { 5193 // For floating-point precision of 12: 5194 // 5195 // Log2ofMantissa = 5196 // -2.51285454f + 5197 // (4.07009056f + 5198 // (-2.12067489f + 5199 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5200 // 5201 // error 0.0000876136000, which is better than 13 bits 5202 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5203 getF32Constant(DAG, 0xbda7262e, dl)); 5204 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5205 getF32Constant(DAG, 0x3f25280b, dl)); 5206 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5207 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5208 getF32Constant(DAG, 0x4007b923, dl)); 5209 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5210 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5211 getF32Constant(DAG, 0x40823e2f, dl)); 5212 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5213 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5214 getF32Constant(DAG, 0x4020d29c, dl)); 5215 } else { // LimitFloatPrecision <= 18 5216 // For floating-point precision of 18: 5217 // 5218 // Log2ofMantissa = 5219 // -3.0400495f + 5220 // (6.1129976f + 5221 // (-5.3420409f + 5222 // (3.2865683f + 5223 // (-1.2669343f + 5224 // (0.27515199f - 5225 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5226 // 5227 // error 0.0000018516, which is better than 18 bits 5228 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5229 getF32Constant(DAG, 0xbcd2769e, dl)); 5230 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5231 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5232 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5233 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5234 getF32Constant(DAG, 0x3fa22ae7, dl)); 5235 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5236 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5237 getF32Constant(DAG, 0x40525723, dl)); 5238 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5239 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5240 getF32Constant(DAG, 0x40aaf200, dl)); 5241 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5242 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5243 getF32Constant(DAG, 0x40c39dad, dl)); 5244 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5245 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5246 getF32Constant(DAG, 0x4042902c, dl)); 5247 } 5248 5249 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5250 } 5251 5252 // No special expansion. 5253 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5254 } 5255 5256 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5257 /// limited-precision mode. 5258 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5259 const TargetLowering &TLI, SDNodeFlags Flags) { 5260 // TODO: What fast-math-flags should be set on the floating-point nodes? 5261 5262 if (Op.getValueType() == MVT::f32 && 5263 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5264 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5265 5266 // Scale the exponent by log10(2) [0.30102999f]. 5267 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5268 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5269 getF32Constant(DAG, 0x3e9a209a, dl)); 5270 5271 // Get the significand and build it into a floating-point number with 5272 // exponent of 1. 5273 SDValue X = GetSignificand(DAG, Op1, dl); 5274 5275 SDValue Log10ofMantissa; 5276 if (LimitFloatPrecision <= 6) { 5277 // For floating-point precision of 6: 5278 // 5279 // Log10ofMantissa = 5280 // -0.50419619f + 5281 // (0.60948995f - 0.10380950f * x) * x; 5282 // 5283 // error 0.0014886165, which is 6 bits 5284 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5285 getF32Constant(DAG, 0xbdd49a13, dl)); 5286 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5287 getF32Constant(DAG, 0x3f1c0789, dl)); 5288 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5289 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5290 getF32Constant(DAG, 0x3f011300, dl)); 5291 } else if (LimitFloatPrecision <= 12) { 5292 // For floating-point precision of 12: 5293 // 5294 // Log10ofMantissa = 5295 // -0.64831180f + 5296 // (0.91751397f + 5297 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5298 // 5299 // error 0.00019228036, which is better than 12 bits 5300 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5301 getF32Constant(DAG, 0x3d431f31, dl)); 5302 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5303 getF32Constant(DAG, 0x3ea21fb2, dl)); 5304 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5305 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5306 getF32Constant(DAG, 0x3f6ae232, dl)); 5307 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5308 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5309 getF32Constant(DAG, 0x3f25f7c3, dl)); 5310 } else { // LimitFloatPrecision <= 18 5311 // For floating-point precision of 18: 5312 // 5313 // Log10ofMantissa = 5314 // -0.84299375f + 5315 // (1.5327582f + 5316 // (-1.0688956f + 5317 // (0.49102474f + 5318 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5319 // 5320 // error 0.0000037995730, which is better than 18 bits 5321 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5322 getF32Constant(DAG, 0x3c5d51ce, dl)); 5323 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5324 getF32Constant(DAG, 0x3e00685a, dl)); 5325 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5326 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5327 getF32Constant(DAG, 0x3efb6798, dl)); 5328 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5329 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5330 getF32Constant(DAG, 0x3f88d192, dl)); 5331 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5332 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5333 getF32Constant(DAG, 0x3fc4316c, dl)); 5334 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5335 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5336 getF32Constant(DAG, 0x3f57ce70, dl)); 5337 } 5338 5339 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5340 } 5341 5342 // No special expansion. 5343 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5344 } 5345 5346 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5347 /// limited-precision mode. 5348 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5349 const TargetLowering &TLI, SDNodeFlags Flags) { 5350 if (Op.getValueType() == MVT::f32 && 5351 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5352 return getLimitedPrecisionExp2(Op, dl, DAG); 5353 5354 // No special expansion. 5355 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5356 } 5357 5358 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5359 /// limited-precision mode with x == 10.0f. 5360 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5361 SelectionDAG &DAG, const TargetLowering &TLI, 5362 SDNodeFlags Flags) { 5363 bool IsExp10 = false; 5364 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5365 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5366 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5367 APFloat Ten(10.0f); 5368 IsExp10 = LHSC->isExactlyValue(Ten); 5369 } 5370 } 5371 5372 // TODO: What fast-math-flags should be set on the FMUL node? 5373 if (IsExp10) { 5374 // Put the exponent in the right bit position for later addition to the 5375 // final result: 5376 // 5377 // #define LOG2OF10 3.3219281f 5378 // t0 = Op * LOG2OF10; 5379 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5380 getF32Constant(DAG, 0x40549a78, dl)); 5381 return getLimitedPrecisionExp2(t0, dl, DAG); 5382 } 5383 5384 // No special expansion. 5385 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5386 } 5387 5388 /// ExpandPowI - Expand a llvm.powi intrinsic. 5389 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5390 SelectionDAG &DAG) { 5391 // If RHS is a constant, we can expand this out to a multiplication tree if 5392 // it's beneficial on the target, otherwise we end up lowering to a call to 5393 // __powidf2 (for example). 5394 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5395 unsigned Val = RHSC->getSExtValue(); 5396 5397 // powi(x, 0) -> 1.0 5398 if (Val == 0) 5399 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5400 5401 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5402 Val, DAG.shouldOptForSize())) { 5403 // Get the exponent as a positive value. 5404 if ((int)Val < 0) 5405 Val = -Val; 5406 // We use the simple binary decomposition method to generate the multiply 5407 // sequence. There are more optimal ways to do this (for example, 5408 // powi(x,15) generates one more multiply than it should), but this has 5409 // the benefit of being both really simple and much better than a libcall. 5410 SDValue Res; // Logically starts equal to 1.0 5411 SDValue CurSquare = LHS; 5412 // TODO: Intrinsics should have fast-math-flags that propagate to these 5413 // nodes. 5414 while (Val) { 5415 if (Val & 1) { 5416 if (Res.getNode()) 5417 Res = 5418 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5419 else 5420 Res = CurSquare; // 1.0*CurSquare. 5421 } 5422 5423 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5424 CurSquare, CurSquare); 5425 Val >>= 1; 5426 } 5427 5428 // If the original was negative, invert the result, producing 1/(x*x*x). 5429 if (RHSC->getSExtValue() < 0) 5430 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5431 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5432 return Res; 5433 } 5434 } 5435 5436 // Otherwise, expand to a libcall. 5437 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5438 } 5439 5440 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5441 SDValue LHS, SDValue RHS, SDValue Scale, 5442 SelectionDAG &DAG, const TargetLowering &TLI) { 5443 EVT VT = LHS.getValueType(); 5444 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5445 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5446 LLVMContext &Ctx = *DAG.getContext(); 5447 5448 // If the type is legal but the operation isn't, this node might survive all 5449 // the way to operation legalization. If we end up there and we do not have 5450 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5451 // node. 5452 5453 // Coax the legalizer into expanding the node during type legalization instead 5454 // by bumping the size by one bit. This will force it to Promote, enabling the 5455 // early expansion and avoiding the need to expand later. 5456 5457 // We don't have to do this if Scale is 0; that can always be expanded, unless 5458 // it's a saturating signed operation. Those can experience true integer 5459 // division overflow, a case which we must avoid. 5460 5461 // FIXME: We wouldn't have to do this (or any of the early 5462 // expansion/promotion) if it was possible to expand a libcall of an 5463 // illegal type during operation legalization. But it's not, so things 5464 // get a bit hacky. 5465 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5466 if ((ScaleInt > 0 || (Saturating && Signed)) && 5467 (TLI.isTypeLegal(VT) || 5468 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5469 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5470 Opcode, VT, ScaleInt); 5471 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5472 EVT PromVT; 5473 if (VT.isScalarInteger()) 5474 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5475 else if (VT.isVector()) { 5476 PromVT = VT.getVectorElementType(); 5477 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5478 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5479 } else 5480 llvm_unreachable("Wrong VT for DIVFIX?"); 5481 if (Signed) { 5482 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5483 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5484 } else { 5485 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5486 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5487 } 5488 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5489 // For saturating operations, we need to shift up the LHS to get the 5490 // proper saturation width, and then shift down again afterwards. 5491 if (Saturating) 5492 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5493 DAG.getConstant(1, DL, ShiftTy)); 5494 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5495 if (Saturating) 5496 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5497 DAG.getConstant(1, DL, ShiftTy)); 5498 return DAG.getZExtOrTrunc(Res, DL, VT); 5499 } 5500 } 5501 5502 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5503 } 5504 5505 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5506 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5507 static void 5508 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5509 const SDValue &N) { 5510 switch (N.getOpcode()) { 5511 case ISD::CopyFromReg: { 5512 SDValue Op = N.getOperand(1); 5513 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5514 Op.getValueType().getSizeInBits()); 5515 return; 5516 } 5517 case ISD::BITCAST: 5518 case ISD::AssertZext: 5519 case ISD::AssertSext: 5520 case ISD::TRUNCATE: 5521 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5522 return; 5523 case ISD::BUILD_PAIR: 5524 case ISD::BUILD_VECTOR: 5525 case ISD::CONCAT_VECTORS: 5526 for (SDValue Op : N->op_values()) 5527 getUnderlyingArgRegs(Regs, Op); 5528 return; 5529 default: 5530 return; 5531 } 5532 } 5533 5534 /// If the DbgValueInst is a dbg_value of a function argument, create the 5535 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5536 /// instruction selection, they will be inserted to the entry BB. 5537 /// We don't currently support this for variadic dbg_values, as they shouldn't 5538 /// appear for function arguments or in the prologue. 5539 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5540 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5541 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5542 const Argument *Arg = dyn_cast<Argument>(V); 5543 if (!Arg) 5544 return false; 5545 5546 MachineFunction &MF = DAG.getMachineFunction(); 5547 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5548 5549 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5550 // we've been asked to pursue. 5551 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5552 bool Indirect) { 5553 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5554 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5555 // pointing at the VReg, which will be patched up later. 5556 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5557 auto MIB = BuildMI(MF, DL, Inst); 5558 MIB.addReg(Reg); 5559 MIB.addImm(0); 5560 MIB.addMetadata(Variable); 5561 auto *NewDIExpr = FragExpr; 5562 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5563 // the DIExpression. 5564 if (Indirect) 5565 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5566 MIB.addMetadata(NewDIExpr); 5567 return MIB; 5568 } else { 5569 // Create a completely standard DBG_VALUE. 5570 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5571 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5572 } 5573 }; 5574 5575 if (Kind == FuncArgumentDbgValueKind::Value) { 5576 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5577 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5578 // the entry block. 5579 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5580 if (!IsInEntryBlock) 5581 return false; 5582 5583 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5584 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5585 // variable that also is a param. 5586 // 5587 // Although, if we are at the top of the entry block already, we can still 5588 // emit using ArgDbgValue. This might catch some situations when the 5589 // dbg.value refers to an argument that isn't used in the entry block, so 5590 // any CopyToReg node would be optimized out and the only way to express 5591 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5592 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5593 // we should only emit as ArgDbgValue if the Variable is an argument to the 5594 // current function, and the dbg.value intrinsic is found in the entry 5595 // block. 5596 bool VariableIsFunctionInputArg = Variable->isParameter() && 5597 !DL->getInlinedAt(); 5598 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5599 if (!IsInPrologue && !VariableIsFunctionInputArg) 5600 return false; 5601 5602 // Here we assume that a function argument on IR level only can be used to 5603 // describe one input parameter on source level. If we for example have 5604 // source code like this 5605 // 5606 // struct A { long x, y; }; 5607 // void foo(struct A a, long b) { 5608 // ... 5609 // b = a.x; 5610 // ... 5611 // } 5612 // 5613 // and IR like this 5614 // 5615 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5616 // entry: 5617 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5618 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5619 // call void @llvm.dbg.value(metadata i32 %b, "b", 5620 // ... 5621 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5622 // ... 5623 // 5624 // then the last dbg.value is describing a parameter "b" using a value that 5625 // is an argument. But since we already has used %a1 to describe a parameter 5626 // we should not handle that last dbg.value here (that would result in an 5627 // incorrect hoisting of the DBG_VALUE to the function entry). 5628 // Notice that we allow one dbg.value per IR level argument, to accommodate 5629 // for the situation with fragments above. 5630 if (VariableIsFunctionInputArg) { 5631 unsigned ArgNo = Arg->getArgNo(); 5632 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5633 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5634 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5635 return false; 5636 FuncInfo.DescribedArgs.set(ArgNo); 5637 } 5638 } 5639 5640 bool IsIndirect = false; 5641 Optional<MachineOperand> Op; 5642 // Some arguments' frame index is recorded during argument lowering. 5643 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5644 if (FI != std::numeric_limits<int>::max()) 5645 Op = MachineOperand::CreateFI(FI); 5646 5647 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5648 if (!Op && N.getNode()) { 5649 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5650 Register Reg; 5651 if (ArgRegsAndSizes.size() == 1) 5652 Reg = ArgRegsAndSizes.front().first; 5653 5654 if (Reg && Reg.isVirtual()) { 5655 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5656 Register PR = RegInfo.getLiveInPhysReg(Reg); 5657 if (PR) 5658 Reg = PR; 5659 } 5660 if (Reg) { 5661 Op = MachineOperand::CreateReg(Reg, false); 5662 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5663 } 5664 } 5665 5666 if (!Op && N.getNode()) { 5667 // Check if frame index is available. 5668 SDValue LCandidate = peekThroughBitcasts(N); 5669 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5670 if (FrameIndexSDNode *FINode = 5671 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5672 Op = MachineOperand::CreateFI(FINode->getIndex()); 5673 } 5674 5675 if (!Op) { 5676 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5677 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5678 SplitRegs) { 5679 unsigned Offset = 0; 5680 for (const auto &RegAndSize : SplitRegs) { 5681 // If the expression is already a fragment, the current register 5682 // offset+size might extend beyond the fragment. In this case, only 5683 // the register bits that are inside the fragment are relevant. 5684 int RegFragmentSizeInBits = RegAndSize.second; 5685 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5686 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5687 // The register is entirely outside the expression fragment, 5688 // so is irrelevant for debug info. 5689 if (Offset >= ExprFragmentSizeInBits) 5690 break; 5691 // The register is partially outside the expression fragment, only 5692 // the low bits within the fragment are relevant for debug info. 5693 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5694 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5695 } 5696 } 5697 5698 auto FragmentExpr = DIExpression::createFragmentExpression( 5699 Expr, Offset, RegFragmentSizeInBits); 5700 Offset += RegAndSize.second; 5701 // If a valid fragment expression cannot be created, the variable's 5702 // correct value cannot be determined and so it is set as Undef. 5703 if (!FragmentExpr) { 5704 SDDbgValue *SDV = DAG.getConstantDbgValue( 5705 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5706 DAG.AddDbgValue(SDV, false); 5707 continue; 5708 } 5709 MachineInstr *NewMI = 5710 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5711 Kind != FuncArgumentDbgValueKind::Value); 5712 FuncInfo.ArgDbgValues.push_back(NewMI); 5713 } 5714 }; 5715 5716 // Check if ValueMap has reg number. 5717 DenseMap<const Value *, Register>::const_iterator 5718 VMI = FuncInfo.ValueMap.find(V); 5719 if (VMI != FuncInfo.ValueMap.end()) { 5720 const auto &TLI = DAG.getTargetLoweringInfo(); 5721 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5722 V->getType(), None); 5723 if (RFV.occupiesMultipleRegs()) { 5724 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5725 return true; 5726 } 5727 5728 Op = MachineOperand::CreateReg(VMI->second, false); 5729 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5730 } else if (ArgRegsAndSizes.size() > 1) { 5731 // This was split due to the calling convention, and no virtual register 5732 // mapping exists for the value. 5733 splitMultiRegDbgValue(ArgRegsAndSizes); 5734 return true; 5735 } 5736 } 5737 5738 if (!Op) 5739 return false; 5740 5741 assert(Variable->isValidLocationForIntrinsic(DL) && 5742 "Expected inlined-at fields to agree"); 5743 MachineInstr *NewMI = nullptr; 5744 5745 if (Op->isReg()) 5746 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5747 else 5748 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5749 Variable, Expr); 5750 5751 // Otherwise, use ArgDbgValues. 5752 FuncInfo.ArgDbgValues.push_back(NewMI); 5753 return true; 5754 } 5755 5756 /// Return the appropriate SDDbgValue based on N. 5757 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5758 DILocalVariable *Variable, 5759 DIExpression *Expr, 5760 const DebugLoc &dl, 5761 unsigned DbgSDNodeOrder) { 5762 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5763 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5764 // stack slot locations. 5765 // 5766 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5767 // debug values here after optimization: 5768 // 5769 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5770 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5771 // 5772 // Both describe the direct values of their associated variables. 5773 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5774 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5775 } 5776 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5777 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5778 } 5779 5780 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5781 switch (Intrinsic) { 5782 case Intrinsic::smul_fix: 5783 return ISD::SMULFIX; 5784 case Intrinsic::umul_fix: 5785 return ISD::UMULFIX; 5786 case Intrinsic::smul_fix_sat: 5787 return ISD::SMULFIXSAT; 5788 case Intrinsic::umul_fix_sat: 5789 return ISD::UMULFIXSAT; 5790 case Intrinsic::sdiv_fix: 5791 return ISD::SDIVFIX; 5792 case Intrinsic::udiv_fix: 5793 return ISD::UDIVFIX; 5794 case Intrinsic::sdiv_fix_sat: 5795 return ISD::SDIVFIXSAT; 5796 case Intrinsic::udiv_fix_sat: 5797 return ISD::UDIVFIXSAT; 5798 default: 5799 llvm_unreachable("Unhandled fixed point intrinsic"); 5800 } 5801 } 5802 5803 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5804 const char *FunctionName) { 5805 assert(FunctionName && "FunctionName must not be nullptr"); 5806 SDValue Callee = DAG.getExternalSymbol( 5807 FunctionName, 5808 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5809 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5810 } 5811 5812 /// Given a @llvm.call.preallocated.setup, return the corresponding 5813 /// preallocated call. 5814 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5815 assert(cast<CallBase>(PreallocatedSetup) 5816 ->getCalledFunction() 5817 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5818 "expected call_preallocated_setup Value"); 5819 for (const auto *U : PreallocatedSetup->users()) { 5820 auto *UseCall = cast<CallBase>(U); 5821 const Function *Fn = UseCall->getCalledFunction(); 5822 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5823 return UseCall; 5824 } 5825 } 5826 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5827 } 5828 5829 /// Lower the call to the specified intrinsic function. 5830 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5831 unsigned Intrinsic) { 5832 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5833 SDLoc sdl = getCurSDLoc(); 5834 DebugLoc dl = getCurDebugLoc(); 5835 SDValue Res; 5836 5837 SDNodeFlags Flags; 5838 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5839 Flags.copyFMF(*FPOp); 5840 5841 switch (Intrinsic) { 5842 default: 5843 // By default, turn this into a target intrinsic node. 5844 visitTargetIntrinsic(I, Intrinsic); 5845 return; 5846 case Intrinsic::vscale: { 5847 match(&I, m_VScale(DAG.getDataLayout())); 5848 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5849 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5850 return; 5851 } 5852 case Intrinsic::vastart: visitVAStart(I); return; 5853 case Intrinsic::vaend: visitVAEnd(I); return; 5854 case Intrinsic::vacopy: visitVACopy(I); return; 5855 case Intrinsic::returnaddress: 5856 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5857 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5858 getValue(I.getArgOperand(0)))); 5859 return; 5860 case Intrinsic::addressofreturnaddress: 5861 setValue(&I, 5862 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5863 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5864 return; 5865 case Intrinsic::sponentry: 5866 setValue(&I, 5867 DAG.getNode(ISD::SPONENTRY, sdl, 5868 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5869 return; 5870 case Intrinsic::frameaddress: 5871 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5872 TLI.getFrameIndexTy(DAG.getDataLayout()), 5873 getValue(I.getArgOperand(0)))); 5874 return; 5875 case Intrinsic::read_volatile_register: 5876 case Intrinsic::read_register: { 5877 Value *Reg = I.getArgOperand(0); 5878 SDValue Chain = getRoot(); 5879 SDValue RegName = 5880 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5881 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5882 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5883 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5884 setValue(&I, Res); 5885 DAG.setRoot(Res.getValue(1)); 5886 return; 5887 } 5888 case Intrinsic::write_register: { 5889 Value *Reg = I.getArgOperand(0); 5890 Value *RegValue = I.getArgOperand(1); 5891 SDValue Chain = getRoot(); 5892 SDValue RegName = 5893 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5894 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5895 RegName, getValue(RegValue))); 5896 return; 5897 } 5898 case Intrinsic::memcpy: { 5899 const auto &MCI = cast<MemCpyInst>(I); 5900 SDValue Op1 = getValue(I.getArgOperand(0)); 5901 SDValue Op2 = getValue(I.getArgOperand(1)); 5902 SDValue Op3 = getValue(I.getArgOperand(2)); 5903 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5904 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5905 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5906 Align Alignment = std::min(DstAlign, SrcAlign); 5907 bool isVol = MCI.isVolatile(); 5908 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5909 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5910 // node. 5911 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5912 SDValue MC = DAG.getMemcpy( 5913 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5914 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 5915 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5916 updateDAGForMaybeTailCall(MC); 5917 return; 5918 } 5919 case Intrinsic::memcpy_inline: { 5920 const auto &MCI = cast<MemCpyInlineInst>(I); 5921 SDValue Dst = getValue(I.getArgOperand(0)); 5922 SDValue Src = getValue(I.getArgOperand(1)); 5923 SDValue Size = getValue(I.getArgOperand(2)); 5924 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5925 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5926 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5927 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5928 Align Alignment = std::min(DstAlign, SrcAlign); 5929 bool isVol = MCI.isVolatile(); 5930 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5931 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5932 // node. 5933 SDValue MC = DAG.getMemcpy( 5934 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5935 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5936 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5937 updateDAGForMaybeTailCall(MC); 5938 return; 5939 } 5940 case Intrinsic::memset: { 5941 const auto &MSI = cast<MemSetInst>(I); 5942 SDValue Op1 = getValue(I.getArgOperand(0)); 5943 SDValue Op2 = getValue(I.getArgOperand(1)); 5944 SDValue Op3 = getValue(I.getArgOperand(2)); 5945 // @llvm.memset defines 0 and 1 to both mean no alignment. 5946 Align Alignment = MSI.getDestAlign().valueOrOne(); 5947 bool isVol = MSI.isVolatile(); 5948 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5949 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5950 SDValue MS = DAG.getMemset( 5951 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 5952 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 5953 updateDAGForMaybeTailCall(MS); 5954 return; 5955 } 5956 case Intrinsic::memset_inline: { 5957 const auto &MSII = cast<MemSetInlineInst>(I); 5958 SDValue Dst = getValue(I.getArgOperand(0)); 5959 SDValue Value = getValue(I.getArgOperand(1)); 5960 SDValue Size = getValue(I.getArgOperand(2)); 5961 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 5962 // @llvm.memset defines 0 and 1 to both mean no alignment. 5963 Align DstAlign = MSII.getDestAlign().valueOrOne(); 5964 bool isVol = MSII.isVolatile(); 5965 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5966 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5967 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 5968 /* AlwaysInline */ true, isTC, 5969 MachinePointerInfo(I.getArgOperand(0)), 5970 I.getAAMetadata()); 5971 updateDAGForMaybeTailCall(MC); 5972 return; 5973 } 5974 case Intrinsic::memmove: { 5975 const auto &MMI = cast<MemMoveInst>(I); 5976 SDValue Op1 = getValue(I.getArgOperand(0)); 5977 SDValue Op2 = getValue(I.getArgOperand(1)); 5978 SDValue Op3 = getValue(I.getArgOperand(2)); 5979 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5980 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5981 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5982 Align Alignment = std::min(DstAlign, SrcAlign); 5983 bool isVol = MMI.isVolatile(); 5984 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5985 // FIXME: Support passing different dest/src alignments to the memmove DAG 5986 // node. 5987 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5988 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5989 isTC, MachinePointerInfo(I.getArgOperand(0)), 5990 MachinePointerInfo(I.getArgOperand(1)), 5991 I.getAAMetadata(), AA); 5992 updateDAGForMaybeTailCall(MM); 5993 return; 5994 } 5995 case Intrinsic::memcpy_element_unordered_atomic: { 5996 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5997 SDValue Dst = getValue(MI.getRawDest()); 5998 SDValue Src = getValue(MI.getRawSource()); 5999 SDValue Length = getValue(MI.getLength()); 6000 6001 Type *LengthTy = MI.getLength()->getType(); 6002 unsigned ElemSz = MI.getElementSizeInBytes(); 6003 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6004 SDValue MC = 6005 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6006 isTC, MachinePointerInfo(MI.getRawDest()), 6007 MachinePointerInfo(MI.getRawSource())); 6008 updateDAGForMaybeTailCall(MC); 6009 return; 6010 } 6011 case Intrinsic::memmove_element_unordered_atomic: { 6012 auto &MI = cast<AtomicMemMoveInst>(I); 6013 SDValue Dst = getValue(MI.getRawDest()); 6014 SDValue Src = getValue(MI.getRawSource()); 6015 SDValue Length = getValue(MI.getLength()); 6016 6017 Type *LengthTy = MI.getLength()->getType(); 6018 unsigned ElemSz = MI.getElementSizeInBytes(); 6019 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6020 SDValue MC = 6021 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6022 isTC, MachinePointerInfo(MI.getRawDest()), 6023 MachinePointerInfo(MI.getRawSource())); 6024 updateDAGForMaybeTailCall(MC); 6025 return; 6026 } 6027 case Intrinsic::memset_element_unordered_atomic: { 6028 auto &MI = cast<AtomicMemSetInst>(I); 6029 SDValue Dst = getValue(MI.getRawDest()); 6030 SDValue Val = getValue(MI.getValue()); 6031 SDValue Length = getValue(MI.getLength()); 6032 6033 Type *LengthTy = MI.getLength()->getType(); 6034 unsigned ElemSz = MI.getElementSizeInBytes(); 6035 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6036 SDValue MC = 6037 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6038 isTC, MachinePointerInfo(MI.getRawDest())); 6039 updateDAGForMaybeTailCall(MC); 6040 return; 6041 } 6042 case Intrinsic::call_preallocated_setup: { 6043 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6044 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6045 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6046 getRoot(), SrcValue); 6047 setValue(&I, Res); 6048 DAG.setRoot(Res); 6049 return; 6050 } 6051 case Intrinsic::call_preallocated_arg: { 6052 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6053 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6054 SDValue Ops[3]; 6055 Ops[0] = getRoot(); 6056 Ops[1] = SrcValue; 6057 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6058 MVT::i32); // arg index 6059 SDValue Res = DAG.getNode( 6060 ISD::PREALLOCATED_ARG, sdl, 6061 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6062 setValue(&I, Res); 6063 DAG.setRoot(Res.getValue(1)); 6064 return; 6065 } 6066 case Intrinsic::dbg_addr: 6067 case Intrinsic::dbg_declare: { 6068 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6069 // they are non-variadic. 6070 const auto &DI = cast<DbgVariableIntrinsic>(I); 6071 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6072 DILocalVariable *Variable = DI.getVariable(); 6073 DIExpression *Expression = DI.getExpression(); 6074 dropDanglingDebugInfo(Variable, Expression); 6075 assert(Variable && "Missing variable"); 6076 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6077 << "\n"); 6078 // Check if address has undef value. 6079 const Value *Address = DI.getVariableLocationOp(0); 6080 if (!Address || isa<UndefValue>(Address) || 6081 (Address->use_empty() && !isa<Argument>(Address))) { 6082 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6083 << " (bad/undef/unused-arg address)\n"); 6084 return; 6085 } 6086 6087 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6088 6089 // Check if this variable can be described by a frame index, typically 6090 // either as a static alloca or a byval parameter. 6091 int FI = std::numeric_limits<int>::max(); 6092 if (const auto *AI = 6093 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6094 if (AI->isStaticAlloca()) { 6095 auto I = FuncInfo.StaticAllocaMap.find(AI); 6096 if (I != FuncInfo.StaticAllocaMap.end()) 6097 FI = I->second; 6098 } 6099 } else if (const auto *Arg = dyn_cast<Argument>( 6100 Address->stripInBoundsConstantOffsets())) { 6101 FI = FuncInfo.getArgumentFrameIndex(Arg); 6102 } 6103 6104 // llvm.dbg.addr is control dependent and always generates indirect 6105 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6106 // the MachineFunction variable table. 6107 if (FI != std::numeric_limits<int>::max()) { 6108 if (Intrinsic == Intrinsic::dbg_addr) { 6109 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6110 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6111 dl, SDNodeOrder); 6112 DAG.AddDbgValue(SDV, isParameter); 6113 } else { 6114 LLVM_DEBUG(dbgs() << "Skipping " << DI 6115 << " (variable info stashed in MF side table)\n"); 6116 } 6117 return; 6118 } 6119 6120 SDValue &N = NodeMap[Address]; 6121 if (!N.getNode() && isa<Argument>(Address)) 6122 // Check unused arguments map. 6123 N = UnusedArgNodeMap[Address]; 6124 SDDbgValue *SDV; 6125 if (N.getNode()) { 6126 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6127 Address = BCI->getOperand(0); 6128 // Parameters are handled specially. 6129 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6130 if (isParameter && FINode) { 6131 // Byval parameter. We have a frame index at this point. 6132 SDV = 6133 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6134 /*IsIndirect*/ true, dl, SDNodeOrder); 6135 } else if (isa<Argument>(Address)) { 6136 // Address is an argument, so try to emit its dbg value using 6137 // virtual register info from the FuncInfo.ValueMap. 6138 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6139 FuncArgumentDbgValueKind::Declare, N); 6140 return; 6141 } else { 6142 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6143 true, dl, SDNodeOrder); 6144 } 6145 DAG.AddDbgValue(SDV, isParameter); 6146 } else { 6147 // If Address is an argument then try to emit its dbg value using 6148 // virtual register info from the FuncInfo.ValueMap. 6149 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6150 FuncArgumentDbgValueKind::Declare, N)) { 6151 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6152 << " (could not emit func-arg dbg_value)\n"); 6153 } 6154 } 6155 return; 6156 } 6157 case Intrinsic::dbg_label: { 6158 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6159 DILabel *Label = DI.getLabel(); 6160 assert(Label && "Missing label"); 6161 6162 SDDbgLabel *SDV; 6163 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6164 DAG.AddDbgLabel(SDV); 6165 return; 6166 } 6167 case Intrinsic::dbg_value: { 6168 const DbgValueInst &DI = cast<DbgValueInst>(I); 6169 assert(DI.getVariable() && "Missing variable"); 6170 6171 DILocalVariable *Variable = DI.getVariable(); 6172 DIExpression *Expression = DI.getExpression(); 6173 dropDanglingDebugInfo(Variable, Expression); 6174 SmallVector<Value *, 4> Values(DI.getValues()); 6175 if (Values.empty()) 6176 return; 6177 6178 if (llvm::is_contained(Values, nullptr)) 6179 return; 6180 6181 bool IsVariadic = DI.hasArgList(); 6182 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6183 SDNodeOrder, IsVariadic)) 6184 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6185 return; 6186 } 6187 6188 case Intrinsic::eh_typeid_for: { 6189 // Find the type id for the given typeinfo. 6190 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6191 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6192 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6193 setValue(&I, Res); 6194 return; 6195 } 6196 6197 case Intrinsic::eh_return_i32: 6198 case Intrinsic::eh_return_i64: 6199 DAG.getMachineFunction().setCallsEHReturn(true); 6200 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6201 MVT::Other, 6202 getControlRoot(), 6203 getValue(I.getArgOperand(0)), 6204 getValue(I.getArgOperand(1)))); 6205 return; 6206 case Intrinsic::eh_unwind_init: 6207 DAG.getMachineFunction().setCallsUnwindInit(true); 6208 return; 6209 case Intrinsic::eh_dwarf_cfa: 6210 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6211 TLI.getPointerTy(DAG.getDataLayout()), 6212 getValue(I.getArgOperand(0)))); 6213 return; 6214 case Intrinsic::eh_sjlj_callsite: { 6215 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6216 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6217 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6218 6219 MMI.setCurrentCallSite(CI->getZExtValue()); 6220 return; 6221 } 6222 case Intrinsic::eh_sjlj_functioncontext: { 6223 // Get and store the index of the function context. 6224 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6225 AllocaInst *FnCtx = 6226 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6227 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6228 MFI.setFunctionContextIndex(FI); 6229 return; 6230 } 6231 case Intrinsic::eh_sjlj_setjmp: { 6232 SDValue Ops[2]; 6233 Ops[0] = getRoot(); 6234 Ops[1] = getValue(I.getArgOperand(0)); 6235 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6236 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6237 setValue(&I, Op.getValue(0)); 6238 DAG.setRoot(Op.getValue(1)); 6239 return; 6240 } 6241 case Intrinsic::eh_sjlj_longjmp: 6242 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6243 getRoot(), getValue(I.getArgOperand(0)))); 6244 return; 6245 case Intrinsic::eh_sjlj_setup_dispatch: 6246 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6247 getRoot())); 6248 return; 6249 case Intrinsic::masked_gather: 6250 visitMaskedGather(I); 6251 return; 6252 case Intrinsic::masked_load: 6253 visitMaskedLoad(I); 6254 return; 6255 case Intrinsic::masked_scatter: 6256 visitMaskedScatter(I); 6257 return; 6258 case Intrinsic::masked_store: 6259 visitMaskedStore(I); 6260 return; 6261 case Intrinsic::masked_expandload: 6262 visitMaskedLoad(I, true /* IsExpanding */); 6263 return; 6264 case Intrinsic::masked_compressstore: 6265 visitMaskedStore(I, true /* IsCompressing */); 6266 return; 6267 case Intrinsic::powi: 6268 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6269 getValue(I.getArgOperand(1)), DAG)); 6270 return; 6271 case Intrinsic::log: 6272 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6273 return; 6274 case Intrinsic::log2: 6275 setValue(&I, 6276 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6277 return; 6278 case Intrinsic::log10: 6279 setValue(&I, 6280 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6281 return; 6282 case Intrinsic::exp: 6283 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6284 return; 6285 case Intrinsic::exp2: 6286 setValue(&I, 6287 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6288 return; 6289 case Intrinsic::pow: 6290 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6291 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6292 return; 6293 case Intrinsic::sqrt: 6294 case Intrinsic::fabs: 6295 case Intrinsic::sin: 6296 case Intrinsic::cos: 6297 case Intrinsic::floor: 6298 case Intrinsic::ceil: 6299 case Intrinsic::trunc: 6300 case Intrinsic::rint: 6301 case Intrinsic::nearbyint: 6302 case Intrinsic::round: 6303 case Intrinsic::roundeven: 6304 case Intrinsic::canonicalize: { 6305 unsigned Opcode; 6306 switch (Intrinsic) { 6307 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6308 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6309 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6310 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6311 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6312 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6313 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6314 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6315 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6316 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6317 case Intrinsic::round: Opcode = ISD::FROUND; break; 6318 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6319 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6320 } 6321 6322 setValue(&I, DAG.getNode(Opcode, sdl, 6323 getValue(I.getArgOperand(0)).getValueType(), 6324 getValue(I.getArgOperand(0)), Flags)); 6325 return; 6326 } 6327 case Intrinsic::lround: 6328 case Intrinsic::llround: 6329 case Intrinsic::lrint: 6330 case Intrinsic::llrint: { 6331 unsigned Opcode; 6332 switch (Intrinsic) { 6333 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6334 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6335 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6336 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6337 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6338 } 6339 6340 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6341 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6342 getValue(I.getArgOperand(0)))); 6343 return; 6344 } 6345 case Intrinsic::minnum: 6346 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6347 getValue(I.getArgOperand(0)).getValueType(), 6348 getValue(I.getArgOperand(0)), 6349 getValue(I.getArgOperand(1)), Flags)); 6350 return; 6351 case Intrinsic::maxnum: 6352 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6353 getValue(I.getArgOperand(0)).getValueType(), 6354 getValue(I.getArgOperand(0)), 6355 getValue(I.getArgOperand(1)), Flags)); 6356 return; 6357 case Intrinsic::minimum: 6358 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6359 getValue(I.getArgOperand(0)).getValueType(), 6360 getValue(I.getArgOperand(0)), 6361 getValue(I.getArgOperand(1)), Flags)); 6362 return; 6363 case Intrinsic::maximum: 6364 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6365 getValue(I.getArgOperand(0)).getValueType(), 6366 getValue(I.getArgOperand(0)), 6367 getValue(I.getArgOperand(1)), Flags)); 6368 return; 6369 case Intrinsic::copysign: 6370 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6371 getValue(I.getArgOperand(0)).getValueType(), 6372 getValue(I.getArgOperand(0)), 6373 getValue(I.getArgOperand(1)), Flags)); 6374 return; 6375 case Intrinsic::arithmetic_fence: { 6376 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6377 getValue(I.getArgOperand(0)).getValueType(), 6378 getValue(I.getArgOperand(0)), Flags)); 6379 return; 6380 } 6381 case Intrinsic::fma: 6382 setValue(&I, DAG.getNode( 6383 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6384 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6385 getValue(I.getArgOperand(2)), Flags)); 6386 return; 6387 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6388 case Intrinsic::INTRINSIC: 6389 #include "llvm/IR/ConstrainedOps.def" 6390 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6391 return; 6392 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6393 #include "llvm/IR/VPIntrinsics.def" 6394 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6395 return; 6396 case Intrinsic::fptrunc_round: { 6397 // Get the last argument, the metadata and convert it to an integer in the 6398 // call 6399 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6400 Optional<RoundingMode> RoundMode = 6401 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6402 6403 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6404 6405 // Propagate fast-math-flags from IR to node(s). 6406 SDNodeFlags Flags; 6407 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6408 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6409 6410 SDValue Result; 6411 Result = DAG.getNode( 6412 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6413 DAG.getTargetConstant((int)*RoundMode, sdl, 6414 TLI.getPointerTy(DAG.getDataLayout()))); 6415 setValue(&I, Result); 6416 6417 return; 6418 } 6419 case Intrinsic::fmuladd: { 6420 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6421 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6422 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6423 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6424 getValue(I.getArgOperand(0)).getValueType(), 6425 getValue(I.getArgOperand(0)), 6426 getValue(I.getArgOperand(1)), 6427 getValue(I.getArgOperand(2)), Flags)); 6428 } else { 6429 // TODO: Intrinsic calls should have fast-math-flags. 6430 SDValue Mul = DAG.getNode( 6431 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6432 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6433 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6434 getValue(I.getArgOperand(0)).getValueType(), 6435 Mul, getValue(I.getArgOperand(2)), Flags); 6436 setValue(&I, Add); 6437 } 6438 return; 6439 } 6440 case Intrinsic::convert_to_fp16: 6441 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6442 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6443 getValue(I.getArgOperand(0)), 6444 DAG.getTargetConstant(0, sdl, 6445 MVT::i32)))); 6446 return; 6447 case Intrinsic::convert_from_fp16: 6448 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6449 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6450 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6451 getValue(I.getArgOperand(0))))); 6452 return; 6453 case Intrinsic::fptosi_sat: { 6454 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6455 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6456 getValue(I.getArgOperand(0)), 6457 DAG.getValueType(VT.getScalarType()))); 6458 return; 6459 } 6460 case Intrinsic::fptoui_sat: { 6461 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6462 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6463 getValue(I.getArgOperand(0)), 6464 DAG.getValueType(VT.getScalarType()))); 6465 return; 6466 } 6467 case Intrinsic::set_rounding: 6468 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6469 {getRoot(), getValue(I.getArgOperand(0))}); 6470 setValue(&I, Res); 6471 DAG.setRoot(Res.getValue(0)); 6472 return; 6473 case Intrinsic::is_fpclass: { 6474 const DataLayout DLayout = DAG.getDataLayout(); 6475 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6476 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6477 unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6478 MachineFunction &MF = DAG.getMachineFunction(); 6479 const Function &F = MF.getFunction(); 6480 SDValue Op = getValue(I.getArgOperand(0)); 6481 SDNodeFlags Flags; 6482 Flags.setNoFPExcept( 6483 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6484 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6485 // expansion can use illegal types. Making expansion early allows 6486 // legalizing these types prior to selection. 6487 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6488 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6489 setValue(&I, Result); 6490 return; 6491 } 6492 6493 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6494 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6495 setValue(&I, V); 6496 return; 6497 } 6498 case Intrinsic::pcmarker: { 6499 SDValue Tmp = getValue(I.getArgOperand(0)); 6500 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6501 return; 6502 } 6503 case Intrinsic::readcyclecounter: { 6504 SDValue Op = getRoot(); 6505 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6506 DAG.getVTList(MVT::i64, MVT::Other), Op); 6507 setValue(&I, Res); 6508 DAG.setRoot(Res.getValue(1)); 6509 return; 6510 } 6511 case Intrinsic::bitreverse: 6512 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6513 getValue(I.getArgOperand(0)).getValueType(), 6514 getValue(I.getArgOperand(0)))); 6515 return; 6516 case Intrinsic::bswap: 6517 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6518 getValue(I.getArgOperand(0)).getValueType(), 6519 getValue(I.getArgOperand(0)))); 6520 return; 6521 case Intrinsic::cttz: { 6522 SDValue Arg = getValue(I.getArgOperand(0)); 6523 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6524 EVT Ty = Arg.getValueType(); 6525 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6526 sdl, Ty, Arg)); 6527 return; 6528 } 6529 case Intrinsic::ctlz: { 6530 SDValue Arg = getValue(I.getArgOperand(0)); 6531 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6532 EVT Ty = Arg.getValueType(); 6533 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6534 sdl, Ty, Arg)); 6535 return; 6536 } 6537 case Intrinsic::ctpop: { 6538 SDValue Arg = getValue(I.getArgOperand(0)); 6539 EVT Ty = Arg.getValueType(); 6540 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6541 return; 6542 } 6543 case Intrinsic::fshl: 6544 case Intrinsic::fshr: { 6545 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6546 SDValue X = getValue(I.getArgOperand(0)); 6547 SDValue Y = getValue(I.getArgOperand(1)); 6548 SDValue Z = getValue(I.getArgOperand(2)); 6549 EVT VT = X.getValueType(); 6550 6551 if (X == Y) { 6552 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6553 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6554 } else { 6555 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6556 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6557 } 6558 return; 6559 } 6560 case Intrinsic::sadd_sat: { 6561 SDValue Op1 = getValue(I.getArgOperand(0)); 6562 SDValue Op2 = getValue(I.getArgOperand(1)); 6563 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6564 return; 6565 } 6566 case Intrinsic::uadd_sat: { 6567 SDValue Op1 = getValue(I.getArgOperand(0)); 6568 SDValue Op2 = getValue(I.getArgOperand(1)); 6569 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6570 return; 6571 } 6572 case Intrinsic::ssub_sat: { 6573 SDValue Op1 = getValue(I.getArgOperand(0)); 6574 SDValue Op2 = getValue(I.getArgOperand(1)); 6575 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6576 return; 6577 } 6578 case Intrinsic::usub_sat: { 6579 SDValue Op1 = getValue(I.getArgOperand(0)); 6580 SDValue Op2 = getValue(I.getArgOperand(1)); 6581 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6582 return; 6583 } 6584 case Intrinsic::sshl_sat: { 6585 SDValue Op1 = getValue(I.getArgOperand(0)); 6586 SDValue Op2 = getValue(I.getArgOperand(1)); 6587 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6588 return; 6589 } 6590 case Intrinsic::ushl_sat: { 6591 SDValue Op1 = getValue(I.getArgOperand(0)); 6592 SDValue Op2 = getValue(I.getArgOperand(1)); 6593 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6594 return; 6595 } 6596 case Intrinsic::smul_fix: 6597 case Intrinsic::umul_fix: 6598 case Intrinsic::smul_fix_sat: 6599 case Intrinsic::umul_fix_sat: { 6600 SDValue Op1 = getValue(I.getArgOperand(0)); 6601 SDValue Op2 = getValue(I.getArgOperand(1)); 6602 SDValue Op3 = getValue(I.getArgOperand(2)); 6603 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6604 Op1.getValueType(), Op1, Op2, Op3)); 6605 return; 6606 } 6607 case Intrinsic::sdiv_fix: 6608 case Intrinsic::udiv_fix: 6609 case Intrinsic::sdiv_fix_sat: 6610 case Intrinsic::udiv_fix_sat: { 6611 SDValue Op1 = getValue(I.getArgOperand(0)); 6612 SDValue Op2 = getValue(I.getArgOperand(1)); 6613 SDValue Op3 = getValue(I.getArgOperand(2)); 6614 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6615 Op1, Op2, Op3, DAG, TLI)); 6616 return; 6617 } 6618 case Intrinsic::smax: { 6619 SDValue Op1 = getValue(I.getArgOperand(0)); 6620 SDValue Op2 = getValue(I.getArgOperand(1)); 6621 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6622 return; 6623 } 6624 case Intrinsic::smin: { 6625 SDValue Op1 = getValue(I.getArgOperand(0)); 6626 SDValue Op2 = getValue(I.getArgOperand(1)); 6627 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6628 return; 6629 } 6630 case Intrinsic::umax: { 6631 SDValue Op1 = getValue(I.getArgOperand(0)); 6632 SDValue Op2 = getValue(I.getArgOperand(1)); 6633 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6634 return; 6635 } 6636 case Intrinsic::umin: { 6637 SDValue Op1 = getValue(I.getArgOperand(0)); 6638 SDValue Op2 = getValue(I.getArgOperand(1)); 6639 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6640 return; 6641 } 6642 case Intrinsic::abs: { 6643 // TODO: Preserve "int min is poison" arg in SDAG? 6644 SDValue Op1 = getValue(I.getArgOperand(0)); 6645 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6646 return; 6647 } 6648 case Intrinsic::stacksave: { 6649 SDValue Op = getRoot(); 6650 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6651 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6652 setValue(&I, Res); 6653 DAG.setRoot(Res.getValue(1)); 6654 return; 6655 } 6656 case Intrinsic::stackrestore: 6657 Res = getValue(I.getArgOperand(0)); 6658 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6659 return; 6660 case Intrinsic::get_dynamic_area_offset: { 6661 SDValue Op = getRoot(); 6662 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6663 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6664 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6665 // target. 6666 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6667 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6668 " intrinsic!"); 6669 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6670 Op); 6671 DAG.setRoot(Op); 6672 setValue(&I, Res); 6673 return; 6674 } 6675 case Intrinsic::stackguard: { 6676 MachineFunction &MF = DAG.getMachineFunction(); 6677 const Module &M = *MF.getFunction().getParent(); 6678 SDValue Chain = getRoot(); 6679 if (TLI.useLoadStackGuardNode()) { 6680 Res = getLoadStackGuard(DAG, sdl, Chain); 6681 } else { 6682 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6683 const Value *Global = TLI.getSDagStackGuard(M); 6684 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6685 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6686 MachinePointerInfo(Global, 0), Align, 6687 MachineMemOperand::MOVolatile); 6688 } 6689 if (TLI.useStackGuardXorFP()) 6690 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6691 DAG.setRoot(Chain); 6692 setValue(&I, Res); 6693 return; 6694 } 6695 case Intrinsic::stackprotector: { 6696 // Emit code into the DAG to store the stack guard onto the stack. 6697 MachineFunction &MF = DAG.getMachineFunction(); 6698 MachineFrameInfo &MFI = MF.getFrameInfo(); 6699 SDValue Src, Chain = getRoot(); 6700 6701 if (TLI.useLoadStackGuardNode()) 6702 Src = getLoadStackGuard(DAG, sdl, Chain); 6703 else 6704 Src = getValue(I.getArgOperand(0)); // The guard's value. 6705 6706 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6707 6708 int FI = FuncInfo.StaticAllocaMap[Slot]; 6709 MFI.setStackProtectorIndex(FI); 6710 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6711 6712 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6713 6714 // Store the stack protector onto the stack. 6715 Res = DAG.getStore( 6716 Chain, sdl, Src, FIN, 6717 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6718 MaybeAlign(), MachineMemOperand::MOVolatile); 6719 setValue(&I, Res); 6720 DAG.setRoot(Res); 6721 return; 6722 } 6723 case Intrinsic::objectsize: 6724 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6725 6726 case Intrinsic::is_constant: 6727 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6728 6729 case Intrinsic::annotation: 6730 case Intrinsic::ptr_annotation: 6731 case Intrinsic::launder_invariant_group: 6732 case Intrinsic::strip_invariant_group: 6733 // Drop the intrinsic, but forward the value 6734 setValue(&I, getValue(I.getOperand(0))); 6735 return; 6736 6737 case Intrinsic::assume: 6738 case Intrinsic::experimental_noalias_scope_decl: 6739 case Intrinsic::var_annotation: 6740 case Intrinsic::sideeffect: 6741 // Discard annotate attributes, noalias scope declarations, assumptions, and 6742 // artificial side-effects. 6743 return; 6744 6745 case Intrinsic::codeview_annotation: { 6746 // Emit a label associated with this metadata. 6747 MachineFunction &MF = DAG.getMachineFunction(); 6748 MCSymbol *Label = 6749 MF.getMMI().getContext().createTempSymbol("annotation", true); 6750 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6751 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6752 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6753 DAG.setRoot(Res); 6754 return; 6755 } 6756 6757 case Intrinsic::init_trampoline: { 6758 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6759 6760 SDValue Ops[6]; 6761 Ops[0] = getRoot(); 6762 Ops[1] = getValue(I.getArgOperand(0)); 6763 Ops[2] = getValue(I.getArgOperand(1)); 6764 Ops[3] = getValue(I.getArgOperand(2)); 6765 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6766 Ops[5] = DAG.getSrcValue(F); 6767 6768 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6769 6770 DAG.setRoot(Res); 6771 return; 6772 } 6773 case Intrinsic::adjust_trampoline: 6774 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6775 TLI.getPointerTy(DAG.getDataLayout()), 6776 getValue(I.getArgOperand(0)))); 6777 return; 6778 case Intrinsic::gcroot: { 6779 assert(DAG.getMachineFunction().getFunction().hasGC() && 6780 "only valid in functions with gc specified, enforced by Verifier"); 6781 assert(GFI && "implied by previous"); 6782 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6783 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6784 6785 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6786 GFI->addStackRoot(FI->getIndex(), TypeMap); 6787 return; 6788 } 6789 case Intrinsic::gcread: 6790 case Intrinsic::gcwrite: 6791 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6792 case Intrinsic::flt_rounds: 6793 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6794 setValue(&I, Res); 6795 DAG.setRoot(Res.getValue(1)); 6796 return; 6797 6798 case Intrinsic::expect: 6799 // Just replace __builtin_expect(exp, c) with EXP. 6800 setValue(&I, getValue(I.getArgOperand(0))); 6801 return; 6802 6803 case Intrinsic::ubsantrap: 6804 case Intrinsic::debugtrap: 6805 case Intrinsic::trap: { 6806 StringRef TrapFuncName = 6807 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6808 if (TrapFuncName.empty()) { 6809 switch (Intrinsic) { 6810 case Intrinsic::trap: 6811 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6812 break; 6813 case Intrinsic::debugtrap: 6814 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6815 break; 6816 case Intrinsic::ubsantrap: 6817 DAG.setRoot(DAG.getNode( 6818 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6819 DAG.getTargetConstant( 6820 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6821 MVT::i32))); 6822 break; 6823 default: llvm_unreachable("unknown trap intrinsic"); 6824 } 6825 return; 6826 } 6827 TargetLowering::ArgListTy Args; 6828 if (Intrinsic == Intrinsic::ubsantrap) { 6829 Args.push_back(TargetLoweringBase::ArgListEntry()); 6830 Args[0].Val = I.getArgOperand(0); 6831 Args[0].Node = getValue(Args[0].Val); 6832 Args[0].Ty = Args[0].Val->getType(); 6833 } 6834 6835 TargetLowering::CallLoweringInfo CLI(DAG); 6836 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6837 CallingConv::C, I.getType(), 6838 DAG.getExternalSymbol(TrapFuncName.data(), 6839 TLI.getPointerTy(DAG.getDataLayout())), 6840 std::move(Args)); 6841 6842 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6843 DAG.setRoot(Result.second); 6844 return; 6845 } 6846 6847 case Intrinsic::uadd_with_overflow: 6848 case Intrinsic::sadd_with_overflow: 6849 case Intrinsic::usub_with_overflow: 6850 case Intrinsic::ssub_with_overflow: 6851 case Intrinsic::umul_with_overflow: 6852 case Intrinsic::smul_with_overflow: { 6853 ISD::NodeType Op; 6854 switch (Intrinsic) { 6855 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6856 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6857 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6858 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6859 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6860 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6861 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6862 } 6863 SDValue Op1 = getValue(I.getArgOperand(0)); 6864 SDValue Op2 = getValue(I.getArgOperand(1)); 6865 6866 EVT ResultVT = Op1.getValueType(); 6867 EVT OverflowVT = MVT::i1; 6868 if (ResultVT.isVector()) 6869 OverflowVT = EVT::getVectorVT( 6870 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6871 6872 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6873 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6874 return; 6875 } 6876 case Intrinsic::prefetch: { 6877 SDValue Ops[5]; 6878 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6879 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6880 Ops[0] = DAG.getRoot(); 6881 Ops[1] = getValue(I.getArgOperand(0)); 6882 Ops[2] = getValue(I.getArgOperand(1)); 6883 Ops[3] = getValue(I.getArgOperand(2)); 6884 Ops[4] = getValue(I.getArgOperand(3)); 6885 SDValue Result = DAG.getMemIntrinsicNode( 6886 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6887 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6888 /* align */ None, Flags); 6889 6890 // Chain the prefetch in parallell with any pending loads, to stay out of 6891 // the way of later optimizations. 6892 PendingLoads.push_back(Result); 6893 Result = getRoot(); 6894 DAG.setRoot(Result); 6895 return; 6896 } 6897 case Intrinsic::lifetime_start: 6898 case Intrinsic::lifetime_end: { 6899 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6900 // Stack coloring is not enabled in O0, discard region information. 6901 if (TM.getOptLevel() == CodeGenOpt::None) 6902 return; 6903 6904 const int64_t ObjectSize = 6905 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6906 Value *const ObjectPtr = I.getArgOperand(1); 6907 SmallVector<const Value *, 4> Allocas; 6908 getUnderlyingObjects(ObjectPtr, Allocas); 6909 6910 for (const Value *Alloca : Allocas) { 6911 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6912 6913 // Could not find an Alloca. 6914 if (!LifetimeObject) 6915 continue; 6916 6917 // First check that the Alloca is static, otherwise it won't have a 6918 // valid frame index. 6919 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6920 if (SI == FuncInfo.StaticAllocaMap.end()) 6921 return; 6922 6923 const int FrameIndex = SI->second; 6924 int64_t Offset; 6925 if (GetPointerBaseWithConstantOffset( 6926 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6927 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6928 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6929 Offset); 6930 DAG.setRoot(Res); 6931 } 6932 return; 6933 } 6934 case Intrinsic::pseudoprobe: { 6935 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6936 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6937 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6938 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6939 DAG.setRoot(Res); 6940 return; 6941 } 6942 case Intrinsic::invariant_start: 6943 // Discard region information. 6944 setValue(&I, 6945 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6946 return; 6947 case Intrinsic::invariant_end: 6948 // Discard region information. 6949 return; 6950 case Intrinsic::clear_cache: 6951 /// FunctionName may be null. 6952 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6953 lowerCallToExternalSymbol(I, FunctionName); 6954 return; 6955 case Intrinsic::donothing: 6956 case Intrinsic::seh_try_begin: 6957 case Intrinsic::seh_scope_begin: 6958 case Intrinsic::seh_try_end: 6959 case Intrinsic::seh_scope_end: 6960 // ignore 6961 return; 6962 case Intrinsic::experimental_stackmap: 6963 visitStackmap(I); 6964 return; 6965 case Intrinsic::experimental_patchpoint_void: 6966 case Intrinsic::experimental_patchpoint_i64: 6967 visitPatchpoint(I); 6968 return; 6969 case Intrinsic::experimental_gc_statepoint: 6970 LowerStatepoint(cast<GCStatepointInst>(I)); 6971 return; 6972 case Intrinsic::experimental_gc_result: 6973 visitGCResult(cast<GCResultInst>(I)); 6974 return; 6975 case Intrinsic::experimental_gc_relocate: 6976 visitGCRelocate(cast<GCRelocateInst>(I)); 6977 return; 6978 case Intrinsic::instrprof_cover: 6979 llvm_unreachable("instrprof failed to lower a cover"); 6980 case Intrinsic::instrprof_increment: 6981 llvm_unreachable("instrprof failed to lower an increment"); 6982 case Intrinsic::instrprof_value_profile: 6983 llvm_unreachable("instrprof failed to lower a value profiling call"); 6984 case Intrinsic::localescape: { 6985 MachineFunction &MF = DAG.getMachineFunction(); 6986 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6987 6988 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6989 // is the same on all targets. 6990 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 6991 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6992 if (isa<ConstantPointerNull>(Arg)) 6993 continue; // Skip null pointers. They represent a hole in index space. 6994 AllocaInst *Slot = cast<AllocaInst>(Arg); 6995 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6996 "can only escape static allocas"); 6997 int FI = FuncInfo.StaticAllocaMap[Slot]; 6998 MCSymbol *FrameAllocSym = 6999 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7000 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7001 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7002 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7003 .addSym(FrameAllocSym) 7004 .addFrameIndex(FI); 7005 } 7006 7007 return; 7008 } 7009 7010 case Intrinsic::localrecover: { 7011 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7012 MachineFunction &MF = DAG.getMachineFunction(); 7013 7014 // Get the symbol that defines the frame offset. 7015 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7016 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7017 unsigned IdxVal = 7018 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7019 MCSymbol *FrameAllocSym = 7020 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7021 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7022 7023 Value *FP = I.getArgOperand(1); 7024 SDValue FPVal = getValue(FP); 7025 EVT PtrVT = FPVal.getValueType(); 7026 7027 // Create a MCSymbol for the label to avoid any target lowering 7028 // that would make this PC relative. 7029 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7030 SDValue OffsetVal = 7031 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7032 7033 // Add the offset to the FP. 7034 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7035 setValue(&I, Add); 7036 7037 return; 7038 } 7039 7040 case Intrinsic::eh_exceptionpointer: 7041 case Intrinsic::eh_exceptioncode: { 7042 // Get the exception pointer vreg, copy from it, and resize it to fit. 7043 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7044 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7045 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7046 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7047 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7048 if (Intrinsic == Intrinsic::eh_exceptioncode) 7049 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7050 setValue(&I, N); 7051 return; 7052 } 7053 case Intrinsic::xray_customevent: { 7054 // Here we want to make sure that the intrinsic behaves as if it has a 7055 // specific calling convention, and only for x86_64. 7056 // FIXME: Support other platforms later. 7057 const auto &Triple = DAG.getTarget().getTargetTriple(); 7058 if (Triple.getArch() != Triple::x86_64) 7059 return; 7060 7061 SmallVector<SDValue, 8> Ops; 7062 7063 // We want to say that we always want the arguments in registers. 7064 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7065 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7066 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7067 SDValue Chain = getRoot(); 7068 Ops.push_back(LogEntryVal); 7069 Ops.push_back(StrSizeVal); 7070 Ops.push_back(Chain); 7071 7072 // We need to enforce the calling convention for the callsite, so that 7073 // argument ordering is enforced correctly, and that register allocation can 7074 // see that some registers may be assumed clobbered and have to preserve 7075 // them across calls to the intrinsic. 7076 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7077 sdl, NodeTys, Ops); 7078 SDValue patchableNode = SDValue(MN, 0); 7079 DAG.setRoot(patchableNode); 7080 setValue(&I, patchableNode); 7081 return; 7082 } 7083 case Intrinsic::xray_typedevent: { 7084 // Here we want to make sure that the intrinsic behaves as if it has a 7085 // specific calling convention, and only for x86_64. 7086 // FIXME: Support other platforms later. 7087 const auto &Triple = DAG.getTarget().getTargetTriple(); 7088 if (Triple.getArch() != Triple::x86_64) 7089 return; 7090 7091 SmallVector<SDValue, 8> Ops; 7092 7093 // We want to say that we always want the arguments in registers. 7094 // It's unclear to me how manipulating the selection DAG here forces callers 7095 // to provide arguments in registers instead of on the stack. 7096 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7097 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7098 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7099 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7100 SDValue Chain = getRoot(); 7101 Ops.push_back(LogTypeId); 7102 Ops.push_back(LogEntryVal); 7103 Ops.push_back(StrSizeVal); 7104 Ops.push_back(Chain); 7105 7106 // We need to enforce the calling convention for the callsite, so that 7107 // argument ordering is enforced correctly, and that register allocation can 7108 // see that some registers may be assumed clobbered and have to preserve 7109 // them across calls to the intrinsic. 7110 MachineSDNode *MN = DAG.getMachineNode( 7111 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7112 SDValue patchableNode = SDValue(MN, 0); 7113 DAG.setRoot(patchableNode); 7114 setValue(&I, patchableNode); 7115 return; 7116 } 7117 case Intrinsic::experimental_deoptimize: 7118 LowerDeoptimizeCall(&I); 7119 return; 7120 case Intrinsic::experimental_stepvector: 7121 visitStepVector(I); 7122 return; 7123 case Intrinsic::vector_reduce_fadd: 7124 case Intrinsic::vector_reduce_fmul: 7125 case Intrinsic::vector_reduce_add: 7126 case Intrinsic::vector_reduce_mul: 7127 case Intrinsic::vector_reduce_and: 7128 case Intrinsic::vector_reduce_or: 7129 case Intrinsic::vector_reduce_xor: 7130 case Intrinsic::vector_reduce_smax: 7131 case Intrinsic::vector_reduce_smin: 7132 case Intrinsic::vector_reduce_umax: 7133 case Intrinsic::vector_reduce_umin: 7134 case Intrinsic::vector_reduce_fmax: 7135 case Intrinsic::vector_reduce_fmin: 7136 visitVectorReduce(I, Intrinsic); 7137 return; 7138 7139 case Intrinsic::icall_branch_funnel: { 7140 SmallVector<SDValue, 16> Ops; 7141 Ops.push_back(getValue(I.getArgOperand(0))); 7142 7143 int64_t Offset; 7144 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7145 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7146 if (!Base) 7147 report_fatal_error( 7148 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7149 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7150 7151 struct BranchFunnelTarget { 7152 int64_t Offset; 7153 SDValue Target; 7154 }; 7155 SmallVector<BranchFunnelTarget, 8> Targets; 7156 7157 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7158 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7159 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7160 if (ElemBase != Base) 7161 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7162 "to the same GlobalValue"); 7163 7164 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7165 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7166 if (!GA) 7167 report_fatal_error( 7168 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7169 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7170 GA->getGlobal(), sdl, Val.getValueType(), 7171 GA->getOffset())}); 7172 } 7173 llvm::sort(Targets, 7174 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7175 return T1.Offset < T2.Offset; 7176 }); 7177 7178 for (auto &T : Targets) { 7179 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7180 Ops.push_back(T.Target); 7181 } 7182 7183 Ops.push_back(DAG.getRoot()); // Chain 7184 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7185 MVT::Other, Ops), 7186 0); 7187 DAG.setRoot(N); 7188 setValue(&I, N); 7189 HasTailCall = true; 7190 return; 7191 } 7192 7193 case Intrinsic::wasm_landingpad_index: 7194 // Information this intrinsic contained has been transferred to 7195 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7196 // delete it now. 7197 return; 7198 7199 case Intrinsic::aarch64_settag: 7200 case Intrinsic::aarch64_settag_zero: { 7201 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7202 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7203 SDValue Val = TSI.EmitTargetCodeForSetTag( 7204 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7205 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7206 ZeroMemory); 7207 DAG.setRoot(Val); 7208 setValue(&I, Val); 7209 return; 7210 } 7211 case Intrinsic::ptrmask: { 7212 SDValue Ptr = getValue(I.getOperand(0)); 7213 SDValue Const = getValue(I.getOperand(1)); 7214 7215 EVT PtrVT = Ptr.getValueType(); 7216 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7217 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7218 return; 7219 } 7220 case Intrinsic::threadlocal_address: { 7221 setValue(&I, getValue(I.getOperand(0))); 7222 return; 7223 } 7224 case Intrinsic::get_active_lane_mask: { 7225 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7226 SDValue Index = getValue(I.getOperand(0)); 7227 EVT ElementVT = Index.getValueType(); 7228 7229 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7230 visitTargetIntrinsic(I, Intrinsic); 7231 return; 7232 } 7233 7234 SDValue TripCount = getValue(I.getOperand(1)); 7235 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7236 7237 SDValue VectorIndex, VectorTripCount; 7238 if (VecTy.isScalableVector()) { 7239 VectorIndex = DAG.getSplatVector(VecTy, sdl, Index); 7240 VectorTripCount = DAG.getSplatVector(VecTy, sdl, TripCount); 7241 } else { 7242 VectorIndex = DAG.getSplatBuildVector(VecTy, sdl, Index); 7243 VectorTripCount = DAG.getSplatBuildVector(VecTy, sdl, TripCount); 7244 } 7245 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7246 SDValue VectorInduction = DAG.getNode( 7247 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7248 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7249 VectorTripCount, ISD::CondCode::SETULT); 7250 setValue(&I, SetCC); 7251 return; 7252 } 7253 case Intrinsic::vector_insert: { 7254 SDValue Vec = getValue(I.getOperand(0)); 7255 SDValue SubVec = getValue(I.getOperand(1)); 7256 SDValue Index = getValue(I.getOperand(2)); 7257 7258 // The intrinsic's index type is i64, but the SDNode requires an index type 7259 // suitable for the target. Convert the index as required. 7260 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7261 if (Index.getValueType() != VectorIdxTy) 7262 Index = DAG.getVectorIdxConstant( 7263 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7264 7265 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7266 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7267 Index)); 7268 return; 7269 } 7270 case Intrinsic::vector_extract: { 7271 SDValue Vec = getValue(I.getOperand(0)); 7272 SDValue Index = getValue(I.getOperand(1)); 7273 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7274 7275 // The intrinsic's index type is i64, but the SDNode requires an index type 7276 // suitable for the target. Convert the index as required. 7277 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7278 if (Index.getValueType() != VectorIdxTy) 7279 Index = DAG.getVectorIdxConstant( 7280 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7281 7282 setValue(&I, 7283 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7284 return; 7285 } 7286 case Intrinsic::experimental_vector_reverse: 7287 visitVectorReverse(I); 7288 return; 7289 case Intrinsic::experimental_vector_splice: 7290 visitVectorSplice(I); 7291 return; 7292 } 7293 } 7294 7295 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7296 const ConstrainedFPIntrinsic &FPI) { 7297 SDLoc sdl = getCurSDLoc(); 7298 7299 // We do not need to serialize constrained FP intrinsics against 7300 // each other or against (nonvolatile) loads, so they can be 7301 // chained like loads. 7302 SDValue Chain = DAG.getRoot(); 7303 SmallVector<SDValue, 4> Opers; 7304 Opers.push_back(Chain); 7305 if (FPI.isUnaryOp()) { 7306 Opers.push_back(getValue(FPI.getArgOperand(0))); 7307 } else if (FPI.isTernaryOp()) { 7308 Opers.push_back(getValue(FPI.getArgOperand(0))); 7309 Opers.push_back(getValue(FPI.getArgOperand(1))); 7310 Opers.push_back(getValue(FPI.getArgOperand(2))); 7311 } else { 7312 Opers.push_back(getValue(FPI.getArgOperand(0))); 7313 Opers.push_back(getValue(FPI.getArgOperand(1))); 7314 } 7315 7316 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7317 assert(Result.getNode()->getNumValues() == 2); 7318 7319 // Push node to the appropriate list so that future instructions can be 7320 // chained up correctly. 7321 SDValue OutChain = Result.getValue(1); 7322 switch (EB) { 7323 case fp::ExceptionBehavior::ebIgnore: 7324 // The only reason why ebIgnore nodes still need to be chained is that 7325 // they might depend on the current rounding mode, and therefore must 7326 // not be moved across instruction that may change that mode. 7327 [[fallthrough]]; 7328 case fp::ExceptionBehavior::ebMayTrap: 7329 // These must not be moved across calls or instructions that may change 7330 // floating-point exception masks. 7331 PendingConstrainedFP.push_back(OutChain); 7332 break; 7333 case fp::ExceptionBehavior::ebStrict: 7334 // These must not be moved across calls or instructions that may change 7335 // floating-point exception masks or read floating-point exception flags. 7336 // In addition, they cannot be optimized out even if unused. 7337 PendingConstrainedFPStrict.push_back(OutChain); 7338 break; 7339 } 7340 }; 7341 7342 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7343 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7344 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7345 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7346 7347 SDNodeFlags Flags; 7348 if (EB == fp::ExceptionBehavior::ebIgnore) 7349 Flags.setNoFPExcept(true); 7350 7351 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7352 Flags.copyFMF(*FPOp); 7353 7354 unsigned Opcode; 7355 switch (FPI.getIntrinsicID()) { 7356 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7357 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7358 case Intrinsic::INTRINSIC: \ 7359 Opcode = ISD::STRICT_##DAGN; \ 7360 break; 7361 #include "llvm/IR/ConstrainedOps.def" 7362 case Intrinsic::experimental_constrained_fmuladd: { 7363 Opcode = ISD::STRICT_FMA; 7364 // Break fmuladd into fmul and fadd. 7365 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7366 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7367 Opers.pop_back(); 7368 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7369 pushOutChain(Mul, EB); 7370 Opcode = ISD::STRICT_FADD; 7371 Opers.clear(); 7372 Opers.push_back(Mul.getValue(1)); 7373 Opers.push_back(Mul.getValue(0)); 7374 Opers.push_back(getValue(FPI.getArgOperand(2))); 7375 } 7376 break; 7377 } 7378 } 7379 7380 // A few strict DAG nodes carry additional operands that are not 7381 // set up by the default code above. 7382 switch (Opcode) { 7383 default: break; 7384 case ISD::STRICT_FP_ROUND: 7385 Opers.push_back( 7386 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7387 break; 7388 case ISD::STRICT_FSETCC: 7389 case ISD::STRICT_FSETCCS: { 7390 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7391 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7392 if (TM.Options.NoNaNsFPMath) 7393 Condition = getFCmpCodeWithoutNaN(Condition); 7394 Opers.push_back(DAG.getCondCode(Condition)); 7395 break; 7396 } 7397 } 7398 7399 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7400 pushOutChain(Result, EB); 7401 7402 SDValue FPResult = Result.getValue(0); 7403 setValue(&FPI, FPResult); 7404 } 7405 7406 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7407 Optional<unsigned> ResOPC; 7408 switch (VPIntrin.getIntrinsicID()) { 7409 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7410 case Intrinsic::VPID: \ 7411 ResOPC = ISD::VPSD; \ 7412 break; 7413 #include "llvm/IR/VPIntrinsics.def" 7414 } 7415 7416 if (!ResOPC) 7417 llvm_unreachable( 7418 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7419 7420 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7421 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7422 if (VPIntrin.getFastMathFlags().allowReassoc()) 7423 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7424 : ISD::VP_REDUCE_FMUL; 7425 } 7426 7427 return *ResOPC; 7428 } 7429 7430 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT, 7431 SmallVector<SDValue, 7> &OpValues) { 7432 SDLoc DL = getCurSDLoc(); 7433 Value *PtrOperand = VPIntrin.getArgOperand(0); 7434 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7435 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7436 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7437 SDValue LD; 7438 bool AddToChain = true; 7439 // Do not serialize variable-length loads of constant memory with 7440 // anything. 7441 if (!Alignment) 7442 Alignment = DAG.getEVTAlign(VT); 7443 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7444 AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7445 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7446 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7447 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7448 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7449 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7450 MMO, false /*IsExpanding */); 7451 if (AddToChain) 7452 PendingLoads.push_back(LD.getValue(1)); 7453 setValue(&VPIntrin, LD); 7454 } 7455 7456 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT, 7457 SmallVector<SDValue, 7> &OpValues) { 7458 SDLoc DL = getCurSDLoc(); 7459 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7460 Value *PtrOperand = VPIntrin.getArgOperand(0); 7461 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7462 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7463 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7464 SDValue LD; 7465 if (!Alignment) 7466 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7467 unsigned AS = 7468 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7469 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7470 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7471 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7472 SDValue Base, Index, Scale; 7473 ISD::MemIndexType IndexType; 7474 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7475 this, VPIntrin.getParent(), 7476 VT.getScalarStoreSize()); 7477 if (!UniformBase) { 7478 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7479 Index = getValue(PtrOperand); 7480 IndexType = ISD::SIGNED_SCALED; 7481 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7482 } 7483 EVT IdxVT = Index.getValueType(); 7484 EVT EltTy = IdxVT.getVectorElementType(); 7485 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7486 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7487 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7488 } 7489 LD = DAG.getGatherVP( 7490 DAG.getVTList(VT, MVT::Other), VT, DL, 7491 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7492 IndexType); 7493 PendingLoads.push_back(LD.getValue(1)); 7494 setValue(&VPIntrin, LD); 7495 } 7496 7497 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin, 7498 SmallVector<SDValue, 7> &OpValues) { 7499 SDLoc DL = getCurSDLoc(); 7500 Value *PtrOperand = VPIntrin.getArgOperand(1); 7501 EVT VT = OpValues[0].getValueType(); 7502 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7503 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7504 SDValue ST; 7505 if (!Alignment) 7506 Alignment = DAG.getEVTAlign(VT); 7507 SDValue Ptr = OpValues[1]; 7508 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7509 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7510 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7511 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7512 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7513 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7514 /* IsTruncating */ false, /*IsCompressing*/ false); 7515 DAG.setRoot(ST); 7516 setValue(&VPIntrin, ST); 7517 } 7518 7519 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin, 7520 SmallVector<SDValue, 7> &OpValues) { 7521 SDLoc DL = getCurSDLoc(); 7522 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7523 Value *PtrOperand = VPIntrin.getArgOperand(1); 7524 EVT VT = OpValues[0].getValueType(); 7525 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7526 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7527 SDValue ST; 7528 if (!Alignment) 7529 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7530 unsigned AS = 7531 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7532 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7533 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7534 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7535 SDValue Base, Index, Scale; 7536 ISD::MemIndexType IndexType; 7537 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7538 this, VPIntrin.getParent(), 7539 VT.getScalarStoreSize()); 7540 if (!UniformBase) { 7541 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7542 Index = getValue(PtrOperand); 7543 IndexType = ISD::SIGNED_SCALED; 7544 Scale = 7545 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7546 } 7547 EVT IdxVT = Index.getValueType(); 7548 EVT EltTy = IdxVT.getVectorElementType(); 7549 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7550 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7551 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7552 } 7553 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7554 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7555 OpValues[2], OpValues[3]}, 7556 MMO, IndexType); 7557 DAG.setRoot(ST); 7558 setValue(&VPIntrin, ST); 7559 } 7560 7561 void SelectionDAGBuilder::visitVPStridedLoad( 7562 const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) { 7563 SDLoc DL = getCurSDLoc(); 7564 Value *PtrOperand = VPIntrin.getArgOperand(0); 7565 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7566 if (!Alignment) 7567 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7568 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7569 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7570 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7571 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7572 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7573 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7574 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7575 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7576 7577 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7578 OpValues[2], OpValues[3], MMO, 7579 false /*IsExpanding*/); 7580 7581 if (AddToChain) 7582 PendingLoads.push_back(LD.getValue(1)); 7583 setValue(&VPIntrin, LD); 7584 } 7585 7586 void SelectionDAGBuilder::visitVPStridedStore( 7587 const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) { 7588 SDLoc DL = getCurSDLoc(); 7589 Value *PtrOperand = VPIntrin.getArgOperand(1); 7590 EVT VT = OpValues[0].getValueType(); 7591 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7592 if (!Alignment) 7593 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7594 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7595 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7596 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7597 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7598 7599 SDValue ST = DAG.getStridedStoreVP( 7600 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7601 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7602 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7603 /*IsCompressing*/ false); 7604 7605 DAG.setRoot(ST); 7606 setValue(&VPIntrin, ST); 7607 } 7608 7609 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7610 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7611 SDLoc DL = getCurSDLoc(); 7612 7613 ISD::CondCode Condition; 7614 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7615 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7616 if (IsFP) { 7617 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7618 // flags, but calls that don't return floating-point types can't be 7619 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7620 Condition = getFCmpCondCode(CondCode); 7621 if (TM.Options.NoNaNsFPMath) 7622 Condition = getFCmpCodeWithoutNaN(Condition); 7623 } else { 7624 Condition = getICmpCondCode(CondCode); 7625 } 7626 7627 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7628 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7629 // #2 is the condition code 7630 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7631 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7632 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7633 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7634 "Unexpected target EVL type"); 7635 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7636 7637 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7638 VPIntrin.getType()); 7639 setValue(&VPIntrin, 7640 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7641 } 7642 7643 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7644 const VPIntrinsic &VPIntrin) { 7645 SDLoc DL = getCurSDLoc(); 7646 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7647 7648 auto IID = VPIntrin.getIntrinsicID(); 7649 7650 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7651 return visitVPCmp(*CmpI); 7652 7653 SmallVector<EVT, 4> ValueVTs; 7654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7655 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7656 SDVTList VTs = DAG.getVTList(ValueVTs); 7657 7658 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7659 7660 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7661 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7662 "Unexpected target EVL type"); 7663 7664 // Request operands. 7665 SmallVector<SDValue, 7> OpValues; 7666 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7667 auto Op = getValue(VPIntrin.getArgOperand(I)); 7668 if (I == EVLParamPos) 7669 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7670 OpValues.push_back(Op); 7671 } 7672 7673 switch (Opcode) { 7674 default: { 7675 SDNodeFlags SDFlags; 7676 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7677 SDFlags.copyFMF(*FPMO); 7678 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7679 setValue(&VPIntrin, Result); 7680 break; 7681 } 7682 case ISD::VP_LOAD: 7683 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7684 break; 7685 case ISD::VP_GATHER: 7686 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7687 break; 7688 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7689 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7690 break; 7691 case ISD::VP_STORE: 7692 visitVPStore(VPIntrin, OpValues); 7693 break; 7694 case ISD::VP_SCATTER: 7695 visitVPScatter(VPIntrin, OpValues); 7696 break; 7697 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7698 visitVPStridedStore(VPIntrin, OpValues); 7699 break; 7700 } 7701 } 7702 7703 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7704 const BasicBlock *EHPadBB, 7705 MCSymbol *&BeginLabel) { 7706 MachineFunction &MF = DAG.getMachineFunction(); 7707 MachineModuleInfo &MMI = MF.getMMI(); 7708 7709 // Insert a label before the invoke call to mark the try range. This can be 7710 // used to detect deletion of the invoke via the MachineModuleInfo. 7711 BeginLabel = MMI.getContext().createTempSymbol(); 7712 7713 // For SjLj, keep track of which landing pads go with which invokes 7714 // so as to maintain the ordering of pads in the LSDA. 7715 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7716 if (CallSiteIndex) { 7717 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7718 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7719 7720 // Now that the call site is handled, stop tracking it. 7721 MMI.setCurrentCallSite(0); 7722 } 7723 7724 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7725 } 7726 7727 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7728 const BasicBlock *EHPadBB, 7729 MCSymbol *BeginLabel) { 7730 assert(BeginLabel && "BeginLabel should've been set"); 7731 7732 MachineFunction &MF = DAG.getMachineFunction(); 7733 MachineModuleInfo &MMI = MF.getMMI(); 7734 7735 // Insert a label at the end of the invoke call to mark the try range. This 7736 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7737 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7738 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7739 7740 // Inform MachineModuleInfo of range. 7741 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7742 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7743 // actually use outlined funclets and their LSDA info style. 7744 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7745 assert(II && "II should've been set"); 7746 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7747 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7748 } else if (!isScopedEHPersonality(Pers)) { 7749 assert(EHPadBB); 7750 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7751 } 7752 7753 return Chain; 7754 } 7755 7756 std::pair<SDValue, SDValue> 7757 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7758 const BasicBlock *EHPadBB) { 7759 MCSymbol *BeginLabel = nullptr; 7760 7761 if (EHPadBB) { 7762 // Both PendingLoads and PendingExports must be flushed here; 7763 // this call might not return. 7764 (void)getRoot(); 7765 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7766 CLI.setChain(getRoot()); 7767 } 7768 7769 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7770 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7771 7772 assert((CLI.IsTailCall || Result.second.getNode()) && 7773 "Non-null chain expected with non-tail call!"); 7774 assert((Result.second.getNode() || !Result.first.getNode()) && 7775 "Null value expected with tail call!"); 7776 7777 if (!Result.second.getNode()) { 7778 // As a special case, a null chain means that a tail call has been emitted 7779 // and the DAG root is already updated. 7780 HasTailCall = true; 7781 7782 // Since there's no actual continuation from this block, nothing can be 7783 // relying on us setting vregs for them. 7784 PendingExports.clear(); 7785 } else { 7786 DAG.setRoot(Result.second); 7787 } 7788 7789 if (EHPadBB) { 7790 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7791 BeginLabel)); 7792 } 7793 7794 return Result; 7795 } 7796 7797 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7798 bool isTailCall, 7799 bool isMustTailCall, 7800 const BasicBlock *EHPadBB) { 7801 auto &DL = DAG.getDataLayout(); 7802 FunctionType *FTy = CB.getFunctionType(); 7803 Type *RetTy = CB.getType(); 7804 7805 TargetLowering::ArgListTy Args; 7806 Args.reserve(CB.arg_size()); 7807 7808 const Value *SwiftErrorVal = nullptr; 7809 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7810 7811 if (isTailCall) { 7812 // Avoid emitting tail calls in functions with the disable-tail-calls 7813 // attribute. 7814 auto *Caller = CB.getParent()->getParent(); 7815 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7816 "true" && !isMustTailCall) 7817 isTailCall = false; 7818 7819 // We can't tail call inside a function with a swifterror argument. Lowering 7820 // does not support this yet. It would have to move into the swifterror 7821 // register before the call. 7822 if (TLI.supportSwiftError() && 7823 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7824 isTailCall = false; 7825 } 7826 7827 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7828 TargetLowering::ArgListEntry Entry; 7829 const Value *V = *I; 7830 7831 // Skip empty types 7832 if (V->getType()->isEmptyTy()) 7833 continue; 7834 7835 SDValue ArgNode = getValue(V); 7836 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7837 7838 Entry.setAttributes(&CB, I - CB.arg_begin()); 7839 7840 // Use swifterror virtual register as input to the call. 7841 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7842 SwiftErrorVal = V; 7843 // We find the virtual register for the actual swifterror argument. 7844 // Instead of using the Value, we use the virtual register instead. 7845 Entry.Node = 7846 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7847 EVT(TLI.getPointerTy(DL))); 7848 } 7849 7850 Args.push_back(Entry); 7851 7852 // If we have an explicit sret argument that is an Instruction, (i.e., it 7853 // might point to function-local memory), we can't meaningfully tail-call. 7854 if (Entry.IsSRet && isa<Instruction>(V)) 7855 isTailCall = false; 7856 } 7857 7858 // If call site has a cfguardtarget operand bundle, create and add an 7859 // additional ArgListEntry. 7860 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7861 TargetLowering::ArgListEntry Entry; 7862 Value *V = Bundle->Inputs[0]; 7863 SDValue ArgNode = getValue(V); 7864 Entry.Node = ArgNode; 7865 Entry.Ty = V->getType(); 7866 Entry.IsCFGuardTarget = true; 7867 Args.push_back(Entry); 7868 } 7869 7870 // Check if target-independent constraints permit a tail call here. 7871 // Target-dependent constraints are checked within TLI->LowerCallTo. 7872 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7873 isTailCall = false; 7874 7875 // Disable tail calls if there is an swifterror argument. Targets have not 7876 // been updated to support tail calls. 7877 if (TLI.supportSwiftError() && SwiftErrorVal) 7878 isTailCall = false; 7879 7880 ConstantInt *CFIType = nullptr; 7881 if (CB.isIndirectCall()) { 7882 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 7883 if (!TLI.supportKCFIBundles()) 7884 report_fatal_error( 7885 "Target doesn't support calls with kcfi operand bundles."); 7886 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 7887 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 7888 } 7889 } 7890 7891 TargetLowering::CallLoweringInfo CLI(DAG); 7892 CLI.setDebugLoc(getCurSDLoc()) 7893 .setChain(getRoot()) 7894 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7895 .setTailCall(isTailCall) 7896 .setConvergent(CB.isConvergent()) 7897 .setIsPreallocated( 7898 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 7899 .setCFIType(CFIType); 7900 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7901 7902 if (Result.first.getNode()) { 7903 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7904 setValue(&CB, Result.first); 7905 } 7906 7907 // The last element of CLI.InVals has the SDValue for swifterror return. 7908 // Here we copy it to a virtual register and update SwiftErrorMap for 7909 // book-keeping. 7910 if (SwiftErrorVal && TLI.supportSwiftError()) { 7911 // Get the last element of InVals. 7912 SDValue Src = CLI.InVals.back(); 7913 Register VReg = 7914 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7915 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7916 DAG.setRoot(CopyNode); 7917 } 7918 } 7919 7920 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7921 SelectionDAGBuilder &Builder) { 7922 // Check to see if this load can be trivially constant folded, e.g. if the 7923 // input is from a string literal. 7924 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7925 // Cast pointer to the type we really want to load. 7926 Type *LoadTy = 7927 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7928 if (LoadVT.isVector()) 7929 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7930 7931 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7932 PointerType::getUnqual(LoadTy)); 7933 7934 if (const Constant *LoadCst = 7935 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 7936 LoadTy, Builder.DAG.getDataLayout())) 7937 return Builder.getValue(LoadCst); 7938 } 7939 7940 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7941 // still constant memory, the input chain can be the entry node. 7942 SDValue Root; 7943 bool ConstantMemory = false; 7944 7945 // Do not serialize (non-volatile) loads of constant memory with anything. 7946 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7947 Root = Builder.DAG.getEntryNode(); 7948 ConstantMemory = true; 7949 } else { 7950 // Do not serialize non-volatile loads against each other. 7951 Root = Builder.DAG.getRoot(); 7952 } 7953 7954 SDValue Ptr = Builder.getValue(PtrVal); 7955 SDValue LoadVal = 7956 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7957 MachinePointerInfo(PtrVal), Align(1)); 7958 7959 if (!ConstantMemory) 7960 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7961 return LoadVal; 7962 } 7963 7964 /// Record the value for an instruction that produces an integer result, 7965 /// converting the type where necessary. 7966 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7967 SDValue Value, 7968 bool IsSigned) { 7969 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7970 I.getType(), true); 7971 if (IsSigned) 7972 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7973 else 7974 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7975 setValue(&I, Value); 7976 } 7977 7978 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7979 /// true and lower it. Otherwise return false, and it will be lowered like a 7980 /// normal call. 7981 /// The caller already checked that \p I calls the appropriate LibFunc with a 7982 /// correct prototype. 7983 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7984 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7985 const Value *Size = I.getArgOperand(2); 7986 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 7987 if (CSize && CSize->getZExtValue() == 0) { 7988 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7989 I.getType(), true); 7990 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7991 return true; 7992 } 7993 7994 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7995 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7996 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7997 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7998 if (Res.first.getNode()) { 7999 processIntegerCallValue(I, Res.first, true); 8000 PendingLoads.push_back(Res.second); 8001 return true; 8002 } 8003 8004 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8005 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8006 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8007 return false; 8008 8009 // If the target has a fast compare for the given size, it will return a 8010 // preferred load type for that size. Require that the load VT is legal and 8011 // that the target supports unaligned loads of that type. Otherwise, return 8012 // INVALID. 8013 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8014 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8015 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8016 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8017 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8018 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8019 // TODO: Check alignment of src and dest ptrs. 8020 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8021 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8022 if (!TLI.isTypeLegal(LVT) || 8023 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8024 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8025 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8026 } 8027 8028 return LVT; 8029 }; 8030 8031 // This turns into unaligned loads. We only do this if the target natively 8032 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8033 // we'll only produce a small number of byte loads. 8034 MVT LoadVT; 8035 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8036 switch (NumBitsToCompare) { 8037 default: 8038 return false; 8039 case 16: 8040 LoadVT = MVT::i16; 8041 break; 8042 case 32: 8043 LoadVT = MVT::i32; 8044 break; 8045 case 64: 8046 case 128: 8047 case 256: 8048 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8049 break; 8050 } 8051 8052 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8053 return false; 8054 8055 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8056 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8057 8058 // Bitcast to a wide integer type if the loads are vectors. 8059 if (LoadVT.isVector()) { 8060 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8061 LoadL = DAG.getBitcast(CmpVT, LoadL); 8062 LoadR = DAG.getBitcast(CmpVT, LoadR); 8063 } 8064 8065 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8066 processIntegerCallValue(I, Cmp, false); 8067 return true; 8068 } 8069 8070 /// See if we can lower a memchr call into an optimized form. If so, return 8071 /// true and lower it. Otherwise return false, and it will be lowered like a 8072 /// normal call. 8073 /// The caller already checked that \p I calls the appropriate LibFunc with a 8074 /// correct prototype. 8075 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8076 const Value *Src = I.getArgOperand(0); 8077 const Value *Char = I.getArgOperand(1); 8078 const Value *Length = I.getArgOperand(2); 8079 8080 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8081 std::pair<SDValue, SDValue> Res = 8082 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8083 getValue(Src), getValue(Char), getValue(Length), 8084 MachinePointerInfo(Src)); 8085 if (Res.first.getNode()) { 8086 setValue(&I, Res.first); 8087 PendingLoads.push_back(Res.second); 8088 return true; 8089 } 8090 8091 return false; 8092 } 8093 8094 /// See if we can lower a mempcpy call into an optimized form. If so, return 8095 /// true and lower it. Otherwise return false, and it will be lowered like a 8096 /// normal call. 8097 /// The caller already checked that \p I calls the appropriate LibFunc with a 8098 /// correct prototype. 8099 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8100 SDValue Dst = getValue(I.getArgOperand(0)); 8101 SDValue Src = getValue(I.getArgOperand(1)); 8102 SDValue Size = getValue(I.getArgOperand(2)); 8103 8104 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8105 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8106 // DAG::getMemcpy needs Alignment to be defined. 8107 Align Alignment = std::min(DstAlign, SrcAlign); 8108 8109 bool isVol = false; 8110 SDLoc sdl = getCurSDLoc(); 8111 8112 // In the mempcpy context we need to pass in a false value for isTailCall 8113 // because the return pointer needs to be adjusted by the size of 8114 // the copied memory. 8115 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 8116 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 8117 /*isTailCall=*/false, 8118 MachinePointerInfo(I.getArgOperand(0)), 8119 MachinePointerInfo(I.getArgOperand(1)), 8120 I.getAAMetadata()); 8121 assert(MC.getNode() != nullptr && 8122 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8123 DAG.setRoot(MC); 8124 8125 // Check if Size needs to be truncated or extended. 8126 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8127 8128 // Adjust return pointer to point just past the last dst byte. 8129 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8130 Dst, Size); 8131 setValue(&I, DstPlusSize); 8132 return true; 8133 } 8134 8135 /// See if we can lower a strcpy call into an optimized form. If so, return 8136 /// true and lower it, otherwise return false and it will be lowered like a 8137 /// normal call. 8138 /// The caller already checked that \p I calls the appropriate LibFunc with a 8139 /// correct prototype. 8140 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8141 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8142 8143 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8144 std::pair<SDValue, SDValue> Res = 8145 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8146 getValue(Arg0), getValue(Arg1), 8147 MachinePointerInfo(Arg0), 8148 MachinePointerInfo(Arg1), isStpcpy); 8149 if (Res.first.getNode()) { 8150 setValue(&I, Res.first); 8151 DAG.setRoot(Res.second); 8152 return true; 8153 } 8154 8155 return false; 8156 } 8157 8158 /// See if we can lower a strcmp call into an optimized form. If so, return 8159 /// true and lower it, otherwise return false and it will be lowered like a 8160 /// normal call. 8161 /// The caller already checked that \p I calls the appropriate LibFunc with a 8162 /// correct prototype. 8163 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8164 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8165 8166 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8167 std::pair<SDValue, SDValue> Res = 8168 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8169 getValue(Arg0), getValue(Arg1), 8170 MachinePointerInfo(Arg0), 8171 MachinePointerInfo(Arg1)); 8172 if (Res.first.getNode()) { 8173 processIntegerCallValue(I, Res.first, true); 8174 PendingLoads.push_back(Res.second); 8175 return true; 8176 } 8177 8178 return false; 8179 } 8180 8181 /// See if we can lower a strlen call into an optimized form. If so, return 8182 /// true and lower it, otherwise return false and it will be lowered like a 8183 /// normal call. 8184 /// The caller already checked that \p I calls the appropriate LibFunc with a 8185 /// correct prototype. 8186 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8187 const Value *Arg0 = I.getArgOperand(0); 8188 8189 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8190 std::pair<SDValue, SDValue> Res = 8191 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8192 getValue(Arg0), MachinePointerInfo(Arg0)); 8193 if (Res.first.getNode()) { 8194 processIntegerCallValue(I, Res.first, false); 8195 PendingLoads.push_back(Res.second); 8196 return true; 8197 } 8198 8199 return false; 8200 } 8201 8202 /// See if we can lower a strnlen call into an optimized form. If so, return 8203 /// true and lower it, otherwise return false and it will be lowered like a 8204 /// normal call. 8205 /// The caller already checked that \p I calls the appropriate LibFunc with a 8206 /// correct prototype. 8207 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8208 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8209 8210 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8211 std::pair<SDValue, SDValue> Res = 8212 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8213 getValue(Arg0), getValue(Arg1), 8214 MachinePointerInfo(Arg0)); 8215 if (Res.first.getNode()) { 8216 processIntegerCallValue(I, Res.first, false); 8217 PendingLoads.push_back(Res.second); 8218 return true; 8219 } 8220 8221 return false; 8222 } 8223 8224 /// See if we can lower a unary floating-point operation into an SDNode with 8225 /// the specified Opcode. If so, return true and lower it, otherwise return 8226 /// false and it will be lowered like a normal call. 8227 /// The caller already checked that \p I calls the appropriate LibFunc with a 8228 /// correct prototype. 8229 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8230 unsigned Opcode) { 8231 // We already checked this call's prototype; verify it doesn't modify errno. 8232 if (!I.onlyReadsMemory()) 8233 return false; 8234 8235 SDNodeFlags Flags; 8236 Flags.copyFMF(cast<FPMathOperator>(I)); 8237 8238 SDValue Tmp = getValue(I.getArgOperand(0)); 8239 setValue(&I, 8240 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8241 return true; 8242 } 8243 8244 /// See if we can lower a binary floating-point operation into an SDNode with 8245 /// the specified Opcode. If so, return true and lower it. Otherwise return 8246 /// false, and it will be lowered like a normal call. 8247 /// The caller already checked that \p I calls the appropriate LibFunc with a 8248 /// correct prototype. 8249 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8250 unsigned Opcode) { 8251 // We already checked this call's prototype; verify it doesn't modify errno. 8252 if (!I.onlyReadsMemory()) 8253 return false; 8254 8255 SDNodeFlags Flags; 8256 Flags.copyFMF(cast<FPMathOperator>(I)); 8257 8258 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8259 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8260 EVT VT = Tmp0.getValueType(); 8261 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8262 return true; 8263 } 8264 8265 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8266 // Handle inline assembly differently. 8267 if (I.isInlineAsm()) { 8268 visitInlineAsm(I); 8269 return; 8270 } 8271 8272 if (Function *F = I.getCalledFunction()) { 8273 diagnoseDontCall(I); 8274 8275 if (F->isDeclaration()) { 8276 // Is this an LLVM intrinsic or a target-specific intrinsic? 8277 unsigned IID = F->getIntrinsicID(); 8278 if (!IID) 8279 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8280 IID = II->getIntrinsicID(F); 8281 8282 if (IID) { 8283 visitIntrinsicCall(I, IID); 8284 return; 8285 } 8286 } 8287 8288 // Check for well-known libc/libm calls. If the function is internal, it 8289 // can't be a library call. Don't do the check if marked as nobuiltin for 8290 // some reason or the call site requires strict floating point semantics. 8291 LibFunc Func; 8292 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8293 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8294 LibInfo->hasOptimizedCodeGen(Func)) { 8295 switch (Func) { 8296 default: break; 8297 case LibFunc_bcmp: 8298 if (visitMemCmpBCmpCall(I)) 8299 return; 8300 break; 8301 case LibFunc_copysign: 8302 case LibFunc_copysignf: 8303 case LibFunc_copysignl: 8304 // We already checked this call's prototype; verify it doesn't modify 8305 // errno. 8306 if (I.onlyReadsMemory()) { 8307 SDValue LHS = getValue(I.getArgOperand(0)); 8308 SDValue RHS = getValue(I.getArgOperand(1)); 8309 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8310 LHS.getValueType(), LHS, RHS)); 8311 return; 8312 } 8313 break; 8314 case LibFunc_fabs: 8315 case LibFunc_fabsf: 8316 case LibFunc_fabsl: 8317 if (visitUnaryFloatCall(I, ISD::FABS)) 8318 return; 8319 break; 8320 case LibFunc_fmin: 8321 case LibFunc_fminf: 8322 case LibFunc_fminl: 8323 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8324 return; 8325 break; 8326 case LibFunc_fmax: 8327 case LibFunc_fmaxf: 8328 case LibFunc_fmaxl: 8329 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8330 return; 8331 break; 8332 case LibFunc_sin: 8333 case LibFunc_sinf: 8334 case LibFunc_sinl: 8335 if (visitUnaryFloatCall(I, ISD::FSIN)) 8336 return; 8337 break; 8338 case LibFunc_cos: 8339 case LibFunc_cosf: 8340 case LibFunc_cosl: 8341 if (visitUnaryFloatCall(I, ISD::FCOS)) 8342 return; 8343 break; 8344 case LibFunc_sqrt: 8345 case LibFunc_sqrtf: 8346 case LibFunc_sqrtl: 8347 case LibFunc_sqrt_finite: 8348 case LibFunc_sqrtf_finite: 8349 case LibFunc_sqrtl_finite: 8350 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8351 return; 8352 break; 8353 case LibFunc_floor: 8354 case LibFunc_floorf: 8355 case LibFunc_floorl: 8356 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8357 return; 8358 break; 8359 case LibFunc_nearbyint: 8360 case LibFunc_nearbyintf: 8361 case LibFunc_nearbyintl: 8362 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8363 return; 8364 break; 8365 case LibFunc_ceil: 8366 case LibFunc_ceilf: 8367 case LibFunc_ceill: 8368 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8369 return; 8370 break; 8371 case LibFunc_rint: 8372 case LibFunc_rintf: 8373 case LibFunc_rintl: 8374 if (visitUnaryFloatCall(I, ISD::FRINT)) 8375 return; 8376 break; 8377 case LibFunc_round: 8378 case LibFunc_roundf: 8379 case LibFunc_roundl: 8380 if (visitUnaryFloatCall(I, ISD::FROUND)) 8381 return; 8382 break; 8383 case LibFunc_trunc: 8384 case LibFunc_truncf: 8385 case LibFunc_truncl: 8386 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8387 return; 8388 break; 8389 case LibFunc_log2: 8390 case LibFunc_log2f: 8391 case LibFunc_log2l: 8392 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8393 return; 8394 break; 8395 case LibFunc_exp2: 8396 case LibFunc_exp2f: 8397 case LibFunc_exp2l: 8398 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8399 return; 8400 break; 8401 case LibFunc_memcmp: 8402 if (visitMemCmpBCmpCall(I)) 8403 return; 8404 break; 8405 case LibFunc_mempcpy: 8406 if (visitMemPCpyCall(I)) 8407 return; 8408 break; 8409 case LibFunc_memchr: 8410 if (visitMemChrCall(I)) 8411 return; 8412 break; 8413 case LibFunc_strcpy: 8414 if (visitStrCpyCall(I, false)) 8415 return; 8416 break; 8417 case LibFunc_stpcpy: 8418 if (visitStrCpyCall(I, true)) 8419 return; 8420 break; 8421 case LibFunc_strcmp: 8422 if (visitStrCmpCall(I)) 8423 return; 8424 break; 8425 case LibFunc_strlen: 8426 if (visitStrLenCall(I)) 8427 return; 8428 break; 8429 case LibFunc_strnlen: 8430 if (visitStrNLenCall(I)) 8431 return; 8432 break; 8433 } 8434 } 8435 } 8436 8437 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8438 // have to do anything here to lower funclet bundles. 8439 // CFGuardTarget bundles are lowered in LowerCallTo. 8440 assert(!I.hasOperandBundlesOtherThan( 8441 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8442 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8443 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8444 "Cannot lower calls with arbitrary operand bundles!"); 8445 8446 SDValue Callee = getValue(I.getCalledOperand()); 8447 8448 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8449 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8450 else 8451 // Check if we can potentially perform a tail call. More detailed checking 8452 // is be done within LowerCallTo, after more information about the call is 8453 // known. 8454 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8455 } 8456 8457 namespace { 8458 8459 /// AsmOperandInfo - This contains information for each constraint that we are 8460 /// lowering. 8461 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8462 public: 8463 /// CallOperand - If this is the result output operand or a clobber 8464 /// this is null, otherwise it is the incoming operand to the CallInst. 8465 /// This gets modified as the asm is processed. 8466 SDValue CallOperand; 8467 8468 /// AssignedRegs - If this is a register or register class operand, this 8469 /// contains the set of register corresponding to the operand. 8470 RegsForValue AssignedRegs; 8471 8472 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8473 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8474 } 8475 8476 /// Whether or not this operand accesses memory 8477 bool hasMemory(const TargetLowering &TLI) const { 8478 // Indirect operand accesses access memory. 8479 if (isIndirect) 8480 return true; 8481 8482 for (const auto &Code : Codes) 8483 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8484 return true; 8485 8486 return false; 8487 } 8488 }; 8489 8490 8491 } // end anonymous namespace 8492 8493 /// Make sure that the output operand \p OpInfo and its corresponding input 8494 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8495 /// out). 8496 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8497 SDISelAsmOperandInfo &MatchingOpInfo, 8498 SelectionDAG &DAG) { 8499 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8500 return; 8501 8502 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8503 const auto &TLI = DAG.getTargetLoweringInfo(); 8504 8505 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8506 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8507 OpInfo.ConstraintVT); 8508 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8509 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8510 MatchingOpInfo.ConstraintVT); 8511 if ((OpInfo.ConstraintVT.isInteger() != 8512 MatchingOpInfo.ConstraintVT.isInteger()) || 8513 (MatchRC.second != InputRC.second)) { 8514 // FIXME: error out in a more elegant fashion 8515 report_fatal_error("Unsupported asm: input constraint" 8516 " with a matching output constraint of" 8517 " incompatible type!"); 8518 } 8519 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8520 } 8521 8522 /// Get a direct memory input to behave well as an indirect operand. 8523 /// This may introduce stores, hence the need for a \p Chain. 8524 /// \return The (possibly updated) chain. 8525 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8526 SDISelAsmOperandInfo &OpInfo, 8527 SelectionDAG &DAG) { 8528 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8529 8530 // If we don't have an indirect input, put it in the constpool if we can, 8531 // otherwise spill it to a stack slot. 8532 // TODO: This isn't quite right. We need to handle these according to 8533 // the addressing mode that the constraint wants. Also, this may take 8534 // an additional register for the computation and we don't want that 8535 // either. 8536 8537 // If the operand is a float, integer, or vector constant, spill to a 8538 // constant pool entry to get its address. 8539 const Value *OpVal = OpInfo.CallOperandVal; 8540 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8541 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8542 OpInfo.CallOperand = DAG.getConstantPool( 8543 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8544 return Chain; 8545 } 8546 8547 // Otherwise, create a stack slot and emit a store to it before the asm. 8548 Type *Ty = OpVal->getType(); 8549 auto &DL = DAG.getDataLayout(); 8550 uint64_t TySize = DL.getTypeAllocSize(Ty); 8551 MachineFunction &MF = DAG.getMachineFunction(); 8552 int SSFI = MF.getFrameInfo().CreateStackObject( 8553 TySize, DL.getPrefTypeAlign(Ty), false); 8554 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8555 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8556 MachinePointerInfo::getFixedStack(MF, SSFI), 8557 TLI.getMemValueType(DL, Ty)); 8558 OpInfo.CallOperand = StackSlot; 8559 8560 return Chain; 8561 } 8562 8563 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8564 /// specified operand. We prefer to assign virtual registers, to allow the 8565 /// register allocator to handle the assignment process. However, if the asm 8566 /// uses features that we can't model on machineinstrs, we have SDISel do the 8567 /// allocation. This produces generally horrible, but correct, code. 8568 /// 8569 /// OpInfo describes the operand 8570 /// RefOpInfo describes the matching operand if any, the operand otherwise 8571 static llvm::Optional<unsigned> 8572 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8573 SDISelAsmOperandInfo &OpInfo, 8574 SDISelAsmOperandInfo &RefOpInfo) { 8575 LLVMContext &Context = *DAG.getContext(); 8576 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8577 8578 MachineFunction &MF = DAG.getMachineFunction(); 8579 SmallVector<unsigned, 4> Regs; 8580 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8581 8582 // No work to do for memory/address operands. 8583 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8584 OpInfo.ConstraintType == TargetLowering::C_Address) 8585 return None; 8586 8587 // If this is a constraint for a single physreg, or a constraint for a 8588 // register class, find it. 8589 unsigned AssignedReg; 8590 const TargetRegisterClass *RC; 8591 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8592 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8593 // RC is unset only on failure. Return immediately. 8594 if (!RC) 8595 return None; 8596 8597 // Get the actual register value type. This is important, because the user 8598 // may have asked for (e.g.) the AX register in i32 type. We need to 8599 // remember that AX is actually i16 to get the right extension. 8600 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8601 8602 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8603 // If this is an FP operand in an integer register (or visa versa), or more 8604 // generally if the operand value disagrees with the register class we plan 8605 // to stick it in, fix the operand type. 8606 // 8607 // If this is an input value, the bitcast to the new type is done now. 8608 // Bitcast for output value is done at the end of visitInlineAsm(). 8609 if ((OpInfo.Type == InlineAsm::isOutput || 8610 OpInfo.Type == InlineAsm::isInput) && 8611 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8612 // Try to convert to the first EVT that the reg class contains. If the 8613 // types are identical size, use a bitcast to convert (e.g. two differing 8614 // vector types). Note: output bitcast is done at the end of 8615 // visitInlineAsm(). 8616 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8617 // Exclude indirect inputs while they are unsupported because the code 8618 // to perform the load is missing and thus OpInfo.CallOperand still 8619 // refers to the input address rather than the pointed-to value. 8620 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8621 OpInfo.CallOperand = 8622 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8623 OpInfo.ConstraintVT = RegVT; 8624 // If the operand is an FP value and we want it in integer registers, 8625 // use the corresponding integer type. This turns an f64 value into 8626 // i64, which can be passed with two i32 values on a 32-bit machine. 8627 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8628 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8629 if (OpInfo.Type == InlineAsm::isInput) 8630 OpInfo.CallOperand = 8631 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8632 OpInfo.ConstraintVT = VT; 8633 } 8634 } 8635 } 8636 8637 // No need to allocate a matching input constraint since the constraint it's 8638 // matching to has already been allocated. 8639 if (OpInfo.isMatchingInputConstraint()) 8640 return None; 8641 8642 EVT ValueVT = OpInfo.ConstraintVT; 8643 if (OpInfo.ConstraintVT == MVT::Other) 8644 ValueVT = RegVT; 8645 8646 // Initialize NumRegs. 8647 unsigned NumRegs = 1; 8648 if (OpInfo.ConstraintVT != MVT::Other) 8649 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8650 8651 // If this is a constraint for a specific physical register, like {r17}, 8652 // assign it now. 8653 8654 // If this associated to a specific register, initialize iterator to correct 8655 // place. If virtual, make sure we have enough registers 8656 8657 // Initialize iterator if necessary 8658 TargetRegisterClass::iterator I = RC->begin(); 8659 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8660 8661 // Do not check for single registers. 8662 if (AssignedReg) { 8663 I = std::find(I, RC->end(), AssignedReg); 8664 if (I == RC->end()) { 8665 // RC does not contain the selected register, which indicates a 8666 // mismatch between the register and the required type/bitwidth. 8667 return {AssignedReg}; 8668 } 8669 } 8670 8671 for (; NumRegs; --NumRegs, ++I) { 8672 assert(I != RC->end() && "Ran out of registers to allocate!"); 8673 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8674 Regs.push_back(R); 8675 } 8676 8677 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8678 return None; 8679 } 8680 8681 static unsigned 8682 findMatchingInlineAsmOperand(unsigned OperandNo, 8683 const std::vector<SDValue> &AsmNodeOperands) { 8684 // Scan until we find the definition we already emitted of this operand. 8685 unsigned CurOp = InlineAsm::Op_FirstOperand; 8686 for (; OperandNo; --OperandNo) { 8687 // Advance to the next operand. 8688 unsigned OpFlag = 8689 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8690 assert((InlineAsm::isRegDefKind(OpFlag) || 8691 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8692 InlineAsm::isMemKind(OpFlag)) && 8693 "Skipped past definitions?"); 8694 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8695 } 8696 return CurOp; 8697 } 8698 8699 namespace { 8700 8701 class ExtraFlags { 8702 unsigned Flags = 0; 8703 8704 public: 8705 explicit ExtraFlags(const CallBase &Call) { 8706 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8707 if (IA->hasSideEffects()) 8708 Flags |= InlineAsm::Extra_HasSideEffects; 8709 if (IA->isAlignStack()) 8710 Flags |= InlineAsm::Extra_IsAlignStack; 8711 if (Call.isConvergent()) 8712 Flags |= InlineAsm::Extra_IsConvergent; 8713 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8714 } 8715 8716 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8717 // Ideally, we would only check against memory constraints. However, the 8718 // meaning of an Other constraint can be target-specific and we can't easily 8719 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8720 // for Other constraints as well. 8721 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8722 OpInfo.ConstraintType == TargetLowering::C_Other) { 8723 if (OpInfo.Type == InlineAsm::isInput) 8724 Flags |= InlineAsm::Extra_MayLoad; 8725 else if (OpInfo.Type == InlineAsm::isOutput) 8726 Flags |= InlineAsm::Extra_MayStore; 8727 else if (OpInfo.Type == InlineAsm::isClobber) 8728 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8729 } 8730 } 8731 8732 unsigned get() const { return Flags; } 8733 }; 8734 8735 } // end anonymous namespace 8736 8737 /// visitInlineAsm - Handle a call to an InlineAsm object. 8738 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8739 const BasicBlock *EHPadBB) { 8740 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8741 8742 /// ConstraintOperands - Information about all of the constraints. 8743 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8744 8745 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8746 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8747 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8748 8749 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8750 // AsmDialect, MayLoad, MayStore). 8751 bool HasSideEffect = IA->hasSideEffects(); 8752 ExtraFlags ExtraInfo(Call); 8753 8754 for (auto &T : TargetConstraints) { 8755 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8756 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8757 8758 if (OpInfo.CallOperandVal) 8759 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8760 8761 if (!HasSideEffect) 8762 HasSideEffect = OpInfo.hasMemory(TLI); 8763 8764 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8765 // FIXME: Could we compute this on OpInfo rather than T? 8766 8767 // Compute the constraint code and ConstraintType to use. 8768 TLI.ComputeConstraintToUse(T, SDValue()); 8769 8770 if (T.ConstraintType == TargetLowering::C_Immediate && 8771 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8772 // We've delayed emitting a diagnostic like the "n" constraint because 8773 // inlining could cause an integer showing up. 8774 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8775 "' expects an integer constant " 8776 "expression"); 8777 8778 ExtraInfo.update(T); 8779 } 8780 8781 // We won't need to flush pending loads if this asm doesn't touch 8782 // memory and is nonvolatile. 8783 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8784 8785 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8786 if (EmitEHLabels) { 8787 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8788 } 8789 bool IsCallBr = isa<CallBrInst>(Call); 8790 8791 if (IsCallBr || EmitEHLabels) { 8792 // If this is a callbr or invoke we need to flush pending exports since 8793 // inlineasm_br and invoke are terminators. 8794 // We need to do this before nodes are glued to the inlineasm_br node. 8795 Chain = getControlRoot(); 8796 } 8797 8798 MCSymbol *BeginLabel = nullptr; 8799 if (EmitEHLabels) { 8800 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8801 } 8802 8803 // Second pass over the constraints: compute which constraint option to use. 8804 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8805 // If this is an output operand with a matching input operand, look up the 8806 // matching input. If their types mismatch, e.g. one is an integer, the 8807 // other is floating point, or their sizes are different, flag it as an 8808 // error. 8809 if (OpInfo.hasMatchingInput()) { 8810 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8811 patchMatchingInput(OpInfo, Input, DAG); 8812 } 8813 8814 // Compute the constraint code and ConstraintType to use. 8815 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8816 8817 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 8818 OpInfo.Type == InlineAsm::isClobber) || 8819 OpInfo.ConstraintType == TargetLowering::C_Address) 8820 continue; 8821 8822 // If this is a memory input, and if the operand is not indirect, do what we 8823 // need to provide an address for the memory input. 8824 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8825 !OpInfo.isIndirect) { 8826 assert((OpInfo.isMultipleAlternative || 8827 (OpInfo.Type == InlineAsm::isInput)) && 8828 "Can only indirectify direct input operands!"); 8829 8830 // Memory operands really want the address of the value. 8831 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8832 8833 // There is no longer a Value* corresponding to this operand. 8834 OpInfo.CallOperandVal = nullptr; 8835 8836 // It is now an indirect operand. 8837 OpInfo.isIndirect = true; 8838 } 8839 8840 } 8841 8842 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8843 std::vector<SDValue> AsmNodeOperands; 8844 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8845 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8846 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8847 8848 // If we have a !srcloc metadata node associated with it, we want to attach 8849 // this to the ultimately generated inline asm machineinstr. To do this, we 8850 // pass in the third operand as this (potentially null) inline asm MDNode. 8851 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8852 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8853 8854 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8855 // bits as operand 3. 8856 AsmNodeOperands.push_back(DAG.getTargetConstant( 8857 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8858 8859 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8860 // this, assign virtual and physical registers for inputs and otput. 8861 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8862 // Assign Registers. 8863 SDISelAsmOperandInfo &RefOpInfo = 8864 OpInfo.isMatchingInputConstraint() 8865 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8866 : OpInfo; 8867 const auto RegError = 8868 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8869 if (RegError) { 8870 const MachineFunction &MF = DAG.getMachineFunction(); 8871 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8872 const char *RegName = TRI.getName(RegError.value()); 8873 emitInlineAsmError(Call, "register '" + Twine(RegName) + 8874 "' allocated for constraint '" + 8875 Twine(OpInfo.ConstraintCode) + 8876 "' does not match required type"); 8877 return; 8878 } 8879 8880 auto DetectWriteToReservedRegister = [&]() { 8881 const MachineFunction &MF = DAG.getMachineFunction(); 8882 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8883 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8884 if (Register::isPhysicalRegister(Reg) && 8885 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8886 const char *RegName = TRI.getName(Reg); 8887 emitInlineAsmError(Call, "write to reserved register '" + 8888 Twine(RegName) + "'"); 8889 return true; 8890 } 8891 } 8892 return false; 8893 }; 8894 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 8895 (OpInfo.Type == InlineAsm::isInput && 8896 !OpInfo.isMatchingInputConstraint())) && 8897 "Only address as input operand is allowed."); 8898 8899 switch (OpInfo.Type) { 8900 case InlineAsm::isOutput: 8901 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8902 unsigned ConstraintID = 8903 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8904 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8905 "Failed to convert memory constraint code to constraint id."); 8906 8907 // Add information to the INLINEASM node to know about this output. 8908 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8909 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8910 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8911 MVT::i32)); 8912 AsmNodeOperands.push_back(OpInfo.CallOperand); 8913 } else { 8914 // Otherwise, this outputs to a register (directly for C_Register / 8915 // C_RegisterClass, and a target-defined fashion for 8916 // C_Immediate/C_Other). Find a register that we can use. 8917 if (OpInfo.AssignedRegs.Regs.empty()) { 8918 emitInlineAsmError( 8919 Call, "couldn't allocate output register for constraint '" + 8920 Twine(OpInfo.ConstraintCode) + "'"); 8921 return; 8922 } 8923 8924 if (DetectWriteToReservedRegister()) 8925 return; 8926 8927 // Add information to the INLINEASM node to know that this register is 8928 // set. 8929 OpInfo.AssignedRegs.AddInlineAsmOperands( 8930 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8931 : InlineAsm::Kind_RegDef, 8932 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8933 } 8934 break; 8935 8936 case InlineAsm::isInput: 8937 case InlineAsm::isLabel: { 8938 SDValue InOperandVal = OpInfo.CallOperand; 8939 8940 if (OpInfo.isMatchingInputConstraint()) { 8941 // If this is required to match an output register we have already set, 8942 // just use its register. 8943 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8944 AsmNodeOperands); 8945 unsigned OpFlag = 8946 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8947 if (InlineAsm::isRegDefKind(OpFlag) || 8948 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8949 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8950 if (OpInfo.isIndirect) { 8951 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8952 emitInlineAsmError(Call, "inline asm not supported yet: " 8953 "don't know how to handle tied " 8954 "indirect register inputs"); 8955 return; 8956 } 8957 8958 SmallVector<unsigned, 4> Regs; 8959 MachineFunction &MF = DAG.getMachineFunction(); 8960 MachineRegisterInfo &MRI = MF.getRegInfo(); 8961 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8962 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 8963 Register TiedReg = R->getReg(); 8964 MVT RegVT = R->getSimpleValueType(0); 8965 const TargetRegisterClass *RC = 8966 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 8967 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 8968 : TRI.getMinimalPhysRegClass(TiedReg); 8969 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8970 for (unsigned i = 0; i != NumRegs; ++i) 8971 Regs.push_back(MRI.createVirtualRegister(RC)); 8972 8973 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8974 8975 SDLoc dl = getCurSDLoc(); 8976 // Use the produced MatchedRegs object to 8977 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8978 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8979 true, OpInfo.getMatchedOperand(), dl, 8980 DAG, AsmNodeOperands); 8981 break; 8982 } 8983 8984 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8985 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8986 "Unexpected number of operands"); 8987 // Add information to the INLINEASM node to know about this input. 8988 // See InlineAsm.h isUseOperandTiedToDef. 8989 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8990 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8991 OpInfo.getMatchedOperand()); 8992 AsmNodeOperands.push_back(DAG.getTargetConstant( 8993 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8994 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8995 break; 8996 } 8997 8998 // Treat indirect 'X' constraint as memory. 8999 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9000 OpInfo.isIndirect) 9001 OpInfo.ConstraintType = TargetLowering::C_Memory; 9002 9003 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9004 OpInfo.ConstraintType == TargetLowering::C_Other) { 9005 std::vector<SDValue> Ops; 9006 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9007 Ops, DAG); 9008 if (Ops.empty()) { 9009 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9010 if (isa<ConstantSDNode>(InOperandVal)) { 9011 emitInlineAsmError(Call, "value out of range for constraint '" + 9012 Twine(OpInfo.ConstraintCode) + "'"); 9013 return; 9014 } 9015 9016 emitInlineAsmError(Call, 9017 "invalid operand for inline asm constraint '" + 9018 Twine(OpInfo.ConstraintCode) + "'"); 9019 return; 9020 } 9021 9022 // Add information to the INLINEASM node to know about this input. 9023 unsigned ResOpType = 9024 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9025 AsmNodeOperands.push_back(DAG.getTargetConstant( 9026 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9027 llvm::append_range(AsmNodeOperands, Ops); 9028 break; 9029 } 9030 9031 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9032 OpInfo.ConstraintType == TargetLowering::C_Address) { 9033 assert((OpInfo.isIndirect || 9034 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9035 "Operand must be indirect to be a mem!"); 9036 assert(InOperandVal.getValueType() == 9037 TLI.getPointerTy(DAG.getDataLayout()) && 9038 "Memory operands expect pointer values"); 9039 9040 unsigned ConstraintID = 9041 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9042 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9043 "Failed to convert memory constraint code to constraint id."); 9044 9045 // Add information to the INLINEASM node to know about this input. 9046 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9047 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9048 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9049 getCurSDLoc(), 9050 MVT::i32)); 9051 AsmNodeOperands.push_back(InOperandVal); 9052 break; 9053 } 9054 9055 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9056 OpInfo.ConstraintType == TargetLowering::C_Register) && 9057 "Unknown constraint type!"); 9058 9059 // TODO: Support this. 9060 if (OpInfo.isIndirect) { 9061 emitInlineAsmError( 9062 Call, "Don't know how to handle indirect register inputs yet " 9063 "for constraint '" + 9064 Twine(OpInfo.ConstraintCode) + "'"); 9065 return; 9066 } 9067 9068 // Copy the input into the appropriate registers. 9069 if (OpInfo.AssignedRegs.Regs.empty()) { 9070 emitInlineAsmError(Call, 9071 "couldn't allocate input reg for constraint '" + 9072 Twine(OpInfo.ConstraintCode) + "'"); 9073 return; 9074 } 9075 9076 if (DetectWriteToReservedRegister()) 9077 return; 9078 9079 SDLoc dl = getCurSDLoc(); 9080 9081 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 9082 &Call); 9083 9084 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9085 dl, DAG, AsmNodeOperands); 9086 break; 9087 } 9088 case InlineAsm::isClobber: 9089 // Add the clobbered value to the operand list, so that the register 9090 // allocator is aware that the physreg got clobbered. 9091 if (!OpInfo.AssignedRegs.Regs.empty()) 9092 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9093 false, 0, getCurSDLoc(), DAG, 9094 AsmNodeOperands); 9095 break; 9096 } 9097 } 9098 9099 // Finish up input operands. Set the input chain and add the flag last. 9100 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9101 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 9102 9103 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9104 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9105 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9106 Flag = Chain.getValue(1); 9107 9108 // Do additional work to generate outputs. 9109 9110 SmallVector<EVT, 1> ResultVTs; 9111 SmallVector<SDValue, 1> ResultValues; 9112 SmallVector<SDValue, 8> OutChains; 9113 9114 llvm::Type *CallResultType = Call.getType(); 9115 ArrayRef<Type *> ResultTypes; 9116 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9117 ResultTypes = StructResult->elements(); 9118 else if (!CallResultType->isVoidTy()) 9119 ResultTypes = makeArrayRef(CallResultType); 9120 9121 auto CurResultType = ResultTypes.begin(); 9122 auto handleRegAssign = [&](SDValue V) { 9123 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9124 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9125 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9126 ++CurResultType; 9127 // If the type of the inline asm call site return value is different but has 9128 // same size as the type of the asm output bitcast it. One example of this 9129 // is for vectors with different width / number of elements. This can 9130 // happen for register classes that can contain multiple different value 9131 // types. The preg or vreg allocated may not have the same VT as was 9132 // expected. 9133 // 9134 // This can also happen for a return value that disagrees with the register 9135 // class it is put in, eg. a double in a general-purpose register on a 9136 // 32-bit machine. 9137 if (ResultVT != V.getValueType() && 9138 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9139 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9140 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9141 V.getValueType().isInteger()) { 9142 // If a result value was tied to an input value, the computed result 9143 // may have a wider width than the expected result. Extract the 9144 // relevant portion. 9145 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9146 } 9147 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9148 ResultVTs.push_back(ResultVT); 9149 ResultValues.push_back(V); 9150 }; 9151 9152 // Deal with output operands. 9153 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9154 if (OpInfo.Type == InlineAsm::isOutput) { 9155 SDValue Val; 9156 // Skip trivial output operands. 9157 if (OpInfo.AssignedRegs.Regs.empty()) 9158 continue; 9159 9160 switch (OpInfo.ConstraintType) { 9161 case TargetLowering::C_Register: 9162 case TargetLowering::C_RegisterClass: 9163 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9164 Chain, &Flag, &Call); 9165 break; 9166 case TargetLowering::C_Immediate: 9167 case TargetLowering::C_Other: 9168 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 9169 OpInfo, DAG); 9170 break; 9171 case TargetLowering::C_Memory: 9172 break; // Already handled. 9173 case TargetLowering::C_Address: 9174 break; // Silence warning. 9175 case TargetLowering::C_Unknown: 9176 assert(false && "Unexpected unknown constraint"); 9177 } 9178 9179 // Indirect output manifest as stores. Record output chains. 9180 if (OpInfo.isIndirect) { 9181 const Value *Ptr = OpInfo.CallOperandVal; 9182 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9183 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9184 MachinePointerInfo(Ptr)); 9185 OutChains.push_back(Store); 9186 } else { 9187 // generate CopyFromRegs to associated registers. 9188 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9189 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9190 for (const SDValue &V : Val->op_values()) 9191 handleRegAssign(V); 9192 } else 9193 handleRegAssign(Val); 9194 } 9195 } 9196 } 9197 9198 // Set results. 9199 if (!ResultValues.empty()) { 9200 assert(CurResultType == ResultTypes.end() && 9201 "Mismatch in number of ResultTypes"); 9202 assert(ResultValues.size() == ResultTypes.size() && 9203 "Mismatch in number of output operands in asm result"); 9204 9205 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9206 DAG.getVTList(ResultVTs), ResultValues); 9207 setValue(&Call, V); 9208 } 9209 9210 // Collect store chains. 9211 if (!OutChains.empty()) 9212 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9213 9214 if (EmitEHLabels) { 9215 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9216 } 9217 9218 // Only Update Root if inline assembly has a memory effect. 9219 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9220 EmitEHLabels) 9221 DAG.setRoot(Chain); 9222 } 9223 9224 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9225 const Twine &Message) { 9226 LLVMContext &Ctx = *DAG.getContext(); 9227 Ctx.emitError(&Call, Message); 9228 9229 // Make sure we leave the DAG in a valid state 9230 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9231 SmallVector<EVT, 1> ValueVTs; 9232 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9233 9234 if (ValueVTs.empty()) 9235 return; 9236 9237 SmallVector<SDValue, 1> Ops; 9238 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9239 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9240 9241 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9242 } 9243 9244 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9245 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9246 MVT::Other, getRoot(), 9247 getValue(I.getArgOperand(0)), 9248 DAG.getSrcValue(I.getArgOperand(0)))); 9249 } 9250 9251 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9252 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9253 const DataLayout &DL = DAG.getDataLayout(); 9254 SDValue V = DAG.getVAArg( 9255 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9256 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9257 DL.getABITypeAlign(I.getType()).value()); 9258 DAG.setRoot(V.getValue(1)); 9259 9260 if (I.getType()->isPointerTy()) 9261 V = DAG.getPtrExtOrTrunc( 9262 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9263 setValue(&I, V); 9264 } 9265 9266 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9267 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9268 MVT::Other, getRoot(), 9269 getValue(I.getArgOperand(0)), 9270 DAG.getSrcValue(I.getArgOperand(0)))); 9271 } 9272 9273 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9274 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9275 MVT::Other, getRoot(), 9276 getValue(I.getArgOperand(0)), 9277 getValue(I.getArgOperand(1)), 9278 DAG.getSrcValue(I.getArgOperand(0)), 9279 DAG.getSrcValue(I.getArgOperand(1)))); 9280 } 9281 9282 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9283 const Instruction &I, 9284 SDValue Op) { 9285 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9286 if (!Range) 9287 return Op; 9288 9289 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9290 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9291 return Op; 9292 9293 APInt Lo = CR.getUnsignedMin(); 9294 if (!Lo.isMinValue()) 9295 return Op; 9296 9297 APInt Hi = CR.getUnsignedMax(); 9298 unsigned Bits = std::max(Hi.getActiveBits(), 9299 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9300 9301 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9302 9303 SDLoc SL = getCurSDLoc(); 9304 9305 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9306 DAG.getValueType(SmallVT)); 9307 unsigned NumVals = Op.getNode()->getNumValues(); 9308 if (NumVals == 1) 9309 return ZExt; 9310 9311 SmallVector<SDValue, 4> Ops; 9312 9313 Ops.push_back(ZExt); 9314 for (unsigned I = 1; I != NumVals; ++I) 9315 Ops.push_back(Op.getValue(I)); 9316 9317 return DAG.getMergeValues(Ops, SL); 9318 } 9319 9320 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9321 /// the call being lowered. 9322 /// 9323 /// This is a helper for lowering intrinsics that follow a target calling 9324 /// convention or require stack pointer adjustment. Only a subset of the 9325 /// intrinsic's operands need to participate in the calling convention. 9326 void SelectionDAGBuilder::populateCallLoweringInfo( 9327 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9328 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9329 bool IsPatchPoint) { 9330 TargetLowering::ArgListTy Args; 9331 Args.reserve(NumArgs); 9332 9333 // Populate the argument list. 9334 // Attributes for args start at offset 1, after the return attribute. 9335 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9336 ArgI != ArgE; ++ArgI) { 9337 const Value *V = Call->getOperand(ArgI); 9338 9339 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9340 9341 TargetLowering::ArgListEntry Entry; 9342 Entry.Node = getValue(V); 9343 Entry.Ty = V->getType(); 9344 Entry.setAttributes(Call, ArgI); 9345 Args.push_back(Entry); 9346 } 9347 9348 CLI.setDebugLoc(getCurSDLoc()) 9349 .setChain(getRoot()) 9350 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9351 .setDiscardResult(Call->use_empty()) 9352 .setIsPatchPoint(IsPatchPoint) 9353 .setIsPreallocated( 9354 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9355 } 9356 9357 /// Add a stack map intrinsic call's live variable operands to a stackmap 9358 /// or patchpoint target node's operand list. 9359 /// 9360 /// Constants are converted to TargetConstants purely as an optimization to 9361 /// avoid constant materialization and register allocation. 9362 /// 9363 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9364 /// generate addess computation nodes, and so FinalizeISel can convert the 9365 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9366 /// address materialization and register allocation, but may also be required 9367 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9368 /// alloca in the entry block, then the runtime may assume that the alloca's 9369 /// StackMap location can be read immediately after compilation and that the 9370 /// location is valid at any point during execution (this is similar to the 9371 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9372 /// only available in a register, then the runtime would need to trap when 9373 /// execution reaches the StackMap in order to read the alloca's location. 9374 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9375 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9376 SelectionDAGBuilder &Builder) { 9377 SelectionDAG &DAG = Builder.DAG; 9378 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9379 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9380 9381 // Things on the stack are pointer-typed, meaning that they are already 9382 // legal and can be emitted directly to target nodes. 9383 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9384 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9385 } else { 9386 // Otherwise emit a target independent node to be legalised. 9387 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9388 } 9389 } 9390 } 9391 9392 /// Lower llvm.experimental.stackmap. 9393 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9394 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9395 // [live variables...]) 9396 9397 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9398 9399 SDValue Chain, InFlag, Callee; 9400 SmallVector<SDValue, 32> Ops; 9401 9402 SDLoc DL = getCurSDLoc(); 9403 Callee = getValue(CI.getCalledOperand()); 9404 9405 // The stackmap intrinsic only records the live variables (the arguments 9406 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9407 // intrinsic, this won't be lowered to a function call. This means we don't 9408 // have to worry about calling conventions and target specific lowering code. 9409 // Instead we perform the call lowering right here. 9410 // 9411 // chain, flag = CALLSEQ_START(chain, 0, 0) 9412 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9413 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9414 // 9415 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9416 InFlag = Chain.getValue(1); 9417 9418 // Add the STACKMAP operands, starting with DAG house-keeping. 9419 Ops.push_back(Chain); 9420 Ops.push_back(InFlag); 9421 9422 // Add the <id>, <numShadowBytes> operands. 9423 // 9424 // These do not require legalisation, and can be emitted directly to target 9425 // constant nodes. 9426 SDValue ID = getValue(CI.getArgOperand(0)); 9427 assert(ID.getValueType() == MVT::i64); 9428 SDValue IDConst = DAG.getTargetConstant( 9429 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9430 Ops.push_back(IDConst); 9431 9432 SDValue Shad = getValue(CI.getArgOperand(1)); 9433 assert(Shad.getValueType() == MVT::i32); 9434 SDValue ShadConst = DAG.getTargetConstant( 9435 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9436 Ops.push_back(ShadConst); 9437 9438 // Add the live variables. 9439 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9440 9441 // Create the STACKMAP node. 9442 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9443 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9444 InFlag = Chain.getValue(1); 9445 9446 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL); 9447 9448 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9449 9450 // Set the root to the target-lowered call chain. 9451 DAG.setRoot(Chain); 9452 9453 // Inform the Frame Information that we have a stackmap in this function. 9454 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9455 } 9456 9457 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9458 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9459 const BasicBlock *EHPadBB) { 9460 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9461 // i32 <numBytes>, 9462 // i8* <target>, 9463 // i32 <numArgs>, 9464 // [Args...], 9465 // [live variables...]) 9466 9467 CallingConv::ID CC = CB.getCallingConv(); 9468 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9469 bool HasDef = !CB.getType()->isVoidTy(); 9470 SDLoc dl = getCurSDLoc(); 9471 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9472 9473 // Handle immediate and symbolic callees. 9474 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9475 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9476 /*isTarget=*/true); 9477 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9478 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9479 SDLoc(SymbolicCallee), 9480 SymbolicCallee->getValueType(0)); 9481 9482 // Get the real number of arguments participating in the call <numArgs> 9483 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9484 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9485 9486 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9487 // Intrinsics include all meta-operands up to but not including CC. 9488 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9489 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9490 "Not enough arguments provided to the patchpoint intrinsic"); 9491 9492 // For AnyRegCC the arguments are lowered later on manually. 9493 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9494 Type *ReturnTy = 9495 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9496 9497 TargetLowering::CallLoweringInfo CLI(DAG); 9498 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9499 ReturnTy, true); 9500 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9501 9502 SDNode *CallEnd = Result.second.getNode(); 9503 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9504 CallEnd = CallEnd->getOperand(0).getNode(); 9505 9506 /// Get a call instruction from the call sequence chain. 9507 /// Tail calls are not allowed. 9508 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9509 "Expected a callseq node."); 9510 SDNode *Call = CallEnd->getOperand(0).getNode(); 9511 bool HasGlue = Call->getGluedNode(); 9512 9513 // Replace the target specific call node with the patchable intrinsic. 9514 SmallVector<SDValue, 8> Ops; 9515 9516 // Push the chain. 9517 Ops.push_back(*(Call->op_begin())); 9518 9519 // Optionally, push the glue (if any). 9520 if (HasGlue) 9521 Ops.push_back(*(Call->op_end() - 1)); 9522 9523 // Push the register mask info. 9524 if (HasGlue) 9525 Ops.push_back(*(Call->op_end() - 2)); 9526 else 9527 Ops.push_back(*(Call->op_end() - 1)); 9528 9529 // Add the <id> and <numBytes> constants. 9530 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9531 Ops.push_back(DAG.getTargetConstant( 9532 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9533 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9534 Ops.push_back(DAG.getTargetConstant( 9535 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9536 MVT::i32)); 9537 9538 // Add the callee. 9539 Ops.push_back(Callee); 9540 9541 // Adjust <numArgs> to account for any arguments that have been passed on the 9542 // stack instead. 9543 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9544 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9545 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9546 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9547 9548 // Add the calling convention 9549 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9550 9551 // Add the arguments we omitted previously. The register allocator should 9552 // place these in any free register. 9553 if (IsAnyRegCC) 9554 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9555 Ops.push_back(getValue(CB.getArgOperand(i))); 9556 9557 // Push the arguments from the call instruction. 9558 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9559 Ops.append(Call->op_begin() + 2, e); 9560 9561 // Push live variables for the stack map. 9562 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9563 9564 SDVTList NodeTys; 9565 if (IsAnyRegCC && HasDef) { 9566 // Create the return types based on the intrinsic definition 9567 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9568 SmallVector<EVT, 3> ValueVTs; 9569 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9570 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9571 9572 // There is always a chain and a glue type at the end 9573 ValueVTs.push_back(MVT::Other); 9574 ValueVTs.push_back(MVT::Glue); 9575 NodeTys = DAG.getVTList(ValueVTs); 9576 } else 9577 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9578 9579 // Replace the target specific call node with a PATCHPOINT node. 9580 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9581 9582 // Update the NodeMap. 9583 if (HasDef) { 9584 if (IsAnyRegCC) 9585 setValue(&CB, SDValue(PPV.getNode(), 0)); 9586 else 9587 setValue(&CB, Result.first); 9588 } 9589 9590 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9591 // call sequence. Furthermore the location of the chain and glue can change 9592 // when the AnyReg calling convention is used and the intrinsic returns a 9593 // value. 9594 if (IsAnyRegCC && HasDef) { 9595 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9596 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9597 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9598 } else 9599 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9600 DAG.DeleteNode(Call); 9601 9602 // Inform the Frame Information that we have a patchpoint in this function. 9603 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9604 } 9605 9606 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9607 unsigned Intrinsic) { 9608 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9609 SDValue Op1 = getValue(I.getArgOperand(0)); 9610 SDValue Op2; 9611 if (I.arg_size() > 1) 9612 Op2 = getValue(I.getArgOperand(1)); 9613 SDLoc dl = getCurSDLoc(); 9614 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9615 SDValue Res; 9616 SDNodeFlags SDFlags; 9617 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9618 SDFlags.copyFMF(*FPMO); 9619 9620 switch (Intrinsic) { 9621 case Intrinsic::vector_reduce_fadd: 9622 if (SDFlags.hasAllowReassociation()) 9623 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9624 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9625 SDFlags); 9626 else 9627 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9628 break; 9629 case Intrinsic::vector_reduce_fmul: 9630 if (SDFlags.hasAllowReassociation()) 9631 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9632 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9633 SDFlags); 9634 else 9635 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9636 break; 9637 case Intrinsic::vector_reduce_add: 9638 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9639 break; 9640 case Intrinsic::vector_reduce_mul: 9641 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9642 break; 9643 case Intrinsic::vector_reduce_and: 9644 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9645 break; 9646 case Intrinsic::vector_reduce_or: 9647 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9648 break; 9649 case Intrinsic::vector_reduce_xor: 9650 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9651 break; 9652 case Intrinsic::vector_reduce_smax: 9653 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9654 break; 9655 case Intrinsic::vector_reduce_smin: 9656 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9657 break; 9658 case Intrinsic::vector_reduce_umax: 9659 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9660 break; 9661 case Intrinsic::vector_reduce_umin: 9662 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9663 break; 9664 case Intrinsic::vector_reduce_fmax: 9665 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9666 break; 9667 case Intrinsic::vector_reduce_fmin: 9668 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9669 break; 9670 default: 9671 llvm_unreachable("Unhandled vector reduce intrinsic"); 9672 } 9673 setValue(&I, Res); 9674 } 9675 9676 /// Returns an AttributeList representing the attributes applied to the return 9677 /// value of the given call. 9678 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9679 SmallVector<Attribute::AttrKind, 2> Attrs; 9680 if (CLI.RetSExt) 9681 Attrs.push_back(Attribute::SExt); 9682 if (CLI.RetZExt) 9683 Attrs.push_back(Attribute::ZExt); 9684 if (CLI.IsInReg) 9685 Attrs.push_back(Attribute::InReg); 9686 9687 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9688 Attrs); 9689 } 9690 9691 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9692 /// implementation, which just calls LowerCall. 9693 /// FIXME: When all targets are 9694 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9695 std::pair<SDValue, SDValue> 9696 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9697 // Handle the incoming return values from the call. 9698 CLI.Ins.clear(); 9699 Type *OrigRetTy = CLI.RetTy; 9700 SmallVector<EVT, 4> RetTys; 9701 SmallVector<uint64_t, 4> Offsets; 9702 auto &DL = CLI.DAG.getDataLayout(); 9703 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9704 9705 if (CLI.IsPostTypeLegalization) { 9706 // If we are lowering a libcall after legalization, split the return type. 9707 SmallVector<EVT, 4> OldRetTys; 9708 SmallVector<uint64_t, 4> OldOffsets; 9709 RetTys.swap(OldRetTys); 9710 Offsets.swap(OldOffsets); 9711 9712 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9713 EVT RetVT = OldRetTys[i]; 9714 uint64_t Offset = OldOffsets[i]; 9715 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9716 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9717 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9718 RetTys.append(NumRegs, RegisterVT); 9719 for (unsigned j = 0; j != NumRegs; ++j) 9720 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9721 } 9722 } 9723 9724 SmallVector<ISD::OutputArg, 4> Outs; 9725 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9726 9727 bool CanLowerReturn = 9728 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9729 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9730 9731 SDValue DemoteStackSlot; 9732 int DemoteStackIdx = -100; 9733 if (!CanLowerReturn) { 9734 // FIXME: equivalent assert? 9735 // assert(!CS.hasInAllocaArgument() && 9736 // "sret demotion is incompatible with inalloca"); 9737 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9738 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9739 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9740 DemoteStackIdx = 9741 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9742 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9743 DL.getAllocaAddrSpace()); 9744 9745 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9746 ArgListEntry Entry; 9747 Entry.Node = DemoteStackSlot; 9748 Entry.Ty = StackSlotPtrType; 9749 Entry.IsSExt = false; 9750 Entry.IsZExt = false; 9751 Entry.IsInReg = false; 9752 Entry.IsSRet = true; 9753 Entry.IsNest = false; 9754 Entry.IsByVal = false; 9755 Entry.IsByRef = false; 9756 Entry.IsReturned = false; 9757 Entry.IsSwiftSelf = false; 9758 Entry.IsSwiftAsync = false; 9759 Entry.IsSwiftError = false; 9760 Entry.IsCFGuardTarget = false; 9761 Entry.Alignment = Alignment; 9762 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9763 CLI.NumFixedArgs += 1; 9764 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9765 9766 // sret demotion isn't compatible with tail-calls, since the sret argument 9767 // points into the callers stack frame. 9768 CLI.IsTailCall = false; 9769 } else { 9770 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9771 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9772 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9773 ISD::ArgFlagsTy Flags; 9774 if (NeedsRegBlock) { 9775 Flags.setInConsecutiveRegs(); 9776 if (I == RetTys.size() - 1) 9777 Flags.setInConsecutiveRegsLast(); 9778 } 9779 EVT VT = RetTys[I]; 9780 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9781 CLI.CallConv, VT); 9782 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9783 CLI.CallConv, VT); 9784 for (unsigned i = 0; i != NumRegs; ++i) { 9785 ISD::InputArg MyFlags; 9786 MyFlags.Flags = Flags; 9787 MyFlags.VT = RegisterVT; 9788 MyFlags.ArgVT = VT; 9789 MyFlags.Used = CLI.IsReturnValueUsed; 9790 if (CLI.RetTy->isPointerTy()) { 9791 MyFlags.Flags.setPointer(); 9792 MyFlags.Flags.setPointerAddrSpace( 9793 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9794 } 9795 if (CLI.RetSExt) 9796 MyFlags.Flags.setSExt(); 9797 if (CLI.RetZExt) 9798 MyFlags.Flags.setZExt(); 9799 if (CLI.IsInReg) 9800 MyFlags.Flags.setInReg(); 9801 CLI.Ins.push_back(MyFlags); 9802 } 9803 } 9804 } 9805 9806 // We push in swifterror return as the last element of CLI.Ins. 9807 ArgListTy &Args = CLI.getArgs(); 9808 if (supportSwiftError()) { 9809 for (const ArgListEntry &Arg : Args) { 9810 if (Arg.IsSwiftError) { 9811 ISD::InputArg MyFlags; 9812 MyFlags.VT = getPointerTy(DL); 9813 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9814 MyFlags.Flags.setSwiftError(); 9815 CLI.Ins.push_back(MyFlags); 9816 } 9817 } 9818 } 9819 9820 // Handle all of the outgoing arguments. 9821 CLI.Outs.clear(); 9822 CLI.OutVals.clear(); 9823 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9824 SmallVector<EVT, 4> ValueVTs; 9825 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9826 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9827 Type *FinalType = Args[i].Ty; 9828 if (Args[i].IsByVal) 9829 FinalType = Args[i].IndirectType; 9830 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9831 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 9832 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9833 ++Value) { 9834 EVT VT = ValueVTs[Value]; 9835 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9836 SDValue Op = SDValue(Args[i].Node.getNode(), 9837 Args[i].Node.getResNo() + Value); 9838 ISD::ArgFlagsTy Flags; 9839 9840 // Certain targets (such as MIPS), may have a different ABI alignment 9841 // for a type depending on the context. Give the target a chance to 9842 // specify the alignment it wants. 9843 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9844 Flags.setOrigAlign(OriginalAlignment); 9845 9846 if (Args[i].Ty->isPointerTy()) { 9847 Flags.setPointer(); 9848 Flags.setPointerAddrSpace( 9849 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9850 } 9851 if (Args[i].IsZExt) 9852 Flags.setZExt(); 9853 if (Args[i].IsSExt) 9854 Flags.setSExt(); 9855 if (Args[i].IsInReg) { 9856 // If we are using vectorcall calling convention, a structure that is 9857 // passed InReg - is surely an HVA 9858 if (CLI.CallConv == CallingConv::X86_VectorCall && 9859 isa<StructType>(FinalType)) { 9860 // The first value of a structure is marked 9861 if (0 == Value) 9862 Flags.setHvaStart(); 9863 Flags.setHva(); 9864 } 9865 // Set InReg Flag 9866 Flags.setInReg(); 9867 } 9868 if (Args[i].IsSRet) 9869 Flags.setSRet(); 9870 if (Args[i].IsSwiftSelf) 9871 Flags.setSwiftSelf(); 9872 if (Args[i].IsSwiftAsync) 9873 Flags.setSwiftAsync(); 9874 if (Args[i].IsSwiftError) 9875 Flags.setSwiftError(); 9876 if (Args[i].IsCFGuardTarget) 9877 Flags.setCFGuardTarget(); 9878 if (Args[i].IsByVal) 9879 Flags.setByVal(); 9880 if (Args[i].IsByRef) 9881 Flags.setByRef(); 9882 if (Args[i].IsPreallocated) { 9883 Flags.setPreallocated(); 9884 // Set the byval flag for CCAssignFn callbacks that don't know about 9885 // preallocated. This way we can know how many bytes we should've 9886 // allocated and how many bytes a callee cleanup function will pop. If 9887 // we port preallocated to more targets, we'll have to add custom 9888 // preallocated handling in the various CC lowering callbacks. 9889 Flags.setByVal(); 9890 } 9891 if (Args[i].IsInAlloca) { 9892 Flags.setInAlloca(); 9893 // Set the byval flag for CCAssignFn callbacks that don't know about 9894 // inalloca. This way we can know how many bytes we should've allocated 9895 // and how many bytes a callee cleanup function will pop. If we port 9896 // inalloca to more targets, we'll have to add custom inalloca handling 9897 // in the various CC lowering callbacks. 9898 Flags.setByVal(); 9899 } 9900 Align MemAlign; 9901 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9902 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 9903 Flags.setByValSize(FrameSize); 9904 9905 // info is not there but there are cases it cannot get right. 9906 if (auto MA = Args[i].Alignment) 9907 MemAlign = *MA; 9908 else 9909 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 9910 } else if (auto MA = Args[i].Alignment) { 9911 MemAlign = *MA; 9912 } else { 9913 MemAlign = OriginalAlignment; 9914 } 9915 Flags.setMemAlign(MemAlign); 9916 if (Args[i].IsNest) 9917 Flags.setNest(); 9918 if (NeedsRegBlock) 9919 Flags.setInConsecutiveRegs(); 9920 9921 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9922 CLI.CallConv, VT); 9923 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9924 CLI.CallConv, VT); 9925 SmallVector<SDValue, 4> Parts(NumParts); 9926 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9927 9928 if (Args[i].IsSExt) 9929 ExtendKind = ISD::SIGN_EXTEND; 9930 else if (Args[i].IsZExt) 9931 ExtendKind = ISD::ZERO_EXTEND; 9932 9933 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9934 // for now. 9935 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9936 CanLowerReturn) { 9937 assert((CLI.RetTy == Args[i].Ty || 9938 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9939 CLI.RetTy->getPointerAddressSpace() == 9940 Args[i].Ty->getPointerAddressSpace())) && 9941 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9942 // Before passing 'returned' to the target lowering code, ensure that 9943 // either the register MVT and the actual EVT are the same size or that 9944 // the return value and argument are extended in the same way; in these 9945 // cases it's safe to pass the argument register value unchanged as the 9946 // return register value (although it's at the target's option whether 9947 // to do so) 9948 // TODO: allow code generation to take advantage of partially preserved 9949 // registers rather than clobbering the entire register when the 9950 // parameter extension method is not compatible with the return 9951 // extension method 9952 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9953 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9954 CLI.RetZExt == Args[i].IsZExt)) 9955 Flags.setReturned(); 9956 } 9957 9958 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9959 CLI.CallConv, ExtendKind); 9960 9961 for (unsigned j = 0; j != NumParts; ++j) { 9962 // if it isn't first piece, alignment must be 1 9963 // For scalable vectors the scalable part is currently handled 9964 // by individual targets, so we just use the known minimum size here. 9965 ISD::OutputArg MyFlags( 9966 Flags, Parts[j].getValueType().getSimpleVT(), VT, 9967 i < CLI.NumFixedArgs, i, 9968 j * Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9969 if (NumParts > 1 && j == 0) 9970 MyFlags.Flags.setSplit(); 9971 else if (j != 0) { 9972 MyFlags.Flags.setOrigAlign(Align(1)); 9973 if (j == NumParts - 1) 9974 MyFlags.Flags.setSplitEnd(); 9975 } 9976 9977 CLI.Outs.push_back(MyFlags); 9978 CLI.OutVals.push_back(Parts[j]); 9979 } 9980 9981 if (NeedsRegBlock && Value == NumValues - 1) 9982 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9983 } 9984 } 9985 9986 SmallVector<SDValue, 4> InVals; 9987 CLI.Chain = LowerCall(CLI, InVals); 9988 9989 // Update CLI.InVals to use outside of this function. 9990 CLI.InVals = InVals; 9991 9992 // Verify that the target's LowerCall behaved as expected. 9993 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9994 "LowerCall didn't return a valid chain!"); 9995 assert((!CLI.IsTailCall || InVals.empty()) && 9996 "LowerCall emitted a return value for a tail call!"); 9997 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9998 "LowerCall didn't emit the correct number of values!"); 9999 10000 // For a tail call, the return value is merely live-out and there aren't 10001 // any nodes in the DAG representing it. Return a special value to 10002 // indicate that a tail call has been emitted and no more Instructions 10003 // should be processed in the current block. 10004 if (CLI.IsTailCall) { 10005 CLI.DAG.setRoot(CLI.Chain); 10006 return std::make_pair(SDValue(), SDValue()); 10007 } 10008 10009 #ifndef NDEBUG 10010 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10011 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10012 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10013 "LowerCall emitted a value with the wrong type!"); 10014 } 10015 #endif 10016 10017 SmallVector<SDValue, 4> ReturnValues; 10018 if (!CanLowerReturn) { 10019 // The instruction result is the result of loading from the 10020 // hidden sret parameter. 10021 SmallVector<EVT, 1> PVTs; 10022 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10023 10024 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10025 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10026 EVT PtrVT = PVTs[0]; 10027 10028 unsigned NumValues = RetTys.size(); 10029 ReturnValues.resize(NumValues); 10030 SmallVector<SDValue, 4> Chains(NumValues); 10031 10032 // An aggregate return value cannot wrap around the address space, so 10033 // offsets to its parts don't wrap either. 10034 SDNodeFlags Flags; 10035 Flags.setNoUnsignedWrap(true); 10036 10037 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10038 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10039 for (unsigned i = 0; i < NumValues; ++i) { 10040 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10041 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10042 PtrVT), Flags); 10043 SDValue L = CLI.DAG.getLoad( 10044 RetTys[i], CLI.DL, CLI.Chain, Add, 10045 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10046 DemoteStackIdx, Offsets[i]), 10047 HiddenSRetAlign); 10048 ReturnValues[i] = L; 10049 Chains[i] = L.getValue(1); 10050 } 10051 10052 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10053 } else { 10054 // Collect the legal value parts into potentially illegal values 10055 // that correspond to the original function's return values. 10056 Optional<ISD::NodeType> AssertOp; 10057 if (CLI.RetSExt) 10058 AssertOp = ISD::AssertSext; 10059 else if (CLI.RetZExt) 10060 AssertOp = ISD::AssertZext; 10061 unsigned CurReg = 0; 10062 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10063 EVT VT = RetTys[I]; 10064 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10065 CLI.CallConv, VT); 10066 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10067 CLI.CallConv, VT); 10068 10069 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10070 NumRegs, RegisterVT, VT, nullptr, 10071 CLI.CallConv, AssertOp)); 10072 CurReg += NumRegs; 10073 } 10074 10075 // For a function returning void, there is no return value. We can't create 10076 // such a node, so we just return a null return value in that case. In 10077 // that case, nothing will actually look at the value. 10078 if (ReturnValues.empty()) 10079 return std::make_pair(SDValue(), CLI.Chain); 10080 } 10081 10082 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10083 CLI.DAG.getVTList(RetTys), ReturnValues); 10084 return std::make_pair(Res, CLI.Chain); 10085 } 10086 10087 /// Places new result values for the node in Results (their number 10088 /// and types must exactly match those of the original return values of 10089 /// the node), or leaves Results empty, which indicates that the node is not 10090 /// to be custom lowered after all. 10091 void TargetLowering::LowerOperationWrapper(SDNode *N, 10092 SmallVectorImpl<SDValue> &Results, 10093 SelectionDAG &DAG) const { 10094 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10095 10096 if (!Res.getNode()) 10097 return; 10098 10099 // If the original node has one result, take the return value from 10100 // LowerOperation as is. It might not be result number 0. 10101 if (N->getNumValues() == 1) { 10102 Results.push_back(Res); 10103 return; 10104 } 10105 10106 // If the original node has multiple results, then the return node should 10107 // have the same number of results. 10108 assert((N->getNumValues() == Res->getNumValues()) && 10109 "Lowering returned the wrong number of results!"); 10110 10111 // Places new result values base on N result number. 10112 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10113 Results.push_back(Res.getValue(I)); 10114 } 10115 10116 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10117 llvm_unreachable("LowerOperation not implemented for this target!"); 10118 } 10119 10120 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10121 unsigned Reg, 10122 ISD::NodeType ExtendType) { 10123 SDValue Op = getNonRegisterValue(V); 10124 assert((Op.getOpcode() != ISD::CopyFromReg || 10125 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10126 "Copy from a reg to the same reg!"); 10127 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10128 10129 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10130 // If this is an InlineAsm we have to match the registers required, not the 10131 // notional registers required by the type. 10132 10133 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10134 None); // This is not an ABI copy. 10135 SDValue Chain = DAG.getEntryNode(); 10136 10137 if (ExtendType == ISD::ANY_EXTEND) { 10138 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10139 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10140 ExtendType = PreferredExtendIt->second; 10141 } 10142 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10143 PendingExports.push_back(Chain); 10144 } 10145 10146 #include "llvm/CodeGen/SelectionDAGISel.h" 10147 10148 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10149 /// entry block, return true. This includes arguments used by switches, since 10150 /// the switch may expand into multiple basic blocks. 10151 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10152 // With FastISel active, we may be splitting blocks, so force creation 10153 // of virtual registers for all non-dead arguments. 10154 if (FastISel) 10155 return A->use_empty(); 10156 10157 const BasicBlock &Entry = A->getParent()->front(); 10158 for (const User *U : A->users()) 10159 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10160 return false; // Use not in entry block. 10161 10162 return true; 10163 } 10164 10165 using ArgCopyElisionMapTy = 10166 DenseMap<const Argument *, 10167 std::pair<const AllocaInst *, const StoreInst *>>; 10168 10169 /// Scan the entry block of the function in FuncInfo for arguments that look 10170 /// like copies into a local alloca. Record any copied arguments in 10171 /// ArgCopyElisionCandidates. 10172 static void 10173 findArgumentCopyElisionCandidates(const DataLayout &DL, 10174 FunctionLoweringInfo *FuncInfo, 10175 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10176 // Record the state of every static alloca used in the entry block. Argument 10177 // allocas are all used in the entry block, so we need approximately as many 10178 // entries as we have arguments. 10179 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10180 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10181 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10182 StaticAllocas.reserve(NumArgs * 2); 10183 10184 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10185 if (!V) 10186 return nullptr; 10187 V = V->stripPointerCasts(); 10188 const auto *AI = dyn_cast<AllocaInst>(V); 10189 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10190 return nullptr; 10191 auto Iter = StaticAllocas.insert({AI, Unknown}); 10192 return &Iter.first->second; 10193 }; 10194 10195 // Look for stores of arguments to static allocas. Look through bitcasts and 10196 // GEPs to handle type coercions, as long as the alloca is fully initialized 10197 // by the store. Any non-store use of an alloca escapes it and any subsequent 10198 // unanalyzed store might write it. 10199 // FIXME: Handle structs initialized with multiple stores. 10200 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10201 // Look for stores, and handle non-store uses conservatively. 10202 const auto *SI = dyn_cast<StoreInst>(&I); 10203 if (!SI) { 10204 // We will look through cast uses, so ignore them completely. 10205 if (I.isCast()) 10206 continue; 10207 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10208 // to allocas. 10209 if (I.isDebugOrPseudoInst()) 10210 continue; 10211 // This is an unknown instruction. Assume it escapes or writes to all 10212 // static alloca operands. 10213 for (const Use &U : I.operands()) { 10214 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10215 *Info = StaticAllocaInfo::Clobbered; 10216 } 10217 continue; 10218 } 10219 10220 // If the stored value is a static alloca, mark it as escaped. 10221 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10222 *Info = StaticAllocaInfo::Clobbered; 10223 10224 // Check if the destination is a static alloca. 10225 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10226 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10227 if (!Info) 10228 continue; 10229 const AllocaInst *AI = cast<AllocaInst>(Dst); 10230 10231 // Skip allocas that have been initialized or clobbered. 10232 if (*Info != StaticAllocaInfo::Unknown) 10233 continue; 10234 10235 // Check if the stored value is an argument, and that this store fully 10236 // initializes the alloca. 10237 // If the argument type has padding bits we can't directly forward a pointer 10238 // as the upper bits may contain garbage. 10239 // Don't elide copies from the same argument twice. 10240 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10241 const auto *Arg = dyn_cast<Argument>(Val); 10242 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10243 Arg->getType()->isEmptyTy() || 10244 DL.getTypeStoreSize(Arg->getType()) != 10245 DL.getTypeAllocSize(AI->getAllocatedType()) || 10246 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10247 ArgCopyElisionCandidates.count(Arg)) { 10248 *Info = StaticAllocaInfo::Clobbered; 10249 continue; 10250 } 10251 10252 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10253 << '\n'); 10254 10255 // Mark this alloca and store for argument copy elision. 10256 *Info = StaticAllocaInfo::Elidable; 10257 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10258 10259 // Stop scanning if we've seen all arguments. This will happen early in -O0 10260 // builds, which is useful, because -O0 builds have large entry blocks and 10261 // many allocas. 10262 if (ArgCopyElisionCandidates.size() == NumArgs) 10263 break; 10264 } 10265 } 10266 10267 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10268 /// ArgVal is a load from a suitable fixed stack object. 10269 static void tryToElideArgumentCopy( 10270 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10271 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10272 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10273 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10274 SDValue ArgVal, bool &ArgHasUses) { 10275 // Check if this is a load from a fixed stack object. 10276 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10277 if (!LNode) 10278 return; 10279 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10280 if (!FINode) 10281 return; 10282 10283 // Check that the fixed stack object is the right size and alignment. 10284 // Look at the alignment that the user wrote on the alloca instead of looking 10285 // at the stack object. 10286 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10287 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10288 const AllocaInst *AI = ArgCopyIter->second.first; 10289 int FixedIndex = FINode->getIndex(); 10290 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10291 int OldIndex = AllocaIndex; 10292 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10293 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10294 LLVM_DEBUG( 10295 dbgs() << " argument copy elision failed due to bad fixed stack " 10296 "object size\n"); 10297 return; 10298 } 10299 Align RequiredAlignment = AI->getAlign(); 10300 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10301 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10302 "greater than stack argument alignment (" 10303 << DebugStr(RequiredAlignment) << " vs " 10304 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10305 return; 10306 } 10307 10308 // Perform the elision. Delete the old stack object and replace its only use 10309 // in the variable info map. Mark the stack object as mutable. 10310 LLVM_DEBUG({ 10311 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10312 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10313 << '\n'; 10314 }); 10315 MFI.RemoveStackObject(OldIndex); 10316 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10317 AllocaIndex = FixedIndex; 10318 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10319 Chains.push_back(ArgVal.getValue(1)); 10320 10321 // Avoid emitting code for the store implementing the copy. 10322 const StoreInst *SI = ArgCopyIter->second.second; 10323 ElidedArgCopyInstrs.insert(SI); 10324 10325 // Check for uses of the argument again so that we can avoid exporting ArgVal 10326 // if it is't used by anything other than the store. 10327 for (const Value *U : Arg.users()) { 10328 if (U != SI) { 10329 ArgHasUses = true; 10330 break; 10331 } 10332 } 10333 } 10334 10335 void SelectionDAGISel::LowerArguments(const Function &F) { 10336 SelectionDAG &DAG = SDB->DAG; 10337 SDLoc dl = SDB->getCurSDLoc(); 10338 const DataLayout &DL = DAG.getDataLayout(); 10339 SmallVector<ISD::InputArg, 16> Ins; 10340 10341 // In Naked functions we aren't going to save any registers. 10342 if (F.hasFnAttribute(Attribute::Naked)) 10343 return; 10344 10345 if (!FuncInfo->CanLowerReturn) { 10346 // Put in an sret pointer parameter before all the other parameters. 10347 SmallVector<EVT, 1> ValueVTs; 10348 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10349 F.getReturnType()->getPointerTo( 10350 DAG.getDataLayout().getAllocaAddrSpace()), 10351 ValueVTs); 10352 10353 // NOTE: Assuming that a pointer will never break down to more than one VT 10354 // or one register. 10355 ISD::ArgFlagsTy Flags; 10356 Flags.setSRet(); 10357 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10358 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10359 ISD::InputArg::NoArgIndex, 0); 10360 Ins.push_back(RetArg); 10361 } 10362 10363 // Look for stores of arguments to static allocas. Mark such arguments with a 10364 // flag to ask the target to give us the memory location of that argument if 10365 // available. 10366 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10367 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10368 ArgCopyElisionCandidates); 10369 10370 // Set up the incoming argument description vector. 10371 for (const Argument &Arg : F.args()) { 10372 unsigned ArgNo = Arg.getArgNo(); 10373 SmallVector<EVT, 4> ValueVTs; 10374 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10375 bool isArgValueUsed = !Arg.use_empty(); 10376 unsigned PartBase = 0; 10377 Type *FinalType = Arg.getType(); 10378 if (Arg.hasAttribute(Attribute::ByVal)) 10379 FinalType = Arg.getParamByValType(); 10380 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10381 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10382 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10383 Value != NumValues; ++Value) { 10384 EVT VT = ValueVTs[Value]; 10385 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10386 ISD::ArgFlagsTy Flags; 10387 10388 10389 if (Arg.getType()->isPointerTy()) { 10390 Flags.setPointer(); 10391 Flags.setPointerAddrSpace( 10392 cast<PointerType>(Arg.getType())->getAddressSpace()); 10393 } 10394 if (Arg.hasAttribute(Attribute::ZExt)) 10395 Flags.setZExt(); 10396 if (Arg.hasAttribute(Attribute::SExt)) 10397 Flags.setSExt(); 10398 if (Arg.hasAttribute(Attribute::InReg)) { 10399 // If we are using vectorcall calling convention, a structure that is 10400 // passed InReg - is surely an HVA 10401 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10402 isa<StructType>(Arg.getType())) { 10403 // The first value of a structure is marked 10404 if (0 == Value) 10405 Flags.setHvaStart(); 10406 Flags.setHva(); 10407 } 10408 // Set InReg Flag 10409 Flags.setInReg(); 10410 } 10411 if (Arg.hasAttribute(Attribute::StructRet)) 10412 Flags.setSRet(); 10413 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10414 Flags.setSwiftSelf(); 10415 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10416 Flags.setSwiftAsync(); 10417 if (Arg.hasAttribute(Attribute::SwiftError)) 10418 Flags.setSwiftError(); 10419 if (Arg.hasAttribute(Attribute::ByVal)) 10420 Flags.setByVal(); 10421 if (Arg.hasAttribute(Attribute::ByRef)) 10422 Flags.setByRef(); 10423 if (Arg.hasAttribute(Attribute::InAlloca)) { 10424 Flags.setInAlloca(); 10425 // Set the byval flag for CCAssignFn callbacks that don't know about 10426 // inalloca. This way we can know how many bytes we should've allocated 10427 // and how many bytes a callee cleanup function will pop. If we port 10428 // inalloca to more targets, we'll have to add custom inalloca handling 10429 // in the various CC lowering callbacks. 10430 Flags.setByVal(); 10431 } 10432 if (Arg.hasAttribute(Attribute::Preallocated)) { 10433 Flags.setPreallocated(); 10434 // Set the byval flag for CCAssignFn callbacks that don't know about 10435 // preallocated. This way we can know how many bytes we should've 10436 // allocated and how many bytes a callee cleanup function will pop. If 10437 // we port preallocated to more targets, we'll have to add custom 10438 // preallocated handling in the various CC lowering callbacks. 10439 Flags.setByVal(); 10440 } 10441 10442 // Certain targets (such as MIPS), may have a different ABI alignment 10443 // for a type depending on the context. Give the target a chance to 10444 // specify the alignment it wants. 10445 const Align OriginalAlignment( 10446 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10447 Flags.setOrigAlign(OriginalAlignment); 10448 10449 Align MemAlign; 10450 Type *ArgMemTy = nullptr; 10451 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10452 Flags.isByRef()) { 10453 if (!ArgMemTy) 10454 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10455 10456 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10457 10458 // For in-memory arguments, size and alignment should be passed from FE. 10459 // BE will guess if this info is not there but there are cases it cannot 10460 // get right. 10461 if (auto ParamAlign = Arg.getParamStackAlign()) 10462 MemAlign = *ParamAlign; 10463 else if ((ParamAlign = Arg.getParamAlign())) 10464 MemAlign = *ParamAlign; 10465 else 10466 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10467 if (Flags.isByRef()) 10468 Flags.setByRefSize(MemSize); 10469 else 10470 Flags.setByValSize(MemSize); 10471 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10472 MemAlign = *ParamAlign; 10473 } else { 10474 MemAlign = OriginalAlignment; 10475 } 10476 Flags.setMemAlign(MemAlign); 10477 10478 if (Arg.hasAttribute(Attribute::Nest)) 10479 Flags.setNest(); 10480 if (NeedsRegBlock) 10481 Flags.setInConsecutiveRegs(); 10482 if (ArgCopyElisionCandidates.count(&Arg)) 10483 Flags.setCopyElisionCandidate(); 10484 if (Arg.hasAttribute(Attribute::Returned)) 10485 Flags.setReturned(); 10486 10487 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10488 *CurDAG->getContext(), F.getCallingConv(), VT); 10489 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10490 *CurDAG->getContext(), F.getCallingConv(), VT); 10491 for (unsigned i = 0; i != NumRegs; ++i) { 10492 // For scalable vectors, use the minimum size; individual targets 10493 // are responsible for handling scalable vector arguments and 10494 // return values. 10495 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10496 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10497 if (NumRegs > 1 && i == 0) 10498 MyFlags.Flags.setSplit(); 10499 // if it isn't first piece, alignment must be 1 10500 else if (i > 0) { 10501 MyFlags.Flags.setOrigAlign(Align(1)); 10502 if (i == NumRegs - 1) 10503 MyFlags.Flags.setSplitEnd(); 10504 } 10505 Ins.push_back(MyFlags); 10506 } 10507 if (NeedsRegBlock && Value == NumValues - 1) 10508 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10509 PartBase += VT.getStoreSize().getKnownMinSize(); 10510 } 10511 } 10512 10513 // Call the target to set up the argument values. 10514 SmallVector<SDValue, 8> InVals; 10515 SDValue NewRoot = TLI->LowerFormalArguments( 10516 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10517 10518 // Verify that the target's LowerFormalArguments behaved as expected. 10519 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10520 "LowerFormalArguments didn't return a valid chain!"); 10521 assert(InVals.size() == Ins.size() && 10522 "LowerFormalArguments didn't emit the correct number of values!"); 10523 LLVM_DEBUG({ 10524 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10525 assert(InVals[i].getNode() && 10526 "LowerFormalArguments emitted a null value!"); 10527 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10528 "LowerFormalArguments emitted a value with the wrong type!"); 10529 } 10530 }); 10531 10532 // Update the DAG with the new chain value resulting from argument lowering. 10533 DAG.setRoot(NewRoot); 10534 10535 // Set up the argument values. 10536 unsigned i = 0; 10537 if (!FuncInfo->CanLowerReturn) { 10538 // Create a virtual register for the sret pointer, and put in a copy 10539 // from the sret argument into it. 10540 SmallVector<EVT, 1> ValueVTs; 10541 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10542 F.getReturnType()->getPointerTo( 10543 DAG.getDataLayout().getAllocaAddrSpace()), 10544 ValueVTs); 10545 MVT VT = ValueVTs[0].getSimpleVT(); 10546 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10547 Optional<ISD::NodeType> AssertOp; 10548 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10549 nullptr, F.getCallingConv(), AssertOp); 10550 10551 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10552 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10553 Register SRetReg = 10554 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10555 FuncInfo->DemoteRegister = SRetReg; 10556 NewRoot = 10557 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10558 DAG.setRoot(NewRoot); 10559 10560 // i indexes lowered arguments. Bump it past the hidden sret argument. 10561 ++i; 10562 } 10563 10564 SmallVector<SDValue, 4> Chains; 10565 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10566 for (const Argument &Arg : F.args()) { 10567 SmallVector<SDValue, 4> ArgValues; 10568 SmallVector<EVT, 4> ValueVTs; 10569 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10570 unsigned NumValues = ValueVTs.size(); 10571 if (NumValues == 0) 10572 continue; 10573 10574 bool ArgHasUses = !Arg.use_empty(); 10575 10576 // Elide the copying store if the target loaded this argument from a 10577 // suitable fixed stack object. 10578 if (Ins[i].Flags.isCopyElisionCandidate()) { 10579 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10580 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10581 InVals[i], ArgHasUses); 10582 } 10583 10584 // If this argument is unused then remember its value. It is used to generate 10585 // debugging information. 10586 bool isSwiftErrorArg = 10587 TLI->supportSwiftError() && 10588 Arg.hasAttribute(Attribute::SwiftError); 10589 if (!ArgHasUses && !isSwiftErrorArg) { 10590 SDB->setUnusedArgValue(&Arg, InVals[i]); 10591 10592 // Also remember any frame index for use in FastISel. 10593 if (FrameIndexSDNode *FI = 10594 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10595 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10596 } 10597 10598 for (unsigned Val = 0; Val != NumValues; ++Val) { 10599 EVT VT = ValueVTs[Val]; 10600 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10601 F.getCallingConv(), VT); 10602 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10603 *CurDAG->getContext(), F.getCallingConv(), VT); 10604 10605 // Even an apparent 'unused' swifterror argument needs to be returned. So 10606 // we do generate a copy for it that can be used on return from the 10607 // function. 10608 if (ArgHasUses || isSwiftErrorArg) { 10609 Optional<ISD::NodeType> AssertOp; 10610 if (Arg.hasAttribute(Attribute::SExt)) 10611 AssertOp = ISD::AssertSext; 10612 else if (Arg.hasAttribute(Attribute::ZExt)) 10613 AssertOp = ISD::AssertZext; 10614 10615 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10616 PartVT, VT, nullptr, 10617 F.getCallingConv(), AssertOp)); 10618 } 10619 10620 i += NumParts; 10621 } 10622 10623 // We don't need to do anything else for unused arguments. 10624 if (ArgValues.empty()) 10625 continue; 10626 10627 // Note down frame index. 10628 if (FrameIndexSDNode *FI = 10629 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10630 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10631 10632 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10633 SDB->getCurSDLoc()); 10634 10635 SDB->setValue(&Arg, Res); 10636 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10637 // We want to associate the argument with the frame index, among 10638 // involved operands, that correspond to the lowest address. The 10639 // getCopyFromParts function, called earlier, is swapping the order of 10640 // the operands to BUILD_PAIR depending on endianness. The result of 10641 // that swapping is that the least significant bits of the argument will 10642 // be in the first operand of the BUILD_PAIR node, and the most 10643 // significant bits will be in the second operand. 10644 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10645 if (LoadSDNode *LNode = 10646 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10647 if (FrameIndexSDNode *FI = 10648 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10649 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10650 } 10651 10652 // Analyses past this point are naive and don't expect an assertion. 10653 if (Res.getOpcode() == ISD::AssertZext) 10654 Res = Res.getOperand(0); 10655 10656 // Update the SwiftErrorVRegDefMap. 10657 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10658 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10659 if (Register::isVirtualRegister(Reg)) 10660 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10661 Reg); 10662 } 10663 10664 // If this argument is live outside of the entry block, insert a copy from 10665 // wherever we got it to the vreg that other BB's will reference it as. 10666 if (Res.getOpcode() == ISD::CopyFromReg) { 10667 // If we can, though, try to skip creating an unnecessary vreg. 10668 // FIXME: This isn't very clean... it would be nice to make this more 10669 // general. 10670 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10671 if (Register::isVirtualRegister(Reg)) { 10672 FuncInfo->ValueMap[&Arg] = Reg; 10673 continue; 10674 } 10675 } 10676 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10677 FuncInfo->InitializeRegForValue(&Arg); 10678 SDB->CopyToExportRegsIfNeeded(&Arg); 10679 } 10680 } 10681 10682 if (!Chains.empty()) { 10683 Chains.push_back(NewRoot); 10684 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10685 } 10686 10687 DAG.setRoot(NewRoot); 10688 10689 assert(i == InVals.size() && "Argument register count mismatch!"); 10690 10691 // If any argument copy elisions occurred and we have debug info, update the 10692 // stale frame indices used in the dbg.declare variable info table. 10693 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10694 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10695 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10696 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10697 if (I != ArgCopyElisionFrameIndexMap.end()) 10698 VI.Slot = I->second; 10699 } 10700 } 10701 10702 // Finally, if the target has anything special to do, allow it to do so. 10703 emitFunctionEntryCode(); 10704 } 10705 10706 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10707 /// ensure constants are generated when needed. Remember the virtual registers 10708 /// that need to be added to the Machine PHI nodes as input. We cannot just 10709 /// directly add them, because expansion might result in multiple MBB's for one 10710 /// BB. As such, the start of the BB might correspond to a different MBB than 10711 /// the end. 10712 void 10713 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10714 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10715 const Instruction *TI = LLVMBB->getTerminator(); 10716 10717 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10718 10719 // Check PHI nodes in successors that expect a value to be available from this 10720 // block. 10721 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10722 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10723 if (!isa<PHINode>(SuccBB->begin())) continue; 10724 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10725 10726 // If this terminator has multiple identical successors (common for 10727 // switches), only handle each succ once. 10728 if (!SuccsHandled.insert(SuccMBB).second) 10729 continue; 10730 10731 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10732 10733 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10734 // nodes and Machine PHI nodes, but the incoming operands have not been 10735 // emitted yet. 10736 for (const PHINode &PN : SuccBB->phis()) { 10737 // Ignore dead phi's. 10738 if (PN.use_empty()) 10739 continue; 10740 10741 // Skip empty types 10742 if (PN.getType()->isEmptyTy()) 10743 continue; 10744 10745 unsigned Reg; 10746 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10747 10748 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10749 unsigned &RegOut = ConstantsOut[C]; 10750 if (RegOut == 0) { 10751 RegOut = FuncInfo.CreateRegs(C); 10752 // We need to zero/sign extend ConstantInt phi operands to match 10753 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 10754 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 10755 if (auto *CI = dyn_cast<ConstantInt>(C)) 10756 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 10757 : ISD::ZERO_EXTEND; 10758 CopyValueToVirtualRegister(C, RegOut, ExtendType); 10759 } 10760 Reg = RegOut; 10761 } else { 10762 DenseMap<const Value *, Register>::iterator I = 10763 FuncInfo.ValueMap.find(PHIOp); 10764 if (I != FuncInfo.ValueMap.end()) 10765 Reg = I->second; 10766 else { 10767 assert(isa<AllocaInst>(PHIOp) && 10768 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10769 "Didn't codegen value into a register!??"); 10770 Reg = FuncInfo.CreateRegs(PHIOp); 10771 CopyValueToVirtualRegister(PHIOp, Reg); 10772 } 10773 } 10774 10775 // Remember that this register needs to added to the machine PHI node as 10776 // the input for this MBB. 10777 SmallVector<EVT, 4> ValueVTs; 10778 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10779 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10780 EVT VT = ValueVTs[vti]; 10781 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10782 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10783 FuncInfo.PHINodesToUpdate.push_back( 10784 std::make_pair(&*MBBI++, Reg + i)); 10785 Reg += NumRegisters; 10786 } 10787 } 10788 } 10789 10790 ConstantsOut.clear(); 10791 } 10792 10793 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10794 MachineFunction::iterator I(MBB); 10795 if (++I == FuncInfo.MF->end()) 10796 return nullptr; 10797 return &*I; 10798 } 10799 10800 /// During lowering new call nodes can be created (such as memset, etc.). 10801 /// Those will become new roots of the current DAG, but complications arise 10802 /// when they are tail calls. In such cases, the call lowering will update 10803 /// the root, but the builder still needs to know that a tail call has been 10804 /// lowered in order to avoid generating an additional return. 10805 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10806 // If the node is null, we do have a tail call. 10807 if (MaybeTC.getNode() != nullptr) 10808 DAG.setRoot(MaybeTC); 10809 else 10810 HasTailCall = true; 10811 } 10812 10813 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10814 MachineBasicBlock *SwitchMBB, 10815 MachineBasicBlock *DefaultMBB) { 10816 MachineFunction *CurMF = FuncInfo.MF; 10817 MachineBasicBlock *NextMBB = nullptr; 10818 MachineFunction::iterator BBI(W.MBB); 10819 if (++BBI != FuncInfo.MF->end()) 10820 NextMBB = &*BBI; 10821 10822 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10823 10824 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10825 10826 if (Size == 2 && W.MBB == SwitchMBB) { 10827 // If any two of the cases has the same destination, and if one value 10828 // is the same as the other, but has one bit unset that the other has set, 10829 // use bit manipulation to do two compares at once. For example: 10830 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10831 // TODO: This could be extended to merge any 2 cases in switches with 3 10832 // cases. 10833 // TODO: Handle cases where W.CaseBB != SwitchBB. 10834 CaseCluster &Small = *W.FirstCluster; 10835 CaseCluster &Big = *W.LastCluster; 10836 10837 if (Small.Low == Small.High && Big.Low == Big.High && 10838 Small.MBB == Big.MBB) { 10839 const APInt &SmallValue = Small.Low->getValue(); 10840 const APInt &BigValue = Big.Low->getValue(); 10841 10842 // Check that there is only one bit different. 10843 APInt CommonBit = BigValue ^ SmallValue; 10844 if (CommonBit.isPowerOf2()) { 10845 SDValue CondLHS = getValue(Cond); 10846 EVT VT = CondLHS.getValueType(); 10847 SDLoc DL = getCurSDLoc(); 10848 10849 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10850 DAG.getConstant(CommonBit, DL, VT)); 10851 SDValue Cond = DAG.getSetCC( 10852 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10853 ISD::SETEQ); 10854 10855 // Update successor info. 10856 // Both Small and Big will jump to Small.BB, so we sum up the 10857 // probabilities. 10858 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10859 if (BPI) 10860 addSuccessorWithProb( 10861 SwitchMBB, DefaultMBB, 10862 // The default destination is the first successor in IR. 10863 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10864 else 10865 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10866 10867 // Insert the true branch. 10868 SDValue BrCond = 10869 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10870 DAG.getBasicBlock(Small.MBB)); 10871 // Insert the false branch. 10872 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10873 DAG.getBasicBlock(DefaultMBB)); 10874 10875 DAG.setRoot(BrCond); 10876 return; 10877 } 10878 } 10879 } 10880 10881 if (TM.getOptLevel() != CodeGenOpt::None) { 10882 // Here, we order cases by probability so the most likely case will be 10883 // checked first. However, two clusters can have the same probability in 10884 // which case their relative ordering is non-deterministic. So we use Low 10885 // as a tie-breaker as clusters are guaranteed to never overlap. 10886 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10887 [](const CaseCluster &a, const CaseCluster &b) { 10888 return a.Prob != b.Prob ? 10889 a.Prob > b.Prob : 10890 a.Low->getValue().slt(b.Low->getValue()); 10891 }); 10892 10893 // Rearrange the case blocks so that the last one falls through if possible 10894 // without changing the order of probabilities. 10895 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10896 --I; 10897 if (I->Prob > W.LastCluster->Prob) 10898 break; 10899 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10900 std::swap(*I, *W.LastCluster); 10901 break; 10902 } 10903 } 10904 } 10905 10906 // Compute total probability. 10907 BranchProbability DefaultProb = W.DefaultProb; 10908 BranchProbability UnhandledProbs = DefaultProb; 10909 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10910 UnhandledProbs += I->Prob; 10911 10912 MachineBasicBlock *CurMBB = W.MBB; 10913 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10914 bool FallthroughUnreachable = false; 10915 MachineBasicBlock *Fallthrough; 10916 if (I == W.LastCluster) { 10917 // For the last cluster, fall through to the default destination. 10918 Fallthrough = DefaultMBB; 10919 FallthroughUnreachable = isa<UnreachableInst>( 10920 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10921 } else { 10922 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10923 CurMF->insert(BBI, Fallthrough); 10924 // Put Cond in a virtual register to make it available from the new blocks. 10925 ExportFromCurrentBlock(Cond); 10926 } 10927 UnhandledProbs -= I->Prob; 10928 10929 switch (I->Kind) { 10930 case CC_JumpTable: { 10931 // FIXME: Optimize away range check based on pivot comparisons. 10932 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10933 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10934 10935 // The jump block hasn't been inserted yet; insert it here. 10936 MachineBasicBlock *JumpMBB = JT->MBB; 10937 CurMF->insert(BBI, JumpMBB); 10938 10939 auto JumpProb = I->Prob; 10940 auto FallthroughProb = UnhandledProbs; 10941 10942 // If the default statement is a target of the jump table, we evenly 10943 // distribute the default probability to successors of CurMBB. Also 10944 // update the probability on the edge from JumpMBB to Fallthrough. 10945 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10946 SE = JumpMBB->succ_end(); 10947 SI != SE; ++SI) { 10948 if (*SI == DefaultMBB) { 10949 JumpProb += DefaultProb / 2; 10950 FallthroughProb -= DefaultProb / 2; 10951 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10952 JumpMBB->normalizeSuccProbs(); 10953 break; 10954 } 10955 } 10956 10957 if (FallthroughUnreachable) 10958 JTH->FallthroughUnreachable = true; 10959 10960 if (!JTH->FallthroughUnreachable) 10961 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10962 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10963 CurMBB->normalizeSuccProbs(); 10964 10965 // The jump table header will be inserted in our current block, do the 10966 // range check, and fall through to our fallthrough block. 10967 JTH->HeaderBB = CurMBB; 10968 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10969 10970 // If we're in the right place, emit the jump table header right now. 10971 if (CurMBB == SwitchMBB) { 10972 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10973 JTH->Emitted = true; 10974 } 10975 break; 10976 } 10977 case CC_BitTests: { 10978 // FIXME: Optimize away range check based on pivot comparisons. 10979 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10980 10981 // The bit test blocks haven't been inserted yet; insert them here. 10982 for (BitTestCase &BTC : BTB->Cases) 10983 CurMF->insert(BBI, BTC.ThisBB); 10984 10985 // Fill in fields of the BitTestBlock. 10986 BTB->Parent = CurMBB; 10987 BTB->Default = Fallthrough; 10988 10989 BTB->DefaultProb = UnhandledProbs; 10990 // If the cases in bit test don't form a contiguous range, we evenly 10991 // distribute the probability on the edge to Fallthrough to two 10992 // successors of CurMBB. 10993 if (!BTB->ContiguousRange) { 10994 BTB->Prob += DefaultProb / 2; 10995 BTB->DefaultProb -= DefaultProb / 2; 10996 } 10997 10998 if (FallthroughUnreachable) 10999 BTB->FallthroughUnreachable = true; 11000 11001 // If we're in the right place, emit the bit test header right now. 11002 if (CurMBB == SwitchMBB) { 11003 visitBitTestHeader(*BTB, SwitchMBB); 11004 BTB->Emitted = true; 11005 } 11006 break; 11007 } 11008 case CC_Range: { 11009 const Value *RHS, *LHS, *MHS; 11010 ISD::CondCode CC; 11011 if (I->Low == I->High) { 11012 // Check Cond == I->Low. 11013 CC = ISD::SETEQ; 11014 LHS = Cond; 11015 RHS=I->Low; 11016 MHS = nullptr; 11017 } else { 11018 // Check I->Low <= Cond <= I->High. 11019 CC = ISD::SETLE; 11020 LHS = I->Low; 11021 MHS = Cond; 11022 RHS = I->High; 11023 } 11024 11025 // If Fallthrough is unreachable, fold away the comparison. 11026 if (FallthroughUnreachable) 11027 CC = ISD::SETTRUE; 11028 11029 // The false probability is the sum of all unhandled cases. 11030 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11031 getCurSDLoc(), I->Prob, UnhandledProbs); 11032 11033 if (CurMBB == SwitchMBB) 11034 visitSwitchCase(CB, SwitchMBB); 11035 else 11036 SL->SwitchCases.push_back(CB); 11037 11038 break; 11039 } 11040 } 11041 CurMBB = Fallthrough; 11042 } 11043 } 11044 11045 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11046 CaseClusterIt First, 11047 CaseClusterIt Last) { 11048 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11049 if (X.Prob != CC.Prob) 11050 return X.Prob > CC.Prob; 11051 11052 // Ties are broken by comparing the case value. 11053 return X.Low->getValue().slt(CC.Low->getValue()); 11054 }); 11055 } 11056 11057 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11058 const SwitchWorkListItem &W, 11059 Value *Cond, 11060 MachineBasicBlock *SwitchMBB) { 11061 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11062 "Clusters not sorted?"); 11063 11064 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11065 11066 // Balance the tree based on branch probabilities to create a near-optimal (in 11067 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11068 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11069 CaseClusterIt LastLeft = W.FirstCluster; 11070 CaseClusterIt FirstRight = W.LastCluster; 11071 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11072 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11073 11074 // Move LastLeft and FirstRight towards each other from opposite directions to 11075 // find a partitioning of the clusters which balances the probability on both 11076 // sides. If LeftProb and RightProb are equal, alternate which side is 11077 // taken to ensure 0-probability nodes are distributed evenly. 11078 unsigned I = 0; 11079 while (LastLeft + 1 < FirstRight) { 11080 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11081 LeftProb += (++LastLeft)->Prob; 11082 else 11083 RightProb += (--FirstRight)->Prob; 11084 I++; 11085 } 11086 11087 while (true) { 11088 // Our binary search tree differs from a typical BST in that ours can have up 11089 // to three values in each leaf. The pivot selection above doesn't take that 11090 // into account, which means the tree might require more nodes and be less 11091 // efficient. We compensate for this here. 11092 11093 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11094 unsigned NumRight = W.LastCluster - FirstRight + 1; 11095 11096 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11097 // If one side has less than 3 clusters, and the other has more than 3, 11098 // consider taking a cluster from the other side. 11099 11100 if (NumLeft < NumRight) { 11101 // Consider moving the first cluster on the right to the left side. 11102 CaseCluster &CC = *FirstRight; 11103 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11104 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11105 if (LeftSideRank <= RightSideRank) { 11106 // Moving the cluster to the left does not demote it. 11107 ++LastLeft; 11108 ++FirstRight; 11109 continue; 11110 } 11111 } else { 11112 assert(NumRight < NumLeft); 11113 // Consider moving the last element on the left to the right side. 11114 CaseCluster &CC = *LastLeft; 11115 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11116 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11117 if (RightSideRank <= LeftSideRank) { 11118 // Moving the cluster to the right does not demot it. 11119 --LastLeft; 11120 --FirstRight; 11121 continue; 11122 } 11123 } 11124 } 11125 break; 11126 } 11127 11128 assert(LastLeft + 1 == FirstRight); 11129 assert(LastLeft >= W.FirstCluster); 11130 assert(FirstRight <= W.LastCluster); 11131 11132 // Use the first element on the right as pivot since we will make less-than 11133 // comparisons against it. 11134 CaseClusterIt PivotCluster = FirstRight; 11135 assert(PivotCluster > W.FirstCluster); 11136 assert(PivotCluster <= W.LastCluster); 11137 11138 CaseClusterIt FirstLeft = W.FirstCluster; 11139 CaseClusterIt LastRight = W.LastCluster; 11140 11141 const ConstantInt *Pivot = PivotCluster->Low; 11142 11143 // New blocks will be inserted immediately after the current one. 11144 MachineFunction::iterator BBI(W.MBB); 11145 ++BBI; 11146 11147 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11148 // we can branch to its destination directly if it's squeezed exactly in 11149 // between the known lower bound and Pivot - 1. 11150 MachineBasicBlock *LeftMBB; 11151 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11152 FirstLeft->Low == W.GE && 11153 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11154 LeftMBB = FirstLeft->MBB; 11155 } else { 11156 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11157 FuncInfo.MF->insert(BBI, LeftMBB); 11158 WorkList.push_back( 11159 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11160 // Put Cond in a virtual register to make it available from the new blocks. 11161 ExportFromCurrentBlock(Cond); 11162 } 11163 11164 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11165 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11166 // directly if RHS.High equals the current upper bound. 11167 MachineBasicBlock *RightMBB; 11168 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11169 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11170 RightMBB = FirstRight->MBB; 11171 } else { 11172 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11173 FuncInfo.MF->insert(BBI, RightMBB); 11174 WorkList.push_back( 11175 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11176 // Put Cond in a virtual register to make it available from the new blocks. 11177 ExportFromCurrentBlock(Cond); 11178 } 11179 11180 // Create the CaseBlock record that will be used to lower the branch. 11181 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11182 getCurSDLoc(), LeftProb, RightProb); 11183 11184 if (W.MBB == SwitchMBB) 11185 visitSwitchCase(CB, SwitchMBB); 11186 else 11187 SL->SwitchCases.push_back(CB); 11188 } 11189 11190 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11191 // from the swith statement. 11192 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11193 BranchProbability PeeledCaseProb) { 11194 if (PeeledCaseProb == BranchProbability::getOne()) 11195 return BranchProbability::getZero(); 11196 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11197 11198 uint32_t Numerator = CaseProb.getNumerator(); 11199 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11200 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11201 } 11202 11203 // Try to peel the top probability case if it exceeds the threshold. 11204 // Return current MachineBasicBlock for the switch statement if the peeling 11205 // does not occur. 11206 // If the peeling is performed, return the newly created MachineBasicBlock 11207 // for the peeled switch statement. Also update Clusters to remove the peeled 11208 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11209 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11210 const SwitchInst &SI, CaseClusterVector &Clusters, 11211 BranchProbability &PeeledCaseProb) { 11212 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11213 // Don't perform if there is only one cluster or optimizing for size. 11214 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11215 TM.getOptLevel() == CodeGenOpt::None || 11216 SwitchMBB->getParent()->getFunction().hasMinSize()) 11217 return SwitchMBB; 11218 11219 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11220 unsigned PeeledCaseIndex = 0; 11221 bool SwitchPeeled = false; 11222 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11223 CaseCluster &CC = Clusters[Index]; 11224 if (CC.Prob < TopCaseProb) 11225 continue; 11226 TopCaseProb = CC.Prob; 11227 PeeledCaseIndex = Index; 11228 SwitchPeeled = true; 11229 } 11230 if (!SwitchPeeled) 11231 return SwitchMBB; 11232 11233 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11234 << TopCaseProb << "\n"); 11235 11236 // Record the MBB for the peeled switch statement. 11237 MachineFunction::iterator BBI(SwitchMBB); 11238 ++BBI; 11239 MachineBasicBlock *PeeledSwitchMBB = 11240 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11241 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11242 11243 ExportFromCurrentBlock(SI.getCondition()); 11244 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11245 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11246 nullptr, nullptr, TopCaseProb.getCompl()}; 11247 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11248 11249 Clusters.erase(PeeledCaseIt); 11250 for (CaseCluster &CC : Clusters) { 11251 LLVM_DEBUG( 11252 dbgs() << "Scale the probablity for one cluster, before scaling: " 11253 << CC.Prob << "\n"); 11254 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11255 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11256 } 11257 PeeledCaseProb = TopCaseProb; 11258 return PeeledSwitchMBB; 11259 } 11260 11261 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11262 // Extract cases from the switch. 11263 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11264 CaseClusterVector Clusters; 11265 Clusters.reserve(SI.getNumCases()); 11266 for (auto I : SI.cases()) { 11267 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11268 const ConstantInt *CaseVal = I.getCaseValue(); 11269 BranchProbability Prob = 11270 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11271 : BranchProbability(1, SI.getNumCases() + 1); 11272 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11273 } 11274 11275 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11276 11277 // Cluster adjacent cases with the same destination. We do this at all 11278 // optimization levels because it's cheap to do and will make codegen faster 11279 // if there are many clusters. 11280 sortAndRangeify(Clusters); 11281 11282 // The branch probablity of the peeled case. 11283 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11284 MachineBasicBlock *PeeledSwitchMBB = 11285 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11286 11287 // If there is only the default destination, jump there directly. 11288 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11289 if (Clusters.empty()) { 11290 assert(PeeledSwitchMBB == SwitchMBB); 11291 SwitchMBB->addSuccessor(DefaultMBB); 11292 if (DefaultMBB != NextBlock(SwitchMBB)) { 11293 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11294 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11295 } 11296 return; 11297 } 11298 11299 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11300 SL->findBitTestClusters(Clusters, &SI); 11301 11302 LLVM_DEBUG({ 11303 dbgs() << "Case clusters: "; 11304 for (const CaseCluster &C : Clusters) { 11305 if (C.Kind == CC_JumpTable) 11306 dbgs() << "JT:"; 11307 if (C.Kind == CC_BitTests) 11308 dbgs() << "BT:"; 11309 11310 C.Low->getValue().print(dbgs(), true); 11311 if (C.Low != C.High) { 11312 dbgs() << '-'; 11313 C.High->getValue().print(dbgs(), true); 11314 } 11315 dbgs() << ' '; 11316 } 11317 dbgs() << '\n'; 11318 }); 11319 11320 assert(!Clusters.empty()); 11321 SwitchWorkList WorkList; 11322 CaseClusterIt First = Clusters.begin(); 11323 CaseClusterIt Last = Clusters.end() - 1; 11324 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11325 // Scale the branchprobability for DefaultMBB if the peel occurs and 11326 // DefaultMBB is not replaced. 11327 if (PeeledCaseProb != BranchProbability::getZero() && 11328 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11329 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11330 WorkList.push_back( 11331 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11332 11333 while (!WorkList.empty()) { 11334 SwitchWorkListItem W = WorkList.pop_back_val(); 11335 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11336 11337 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11338 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11339 // For optimized builds, lower large range as a balanced binary tree. 11340 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11341 continue; 11342 } 11343 11344 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11345 } 11346 } 11347 11348 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11349 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11350 auto DL = getCurSDLoc(); 11351 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11352 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11353 } 11354 11355 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11356 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11357 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11358 11359 SDLoc DL = getCurSDLoc(); 11360 SDValue V = getValue(I.getOperand(0)); 11361 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11362 11363 if (VT.isScalableVector()) { 11364 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11365 return; 11366 } 11367 11368 // Use VECTOR_SHUFFLE for the fixed-length vector 11369 // to maintain existing behavior. 11370 SmallVector<int, 8> Mask; 11371 unsigned NumElts = VT.getVectorMinNumElements(); 11372 for (unsigned i = 0; i != NumElts; ++i) 11373 Mask.push_back(NumElts - 1 - i); 11374 11375 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11376 } 11377 11378 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11379 SmallVector<EVT, 4> ValueVTs; 11380 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11381 ValueVTs); 11382 unsigned NumValues = ValueVTs.size(); 11383 if (NumValues == 0) return; 11384 11385 SmallVector<SDValue, 4> Values(NumValues); 11386 SDValue Op = getValue(I.getOperand(0)); 11387 11388 for (unsigned i = 0; i != NumValues; ++i) 11389 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11390 SDValue(Op.getNode(), Op.getResNo() + i)); 11391 11392 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11393 DAG.getVTList(ValueVTs), Values)); 11394 } 11395 11396 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11397 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11398 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11399 11400 SDLoc DL = getCurSDLoc(); 11401 SDValue V1 = getValue(I.getOperand(0)); 11402 SDValue V2 = getValue(I.getOperand(1)); 11403 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11404 11405 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11406 if (VT.isScalableVector()) { 11407 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11408 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11409 DAG.getConstant(Imm, DL, IdxVT))); 11410 return; 11411 } 11412 11413 unsigned NumElts = VT.getVectorNumElements(); 11414 11415 uint64_t Idx = (NumElts + Imm) % NumElts; 11416 11417 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11418 SmallVector<int, 8> Mask; 11419 for (unsigned i = 0; i < NumElts; ++i) 11420 Mask.push_back(Idx + i); 11421 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11422 } 11423