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 unsigned ValueSize = ValueSVT.getSizeInBits(); 452 if (ValueSize == PartEVT.getSizeInBits()) { 453 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 454 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 455 // It's possible a scalar floating point type gets softened to integer and 456 // then promoted to a larger integer. If PartEVT is the larger integer 457 // we need to truncate it and then bitcast to the FP type. 458 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 459 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 460 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 461 Val = DAG.getBitcast(ValueSVT, Val); 462 } else { 463 Val = ValueVT.isFloatingPoint() 464 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 465 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 466 } 467 } 468 469 return DAG.getBuildVector(ValueVT, DL, Val); 470 } 471 472 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 473 SDValue Val, SDValue *Parts, unsigned NumParts, 474 MVT PartVT, const Value *V, 475 Optional<CallingConv::ID> CallConv); 476 477 /// getCopyToParts - Create a series of nodes that contain the specified value 478 /// split into legal parts. If the parts contain more bits than Val, then, for 479 /// integers, ExtendKind can be used to specify how to generate the extra bits. 480 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 481 SDValue *Parts, unsigned NumParts, MVT PartVT, 482 const Value *V, 483 Optional<CallingConv::ID> CallConv = None, 484 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 485 // Let the target split the parts if it wants to 486 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 487 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 488 CallConv)) 489 return; 490 EVT ValueVT = Val.getValueType(); 491 492 // Handle the vector case separately. 493 if (ValueVT.isVector()) 494 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 495 CallConv); 496 497 unsigned PartBits = PartVT.getSizeInBits(); 498 unsigned OrigNumParts = NumParts; 499 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 500 "Copying to an illegal type!"); 501 502 if (NumParts == 0) 503 return; 504 505 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 506 EVT PartEVT = PartVT; 507 if (PartEVT == ValueVT) { 508 assert(NumParts == 1 && "No-op copy with multiple parts!"); 509 Parts[0] = Val; 510 return; 511 } 512 513 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 514 // If the parts cover more bits than the value has, promote the value. 515 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 516 assert(NumParts == 1 && "Do not know what to promote to!"); 517 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 518 } else { 519 if (ValueVT.isFloatingPoint()) { 520 // FP values need to be bitcast, then extended if they are being put 521 // into a larger container. 522 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 523 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 524 } 525 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 526 ValueVT.isInteger() && 527 "Unknown mismatch!"); 528 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 529 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 530 if (PartVT == MVT::x86mmx) 531 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 532 } 533 } else if (PartBits == ValueVT.getSizeInBits()) { 534 // Different types of the same size. 535 assert(NumParts == 1 && PartEVT != ValueVT); 536 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 537 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 538 // If the parts cover less bits than value has, truncate the value. 539 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 540 ValueVT.isInteger() && 541 "Unknown mismatch!"); 542 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 543 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 544 if (PartVT == MVT::x86mmx) 545 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 546 } 547 548 // The value may have changed - recompute ValueVT. 549 ValueVT = Val.getValueType(); 550 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 551 "Failed to tile the value with PartVT!"); 552 553 if (NumParts == 1) { 554 if (PartEVT != ValueVT) { 555 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 556 "scalar-to-vector conversion failed"); 557 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 558 } 559 560 Parts[0] = Val; 561 return; 562 } 563 564 // Expand the value into multiple parts. 565 if (NumParts & (NumParts - 1)) { 566 // The number of parts is not a power of 2. Split off and copy the tail. 567 assert(PartVT.isInteger() && ValueVT.isInteger() && 568 "Do not know what to expand to!"); 569 unsigned RoundParts = 1 << Log2_32(NumParts); 570 unsigned RoundBits = RoundParts * PartBits; 571 unsigned OddParts = NumParts - RoundParts; 572 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 573 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 574 575 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 576 CallConv); 577 578 if (DAG.getDataLayout().isBigEndian()) 579 // The odd parts were reversed by getCopyToParts - unreverse them. 580 std::reverse(Parts + RoundParts, Parts + NumParts); 581 582 NumParts = RoundParts; 583 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 584 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 585 } 586 587 // The number of parts is a power of 2. Repeatedly bisect the value using 588 // EXTRACT_ELEMENT. 589 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 590 EVT::getIntegerVT(*DAG.getContext(), 591 ValueVT.getSizeInBits()), 592 Val); 593 594 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 595 for (unsigned i = 0; i < NumParts; i += StepSize) { 596 unsigned ThisBits = StepSize * PartBits / 2; 597 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 598 SDValue &Part0 = Parts[i]; 599 SDValue &Part1 = Parts[i+StepSize/2]; 600 601 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 602 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 603 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 604 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 605 606 if (ThisBits == PartBits && ThisVT != PartVT) { 607 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 608 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 609 } 610 } 611 } 612 613 if (DAG.getDataLayout().isBigEndian()) 614 std::reverse(Parts, Parts + OrigNumParts); 615 } 616 617 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 618 const SDLoc &DL, EVT PartVT) { 619 if (!PartVT.isVector()) 620 return SDValue(); 621 622 EVT ValueVT = Val.getValueType(); 623 ElementCount PartNumElts = PartVT.getVectorElementCount(); 624 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 625 626 // We only support widening vectors with equivalent element types and 627 // fixed/scalable properties. If a target needs to widen a fixed-length type 628 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 629 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 630 PartNumElts.isScalable() != ValueNumElts.isScalable() || 631 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 632 return SDValue(); 633 634 // Widening a scalable vector to another scalable vector is done by inserting 635 // the vector into a larger undef one. 636 if (PartNumElts.isScalable()) 637 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 638 Val, DAG.getVectorIdxConstant(0, DL)); 639 640 EVT ElementVT = PartVT.getVectorElementType(); 641 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 642 // undef elements. 643 SmallVector<SDValue, 16> Ops; 644 DAG.ExtractVectorElements(Val, Ops); 645 SDValue EltUndef = DAG.getUNDEF(ElementVT); 646 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 647 648 // FIXME: Use CONCAT for 2x -> 4x. 649 return DAG.getBuildVector(PartVT, DL, Ops); 650 } 651 652 /// getCopyToPartsVector - Create a series of nodes that contain the specified 653 /// value split into legal parts. 654 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 655 SDValue Val, SDValue *Parts, unsigned NumParts, 656 MVT PartVT, const Value *V, 657 Optional<CallingConv::ID> CallConv) { 658 EVT ValueVT = Val.getValueType(); 659 assert(ValueVT.isVector() && "Not a vector"); 660 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 661 const bool IsABIRegCopy = CallConv.has_value(); 662 663 if (NumParts == 1) { 664 EVT PartEVT = PartVT; 665 if (PartEVT == ValueVT) { 666 // Nothing to do. 667 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 668 // Bitconvert vector->vector case. 669 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 670 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 671 Val = Widened; 672 } else if (PartVT.isVector() && 673 PartEVT.getVectorElementType().bitsGE( 674 ValueVT.getVectorElementType()) && 675 PartEVT.getVectorElementCount() == 676 ValueVT.getVectorElementCount()) { 677 678 // Promoted vector extract 679 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 680 } else if (PartEVT.isVector() && 681 PartEVT.getVectorElementType() != 682 ValueVT.getVectorElementType() && 683 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 684 TargetLowering::TypeWidenVector) { 685 // Combination of widening and promotion. 686 EVT WidenVT = 687 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 688 PartVT.getVectorElementCount()); 689 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 690 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 691 } else { 692 // Don't extract an integer from a float vector. This can happen if the 693 // FP type gets softened to integer and then promoted. The promotion 694 // prevents it from being picked up by the earlier bitcast case. 695 if (ValueVT.getVectorElementCount().isScalar() && 696 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 697 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 698 DAG.getVectorIdxConstant(0, DL)); 699 } else { 700 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 701 assert(PartVT.getFixedSizeInBits() > ValueSize && 702 "lossy conversion of vector to scalar type"); 703 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 704 Val = DAG.getBitcast(IntermediateType, Val); 705 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 706 } 707 } 708 709 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 710 Parts[0] = Val; 711 return; 712 } 713 714 // Handle a multi-element vector. 715 EVT IntermediateVT; 716 MVT RegisterVT; 717 unsigned NumIntermediates; 718 unsigned NumRegs; 719 if (IsABIRegCopy) { 720 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 721 *DAG.getContext(), CallConv.value(), ValueVT, IntermediateVT, 722 NumIntermediates, RegisterVT); 723 } else { 724 NumRegs = 725 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 726 NumIntermediates, RegisterVT); 727 } 728 729 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 730 NumParts = NumRegs; // Silence a compiler warning. 731 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 732 733 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 734 "Mixing scalable and fixed vectors when copying in parts"); 735 736 Optional<ElementCount> DestEltCnt; 737 738 if (IntermediateVT.isVector()) 739 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 740 else 741 DestEltCnt = ElementCount::getFixed(NumIntermediates); 742 743 EVT BuiltVectorTy = EVT::getVectorVT( 744 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 745 746 if (ValueVT == BuiltVectorTy) { 747 // Nothing to do. 748 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 749 // Bitconvert vector->vector case. 750 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 751 } else { 752 if (BuiltVectorTy.getVectorElementType().bitsGT( 753 ValueVT.getVectorElementType())) { 754 // Integer promotion. 755 ValueVT = EVT::getVectorVT(*DAG.getContext(), 756 BuiltVectorTy.getVectorElementType(), 757 ValueVT.getVectorElementCount()); 758 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 759 } 760 761 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 762 Val = Widened; 763 } 764 } 765 766 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 767 768 // Split the vector into intermediate operands. 769 SmallVector<SDValue, 8> Ops(NumIntermediates); 770 for (unsigned i = 0; i != NumIntermediates; ++i) { 771 if (IntermediateVT.isVector()) { 772 // This does something sensible for scalable vectors - see the 773 // definition of EXTRACT_SUBVECTOR for further details. 774 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 775 Ops[i] = 776 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 777 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 778 } else { 779 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 780 DAG.getVectorIdxConstant(i, DL)); 781 } 782 } 783 784 // Split the intermediate operands into legal parts. 785 if (NumParts == NumIntermediates) { 786 // If the register was not expanded, promote or copy the value, 787 // as appropriate. 788 for (unsigned i = 0; i != NumParts; ++i) 789 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 790 } else if (NumParts > 0) { 791 // If the intermediate type was expanded, split each the value into 792 // legal parts. 793 assert(NumIntermediates != 0 && "division by zero"); 794 assert(NumParts % NumIntermediates == 0 && 795 "Must expand into a divisible number of parts!"); 796 unsigned Factor = NumParts / NumIntermediates; 797 for (unsigned i = 0; i != NumIntermediates; ++i) 798 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 799 CallConv); 800 } 801 } 802 803 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 804 EVT valuevt, Optional<CallingConv::ID> CC) 805 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 806 RegCount(1, regs.size()), CallConv(CC) {} 807 808 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 809 const DataLayout &DL, unsigned Reg, Type *Ty, 810 Optional<CallingConv::ID> CC) { 811 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 812 813 CallConv = CC; 814 815 for (EVT ValueVT : ValueVTs) { 816 unsigned NumRegs = 817 isABIMangled() 818 ? TLI.getNumRegistersForCallingConv(Context, CC.value(), ValueVT) 819 : TLI.getNumRegisters(Context, ValueVT); 820 MVT RegisterVT = 821 isABIMangled() 822 ? TLI.getRegisterTypeForCallingConv(Context, CC.value(), ValueVT) 823 : TLI.getRegisterType(Context, ValueVT); 824 for (unsigned i = 0; i != NumRegs; ++i) 825 Regs.push_back(Reg + i); 826 RegVTs.push_back(RegisterVT); 827 RegCount.push_back(NumRegs); 828 Reg += NumRegs; 829 } 830 } 831 832 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 833 FunctionLoweringInfo &FuncInfo, 834 const SDLoc &dl, SDValue &Chain, 835 SDValue *Flag, const Value *V) const { 836 // A Value with type {} or [0 x %t] needs no registers. 837 if (ValueVTs.empty()) 838 return SDValue(); 839 840 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 841 842 // Assemble the legal parts into the final values. 843 SmallVector<SDValue, 4> Values(ValueVTs.size()); 844 SmallVector<SDValue, 8> Parts; 845 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 846 // Copy the legal parts from the registers. 847 EVT ValueVT = ValueVTs[Value]; 848 unsigned NumRegs = RegCount[Value]; 849 MVT RegisterVT = 850 isABIMangled() ? TLI.getRegisterTypeForCallingConv( 851 *DAG.getContext(), CallConv.value(), RegVTs[Value]) 852 : RegVTs[Value]; 853 854 Parts.resize(NumRegs); 855 for (unsigned i = 0; i != NumRegs; ++i) { 856 SDValue P; 857 if (!Flag) { 858 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 859 } else { 860 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 861 *Flag = P.getValue(2); 862 } 863 864 Chain = P.getValue(1); 865 Parts[i] = P; 866 867 // If the source register was virtual and if we know something about it, 868 // add an assert node. 869 if (!Register::isVirtualRegister(Regs[Part + i]) || 870 !RegisterVT.isInteger()) 871 continue; 872 873 const FunctionLoweringInfo::LiveOutInfo *LOI = 874 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 875 if (!LOI) 876 continue; 877 878 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 879 unsigned NumSignBits = LOI->NumSignBits; 880 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 881 882 if (NumZeroBits == RegSize) { 883 // The current value is a zero. 884 // Explicitly express that as it would be easier for 885 // optimizations to kick in. 886 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 887 continue; 888 } 889 890 // FIXME: We capture more information than the dag can represent. For 891 // now, just use the tightest assertzext/assertsext possible. 892 bool isSExt; 893 EVT FromVT(MVT::Other); 894 if (NumZeroBits) { 895 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 896 isSExt = false; 897 } else if (NumSignBits > 1) { 898 FromVT = 899 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 900 isSExt = true; 901 } else { 902 continue; 903 } 904 // Add an assertion node. 905 assert(FromVT != MVT::Other); 906 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 907 RegisterVT, P, DAG.getValueType(FromVT)); 908 } 909 910 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 911 RegisterVT, ValueVT, V, CallConv); 912 Part += NumRegs; 913 Parts.clear(); 914 } 915 916 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 917 } 918 919 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 920 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 921 const Value *V, 922 ISD::NodeType PreferredExtendType) const { 923 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 924 ISD::NodeType ExtendKind = PreferredExtendType; 925 926 // Get the list of the values's legal parts. 927 unsigned NumRegs = Regs.size(); 928 SmallVector<SDValue, 8> Parts(NumRegs); 929 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 930 unsigned NumParts = RegCount[Value]; 931 932 MVT RegisterVT = 933 isABIMangled() ? TLI.getRegisterTypeForCallingConv( 934 *DAG.getContext(), CallConv.value(), RegVTs[Value]) 935 : RegVTs[Value]; 936 937 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 938 ExtendKind = ISD::ZERO_EXTEND; 939 940 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 941 NumParts, RegisterVT, V, CallConv, ExtendKind); 942 Part += NumParts; 943 } 944 945 // Copy the parts into the registers. 946 SmallVector<SDValue, 8> Chains(NumRegs); 947 for (unsigned i = 0; i != NumRegs; ++i) { 948 SDValue Part; 949 if (!Flag) { 950 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 951 } else { 952 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 953 *Flag = Part.getValue(1); 954 } 955 956 Chains[i] = Part.getValue(0); 957 } 958 959 if (NumRegs == 1 || Flag) 960 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 961 // flagged to it. That is the CopyToReg nodes and the user are considered 962 // a single scheduling unit. If we create a TokenFactor and return it as 963 // chain, then the TokenFactor is both a predecessor (operand) of the 964 // user as well as a successor (the TF operands are flagged to the user). 965 // c1, f1 = CopyToReg 966 // c2, f2 = CopyToReg 967 // c3 = TokenFactor c1, c2 968 // ... 969 // = op c3, ..., f2 970 Chain = Chains[NumRegs-1]; 971 else 972 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 973 } 974 975 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 976 unsigned MatchingIdx, const SDLoc &dl, 977 SelectionDAG &DAG, 978 std::vector<SDValue> &Ops) const { 979 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 980 981 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 982 if (HasMatching) 983 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 984 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 985 // Put the register class of the virtual registers in the flag word. That 986 // way, later passes can recompute register class constraints for inline 987 // assembly as well as normal instructions. 988 // Don't do this for tied operands that can use the regclass information 989 // from the def. 990 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 991 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 992 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 993 } 994 995 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 996 Ops.push_back(Res); 997 998 if (Code == InlineAsm::Kind_Clobber) { 999 // Clobbers should always have a 1:1 mapping with registers, and may 1000 // reference registers that have illegal (e.g. vector) types. Hence, we 1001 // shouldn't try to apply any sort of splitting logic to them. 1002 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1003 "No 1:1 mapping from clobbers to regs?"); 1004 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1005 (void)SP; 1006 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1007 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1008 assert( 1009 (Regs[I] != SP || 1010 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1011 "If we clobbered the stack pointer, MFI should know about it."); 1012 } 1013 return; 1014 } 1015 1016 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1017 MVT RegisterVT = RegVTs[Value]; 1018 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1019 RegisterVT); 1020 for (unsigned i = 0; i != NumRegs; ++i) { 1021 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1022 unsigned TheReg = Regs[Reg++]; 1023 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1024 } 1025 } 1026 } 1027 1028 SmallVector<std::pair<unsigned, TypeSize>, 4> 1029 RegsForValue::getRegsAndSizes() const { 1030 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1031 unsigned I = 0; 1032 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1033 unsigned RegCount = std::get<0>(CountAndVT); 1034 MVT RegisterVT = std::get<1>(CountAndVT); 1035 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1036 for (unsigned E = I + RegCount; I != E; ++I) 1037 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1038 } 1039 return OutVec; 1040 } 1041 1042 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1043 AssumptionCache *ac, 1044 const TargetLibraryInfo *li) { 1045 AA = aa; 1046 AC = ac; 1047 GFI = gfi; 1048 LibInfo = li; 1049 Context = DAG.getContext(); 1050 LPadToCallSiteMap.clear(); 1051 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1052 } 1053 1054 void SelectionDAGBuilder::clear() { 1055 NodeMap.clear(); 1056 UnusedArgNodeMap.clear(); 1057 PendingLoads.clear(); 1058 PendingExports.clear(); 1059 PendingConstrainedFP.clear(); 1060 PendingConstrainedFPStrict.clear(); 1061 CurInst = nullptr; 1062 HasTailCall = false; 1063 SDNodeOrder = LowestSDNodeOrder; 1064 StatepointLowering.clear(); 1065 } 1066 1067 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1068 DanglingDebugInfoMap.clear(); 1069 } 1070 1071 // Update DAG root to include dependencies on Pending chains. 1072 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1073 SDValue Root = DAG.getRoot(); 1074 1075 if (Pending.empty()) 1076 return Root; 1077 1078 // Add current root to PendingChains, unless we already indirectly 1079 // depend on it. 1080 if (Root.getOpcode() != ISD::EntryToken) { 1081 unsigned i = 0, e = Pending.size(); 1082 for (; i != e; ++i) { 1083 assert(Pending[i].getNode()->getNumOperands() > 1); 1084 if (Pending[i].getNode()->getOperand(0) == Root) 1085 break; // Don't add the root if we already indirectly depend on it. 1086 } 1087 1088 if (i == e) 1089 Pending.push_back(Root); 1090 } 1091 1092 if (Pending.size() == 1) 1093 Root = Pending[0]; 1094 else 1095 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1096 1097 DAG.setRoot(Root); 1098 Pending.clear(); 1099 return Root; 1100 } 1101 1102 SDValue SelectionDAGBuilder::getMemoryRoot() { 1103 return updateRoot(PendingLoads); 1104 } 1105 1106 SDValue SelectionDAGBuilder::getRoot() { 1107 // Chain up all pending constrained intrinsics together with all 1108 // pending loads, by simply appending them to PendingLoads and 1109 // then calling getMemoryRoot(). 1110 PendingLoads.reserve(PendingLoads.size() + 1111 PendingConstrainedFP.size() + 1112 PendingConstrainedFPStrict.size()); 1113 PendingLoads.append(PendingConstrainedFP.begin(), 1114 PendingConstrainedFP.end()); 1115 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1116 PendingConstrainedFPStrict.end()); 1117 PendingConstrainedFP.clear(); 1118 PendingConstrainedFPStrict.clear(); 1119 return getMemoryRoot(); 1120 } 1121 1122 SDValue SelectionDAGBuilder::getControlRoot() { 1123 // We need to emit pending fpexcept.strict constrained intrinsics, 1124 // so append them to the PendingExports list. 1125 PendingExports.append(PendingConstrainedFPStrict.begin(), 1126 PendingConstrainedFPStrict.end()); 1127 PendingConstrainedFPStrict.clear(); 1128 return updateRoot(PendingExports); 1129 } 1130 1131 void SelectionDAGBuilder::visit(const Instruction &I) { 1132 // Set up outgoing PHI node register values before emitting the terminator. 1133 if (I.isTerminator()) { 1134 HandlePHINodesInSuccessorBlocks(I.getParent()); 1135 } 1136 1137 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1138 if (!isa<DbgInfoIntrinsic>(I)) 1139 ++SDNodeOrder; 1140 1141 CurInst = &I; 1142 1143 // Set inserted listener only if required. 1144 bool NodeInserted = false; 1145 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1146 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1147 if (PCSectionsMD) { 1148 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1149 DAG, [&](SDNode *) { NodeInserted = true; }); 1150 } 1151 1152 visit(I.getOpcode(), I); 1153 1154 if (!I.isTerminator() && !HasTailCall && 1155 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1156 CopyToExportRegsIfNeeded(&I); 1157 1158 // Handle metadata. 1159 if (PCSectionsMD) { 1160 auto It = NodeMap.find(&I); 1161 if (It != NodeMap.end()) { 1162 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1163 } else if (NodeInserted) { 1164 // This should not happen; if it does, don't let it go unnoticed so we can 1165 // fix it. Relevant visit*() function is probably missing a setValue(). 1166 errs() << "warning: loosing !pcsections metadata [" 1167 << I.getModule()->getName() << "]\n"; 1168 LLVM_DEBUG(I.dump()); 1169 assert(false); 1170 } 1171 } 1172 1173 CurInst = nullptr; 1174 } 1175 1176 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1177 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1178 } 1179 1180 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1181 // Note: this doesn't use InstVisitor, because it has to work with 1182 // ConstantExpr's in addition to instructions. 1183 switch (Opcode) { 1184 default: llvm_unreachable("Unknown instruction type encountered!"); 1185 // Build the switch statement using the Instruction.def file. 1186 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1187 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1188 #include "llvm/IR/Instruction.def" 1189 } 1190 } 1191 1192 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1193 DebugLoc DL, unsigned Order) { 1194 // We treat variadic dbg_values differently at this stage. 1195 if (DI->hasArgList()) { 1196 // For variadic dbg_values we will now insert an undef. 1197 // FIXME: We can potentially recover these! 1198 SmallVector<SDDbgOperand, 2> Locs; 1199 for (const Value *V : DI->getValues()) { 1200 auto Undef = UndefValue::get(V->getType()); 1201 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1202 } 1203 SDDbgValue *SDV = DAG.getDbgValueList( 1204 DI->getVariable(), DI->getExpression(), Locs, {}, 1205 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1206 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1207 } else { 1208 // TODO: Dangling debug info will eventually either be resolved or produce 1209 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1210 // between the original dbg.value location and its resolved DBG_VALUE, 1211 // which we should ideally fill with an extra Undef DBG_VALUE. 1212 assert(DI->getNumVariableLocationOps() == 1 && 1213 "DbgValueInst without an ArgList should have a single location " 1214 "operand."); 1215 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1216 } 1217 } 1218 1219 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1220 const DIExpression *Expr) { 1221 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1222 const DbgValueInst *DI = DDI.getDI(); 1223 DIVariable *DanglingVariable = DI->getVariable(); 1224 DIExpression *DanglingExpr = DI->getExpression(); 1225 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1226 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1227 return true; 1228 } 1229 return false; 1230 }; 1231 1232 for (auto &DDIMI : DanglingDebugInfoMap) { 1233 DanglingDebugInfoVector &DDIV = DDIMI.second; 1234 1235 // If debug info is to be dropped, run it through final checks to see 1236 // whether it can be salvaged. 1237 for (auto &DDI : DDIV) 1238 if (isMatchingDbgValue(DDI)) 1239 salvageUnresolvedDbgValue(DDI); 1240 1241 erase_if(DDIV, isMatchingDbgValue); 1242 } 1243 } 1244 1245 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1246 // generate the debug data structures now that we've seen its definition. 1247 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1248 SDValue Val) { 1249 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1250 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1251 return; 1252 1253 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1254 for (auto &DDI : DDIV) { 1255 const DbgValueInst *DI = DDI.getDI(); 1256 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1257 assert(DI && "Ill-formed DanglingDebugInfo"); 1258 DebugLoc dl = DDI.getdl(); 1259 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1260 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1261 DILocalVariable *Variable = DI->getVariable(); 1262 DIExpression *Expr = DI->getExpression(); 1263 assert(Variable->isValidLocationForIntrinsic(dl) && 1264 "Expected inlined-at fields to agree"); 1265 SDDbgValue *SDV; 1266 if (Val.getNode()) { 1267 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1268 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1269 // we couldn't resolve it directly when examining the DbgValue intrinsic 1270 // in the first place we should not be more successful here). Unless we 1271 // have some test case that prove this to be correct we should avoid 1272 // calling EmitFuncArgumentDbgValue here. 1273 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, 1274 FuncArgumentDbgValueKind::Value, Val)) { 1275 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1276 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1277 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1278 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1279 // inserted after the definition of Val when emitting the instructions 1280 // after ISel. An alternative could be to teach 1281 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1282 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1283 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1284 << ValSDNodeOrder << "\n"); 1285 SDV = getDbgValue(Val, Variable, Expr, dl, 1286 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1287 DAG.AddDbgValue(SDV, false); 1288 } else 1289 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1290 << "in EmitFuncArgumentDbgValue\n"); 1291 } else { 1292 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1293 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1294 auto SDV = 1295 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1296 DAG.AddDbgValue(SDV, false); 1297 } 1298 } 1299 DDIV.clear(); 1300 } 1301 1302 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1303 // TODO: For the variadic implementation, instead of only checking the fail 1304 // state of `handleDebugValue`, we need know specifically which values were 1305 // invalid, so that we attempt to salvage only those values when processing 1306 // a DIArgList. 1307 assert(!DDI.getDI()->hasArgList() && 1308 "Not implemented for variadic dbg_values"); 1309 Value *V = DDI.getDI()->getValue(0); 1310 DILocalVariable *Var = DDI.getDI()->getVariable(); 1311 DIExpression *Expr = DDI.getDI()->getExpression(); 1312 DebugLoc DL = DDI.getdl(); 1313 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1314 unsigned SDOrder = DDI.getSDNodeOrder(); 1315 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1316 // that DW_OP_stack_value is desired. 1317 assert(isa<DbgValueInst>(DDI.getDI())); 1318 bool StackValue = true; 1319 1320 // Can this Value can be encoded without any further work? 1321 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1322 return; 1323 1324 // Attempt to salvage back through as many instructions as possible. Bail if 1325 // a non-instruction is seen, such as a constant expression or global 1326 // variable. FIXME: Further work could recover those too. 1327 while (isa<Instruction>(V)) { 1328 Instruction &VAsInst = *cast<Instruction>(V); 1329 // Temporary "0", awaiting real implementation. 1330 SmallVector<uint64_t, 16> Ops; 1331 SmallVector<Value *, 4> AdditionalValues; 1332 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1333 AdditionalValues); 1334 // If we cannot salvage any further, and haven't yet found a suitable debug 1335 // expression, bail out. 1336 if (!V) 1337 break; 1338 1339 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1340 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1341 // here for variadic dbg_values, remove that condition. 1342 if (!AdditionalValues.empty()) 1343 break; 1344 1345 // New value and expr now represent this debuginfo. 1346 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1347 1348 // Some kind of simplification occurred: check whether the operand of the 1349 // salvaged debug expression can be encoded in this DAG. 1350 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1351 /*IsVariadic=*/false)) { 1352 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1353 << *DDI.getDI() << "\nBy stripping back to:\n " << *V); 1354 return; 1355 } 1356 } 1357 1358 // This was the final opportunity to salvage this debug information, and it 1359 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1360 // any earlier variable location. 1361 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1362 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1363 DAG.AddDbgValue(SDV, false); 1364 1365 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << *DDI.getDI() 1366 << "\n"); 1367 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1368 << "\n"); 1369 } 1370 1371 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1372 DILocalVariable *Var, 1373 DIExpression *Expr, DebugLoc dl, 1374 DebugLoc InstDL, unsigned Order, 1375 bool IsVariadic) { 1376 if (Values.empty()) 1377 return true; 1378 SmallVector<SDDbgOperand> LocationOps; 1379 SmallVector<SDNode *> Dependencies; 1380 for (const Value *V : Values) { 1381 // Constant value. 1382 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1383 isa<ConstantPointerNull>(V)) { 1384 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1385 continue; 1386 } 1387 1388 // Look through IntToPtr constants. 1389 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1390 if (CE->getOpcode() == Instruction::IntToPtr) { 1391 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1392 continue; 1393 } 1394 1395 // If the Value is a frame index, we can create a FrameIndex debug value 1396 // without relying on the DAG at all. 1397 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1398 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1399 if (SI != FuncInfo.StaticAllocaMap.end()) { 1400 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1401 continue; 1402 } 1403 } 1404 1405 // Do not use getValue() in here; we don't want to generate code at 1406 // this point if it hasn't been done yet. 1407 SDValue N = NodeMap[V]; 1408 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1409 N = UnusedArgNodeMap[V]; 1410 if (N.getNode()) { 1411 // Only emit func arg dbg value for non-variadic dbg.values for now. 1412 if (!IsVariadic && 1413 EmitFuncArgumentDbgValue(V, Var, Expr, dl, 1414 FuncArgumentDbgValueKind::Value, N)) 1415 return true; 1416 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1417 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1418 // describe stack slot locations. 1419 // 1420 // Consider "int x = 0; int *px = &x;". There are two kinds of 1421 // interesting debug values here after optimization: 1422 // 1423 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1424 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1425 // 1426 // Both describe the direct values of their associated variables. 1427 Dependencies.push_back(N.getNode()); 1428 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1429 continue; 1430 } 1431 LocationOps.emplace_back( 1432 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1433 continue; 1434 } 1435 1436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1437 // Special rules apply for the first dbg.values of parameter variables in a 1438 // function. Identify them by the fact they reference Argument Values, that 1439 // they're parameters, and they are parameters of the current function. We 1440 // need to let them dangle until they get an SDNode. 1441 bool IsParamOfFunc = 1442 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1443 if (IsParamOfFunc) 1444 return false; 1445 1446 // The value is not used in this block yet (or it would have an SDNode). 1447 // We still want the value to appear for the user if possible -- if it has 1448 // an associated VReg, we can refer to that instead. 1449 auto VMI = FuncInfo.ValueMap.find(V); 1450 if (VMI != FuncInfo.ValueMap.end()) { 1451 unsigned Reg = VMI->second; 1452 // If this is a PHI node, it may be split up into several MI PHI nodes 1453 // (in FunctionLoweringInfo::set). 1454 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1455 V->getType(), None); 1456 if (RFV.occupiesMultipleRegs()) { 1457 // FIXME: We could potentially support variadic dbg_values here. 1458 if (IsVariadic) 1459 return false; 1460 unsigned Offset = 0; 1461 unsigned BitsToDescribe = 0; 1462 if (auto VarSize = Var->getSizeInBits()) 1463 BitsToDescribe = *VarSize; 1464 if (auto Fragment = Expr->getFragmentInfo()) 1465 BitsToDescribe = Fragment->SizeInBits; 1466 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1467 // Bail out if all bits are described already. 1468 if (Offset >= BitsToDescribe) 1469 break; 1470 // TODO: handle scalable vectors. 1471 unsigned RegisterSize = RegAndSize.second; 1472 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1473 ? BitsToDescribe - Offset 1474 : RegisterSize; 1475 auto FragmentExpr = DIExpression::createFragmentExpression( 1476 Expr, Offset, FragmentSize); 1477 if (!FragmentExpr) 1478 continue; 1479 SDDbgValue *SDV = DAG.getVRegDbgValue( 1480 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1481 DAG.AddDbgValue(SDV, false); 1482 Offset += RegisterSize; 1483 } 1484 return true; 1485 } 1486 // We can use simple vreg locations for variadic dbg_values as well. 1487 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1488 continue; 1489 } 1490 // We failed to create a SDDbgOperand for V. 1491 return false; 1492 } 1493 1494 // We have created a SDDbgOperand for each Value in Values. 1495 // Should use Order instead of SDNodeOrder? 1496 assert(!LocationOps.empty()); 1497 SDDbgValue *SDV = 1498 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1499 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1500 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1501 return true; 1502 } 1503 1504 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1505 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1506 for (auto &Pair : DanglingDebugInfoMap) 1507 for (auto &DDI : Pair.second) 1508 salvageUnresolvedDbgValue(DDI); 1509 clearDanglingDebugInfo(); 1510 } 1511 1512 /// getCopyFromRegs - If there was virtual register allocated for the value V 1513 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1514 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1515 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1516 SDValue Result; 1517 1518 if (It != FuncInfo.ValueMap.end()) { 1519 Register InReg = It->second; 1520 1521 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1522 DAG.getDataLayout(), InReg, Ty, 1523 None); // This is not an ABI copy. 1524 SDValue Chain = DAG.getEntryNode(); 1525 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1526 V); 1527 resolveDanglingDebugInfo(V, Result); 1528 } 1529 1530 return Result; 1531 } 1532 1533 /// getValue - Return an SDValue for the given Value. 1534 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1535 // If we already have an SDValue for this value, use it. It's important 1536 // to do this first, so that we don't create a CopyFromReg if we already 1537 // have a regular SDValue. 1538 SDValue &N = NodeMap[V]; 1539 if (N.getNode()) return N; 1540 1541 // If there's a virtual register allocated and initialized for this 1542 // value, use it. 1543 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1544 return copyFromReg; 1545 1546 // Otherwise create a new SDValue and remember it. 1547 SDValue Val = getValueImpl(V); 1548 NodeMap[V] = Val; 1549 resolveDanglingDebugInfo(V, Val); 1550 return Val; 1551 } 1552 1553 /// getNonRegisterValue - Return an SDValue for the given Value, but 1554 /// don't look in FuncInfo.ValueMap for a virtual register. 1555 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1556 // If we already have an SDValue for this value, use it. 1557 SDValue &N = NodeMap[V]; 1558 if (N.getNode()) { 1559 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1560 // Remove the debug location from the node as the node is about to be used 1561 // in a location which may differ from the original debug location. This 1562 // is relevant to Constant and ConstantFP nodes because they can appear 1563 // as constant expressions inside PHI nodes. 1564 N->setDebugLoc(DebugLoc()); 1565 } 1566 return N; 1567 } 1568 1569 // Otherwise create a new SDValue and remember it. 1570 SDValue Val = getValueImpl(V); 1571 NodeMap[V] = Val; 1572 resolveDanglingDebugInfo(V, Val); 1573 return Val; 1574 } 1575 1576 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1577 /// Create an SDValue for the given value. 1578 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1579 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1580 1581 if (const Constant *C = dyn_cast<Constant>(V)) { 1582 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1583 1584 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1585 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1586 1587 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1588 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1589 1590 if (isa<ConstantPointerNull>(C)) { 1591 unsigned AS = V->getType()->getPointerAddressSpace(); 1592 return DAG.getConstant(0, getCurSDLoc(), 1593 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1594 } 1595 1596 if (match(C, m_VScale(DAG.getDataLayout()))) 1597 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1598 1599 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1600 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1601 1602 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1603 return DAG.getUNDEF(VT); 1604 1605 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1606 visit(CE->getOpcode(), *CE); 1607 SDValue N1 = NodeMap[V]; 1608 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1609 return N1; 1610 } 1611 1612 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1613 SmallVector<SDValue, 4> Constants; 1614 for (const Use &U : C->operands()) { 1615 SDNode *Val = getValue(U).getNode(); 1616 // If the operand is an empty aggregate, there are no values. 1617 if (!Val) continue; 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 Constants.push_back(SDValue(Val, i)); 1622 } 1623 1624 return DAG.getMergeValues(Constants, getCurSDLoc()); 1625 } 1626 1627 if (const ConstantDataSequential *CDS = 1628 dyn_cast<ConstantDataSequential>(C)) { 1629 SmallVector<SDValue, 4> Ops; 1630 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1631 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1632 // Add each leaf value from the operand to the Constants list 1633 // to form a flattened list of all the values. 1634 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1635 Ops.push_back(SDValue(Val, i)); 1636 } 1637 1638 if (isa<ArrayType>(CDS->getType())) 1639 return DAG.getMergeValues(Ops, getCurSDLoc()); 1640 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1641 } 1642 1643 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1644 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1645 "Unknown struct or array constant!"); 1646 1647 SmallVector<EVT, 4> ValueVTs; 1648 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1649 unsigned NumElts = ValueVTs.size(); 1650 if (NumElts == 0) 1651 return SDValue(); // empty struct 1652 SmallVector<SDValue, 4> Constants(NumElts); 1653 for (unsigned i = 0; i != NumElts; ++i) { 1654 EVT EltVT = ValueVTs[i]; 1655 if (isa<UndefValue>(C)) 1656 Constants[i] = DAG.getUNDEF(EltVT); 1657 else if (EltVT.isFloatingPoint()) 1658 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1659 else 1660 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1661 } 1662 1663 return DAG.getMergeValues(Constants, getCurSDLoc()); 1664 } 1665 1666 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1667 return DAG.getBlockAddress(BA, VT); 1668 1669 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1670 return getValue(Equiv->getGlobalValue()); 1671 1672 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1673 return getValue(NC->getGlobalValue()); 1674 1675 VectorType *VecTy = cast<VectorType>(V->getType()); 1676 1677 // Now that we know the number and type of the elements, get that number of 1678 // elements into the Ops array based on what kind of constant it is. 1679 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1680 SmallVector<SDValue, 16> Ops; 1681 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1682 for (unsigned i = 0; i != NumElements; ++i) 1683 Ops.push_back(getValue(CV->getOperand(i))); 1684 1685 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1686 } 1687 1688 if (isa<ConstantAggregateZero>(C)) { 1689 EVT EltVT = 1690 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1691 1692 SDValue Op; 1693 if (EltVT.isFloatingPoint()) 1694 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1695 else 1696 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1697 1698 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1699 } 1700 1701 llvm_unreachable("Unknown vector constant"); 1702 } 1703 1704 // If this is a static alloca, generate it as the frameindex instead of 1705 // computation. 1706 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1707 DenseMap<const AllocaInst*, int>::iterator SI = 1708 FuncInfo.StaticAllocaMap.find(AI); 1709 if (SI != FuncInfo.StaticAllocaMap.end()) 1710 return DAG.getFrameIndex(SI->second, 1711 TLI.getFrameIndexTy(DAG.getDataLayout())); 1712 } 1713 1714 // If this is an instruction which fast-isel has deferred, select it now. 1715 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1716 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1717 1718 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1719 Inst->getType(), None); 1720 SDValue Chain = DAG.getEntryNode(); 1721 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1722 } 1723 1724 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1725 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1726 1727 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1728 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1729 1730 llvm_unreachable("Can't get register for value!"); 1731 } 1732 1733 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1734 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1735 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1736 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1737 bool IsSEH = isAsynchronousEHPersonality(Pers); 1738 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1739 if (!IsSEH) 1740 CatchPadMBB->setIsEHScopeEntry(); 1741 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1742 if (IsMSVCCXX || IsCoreCLR) 1743 CatchPadMBB->setIsEHFuncletEntry(); 1744 } 1745 1746 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1747 // Update machine-CFG edge. 1748 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1749 FuncInfo.MBB->addSuccessor(TargetMBB); 1750 TargetMBB->setIsEHCatchretTarget(true); 1751 DAG.getMachineFunction().setHasEHCatchret(true); 1752 1753 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1754 bool IsSEH = isAsynchronousEHPersonality(Pers); 1755 if (IsSEH) { 1756 // If this is not a fall-through branch or optimizations are switched off, 1757 // emit the branch. 1758 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1759 TM.getOptLevel() == CodeGenOpt::None) 1760 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1761 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1762 return; 1763 } 1764 1765 // Figure out the funclet membership for the catchret's successor. 1766 // This will be used by the FuncletLayout pass to determine how to order the 1767 // BB's. 1768 // A 'catchret' returns to the outer scope's color. 1769 Value *ParentPad = I.getCatchSwitchParentPad(); 1770 const BasicBlock *SuccessorColor; 1771 if (isa<ConstantTokenNone>(ParentPad)) 1772 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1773 else 1774 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1775 assert(SuccessorColor && "No parent funclet for catchret!"); 1776 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1777 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1778 1779 // Create the terminator node. 1780 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1781 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1782 DAG.getBasicBlock(SuccessorColorMBB)); 1783 DAG.setRoot(Ret); 1784 } 1785 1786 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1787 // Don't emit any special code for the cleanuppad instruction. It just marks 1788 // the start of an EH scope/funclet. 1789 FuncInfo.MBB->setIsEHScopeEntry(); 1790 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1791 if (Pers != EHPersonality::Wasm_CXX) { 1792 FuncInfo.MBB->setIsEHFuncletEntry(); 1793 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1794 } 1795 } 1796 1797 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1798 // not match, it is OK to add only the first unwind destination catchpad to the 1799 // successors, because there will be at least one invoke instruction within the 1800 // catch scope that points to the next unwind destination, if one exists, so 1801 // CFGSort cannot mess up with BB sorting order. 1802 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1803 // call within them, and catchpads only consisting of 'catch (...)' have a 1804 // '__cxa_end_catch' call within them, both of which generate invokes in case 1805 // the next unwind destination exists, i.e., the next unwind destination is not 1806 // the caller.) 1807 // 1808 // Having at most one EH pad successor is also simpler and helps later 1809 // transformations. 1810 // 1811 // For example, 1812 // current: 1813 // invoke void @foo to ... unwind label %catch.dispatch 1814 // catch.dispatch: 1815 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1816 // catch.start: 1817 // ... 1818 // ... in this BB or some other child BB dominated by this BB there will be an 1819 // invoke that points to 'next' BB as an unwind destination 1820 // 1821 // next: ; We don't need to add this to 'current' BB's successor 1822 // ... 1823 static void findWasmUnwindDestinations( 1824 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1825 BranchProbability Prob, 1826 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1827 &UnwindDests) { 1828 while (EHPadBB) { 1829 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1830 if (isa<CleanupPadInst>(Pad)) { 1831 // Stop on cleanup pads. 1832 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1833 UnwindDests.back().first->setIsEHScopeEntry(); 1834 break; 1835 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1836 // Add the catchpad handlers to the possible destinations. We don't 1837 // continue to the unwind destination of the catchswitch for wasm. 1838 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1839 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1840 UnwindDests.back().first->setIsEHScopeEntry(); 1841 } 1842 break; 1843 } else { 1844 continue; 1845 } 1846 } 1847 } 1848 1849 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1850 /// many places it could ultimately go. In the IR, we have a single unwind 1851 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1852 /// This function skips over imaginary basic blocks that hold catchswitch 1853 /// instructions, and finds all the "real" machine 1854 /// basic block destinations. As those destinations may not be successors of 1855 /// EHPadBB, here we also calculate the edge probability to those destinations. 1856 /// The passed-in Prob is the edge probability to EHPadBB. 1857 static void findUnwindDestinations( 1858 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1859 BranchProbability Prob, 1860 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1861 &UnwindDests) { 1862 EHPersonality Personality = 1863 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1864 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1865 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1866 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1867 bool IsSEH = isAsynchronousEHPersonality(Personality); 1868 1869 if (IsWasmCXX) { 1870 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1871 assert(UnwindDests.size() <= 1 && 1872 "There should be at most one unwind destination for wasm"); 1873 return; 1874 } 1875 1876 while (EHPadBB) { 1877 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1878 BasicBlock *NewEHPadBB = nullptr; 1879 if (isa<LandingPadInst>(Pad)) { 1880 // Stop on landingpads. They are not funclets. 1881 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1882 break; 1883 } else if (isa<CleanupPadInst>(Pad)) { 1884 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1885 // personalities. 1886 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1887 UnwindDests.back().first->setIsEHScopeEntry(); 1888 UnwindDests.back().first->setIsEHFuncletEntry(); 1889 break; 1890 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1891 // Add the catchpad handlers to the possible destinations. 1892 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1893 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1894 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1895 if (IsMSVCCXX || IsCoreCLR) 1896 UnwindDests.back().first->setIsEHFuncletEntry(); 1897 if (!IsSEH) 1898 UnwindDests.back().first->setIsEHScopeEntry(); 1899 } 1900 NewEHPadBB = CatchSwitch->getUnwindDest(); 1901 } else { 1902 continue; 1903 } 1904 1905 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1906 if (BPI && NewEHPadBB) 1907 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1908 EHPadBB = NewEHPadBB; 1909 } 1910 } 1911 1912 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1913 // Update successor info. 1914 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1915 auto UnwindDest = I.getUnwindDest(); 1916 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1917 BranchProbability UnwindDestProb = 1918 (BPI && UnwindDest) 1919 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1920 : BranchProbability::getZero(); 1921 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1922 for (auto &UnwindDest : UnwindDests) { 1923 UnwindDest.first->setIsEHPad(); 1924 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1925 } 1926 FuncInfo.MBB->normalizeSuccProbs(); 1927 1928 // Create the terminator node. 1929 SDValue Ret = 1930 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1931 DAG.setRoot(Ret); 1932 } 1933 1934 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1935 report_fatal_error("visitCatchSwitch not yet implemented!"); 1936 } 1937 1938 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1939 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1940 auto &DL = DAG.getDataLayout(); 1941 SDValue Chain = getControlRoot(); 1942 SmallVector<ISD::OutputArg, 8> Outs; 1943 SmallVector<SDValue, 8> OutVals; 1944 1945 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1946 // lower 1947 // 1948 // %val = call <ty> @llvm.experimental.deoptimize() 1949 // ret <ty> %val 1950 // 1951 // differently. 1952 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1953 LowerDeoptimizingReturn(); 1954 return; 1955 } 1956 1957 if (!FuncInfo.CanLowerReturn) { 1958 unsigned DemoteReg = FuncInfo.DemoteRegister; 1959 const Function *F = I.getParent()->getParent(); 1960 1961 // Emit a store of the return value through the virtual register. 1962 // Leave Outs empty so that LowerReturn won't try to load return 1963 // registers the usual way. 1964 SmallVector<EVT, 1> PtrValueVTs; 1965 ComputeValueVTs(TLI, DL, 1966 F->getReturnType()->getPointerTo( 1967 DAG.getDataLayout().getAllocaAddrSpace()), 1968 PtrValueVTs); 1969 1970 SDValue RetPtr = 1971 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 1972 SDValue RetOp = getValue(I.getOperand(0)); 1973 1974 SmallVector<EVT, 4> ValueVTs, MemVTs; 1975 SmallVector<uint64_t, 4> Offsets; 1976 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1977 &Offsets); 1978 unsigned NumValues = ValueVTs.size(); 1979 1980 SmallVector<SDValue, 4> Chains(NumValues); 1981 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1982 for (unsigned i = 0; i != NumValues; ++i) { 1983 // An aggregate return value cannot wrap around the address space, so 1984 // offsets to its parts don't wrap either. 1985 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1986 TypeSize::Fixed(Offsets[i])); 1987 1988 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1989 if (MemVTs[i] != ValueVTs[i]) 1990 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1991 Chains[i] = DAG.getStore( 1992 Chain, getCurSDLoc(), Val, 1993 // FIXME: better loc info would be nice. 1994 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1995 commonAlignment(BaseAlign, Offsets[i])); 1996 } 1997 1998 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1999 MVT::Other, Chains); 2000 } else if (I.getNumOperands() != 0) { 2001 SmallVector<EVT, 4> ValueVTs; 2002 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2003 unsigned NumValues = ValueVTs.size(); 2004 if (NumValues) { 2005 SDValue RetOp = getValue(I.getOperand(0)); 2006 2007 const Function *F = I.getParent()->getParent(); 2008 2009 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2010 I.getOperand(0)->getType(), F->getCallingConv(), 2011 /*IsVarArg*/ false, DL); 2012 2013 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2014 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2015 ExtendKind = ISD::SIGN_EXTEND; 2016 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2017 ExtendKind = ISD::ZERO_EXTEND; 2018 2019 LLVMContext &Context = F->getContext(); 2020 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2021 2022 for (unsigned j = 0; j != NumValues; ++j) { 2023 EVT VT = ValueVTs[j]; 2024 2025 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2026 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2027 2028 CallingConv::ID CC = F->getCallingConv(); 2029 2030 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2031 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2032 SmallVector<SDValue, 4> Parts(NumParts); 2033 getCopyToParts(DAG, getCurSDLoc(), 2034 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2035 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2036 2037 // 'inreg' on function refers to return value 2038 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2039 if (RetInReg) 2040 Flags.setInReg(); 2041 2042 if (I.getOperand(0)->getType()->isPointerTy()) { 2043 Flags.setPointer(); 2044 Flags.setPointerAddrSpace( 2045 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2046 } 2047 2048 if (NeedsRegBlock) { 2049 Flags.setInConsecutiveRegs(); 2050 if (j == NumValues - 1) 2051 Flags.setInConsecutiveRegsLast(); 2052 } 2053 2054 // Propagate extension type if any 2055 if (ExtendKind == ISD::SIGN_EXTEND) 2056 Flags.setSExt(); 2057 else if (ExtendKind == ISD::ZERO_EXTEND) 2058 Flags.setZExt(); 2059 2060 for (unsigned i = 0; i < NumParts; ++i) { 2061 Outs.push_back(ISD::OutputArg(Flags, 2062 Parts[i].getValueType().getSimpleVT(), 2063 VT, /*isfixed=*/true, 0, 0)); 2064 OutVals.push_back(Parts[i]); 2065 } 2066 } 2067 } 2068 } 2069 2070 // Push in swifterror virtual register as the last element of Outs. This makes 2071 // sure swifterror virtual register will be returned in the swifterror 2072 // physical register. 2073 const Function *F = I.getParent()->getParent(); 2074 if (TLI.supportSwiftError() && 2075 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2076 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2077 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2078 Flags.setSwiftError(); 2079 Outs.push_back(ISD::OutputArg( 2080 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2081 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2082 // Create SDNode for the swifterror virtual register. 2083 OutVals.push_back( 2084 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2085 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2086 EVT(TLI.getPointerTy(DL)))); 2087 } 2088 2089 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2090 CallingConv::ID CallConv = 2091 DAG.getMachineFunction().getFunction().getCallingConv(); 2092 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2093 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2094 2095 // Verify that the target's LowerReturn behaved as expected. 2096 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2097 "LowerReturn didn't return a valid chain!"); 2098 2099 // Update the DAG with the new chain value resulting from return lowering. 2100 DAG.setRoot(Chain); 2101 } 2102 2103 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2104 /// created for it, emit nodes to copy the value into the virtual 2105 /// registers. 2106 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2107 // Skip empty types 2108 if (V->getType()->isEmptyTy()) 2109 return; 2110 2111 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2112 if (VMI != FuncInfo.ValueMap.end()) { 2113 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2114 CopyValueToVirtualRegister(V, VMI->second); 2115 } 2116 } 2117 2118 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2119 /// the current basic block, add it to ValueMap now so that we'll get a 2120 /// CopyTo/FromReg. 2121 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2122 // No need to export constants. 2123 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2124 2125 // Already exported? 2126 if (FuncInfo.isExportedInst(V)) return; 2127 2128 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2129 CopyValueToVirtualRegister(V, Reg); 2130 } 2131 2132 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2133 const BasicBlock *FromBB) { 2134 // The operands of the setcc have to be in this block. We don't know 2135 // how to export them from some other block. 2136 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2137 // Can export from current BB. 2138 if (VI->getParent() == FromBB) 2139 return true; 2140 2141 // Is already exported, noop. 2142 return FuncInfo.isExportedInst(V); 2143 } 2144 2145 // If this is an argument, we can export it if the BB is the entry block or 2146 // if it is already exported. 2147 if (isa<Argument>(V)) { 2148 if (FromBB->isEntryBlock()) 2149 return true; 2150 2151 // Otherwise, can only export this if it is already exported. 2152 return FuncInfo.isExportedInst(V); 2153 } 2154 2155 // Otherwise, constants can always be exported. 2156 return true; 2157 } 2158 2159 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2160 BranchProbability 2161 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2162 const MachineBasicBlock *Dst) const { 2163 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2164 const BasicBlock *SrcBB = Src->getBasicBlock(); 2165 const BasicBlock *DstBB = Dst->getBasicBlock(); 2166 if (!BPI) { 2167 // If BPI is not available, set the default probability as 1 / N, where N is 2168 // the number of successors. 2169 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2170 return BranchProbability(1, SuccSize); 2171 } 2172 return BPI->getEdgeProbability(SrcBB, DstBB); 2173 } 2174 2175 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2176 MachineBasicBlock *Dst, 2177 BranchProbability Prob) { 2178 if (!FuncInfo.BPI) 2179 Src->addSuccessorWithoutProb(Dst); 2180 else { 2181 if (Prob.isUnknown()) 2182 Prob = getEdgeProbability(Src, Dst); 2183 Src->addSuccessor(Dst, Prob); 2184 } 2185 } 2186 2187 static bool InBlock(const Value *V, const BasicBlock *BB) { 2188 if (const Instruction *I = dyn_cast<Instruction>(V)) 2189 return I->getParent() == BB; 2190 return true; 2191 } 2192 2193 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2194 /// This function emits a branch and is used at the leaves of an OR or an 2195 /// AND operator tree. 2196 void 2197 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2198 MachineBasicBlock *TBB, 2199 MachineBasicBlock *FBB, 2200 MachineBasicBlock *CurBB, 2201 MachineBasicBlock *SwitchBB, 2202 BranchProbability TProb, 2203 BranchProbability FProb, 2204 bool InvertCond) { 2205 const BasicBlock *BB = CurBB->getBasicBlock(); 2206 2207 // If the leaf of the tree is a comparison, merge the condition into 2208 // the caseblock. 2209 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2210 // The operands of the cmp have to be in this block. We don't know 2211 // how to export them from some other block. If this is the first block 2212 // of the sequence, no exporting is needed. 2213 if (CurBB == SwitchBB || 2214 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2215 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2216 ISD::CondCode Condition; 2217 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2218 ICmpInst::Predicate Pred = 2219 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2220 Condition = getICmpCondCode(Pred); 2221 } else { 2222 const FCmpInst *FC = cast<FCmpInst>(Cond); 2223 FCmpInst::Predicate Pred = 2224 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2225 Condition = getFCmpCondCode(Pred); 2226 if (TM.Options.NoNaNsFPMath) 2227 Condition = getFCmpCodeWithoutNaN(Condition); 2228 } 2229 2230 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2231 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2232 SL->SwitchCases.push_back(CB); 2233 return; 2234 } 2235 } 2236 2237 // Create a CaseBlock record representing this branch. 2238 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2239 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2240 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2241 SL->SwitchCases.push_back(CB); 2242 } 2243 2244 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2245 MachineBasicBlock *TBB, 2246 MachineBasicBlock *FBB, 2247 MachineBasicBlock *CurBB, 2248 MachineBasicBlock *SwitchBB, 2249 Instruction::BinaryOps Opc, 2250 BranchProbability TProb, 2251 BranchProbability FProb, 2252 bool InvertCond) { 2253 // Skip over not part of the tree and remember to invert op and operands at 2254 // next level. 2255 Value *NotCond; 2256 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2257 InBlock(NotCond, CurBB->getBasicBlock())) { 2258 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2259 !InvertCond); 2260 return; 2261 } 2262 2263 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2264 const Value *BOpOp0, *BOpOp1; 2265 // Compute the effective opcode for Cond, taking into account whether it needs 2266 // to be inverted, e.g. 2267 // and (not (or A, B)), C 2268 // gets lowered as 2269 // and (and (not A, not B), C) 2270 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2271 if (BOp) { 2272 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2273 ? Instruction::And 2274 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2275 ? Instruction::Or 2276 : (Instruction::BinaryOps)0); 2277 if (InvertCond) { 2278 if (BOpc == Instruction::And) 2279 BOpc = Instruction::Or; 2280 else if (BOpc == Instruction::Or) 2281 BOpc = Instruction::And; 2282 } 2283 } 2284 2285 // If this node is not part of the or/and tree, emit it as a branch. 2286 // Note that all nodes in the tree should have same opcode. 2287 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2288 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2289 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2290 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2291 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2292 TProb, FProb, InvertCond); 2293 return; 2294 } 2295 2296 // Create TmpBB after CurBB. 2297 MachineFunction::iterator BBI(CurBB); 2298 MachineFunction &MF = DAG.getMachineFunction(); 2299 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2300 CurBB->getParent()->insert(++BBI, TmpBB); 2301 2302 if (Opc == Instruction::Or) { 2303 // Codegen X | Y as: 2304 // BB1: 2305 // jmp_if_X TBB 2306 // jmp TmpBB 2307 // TmpBB: 2308 // jmp_if_Y TBB 2309 // jmp FBB 2310 // 2311 2312 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2313 // The requirement is that 2314 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2315 // = TrueProb for original BB. 2316 // Assuming the original probabilities are A and B, one choice is to set 2317 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2318 // A/(1+B) and 2B/(1+B). This choice assumes that 2319 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2320 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2321 // TmpBB, but the math is more complicated. 2322 2323 auto NewTrueProb = TProb / 2; 2324 auto NewFalseProb = TProb / 2 + FProb; 2325 // Emit the LHS condition. 2326 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2327 NewFalseProb, InvertCond); 2328 2329 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2330 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2331 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2332 // Emit the RHS condition into TmpBB. 2333 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2334 Probs[1], InvertCond); 2335 } else { 2336 assert(Opc == Instruction::And && "Unknown merge op!"); 2337 // Codegen X & Y as: 2338 // BB1: 2339 // jmp_if_X TmpBB 2340 // jmp FBB 2341 // TmpBB: 2342 // jmp_if_Y TBB 2343 // jmp FBB 2344 // 2345 // This requires creation of TmpBB after CurBB. 2346 2347 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2348 // The requirement is that 2349 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2350 // = FalseProb for original BB. 2351 // Assuming the original probabilities are A and B, one choice is to set 2352 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2353 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2354 // TrueProb for BB1 * FalseProb for TmpBB. 2355 2356 auto NewTrueProb = TProb + FProb / 2; 2357 auto NewFalseProb = FProb / 2; 2358 // Emit the LHS condition. 2359 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2360 NewFalseProb, InvertCond); 2361 2362 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2363 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2364 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2365 // Emit the RHS condition into TmpBB. 2366 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2367 Probs[1], InvertCond); 2368 } 2369 } 2370 2371 /// If the set of cases should be emitted as a series of branches, return true. 2372 /// If we should emit this as a bunch of and/or'd together conditions, return 2373 /// false. 2374 bool 2375 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2376 if (Cases.size() != 2) return true; 2377 2378 // If this is two comparisons of the same values or'd or and'd together, they 2379 // will get folded into a single comparison, so don't emit two blocks. 2380 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2381 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2382 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2383 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2384 return false; 2385 } 2386 2387 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2388 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2389 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2390 Cases[0].CC == Cases[1].CC && 2391 isa<Constant>(Cases[0].CmpRHS) && 2392 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2393 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2394 return false; 2395 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2396 return false; 2397 } 2398 2399 return true; 2400 } 2401 2402 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2403 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2404 2405 // Update machine-CFG edges. 2406 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2407 2408 if (I.isUnconditional()) { 2409 // Update machine-CFG edges. 2410 BrMBB->addSuccessor(Succ0MBB); 2411 2412 // If this is not a fall-through branch or optimizations are switched off, 2413 // emit the branch. 2414 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2415 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2416 MVT::Other, getControlRoot(), 2417 DAG.getBasicBlock(Succ0MBB))); 2418 2419 return; 2420 } 2421 2422 // If this condition is one of the special cases we handle, do special stuff 2423 // now. 2424 const Value *CondVal = I.getCondition(); 2425 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2426 2427 // If this is a series of conditions that are or'd or and'd together, emit 2428 // this as a sequence of branches instead of setcc's with and/or operations. 2429 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2430 // unpredictable branches, and vector extracts because those jumps are likely 2431 // expensive for any target), this should improve performance. 2432 // For example, instead of something like: 2433 // cmp A, B 2434 // C = seteq 2435 // cmp D, E 2436 // F = setle 2437 // or C, F 2438 // jnz foo 2439 // Emit: 2440 // cmp A, B 2441 // je foo 2442 // cmp D, E 2443 // jle foo 2444 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2445 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2446 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2447 Value *Vec; 2448 const Value *BOp0, *BOp1; 2449 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2450 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2451 Opcode = Instruction::And; 2452 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2453 Opcode = Instruction::Or; 2454 2455 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2456 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2457 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2458 getEdgeProbability(BrMBB, Succ0MBB), 2459 getEdgeProbability(BrMBB, Succ1MBB), 2460 /*InvertCond=*/false); 2461 // If the compares in later blocks need to use values not currently 2462 // exported from this block, export them now. This block should always 2463 // be the first entry. 2464 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2465 2466 // Allow some cases to be rejected. 2467 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2468 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2469 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2470 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2471 } 2472 2473 // Emit the branch for this block. 2474 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2475 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2476 return; 2477 } 2478 2479 // Okay, we decided not to do this, remove any inserted MBB's and clear 2480 // SwitchCases. 2481 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2482 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2483 2484 SL->SwitchCases.clear(); 2485 } 2486 } 2487 2488 // Create a CaseBlock record representing this branch. 2489 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2490 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2491 2492 // Use visitSwitchCase to actually insert the fast branch sequence for this 2493 // cond branch. 2494 visitSwitchCase(CB, BrMBB); 2495 } 2496 2497 /// visitSwitchCase - Emits the necessary code to represent a single node in 2498 /// the binary search tree resulting from lowering a switch instruction. 2499 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2500 MachineBasicBlock *SwitchBB) { 2501 SDValue Cond; 2502 SDValue CondLHS = getValue(CB.CmpLHS); 2503 SDLoc dl = CB.DL; 2504 2505 if (CB.CC == ISD::SETTRUE) { 2506 // Branch or fall through to TrueBB. 2507 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2508 SwitchBB->normalizeSuccProbs(); 2509 if (CB.TrueBB != NextBlock(SwitchBB)) { 2510 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2511 DAG.getBasicBlock(CB.TrueBB))); 2512 } 2513 return; 2514 } 2515 2516 auto &TLI = DAG.getTargetLoweringInfo(); 2517 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2518 2519 // Build the setcc now. 2520 if (!CB.CmpMHS) { 2521 // Fold "(X == true)" to X and "(X == false)" to !X to 2522 // handle common cases produced by branch lowering. 2523 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2524 CB.CC == ISD::SETEQ) 2525 Cond = CondLHS; 2526 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2527 CB.CC == ISD::SETEQ) { 2528 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2529 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2530 } else { 2531 SDValue CondRHS = getValue(CB.CmpRHS); 2532 2533 // If a pointer's DAG type is larger than its memory type then the DAG 2534 // values are zero-extended. This breaks signed comparisons so truncate 2535 // back to the underlying type before doing the compare. 2536 if (CondLHS.getValueType() != MemVT) { 2537 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2538 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2539 } 2540 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2541 } 2542 } else { 2543 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2544 2545 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2546 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2547 2548 SDValue CmpOp = getValue(CB.CmpMHS); 2549 EVT VT = CmpOp.getValueType(); 2550 2551 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2552 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2553 ISD::SETLE); 2554 } else { 2555 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2556 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2557 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2558 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2559 } 2560 } 2561 2562 // Update successor info 2563 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2564 // TrueBB and FalseBB are always different unless the incoming IR is 2565 // degenerate. This only happens when running llc on weird IR. 2566 if (CB.TrueBB != CB.FalseBB) 2567 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2568 SwitchBB->normalizeSuccProbs(); 2569 2570 // If the lhs block is the next block, invert the condition so that we can 2571 // fall through to the lhs instead of the rhs block. 2572 if (CB.TrueBB == NextBlock(SwitchBB)) { 2573 std::swap(CB.TrueBB, CB.FalseBB); 2574 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2575 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2576 } 2577 2578 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2579 MVT::Other, getControlRoot(), Cond, 2580 DAG.getBasicBlock(CB.TrueBB)); 2581 2582 setValue(CurInst, BrCond); 2583 2584 // Insert the false branch. Do this even if it's a fall through branch, 2585 // this makes it easier to do DAG optimizations which require inverting 2586 // the branch condition. 2587 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2588 DAG.getBasicBlock(CB.FalseBB)); 2589 2590 DAG.setRoot(BrCond); 2591 } 2592 2593 /// visitJumpTable - Emit JumpTable node in the current MBB 2594 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2595 // Emit the code for the jump table 2596 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2597 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2598 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2599 JT.Reg, PTy); 2600 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2601 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2602 MVT::Other, Index.getValue(1), 2603 Table, Index); 2604 DAG.setRoot(BrJumpTable); 2605 } 2606 2607 /// visitJumpTableHeader - This function emits necessary code to produce index 2608 /// in the JumpTable from switch case. 2609 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2610 JumpTableHeader &JTH, 2611 MachineBasicBlock *SwitchBB) { 2612 SDLoc dl = getCurSDLoc(); 2613 2614 // Subtract the lowest switch case value from the value being switched on. 2615 SDValue SwitchOp = getValue(JTH.SValue); 2616 EVT VT = SwitchOp.getValueType(); 2617 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2618 DAG.getConstant(JTH.First, dl, VT)); 2619 2620 // The SDNode we just created, which holds the value being switched on minus 2621 // the smallest case value, needs to be copied to a virtual register so it 2622 // can be used as an index into the jump table in a subsequent basic block. 2623 // This value may be smaller or larger than the target's pointer type, and 2624 // therefore require extension or truncating. 2625 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2626 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2627 2628 unsigned JumpTableReg = 2629 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2630 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2631 JumpTableReg, SwitchOp); 2632 JT.Reg = JumpTableReg; 2633 2634 if (!JTH.FallthroughUnreachable) { 2635 // Emit the range check for the jump table, and branch to the default block 2636 // for the switch statement if the value being switched on exceeds the 2637 // largest case in the switch. 2638 SDValue CMP = DAG.getSetCC( 2639 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2640 Sub.getValueType()), 2641 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2642 2643 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2644 MVT::Other, CopyTo, CMP, 2645 DAG.getBasicBlock(JT.Default)); 2646 2647 // Avoid emitting unnecessary branches to the next block. 2648 if (JT.MBB != NextBlock(SwitchBB)) 2649 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2650 DAG.getBasicBlock(JT.MBB)); 2651 2652 DAG.setRoot(BrCond); 2653 } else { 2654 // Avoid emitting unnecessary branches to the next block. 2655 if (JT.MBB != NextBlock(SwitchBB)) 2656 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2657 DAG.getBasicBlock(JT.MBB))); 2658 else 2659 DAG.setRoot(CopyTo); 2660 } 2661 } 2662 2663 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2664 /// variable if there exists one. 2665 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2666 SDValue &Chain) { 2667 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2668 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2669 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2670 MachineFunction &MF = DAG.getMachineFunction(); 2671 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2672 MachineSDNode *Node = 2673 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2674 if (Global) { 2675 MachinePointerInfo MPInfo(Global); 2676 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2677 MachineMemOperand::MODereferenceable; 2678 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2679 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2680 DAG.setNodeMemRefs(Node, {MemRef}); 2681 } 2682 if (PtrTy != PtrMemTy) 2683 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2684 return SDValue(Node, 0); 2685 } 2686 2687 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2688 /// tail spliced into a stack protector check success bb. 2689 /// 2690 /// For a high level explanation of how this fits into the stack protector 2691 /// generation see the comment on the declaration of class 2692 /// StackProtectorDescriptor. 2693 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2694 MachineBasicBlock *ParentBB) { 2695 2696 // First create the loads to the guard/stack slot for the comparison. 2697 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2698 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2699 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2700 2701 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2702 int FI = MFI.getStackProtectorIndex(); 2703 2704 SDValue Guard; 2705 SDLoc dl = getCurSDLoc(); 2706 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2707 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2708 Align Align = 2709 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2710 2711 // Generate code to load the content of the guard slot. 2712 SDValue GuardVal = DAG.getLoad( 2713 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2714 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2715 MachineMemOperand::MOVolatile); 2716 2717 if (TLI.useStackGuardXorFP()) 2718 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2719 2720 // Retrieve guard check function, nullptr if instrumentation is inlined. 2721 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2722 // The target provides a guard check function to validate the guard value. 2723 // Generate a call to that function with the content of the guard slot as 2724 // argument. 2725 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2726 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2727 2728 TargetLowering::ArgListTy Args; 2729 TargetLowering::ArgListEntry Entry; 2730 Entry.Node = GuardVal; 2731 Entry.Ty = FnTy->getParamType(0); 2732 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2733 Entry.IsInReg = true; 2734 Args.push_back(Entry); 2735 2736 TargetLowering::CallLoweringInfo CLI(DAG); 2737 CLI.setDebugLoc(getCurSDLoc()) 2738 .setChain(DAG.getEntryNode()) 2739 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2740 getValue(GuardCheckFn), std::move(Args)); 2741 2742 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2743 DAG.setRoot(Result.second); 2744 return; 2745 } 2746 2747 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2748 // Otherwise, emit a volatile load to retrieve the stack guard value. 2749 SDValue Chain = DAG.getEntryNode(); 2750 if (TLI.useLoadStackGuardNode()) { 2751 Guard = getLoadStackGuard(DAG, dl, Chain); 2752 } else { 2753 const Value *IRGuard = TLI.getSDagStackGuard(M); 2754 SDValue GuardPtr = getValue(IRGuard); 2755 2756 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2757 MachinePointerInfo(IRGuard, 0), Align, 2758 MachineMemOperand::MOVolatile); 2759 } 2760 2761 // Perform the comparison via a getsetcc. 2762 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2763 *DAG.getContext(), 2764 Guard.getValueType()), 2765 Guard, GuardVal, ISD::SETNE); 2766 2767 // If the guard/stackslot do not equal, branch to failure MBB. 2768 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2769 MVT::Other, GuardVal.getOperand(0), 2770 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2771 // Otherwise branch to success MBB. 2772 SDValue Br = DAG.getNode(ISD::BR, dl, 2773 MVT::Other, BrCond, 2774 DAG.getBasicBlock(SPD.getSuccessMBB())); 2775 2776 DAG.setRoot(Br); 2777 } 2778 2779 /// Codegen the failure basic block for a stack protector check. 2780 /// 2781 /// A failure stack protector machine basic block consists simply of a call to 2782 /// __stack_chk_fail(). 2783 /// 2784 /// For a high level explanation of how this fits into the stack protector 2785 /// generation see the comment on the declaration of class 2786 /// StackProtectorDescriptor. 2787 void 2788 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2789 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2790 TargetLowering::MakeLibCallOptions CallOptions; 2791 CallOptions.setDiscardResult(true); 2792 SDValue Chain = 2793 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2794 None, CallOptions, getCurSDLoc()).second; 2795 // On PS4/PS5, the "return address" must still be within the calling 2796 // function, even if it's at the very end, so emit an explicit TRAP here. 2797 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2798 if (TM.getTargetTriple().isPS()) 2799 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2800 // WebAssembly needs an unreachable instruction after a non-returning call, 2801 // because the function return type can be different from __stack_chk_fail's 2802 // return type (void). 2803 if (TM.getTargetTriple().isWasm()) 2804 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2805 2806 DAG.setRoot(Chain); 2807 } 2808 2809 /// visitBitTestHeader - This function emits necessary code to produce value 2810 /// suitable for "bit tests" 2811 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2812 MachineBasicBlock *SwitchBB) { 2813 SDLoc dl = getCurSDLoc(); 2814 2815 // Subtract the minimum value. 2816 SDValue SwitchOp = getValue(B.SValue); 2817 EVT VT = SwitchOp.getValueType(); 2818 SDValue RangeSub = 2819 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2820 2821 // Determine the type of the test operands. 2822 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2823 bool UsePtrType = false; 2824 if (!TLI.isTypeLegal(VT)) { 2825 UsePtrType = true; 2826 } else { 2827 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2828 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2829 // Switch table case range are encoded into series of masks. 2830 // Just use pointer type, it's guaranteed to fit. 2831 UsePtrType = true; 2832 break; 2833 } 2834 } 2835 SDValue Sub = RangeSub; 2836 if (UsePtrType) { 2837 VT = TLI.getPointerTy(DAG.getDataLayout()); 2838 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2839 } 2840 2841 B.RegVT = VT.getSimpleVT(); 2842 B.Reg = FuncInfo.CreateReg(B.RegVT); 2843 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2844 2845 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2846 2847 if (!B.FallthroughUnreachable) 2848 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2849 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2850 SwitchBB->normalizeSuccProbs(); 2851 2852 SDValue Root = CopyTo; 2853 if (!B.FallthroughUnreachable) { 2854 // Conditional branch to the default block. 2855 SDValue RangeCmp = DAG.getSetCC(dl, 2856 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2857 RangeSub.getValueType()), 2858 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2859 ISD::SETUGT); 2860 2861 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2862 DAG.getBasicBlock(B.Default)); 2863 } 2864 2865 // Avoid emitting unnecessary branches to the next block. 2866 if (MBB != NextBlock(SwitchBB)) 2867 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2868 2869 DAG.setRoot(Root); 2870 } 2871 2872 /// visitBitTestCase - this function produces one "bit test" 2873 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2874 MachineBasicBlock* NextMBB, 2875 BranchProbability BranchProbToNext, 2876 unsigned Reg, 2877 BitTestCase &B, 2878 MachineBasicBlock *SwitchBB) { 2879 SDLoc dl = getCurSDLoc(); 2880 MVT VT = BB.RegVT; 2881 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2882 SDValue Cmp; 2883 unsigned PopCount = countPopulation(B.Mask); 2884 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2885 if (PopCount == 1) { 2886 // Testing for a single bit; just compare the shift count with what it 2887 // would need to be to shift a 1 bit in that position. 2888 Cmp = DAG.getSetCC( 2889 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2890 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2891 ISD::SETEQ); 2892 } else if (PopCount == BB.Range) { 2893 // There is only one zero bit in the range, test for it directly. 2894 Cmp = DAG.getSetCC( 2895 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2896 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2897 ISD::SETNE); 2898 } else { 2899 // Make desired shift 2900 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2901 DAG.getConstant(1, dl, VT), ShiftOp); 2902 2903 // Emit bit tests and jumps 2904 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2905 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2906 Cmp = DAG.getSetCC( 2907 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2908 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2909 } 2910 2911 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2912 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2913 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2914 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2915 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2916 // one as they are relative probabilities (and thus work more like weights), 2917 // and hence we need to normalize them to let the sum of them become one. 2918 SwitchBB->normalizeSuccProbs(); 2919 2920 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2921 MVT::Other, getControlRoot(), 2922 Cmp, DAG.getBasicBlock(B.TargetBB)); 2923 2924 // Avoid emitting unnecessary branches to the next block. 2925 if (NextMBB != NextBlock(SwitchBB)) 2926 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2927 DAG.getBasicBlock(NextMBB)); 2928 2929 DAG.setRoot(BrAnd); 2930 } 2931 2932 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2933 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2934 2935 // Retrieve successors. Look through artificial IR level blocks like 2936 // catchswitch for successors. 2937 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2938 const BasicBlock *EHPadBB = I.getSuccessor(1); 2939 2940 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2941 // have to do anything here to lower funclet bundles. 2942 assert(!I.hasOperandBundlesOtherThan( 2943 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2944 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2945 LLVMContext::OB_cfguardtarget, 2946 LLVMContext::OB_clang_arc_attachedcall}) && 2947 "Cannot lower invokes with arbitrary operand bundles yet!"); 2948 2949 const Value *Callee(I.getCalledOperand()); 2950 const Function *Fn = dyn_cast<Function>(Callee); 2951 if (isa<InlineAsm>(Callee)) 2952 visitInlineAsm(I, EHPadBB); 2953 else if (Fn && Fn->isIntrinsic()) { 2954 switch (Fn->getIntrinsicID()) { 2955 default: 2956 llvm_unreachable("Cannot invoke this intrinsic"); 2957 case Intrinsic::donothing: 2958 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2959 case Intrinsic::seh_try_begin: 2960 case Intrinsic::seh_scope_begin: 2961 case Intrinsic::seh_try_end: 2962 case Intrinsic::seh_scope_end: 2963 break; 2964 case Intrinsic::experimental_patchpoint_void: 2965 case Intrinsic::experimental_patchpoint_i64: 2966 visitPatchpoint(I, EHPadBB); 2967 break; 2968 case Intrinsic::experimental_gc_statepoint: 2969 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2970 break; 2971 case Intrinsic::wasm_rethrow: { 2972 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2973 // special because it can be invoked, so we manually lower it to a DAG 2974 // node here. 2975 SmallVector<SDValue, 8> Ops; 2976 Ops.push_back(getRoot()); // inchain 2977 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2978 Ops.push_back( 2979 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2980 TLI.getPointerTy(DAG.getDataLayout()))); 2981 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2982 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2983 break; 2984 } 2985 } 2986 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2987 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2988 // Eventually we will support lowering the @llvm.experimental.deoptimize 2989 // intrinsic, and right now there are no plans to support other intrinsics 2990 // with deopt state. 2991 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2992 } else { 2993 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 2994 } 2995 2996 // If the value of the invoke is used outside of its defining block, make it 2997 // available as a virtual register. 2998 // We already took care of the exported value for the statepoint instruction 2999 // during call to the LowerStatepoint. 3000 if (!isa<GCStatepointInst>(I)) { 3001 CopyToExportRegsIfNeeded(&I); 3002 } 3003 3004 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3005 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3006 BranchProbability EHPadBBProb = 3007 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3008 : BranchProbability::getZero(); 3009 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3010 3011 // Update successor info. 3012 addSuccessorWithProb(InvokeMBB, Return); 3013 for (auto &UnwindDest : UnwindDests) { 3014 UnwindDest.first->setIsEHPad(); 3015 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3016 } 3017 InvokeMBB->normalizeSuccProbs(); 3018 3019 // Drop into normal successor. 3020 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3021 DAG.getBasicBlock(Return))); 3022 } 3023 3024 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3025 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3026 3027 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3028 // have to do anything here to lower funclet bundles. 3029 assert(!I.hasOperandBundlesOtherThan( 3030 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3031 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3032 3033 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3034 visitInlineAsm(I); 3035 CopyToExportRegsIfNeeded(&I); 3036 3037 // Retrieve successors. 3038 SmallPtrSet<BasicBlock *, 8> Dests; 3039 Dests.insert(I.getDefaultDest()); 3040 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3041 3042 // Update successor info. 3043 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3044 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3045 BasicBlock *Dest = I.getIndirectDest(i); 3046 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3047 Target->setIsInlineAsmBrIndirectTarget(); 3048 Target->setMachineBlockAddressTaken(); 3049 Target->setLabelMustBeEmitted(); 3050 // Don't add duplicate machine successors. 3051 if (Dests.insert(Dest).second) 3052 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3053 } 3054 CallBrMBB->normalizeSuccProbs(); 3055 3056 // Drop into default successor. 3057 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3058 MVT::Other, getControlRoot(), 3059 DAG.getBasicBlock(Return))); 3060 } 3061 3062 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3063 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3064 } 3065 3066 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3067 assert(FuncInfo.MBB->isEHPad() && 3068 "Call to landingpad not in landing pad!"); 3069 3070 // If there aren't registers to copy the values into (e.g., during SjLj 3071 // exceptions), then don't bother to create these DAG nodes. 3072 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3073 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3074 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3075 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3076 return; 3077 3078 // If landingpad's return type is token type, we don't create DAG nodes 3079 // for its exception pointer and selector value. The extraction of exception 3080 // pointer or selector value from token type landingpads is not currently 3081 // supported. 3082 if (LP.getType()->isTokenTy()) 3083 return; 3084 3085 SmallVector<EVT, 2> ValueVTs; 3086 SDLoc dl = getCurSDLoc(); 3087 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3088 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3089 3090 // Get the two live-in registers as SDValues. The physregs have already been 3091 // copied into virtual registers. 3092 SDValue Ops[2]; 3093 if (FuncInfo.ExceptionPointerVirtReg) { 3094 Ops[0] = DAG.getZExtOrTrunc( 3095 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3096 FuncInfo.ExceptionPointerVirtReg, 3097 TLI.getPointerTy(DAG.getDataLayout())), 3098 dl, ValueVTs[0]); 3099 } else { 3100 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3101 } 3102 Ops[1] = DAG.getZExtOrTrunc( 3103 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3104 FuncInfo.ExceptionSelectorVirtReg, 3105 TLI.getPointerTy(DAG.getDataLayout())), 3106 dl, ValueVTs[1]); 3107 3108 // Merge into one. 3109 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3110 DAG.getVTList(ValueVTs), Ops); 3111 setValue(&LP, Res); 3112 } 3113 3114 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3115 MachineBasicBlock *Last) { 3116 // Update JTCases. 3117 for (JumpTableBlock &JTB : SL->JTCases) 3118 if (JTB.first.HeaderBB == First) 3119 JTB.first.HeaderBB = Last; 3120 3121 // Update BitTestCases. 3122 for (BitTestBlock &BTB : SL->BitTestCases) 3123 if (BTB.Parent == First) 3124 BTB.Parent = Last; 3125 } 3126 3127 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3128 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3129 3130 // Update machine-CFG edges with unique successors. 3131 SmallSet<BasicBlock*, 32> Done; 3132 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3133 BasicBlock *BB = I.getSuccessor(i); 3134 bool Inserted = Done.insert(BB).second; 3135 if (!Inserted) 3136 continue; 3137 3138 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3139 addSuccessorWithProb(IndirectBrMBB, Succ); 3140 } 3141 IndirectBrMBB->normalizeSuccProbs(); 3142 3143 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3144 MVT::Other, getControlRoot(), 3145 getValue(I.getAddress()))); 3146 } 3147 3148 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3149 if (!DAG.getTarget().Options.TrapUnreachable) 3150 return; 3151 3152 // We may be able to ignore unreachable behind a noreturn call. 3153 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3154 const BasicBlock &BB = *I.getParent(); 3155 if (&I != &BB.front()) { 3156 BasicBlock::const_iterator PredI = 3157 std::prev(BasicBlock::const_iterator(&I)); 3158 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3159 if (Call->doesNotReturn()) 3160 return; 3161 } 3162 } 3163 } 3164 3165 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3166 } 3167 3168 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3169 SDNodeFlags Flags; 3170 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3171 Flags.copyFMF(*FPOp); 3172 3173 SDValue Op = getValue(I.getOperand(0)); 3174 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3175 Op, Flags); 3176 setValue(&I, UnNodeValue); 3177 } 3178 3179 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3180 SDNodeFlags Flags; 3181 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3182 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3183 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3184 } 3185 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3186 Flags.setExact(ExactOp->isExact()); 3187 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3188 Flags.copyFMF(*FPOp); 3189 3190 SDValue Op1 = getValue(I.getOperand(0)); 3191 SDValue Op2 = getValue(I.getOperand(1)); 3192 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3193 Op1, Op2, Flags); 3194 setValue(&I, BinNodeValue); 3195 } 3196 3197 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3198 SDValue Op1 = getValue(I.getOperand(0)); 3199 SDValue Op2 = getValue(I.getOperand(1)); 3200 3201 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3202 Op1.getValueType(), DAG.getDataLayout()); 3203 3204 // Coerce the shift amount to the right type if we can. This exposes the 3205 // truncate or zext to optimization early. 3206 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3207 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3208 "Unexpected shift type"); 3209 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3210 } 3211 3212 bool nuw = false; 3213 bool nsw = false; 3214 bool exact = false; 3215 3216 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3217 3218 if (const OverflowingBinaryOperator *OFBinOp = 3219 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3220 nuw = OFBinOp->hasNoUnsignedWrap(); 3221 nsw = OFBinOp->hasNoSignedWrap(); 3222 } 3223 if (const PossiblyExactOperator *ExactOp = 3224 dyn_cast<const PossiblyExactOperator>(&I)) 3225 exact = ExactOp->isExact(); 3226 } 3227 SDNodeFlags Flags; 3228 Flags.setExact(exact); 3229 Flags.setNoSignedWrap(nsw); 3230 Flags.setNoUnsignedWrap(nuw); 3231 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3232 Flags); 3233 setValue(&I, Res); 3234 } 3235 3236 void SelectionDAGBuilder::visitSDiv(const User &I) { 3237 SDValue Op1 = getValue(I.getOperand(0)); 3238 SDValue Op2 = getValue(I.getOperand(1)); 3239 3240 SDNodeFlags Flags; 3241 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3242 cast<PossiblyExactOperator>(&I)->isExact()); 3243 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3244 Op2, Flags)); 3245 } 3246 3247 void SelectionDAGBuilder::visitICmp(const User &I) { 3248 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3249 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3250 predicate = IC->getPredicate(); 3251 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3252 predicate = ICmpInst::Predicate(IC->getPredicate()); 3253 SDValue Op1 = getValue(I.getOperand(0)); 3254 SDValue Op2 = getValue(I.getOperand(1)); 3255 ISD::CondCode Opcode = getICmpCondCode(predicate); 3256 3257 auto &TLI = DAG.getTargetLoweringInfo(); 3258 EVT MemVT = 3259 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3260 3261 // If a pointer's DAG type is larger than its memory type then the DAG values 3262 // are zero-extended. This breaks signed comparisons so truncate back to the 3263 // underlying type before doing the compare. 3264 if (Op1.getValueType() != MemVT) { 3265 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3266 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3267 } 3268 3269 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3270 I.getType()); 3271 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3272 } 3273 3274 void SelectionDAGBuilder::visitFCmp(const User &I) { 3275 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3276 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3277 predicate = FC->getPredicate(); 3278 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3279 predicate = FCmpInst::Predicate(FC->getPredicate()); 3280 SDValue Op1 = getValue(I.getOperand(0)); 3281 SDValue Op2 = getValue(I.getOperand(1)); 3282 3283 ISD::CondCode Condition = getFCmpCondCode(predicate); 3284 auto *FPMO = cast<FPMathOperator>(&I); 3285 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3286 Condition = getFCmpCodeWithoutNaN(Condition); 3287 3288 SDNodeFlags Flags; 3289 Flags.copyFMF(*FPMO); 3290 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3291 3292 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3293 I.getType()); 3294 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3295 } 3296 3297 // Check if the condition of the select has one use or two users that are both 3298 // selects with the same condition. 3299 static bool hasOnlySelectUsers(const Value *Cond) { 3300 return llvm::all_of(Cond->users(), [](const Value *V) { 3301 return isa<SelectInst>(V); 3302 }); 3303 } 3304 3305 void SelectionDAGBuilder::visitSelect(const User &I) { 3306 SmallVector<EVT, 4> ValueVTs; 3307 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3308 ValueVTs); 3309 unsigned NumValues = ValueVTs.size(); 3310 if (NumValues == 0) return; 3311 3312 SmallVector<SDValue, 4> Values(NumValues); 3313 SDValue Cond = getValue(I.getOperand(0)); 3314 SDValue LHSVal = getValue(I.getOperand(1)); 3315 SDValue RHSVal = getValue(I.getOperand(2)); 3316 SmallVector<SDValue, 1> BaseOps(1, Cond); 3317 ISD::NodeType OpCode = 3318 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3319 3320 bool IsUnaryAbs = false; 3321 bool Negate = false; 3322 3323 SDNodeFlags Flags; 3324 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3325 Flags.copyFMF(*FPOp); 3326 3327 // Min/max matching is only viable if all output VTs are the same. 3328 if (all_equal(ValueVTs)) { 3329 EVT VT = ValueVTs[0]; 3330 LLVMContext &Ctx = *DAG.getContext(); 3331 auto &TLI = DAG.getTargetLoweringInfo(); 3332 3333 // We care about the legality of the operation after it has been type 3334 // legalized. 3335 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3336 VT = TLI.getTypeToTransformTo(Ctx, VT); 3337 3338 // If the vselect is legal, assume we want to leave this as a vector setcc + 3339 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3340 // min/max is legal on the scalar type. 3341 bool UseScalarMinMax = VT.isVector() && 3342 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3343 3344 Value *LHS, *RHS; 3345 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3346 ISD::NodeType Opc = ISD::DELETED_NODE; 3347 switch (SPR.Flavor) { 3348 case SPF_UMAX: Opc = ISD::UMAX; break; 3349 case SPF_UMIN: Opc = ISD::UMIN; break; 3350 case SPF_SMAX: Opc = ISD::SMAX; break; 3351 case SPF_SMIN: Opc = ISD::SMIN; break; 3352 case SPF_FMINNUM: 3353 switch (SPR.NaNBehavior) { 3354 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3355 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3356 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3357 case SPNB_RETURNS_ANY: { 3358 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3359 Opc = ISD::FMINNUM; 3360 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3361 Opc = ISD::FMINIMUM; 3362 else if (UseScalarMinMax) 3363 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3364 ISD::FMINNUM : ISD::FMINIMUM; 3365 break; 3366 } 3367 } 3368 break; 3369 case SPF_FMAXNUM: 3370 switch (SPR.NaNBehavior) { 3371 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3372 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3373 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3374 case SPNB_RETURNS_ANY: 3375 3376 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3377 Opc = ISD::FMAXNUM; 3378 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3379 Opc = ISD::FMAXIMUM; 3380 else if (UseScalarMinMax) 3381 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3382 ISD::FMAXNUM : ISD::FMAXIMUM; 3383 break; 3384 } 3385 break; 3386 case SPF_NABS: 3387 Negate = true; 3388 [[fallthrough]]; 3389 case SPF_ABS: 3390 IsUnaryAbs = true; 3391 Opc = ISD::ABS; 3392 break; 3393 default: break; 3394 } 3395 3396 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3397 (TLI.isOperationLegalOrCustom(Opc, VT) || 3398 (UseScalarMinMax && 3399 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3400 // If the underlying comparison instruction is used by any other 3401 // instruction, the consumed instructions won't be destroyed, so it is 3402 // not profitable to convert to a min/max. 3403 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3404 OpCode = Opc; 3405 LHSVal = getValue(LHS); 3406 RHSVal = getValue(RHS); 3407 BaseOps.clear(); 3408 } 3409 3410 if (IsUnaryAbs) { 3411 OpCode = Opc; 3412 LHSVal = getValue(LHS); 3413 BaseOps.clear(); 3414 } 3415 } 3416 3417 if (IsUnaryAbs) { 3418 for (unsigned i = 0; i != NumValues; ++i) { 3419 SDLoc dl = getCurSDLoc(); 3420 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3421 Values[i] = 3422 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3423 if (Negate) 3424 Values[i] = DAG.getNegative(Values[i], dl, VT); 3425 } 3426 } else { 3427 for (unsigned i = 0; i != NumValues; ++i) { 3428 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3429 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3430 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3431 Values[i] = DAG.getNode( 3432 OpCode, getCurSDLoc(), 3433 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3434 } 3435 } 3436 3437 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3438 DAG.getVTList(ValueVTs), Values)); 3439 } 3440 3441 void SelectionDAGBuilder::visitTrunc(const User &I) { 3442 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3443 SDValue N = getValue(I.getOperand(0)); 3444 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3445 I.getType()); 3446 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3447 } 3448 3449 void SelectionDAGBuilder::visitZExt(const User &I) { 3450 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3451 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3452 SDValue N = getValue(I.getOperand(0)); 3453 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3454 I.getType()); 3455 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3456 } 3457 3458 void SelectionDAGBuilder::visitSExt(const User &I) { 3459 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3460 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3461 SDValue N = getValue(I.getOperand(0)); 3462 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3463 I.getType()); 3464 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3465 } 3466 3467 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3468 // FPTrunc is never a no-op cast, no need to check 3469 SDValue N = getValue(I.getOperand(0)); 3470 SDLoc dl = getCurSDLoc(); 3471 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3472 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3473 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3474 DAG.getTargetConstant( 3475 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3476 } 3477 3478 void SelectionDAGBuilder::visitFPExt(const User &I) { 3479 // FPExt 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_EXTEND, getCurSDLoc(), DestVT, N)); 3484 } 3485 3486 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3487 // FPToUI 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_UINT, getCurSDLoc(), DestVT, N)); 3492 } 3493 3494 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3495 // FPToSI 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::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3500 } 3501 3502 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3503 // UIToFP 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::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3508 } 3509 3510 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3511 // SIToFP is never a no-op cast, no need to check 3512 SDValue N = getValue(I.getOperand(0)); 3513 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3514 I.getType()); 3515 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3516 } 3517 3518 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3519 // What to do depends on the size of the integer and the size of the pointer. 3520 // We can either truncate, zero extend, or no-op, accordingly. 3521 SDValue N = getValue(I.getOperand(0)); 3522 auto &TLI = DAG.getTargetLoweringInfo(); 3523 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3524 I.getType()); 3525 EVT PtrMemVT = 3526 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3527 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3528 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3529 setValue(&I, N); 3530 } 3531 3532 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3533 // What to do depends on the size of the integer and the size of the pointer. 3534 // We can either truncate, zero extend, or no-op, accordingly. 3535 SDValue N = getValue(I.getOperand(0)); 3536 auto &TLI = DAG.getTargetLoweringInfo(); 3537 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3538 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3539 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3540 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3541 setValue(&I, N); 3542 } 3543 3544 void SelectionDAGBuilder::visitBitCast(const User &I) { 3545 SDValue N = getValue(I.getOperand(0)); 3546 SDLoc dl = getCurSDLoc(); 3547 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3548 I.getType()); 3549 3550 // BitCast assures us that source and destination are the same size so this is 3551 // either a BITCAST or a no-op. 3552 if (DestVT != N.getValueType()) 3553 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3554 DestVT, N)); // convert types. 3555 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3556 // might fold any kind of constant expression to an integer constant and that 3557 // is not what we are looking for. Only recognize a bitcast of a genuine 3558 // constant integer as an opaque constant. 3559 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3560 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3561 /*isOpaque*/true)); 3562 else 3563 setValue(&I, N); // noop cast. 3564 } 3565 3566 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3567 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3568 const Value *SV = I.getOperand(0); 3569 SDValue N = getValue(SV); 3570 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3571 3572 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3573 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3574 3575 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3576 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3577 3578 setValue(&I, N); 3579 } 3580 3581 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3582 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3583 SDValue InVec = getValue(I.getOperand(0)); 3584 SDValue InVal = getValue(I.getOperand(1)); 3585 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3586 TLI.getVectorIdxTy(DAG.getDataLayout())); 3587 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3588 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3589 InVec, InVal, InIdx)); 3590 } 3591 3592 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3593 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3594 SDValue InVec = getValue(I.getOperand(0)); 3595 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3596 TLI.getVectorIdxTy(DAG.getDataLayout())); 3597 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3598 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3599 InVec, InIdx)); 3600 } 3601 3602 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3603 SDValue Src1 = getValue(I.getOperand(0)); 3604 SDValue Src2 = getValue(I.getOperand(1)); 3605 ArrayRef<int> Mask; 3606 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3607 Mask = SVI->getShuffleMask(); 3608 else 3609 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3610 SDLoc DL = getCurSDLoc(); 3611 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3612 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3613 EVT SrcVT = Src1.getValueType(); 3614 3615 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3616 VT.isScalableVector()) { 3617 // Canonical splat form of first element of first input vector. 3618 SDValue FirstElt = 3619 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3620 DAG.getVectorIdxConstant(0, DL)); 3621 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3622 return; 3623 } 3624 3625 // For now, we only handle splats for scalable vectors. 3626 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3627 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3628 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3629 3630 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3631 unsigned MaskNumElts = Mask.size(); 3632 3633 if (SrcNumElts == MaskNumElts) { 3634 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3635 return; 3636 } 3637 3638 // Normalize the shuffle vector since mask and vector length don't match. 3639 if (SrcNumElts < MaskNumElts) { 3640 // Mask is longer than the source vectors. We can use concatenate vector to 3641 // make the mask and vectors lengths match. 3642 3643 if (MaskNumElts % SrcNumElts == 0) { 3644 // Mask length is a multiple of the source vector length. 3645 // Check if the shuffle is some kind of concatenation of the input 3646 // vectors. 3647 unsigned NumConcat = MaskNumElts / SrcNumElts; 3648 bool IsConcat = true; 3649 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3650 for (unsigned i = 0; i != MaskNumElts; ++i) { 3651 int Idx = Mask[i]; 3652 if (Idx < 0) 3653 continue; 3654 // Ensure the indices in each SrcVT sized piece are sequential and that 3655 // the same source is used for the whole piece. 3656 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3657 (ConcatSrcs[i / SrcNumElts] >= 0 && 3658 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3659 IsConcat = false; 3660 break; 3661 } 3662 // Remember which source this index came from. 3663 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3664 } 3665 3666 // The shuffle is concatenating multiple vectors together. Just emit 3667 // a CONCAT_VECTORS operation. 3668 if (IsConcat) { 3669 SmallVector<SDValue, 8> ConcatOps; 3670 for (auto Src : ConcatSrcs) { 3671 if (Src < 0) 3672 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3673 else if (Src == 0) 3674 ConcatOps.push_back(Src1); 3675 else 3676 ConcatOps.push_back(Src2); 3677 } 3678 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3679 return; 3680 } 3681 } 3682 3683 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3684 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3685 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3686 PaddedMaskNumElts); 3687 3688 // Pad both vectors with undefs to make them the same length as the mask. 3689 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3690 3691 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3692 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3693 MOps1[0] = Src1; 3694 MOps2[0] = Src2; 3695 3696 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3697 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3698 3699 // Readjust mask for new input vector length. 3700 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3701 for (unsigned i = 0; i != MaskNumElts; ++i) { 3702 int Idx = Mask[i]; 3703 if (Idx >= (int)SrcNumElts) 3704 Idx -= SrcNumElts - PaddedMaskNumElts; 3705 MappedOps[i] = Idx; 3706 } 3707 3708 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3709 3710 // If the concatenated vector was padded, extract a subvector with the 3711 // correct number of elements. 3712 if (MaskNumElts != PaddedMaskNumElts) 3713 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3714 DAG.getVectorIdxConstant(0, DL)); 3715 3716 setValue(&I, Result); 3717 return; 3718 } 3719 3720 if (SrcNumElts > MaskNumElts) { 3721 // Analyze the access pattern of the vector to see if we can extract 3722 // two subvectors and do the shuffle. 3723 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3724 bool CanExtract = true; 3725 for (int Idx : Mask) { 3726 unsigned Input = 0; 3727 if (Idx < 0) 3728 continue; 3729 3730 if (Idx >= (int)SrcNumElts) { 3731 Input = 1; 3732 Idx -= SrcNumElts; 3733 } 3734 3735 // If all the indices come from the same MaskNumElts sized portion of 3736 // the sources we can use extract. Also make sure the extract wouldn't 3737 // extract past the end of the source. 3738 int NewStartIdx = alignDown(Idx, MaskNumElts); 3739 if (NewStartIdx + MaskNumElts > SrcNumElts || 3740 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3741 CanExtract = false; 3742 // Make sure we always update StartIdx as we use it to track if all 3743 // elements are undef. 3744 StartIdx[Input] = NewStartIdx; 3745 } 3746 3747 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3748 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3749 return; 3750 } 3751 if (CanExtract) { 3752 // Extract appropriate subvector and generate a vector shuffle 3753 for (unsigned Input = 0; Input < 2; ++Input) { 3754 SDValue &Src = Input == 0 ? Src1 : Src2; 3755 if (StartIdx[Input] < 0) 3756 Src = DAG.getUNDEF(VT); 3757 else { 3758 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3759 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3760 } 3761 } 3762 3763 // Calculate new mask. 3764 SmallVector<int, 8> MappedOps(Mask); 3765 for (int &Idx : MappedOps) { 3766 if (Idx >= (int)SrcNumElts) 3767 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3768 else if (Idx >= 0) 3769 Idx -= StartIdx[0]; 3770 } 3771 3772 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3773 return; 3774 } 3775 } 3776 3777 // We can't use either concat vectors or extract subvectors so fall back to 3778 // replacing the shuffle with extract and build vector. 3779 // to insert and build vector. 3780 EVT EltVT = VT.getVectorElementType(); 3781 SmallVector<SDValue,8> Ops; 3782 for (int Idx : Mask) { 3783 SDValue Res; 3784 3785 if (Idx < 0) { 3786 Res = DAG.getUNDEF(EltVT); 3787 } else { 3788 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3789 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3790 3791 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3792 DAG.getVectorIdxConstant(Idx, DL)); 3793 } 3794 3795 Ops.push_back(Res); 3796 } 3797 3798 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3799 } 3800 3801 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3802 ArrayRef<unsigned> Indices = I.getIndices(); 3803 const Value *Op0 = I.getOperand(0); 3804 const Value *Op1 = I.getOperand(1); 3805 Type *AggTy = I.getType(); 3806 Type *ValTy = Op1->getType(); 3807 bool IntoUndef = isa<UndefValue>(Op0); 3808 bool FromUndef = isa<UndefValue>(Op1); 3809 3810 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3811 3812 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3813 SmallVector<EVT, 4> AggValueVTs; 3814 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3815 SmallVector<EVT, 4> ValValueVTs; 3816 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3817 3818 unsigned NumAggValues = AggValueVTs.size(); 3819 unsigned NumValValues = ValValueVTs.size(); 3820 SmallVector<SDValue, 4> Values(NumAggValues); 3821 3822 // Ignore an insertvalue that produces an empty object 3823 if (!NumAggValues) { 3824 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3825 return; 3826 } 3827 3828 SDValue Agg = getValue(Op0); 3829 unsigned i = 0; 3830 // Copy the beginning value(s) from the original aggregate. 3831 for (; i != LinearIndex; ++i) 3832 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3833 SDValue(Agg.getNode(), Agg.getResNo() + i); 3834 // Copy values from the inserted value(s). 3835 if (NumValValues) { 3836 SDValue Val = getValue(Op1); 3837 for (; i != LinearIndex + NumValValues; ++i) 3838 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3839 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3840 } 3841 // Copy remaining value(s) from the original aggregate. 3842 for (; i != NumAggValues; ++i) 3843 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3844 SDValue(Agg.getNode(), Agg.getResNo() + i); 3845 3846 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3847 DAG.getVTList(AggValueVTs), Values)); 3848 } 3849 3850 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3851 ArrayRef<unsigned> Indices = I.getIndices(); 3852 const Value *Op0 = I.getOperand(0); 3853 Type *AggTy = Op0->getType(); 3854 Type *ValTy = I.getType(); 3855 bool OutOfUndef = isa<UndefValue>(Op0); 3856 3857 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3858 3859 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3860 SmallVector<EVT, 4> ValValueVTs; 3861 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3862 3863 unsigned NumValValues = ValValueVTs.size(); 3864 3865 // Ignore a extractvalue that produces an empty object 3866 if (!NumValValues) { 3867 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3868 return; 3869 } 3870 3871 SmallVector<SDValue, 4> Values(NumValValues); 3872 3873 SDValue Agg = getValue(Op0); 3874 // Copy out the selected value(s). 3875 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3876 Values[i - LinearIndex] = 3877 OutOfUndef ? 3878 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3879 SDValue(Agg.getNode(), Agg.getResNo() + i); 3880 3881 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3882 DAG.getVTList(ValValueVTs), Values)); 3883 } 3884 3885 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3886 Value *Op0 = I.getOperand(0); 3887 // Note that the pointer operand may be a vector of pointers. Take the scalar 3888 // element which holds a pointer. 3889 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3890 SDValue N = getValue(Op0); 3891 SDLoc dl = getCurSDLoc(); 3892 auto &TLI = DAG.getTargetLoweringInfo(); 3893 3894 // Normalize Vector GEP - all scalar operands should be converted to the 3895 // splat vector. 3896 bool IsVectorGEP = I.getType()->isVectorTy(); 3897 ElementCount VectorElementCount = 3898 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3899 : ElementCount::getFixed(0); 3900 3901 if (IsVectorGEP && !N.getValueType().isVector()) { 3902 LLVMContext &Context = *DAG.getContext(); 3903 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3904 N = DAG.getSplat(VT, dl, N); 3905 } 3906 3907 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3908 GTI != E; ++GTI) { 3909 const Value *Idx = GTI.getOperand(); 3910 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3911 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3912 if (Field) { 3913 // N = N + Offset 3914 uint64_t Offset = 3915 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3916 3917 // In an inbounds GEP with an offset that is nonnegative even when 3918 // interpreted as signed, assume there is no unsigned overflow. 3919 SDNodeFlags Flags; 3920 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3921 Flags.setNoUnsignedWrap(true); 3922 3923 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3924 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3925 } 3926 } else { 3927 // IdxSize is the width of the arithmetic according to IR semantics. 3928 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3929 // (and fix up the result later). 3930 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3931 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3932 TypeSize ElementSize = 3933 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3934 // We intentionally mask away the high bits here; ElementSize may not 3935 // fit in IdxTy. 3936 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3937 bool ElementScalable = ElementSize.isScalable(); 3938 3939 // If this is a scalar constant or a splat vector of constants, 3940 // handle it quickly. 3941 const auto *C = dyn_cast<Constant>(Idx); 3942 if (C && isa<VectorType>(C->getType())) 3943 C = C->getSplatValue(); 3944 3945 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3946 if (CI && CI->isZero()) 3947 continue; 3948 if (CI && !ElementScalable) { 3949 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3950 LLVMContext &Context = *DAG.getContext(); 3951 SDValue OffsVal; 3952 if (IsVectorGEP) 3953 OffsVal = DAG.getConstant( 3954 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3955 else 3956 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3957 3958 // In an inbounds GEP with an offset that is nonnegative even when 3959 // interpreted as signed, assume there is no unsigned overflow. 3960 SDNodeFlags Flags; 3961 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3962 Flags.setNoUnsignedWrap(true); 3963 3964 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3965 3966 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3967 continue; 3968 } 3969 3970 // N = N + Idx * ElementMul; 3971 SDValue IdxN = getValue(Idx); 3972 3973 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3974 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3975 VectorElementCount); 3976 IdxN = DAG.getSplat(VT, dl, IdxN); 3977 } 3978 3979 // If the index is smaller or larger than intptr_t, truncate or extend 3980 // it. 3981 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3982 3983 if (ElementScalable) { 3984 EVT VScaleTy = N.getValueType().getScalarType(); 3985 SDValue VScale = DAG.getNode( 3986 ISD::VSCALE, dl, VScaleTy, 3987 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3988 if (IsVectorGEP) 3989 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3990 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3991 } else { 3992 // If this is a multiply by a power of two, turn it into a shl 3993 // immediately. This is a very common case. 3994 if (ElementMul != 1) { 3995 if (ElementMul.isPowerOf2()) { 3996 unsigned Amt = ElementMul.logBase2(); 3997 IdxN = DAG.getNode(ISD::SHL, dl, 3998 N.getValueType(), IdxN, 3999 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4000 } else { 4001 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4002 IdxN.getValueType()); 4003 IdxN = DAG.getNode(ISD::MUL, dl, 4004 N.getValueType(), IdxN, Scale); 4005 } 4006 } 4007 } 4008 4009 N = DAG.getNode(ISD::ADD, dl, 4010 N.getValueType(), N, IdxN); 4011 } 4012 } 4013 4014 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4015 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4016 if (IsVectorGEP) { 4017 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4018 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4019 } 4020 4021 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4022 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4023 4024 setValue(&I, N); 4025 } 4026 4027 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4028 // If this is a fixed sized alloca in the entry block of the function, 4029 // allocate it statically on the stack. 4030 if (FuncInfo.StaticAllocaMap.count(&I)) 4031 return; // getValue will auto-populate this. 4032 4033 SDLoc dl = getCurSDLoc(); 4034 Type *Ty = I.getAllocatedType(); 4035 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4036 auto &DL = DAG.getDataLayout(); 4037 TypeSize TySize = DL.getTypeAllocSize(Ty); 4038 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4039 4040 SDValue AllocSize = getValue(I.getArraySize()); 4041 4042 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 4043 if (AllocSize.getValueType() != IntPtr) 4044 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4045 4046 if (TySize.isScalable()) 4047 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4048 DAG.getVScale(dl, IntPtr, 4049 APInt(IntPtr.getScalarSizeInBits(), 4050 TySize.getKnownMinValue()))); 4051 else 4052 AllocSize = 4053 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4054 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4055 4056 // Handle alignment. If the requested alignment is less than or equal to 4057 // the stack alignment, ignore it. If the size is greater than or equal to 4058 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4059 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4060 if (*Alignment <= StackAlign) 4061 Alignment = None; 4062 4063 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4064 // Round the size of the allocation up to the stack alignment size 4065 // by add SA-1 to the size. This doesn't overflow because we're computing 4066 // an address inside an alloca. 4067 SDNodeFlags Flags; 4068 Flags.setNoUnsignedWrap(true); 4069 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4070 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4071 4072 // Mask out the low bits for alignment purposes. 4073 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4074 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4075 4076 SDValue Ops[] = { 4077 getRoot(), AllocSize, 4078 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4079 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4080 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4081 setValue(&I, DSA); 4082 DAG.setRoot(DSA.getValue(1)); 4083 4084 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4085 } 4086 4087 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4088 if (I.isAtomic()) 4089 return visitAtomicLoad(I); 4090 4091 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4092 const Value *SV = I.getOperand(0); 4093 if (TLI.supportSwiftError()) { 4094 // Swifterror values can come from either a function parameter with 4095 // swifterror attribute or an alloca with swifterror attribute. 4096 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4097 if (Arg->hasSwiftErrorAttr()) 4098 return visitLoadFromSwiftError(I); 4099 } 4100 4101 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4102 if (Alloca->isSwiftError()) 4103 return visitLoadFromSwiftError(I); 4104 } 4105 } 4106 4107 SDValue Ptr = getValue(SV); 4108 4109 Type *Ty = I.getType(); 4110 SmallVector<EVT, 4> ValueVTs, MemVTs; 4111 SmallVector<uint64_t, 4> Offsets; 4112 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4113 unsigned NumValues = ValueVTs.size(); 4114 if (NumValues == 0) 4115 return; 4116 4117 Align Alignment = I.getAlign(); 4118 AAMDNodes AAInfo = I.getAAMetadata(); 4119 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4120 bool isVolatile = I.isVolatile(); 4121 MachineMemOperand::Flags MMOFlags = 4122 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4123 4124 SDValue Root; 4125 bool ConstantMemory = false; 4126 if (isVolatile) 4127 // Serialize volatile loads with other side effects. 4128 Root = getRoot(); 4129 else if (NumValues > MaxParallelChains) 4130 Root = getMemoryRoot(); 4131 else if (AA && 4132 AA->pointsToConstantMemory(MemoryLocation( 4133 SV, 4134 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4135 AAInfo))) { 4136 // Do not serialize (non-volatile) loads of constant memory with anything. 4137 Root = DAG.getEntryNode(); 4138 ConstantMemory = true; 4139 MMOFlags |= MachineMemOperand::MOInvariant; 4140 } else { 4141 // Do not serialize non-volatile loads against each other. 4142 Root = DAG.getRoot(); 4143 } 4144 4145 if (isDereferenceableAndAlignedPointer(SV, Ty, Alignment, DAG.getDataLayout(), 4146 &I, AC, nullptr, LibInfo)) 4147 MMOFlags |= MachineMemOperand::MODereferenceable; 4148 4149 SDLoc dl = getCurSDLoc(); 4150 4151 if (isVolatile) 4152 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4153 4154 // An aggregate load cannot wrap around the address space, so offsets to its 4155 // parts don't wrap either. 4156 SDNodeFlags Flags; 4157 Flags.setNoUnsignedWrap(true); 4158 4159 SmallVector<SDValue, 4> Values(NumValues); 4160 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4161 EVT PtrVT = Ptr.getValueType(); 4162 4163 unsigned ChainI = 0; 4164 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4165 // Serializing loads here may result in excessive register pressure, and 4166 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4167 // could recover a bit by hoisting nodes upward in the chain by recognizing 4168 // they are side-effect free or do not alias. The optimizer should really 4169 // avoid this case by converting large object/array copies to llvm.memcpy 4170 // (MaxParallelChains should always remain as failsafe). 4171 if (ChainI == MaxParallelChains) { 4172 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4173 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4174 makeArrayRef(Chains.data(), ChainI)); 4175 Root = Chain; 4176 ChainI = 0; 4177 } 4178 SDValue A = DAG.getNode(ISD::ADD, dl, 4179 PtrVT, Ptr, 4180 DAG.getConstant(Offsets[i], dl, PtrVT), 4181 Flags); 4182 4183 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4184 MachinePointerInfo(SV, Offsets[i]), Alignment, 4185 MMOFlags, AAInfo, Ranges); 4186 Chains[ChainI] = L.getValue(1); 4187 4188 if (MemVTs[i] != ValueVTs[i]) 4189 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4190 4191 Values[i] = L; 4192 } 4193 4194 if (!ConstantMemory) { 4195 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4196 makeArrayRef(Chains.data(), ChainI)); 4197 if (isVolatile) 4198 DAG.setRoot(Chain); 4199 else 4200 PendingLoads.push_back(Chain); 4201 } 4202 4203 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4204 DAG.getVTList(ValueVTs), Values)); 4205 } 4206 4207 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4208 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4209 "call visitStoreToSwiftError when backend supports swifterror"); 4210 4211 SmallVector<EVT, 4> ValueVTs; 4212 SmallVector<uint64_t, 4> Offsets; 4213 const Value *SrcV = I.getOperand(0); 4214 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4215 SrcV->getType(), ValueVTs, &Offsets); 4216 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4217 "expect a single EVT for swifterror"); 4218 4219 SDValue Src = getValue(SrcV); 4220 // Create a virtual register, then update the virtual register. 4221 Register VReg = 4222 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4223 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4224 // Chain can be getRoot or getControlRoot. 4225 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4226 SDValue(Src.getNode(), Src.getResNo())); 4227 DAG.setRoot(CopyNode); 4228 } 4229 4230 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4231 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4232 "call visitLoadFromSwiftError when backend supports swifterror"); 4233 4234 assert(!I.isVolatile() && 4235 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4236 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4237 "Support volatile, non temporal, invariant for load_from_swift_error"); 4238 4239 const Value *SV = I.getOperand(0); 4240 Type *Ty = I.getType(); 4241 assert( 4242 (!AA || 4243 !AA->pointsToConstantMemory(MemoryLocation( 4244 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4245 I.getAAMetadata()))) && 4246 "load_from_swift_error should not be constant memory"); 4247 4248 SmallVector<EVT, 4> ValueVTs; 4249 SmallVector<uint64_t, 4> Offsets; 4250 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4251 ValueVTs, &Offsets); 4252 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4253 "expect a single EVT for swifterror"); 4254 4255 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4256 SDValue L = DAG.getCopyFromReg( 4257 getRoot(), getCurSDLoc(), 4258 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4259 4260 setValue(&I, L); 4261 } 4262 4263 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4264 if (I.isAtomic()) 4265 return visitAtomicStore(I); 4266 4267 const Value *SrcV = I.getOperand(0); 4268 const Value *PtrV = I.getOperand(1); 4269 4270 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4271 if (TLI.supportSwiftError()) { 4272 // Swifterror values can come from either a function parameter with 4273 // swifterror attribute or an alloca with swifterror attribute. 4274 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4275 if (Arg->hasSwiftErrorAttr()) 4276 return visitStoreToSwiftError(I); 4277 } 4278 4279 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4280 if (Alloca->isSwiftError()) 4281 return visitStoreToSwiftError(I); 4282 } 4283 } 4284 4285 SmallVector<EVT, 4> ValueVTs, MemVTs; 4286 SmallVector<uint64_t, 4> Offsets; 4287 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4288 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4289 unsigned NumValues = ValueVTs.size(); 4290 if (NumValues == 0) 4291 return; 4292 4293 // Get the lowered operands. Note that we do this after 4294 // checking if NumResults is zero, because with zero results 4295 // the operands won't have values in the map. 4296 SDValue Src = getValue(SrcV); 4297 SDValue Ptr = getValue(PtrV); 4298 4299 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4300 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4301 SDLoc dl = getCurSDLoc(); 4302 Align Alignment = I.getAlign(); 4303 AAMDNodes AAInfo = I.getAAMetadata(); 4304 4305 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4306 4307 // An aggregate load cannot wrap around the address space, so offsets to its 4308 // parts don't wrap either. 4309 SDNodeFlags Flags; 4310 Flags.setNoUnsignedWrap(true); 4311 4312 unsigned ChainI = 0; 4313 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4314 // See visitLoad comments. 4315 if (ChainI == MaxParallelChains) { 4316 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4317 makeArrayRef(Chains.data(), ChainI)); 4318 Root = Chain; 4319 ChainI = 0; 4320 } 4321 SDValue Add = 4322 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4323 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4324 if (MemVTs[i] != ValueVTs[i]) 4325 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4326 SDValue St = 4327 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4328 Alignment, MMOFlags, AAInfo); 4329 Chains[ChainI] = St; 4330 } 4331 4332 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4333 makeArrayRef(Chains.data(), ChainI)); 4334 setValue(&I, StoreNode); 4335 DAG.setRoot(StoreNode); 4336 } 4337 4338 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4339 bool IsCompressing) { 4340 SDLoc sdl = getCurSDLoc(); 4341 4342 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4343 MaybeAlign &Alignment) { 4344 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4345 Src0 = I.getArgOperand(0); 4346 Ptr = I.getArgOperand(1); 4347 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4348 Mask = I.getArgOperand(3); 4349 }; 4350 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4351 MaybeAlign &Alignment) { 4352 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4353 Src0 = I.getArgOperand(0); 4354 Ptr = I.getArgOperand(1); 4355 Mask = I.getArgOperand(2); 4356 Alignment = None; 4357 }; 4358 4359 Value *PtrOperand, *MaskOperand, *Src0Operand; 4360 MaybeAlign Alignment; 4361 if (IsCompressing) 4362 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4363 else 4364 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4365 4366 SDValue Ptr = getValue(PtrOperand); 4367 SDValue Src0 = getValue(Src0Operand); 4368 SDValue Mask = getValue(MaskOperand); 4369 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4370 4371 EVT VT = Src0.getValueType(); 4372 if (!Alignment) 4373 Alignment = DAG.getEVTAlign(VT); 4374 4375 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4376 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4377 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4378 SDValue StoreNode = 4379 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4380 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4381 DAG.setRoot(StoreNode); 4382 setValue(&I, StoreNode); 4383 } 4384 4385 // Get a uniform base for the Gather/Scatter intrinsic. 4386 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4387 // We try to represent it as a base pointer + vector of indices. 4388 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4389 // The first operand of the GEP may be a single pointer or a vector of pointers 4390 // Example: 4391 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4392 // or 4393 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4394 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4395 // 4396 // When the first GEP operand is a single pointer - it is the uniform base we 4397 // are looking for. If first operand of the GEP is a splat vector - we 4398 // extract the splat value and use it as a uniform base. 4399 // In all other cases the function returns 'false'. 4400 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4401 ISD::MemIndexType &IndexType, SDValue &Scale, 4402 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4403 uint64_t ElemSize) { 4404 SelectionDAG& DAG = SDB->DAG; 4405 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4406 const DataLayout &DL = DAG.getDataLayout(); 4407 4408 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4409 4410 // Handle splat constant pointer. 4411 if (auto *C = dyn_cast<Constant>(Ptr)) { 4412 C = C->getSplatValue(); 4413 if (!C) 4414 return false; 4415 4416 Base = SDB->getValue(C); 4417 4418 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4419 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4420 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4421 IndexType = ISD::SIGNED_SCALED; 4422 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4423 return true; 4424 } 4425 4426 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4427 if (!GEP || GEP->getParent() != CurBB) 4428 return false; 4429 4430 if (GEP->getNumOperands() != 2) 4431 return false; 4432 4433 const Value *BasePtr = GEP->getPointerOperand(); 4434 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4435 4436 // Make sure the base is scalar and the index is a vector. 4437 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4438 return false; 4439 4440 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4441 4442 // Target may not support the required addressing mode. 4443 if (ScaleVal != 1 && 4444 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4445 return false; 4446 4447 Base = SDB->getValue(BasePtr); 4448 Index = SDB->getValue(IndexVal); 4449 IndexType = ISD::SIGNED_SCALED; 4450 4451 Scale = 4452 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4453 return true; 4454 } 4455 4456 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4457 SDLoc sdl = getCurSDLoc(); 4458 4459 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4460 const Value *Ptr = I.getArgOperand(1); 4461 SDValue Src0 = getValue(I.getArgOperand(0)); 4462 SDValue Mask = getValue(I.getArgOperand(3)); 4463 EVT VT = Src0.getValueType(); 4464 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4465 ->getMaybeAlignValue() 4466 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4467 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4468 4469 SDValue Base; 4470 SDValue Index; 4471 ISD::MemIndexType IndexType; 4472 SDValue Scale; 4473 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4474 I.getParent(), VT.getScalarStoreSize()); 4475 4476 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4477 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4478 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4479 // TODO: Make MachineMemOperands aware of scalable 4480 // vectors. 4481 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4482 if (!UniformBase) { 4483 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4484 Index = getValue(Ptr); 4485 IndexType = ISD::SIGNED_SCALED; 4486 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4487 } 4488 4489 EVT IdxVT = Index.getValueType(); 4490 EVT EltTy = IdxVT.getVectorElementType(); 4491 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4492 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4493 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4494 } 4495 4496 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4497 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4498 Ops, MMO, IndexType, false); 4499 DAG.setRoot(Scatter); 4500 setValue(&I, Scatter); 4501 } 4502 4503 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4504 SDLoc sdl = getCurSDLoc(); 4505 4506 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4507 MaybeAlign &Alignment) { 4508 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4509 Ptr = I.getArgOperand(0); 4510 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4511 Mask = I.getArgOperand(2); 4512 Src0 = I.getArgOperand(3); 4513 }; 4514 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4515 MaybeAlign &Alignment) { 4516 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4517 Ptr = I.getArgOperand(0); 4518 Alignment = None; 4519 Mask = I.getArgOperand(1); 4520 Src0 = I.getArgOperand(2); 4521 }; 4522 4523 Value *PtrOperand, *MaskOperand, *Src0Operand; 4524 MaybeAlign Alignment; 4525 if (IsExpanding) 4526 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4527 else 4528 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4529 4530 SDValue Ptr = getValue(PtrOperand); 4531 SDValue Src0 = getValue(Src0Operand); 4532 SDValue Mask = getValue(MaskOperand); 4533 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4534 4535 EVT VT = Src0.getValueType(); 4536 if (!Alignment) 4537 Alignment = DAG.getEVTAlign(VT); 4538 4539 AAMDNodes AAInfo = I.getAAMetadata(); 4540 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4541 4542 // Do not serialize masked loads of constant memory with anything. 4543 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4544 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4545 4546 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4547 4548 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4549 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4550 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4551 4552 SDValue Load = 4553 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4554 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4555 if (AddToChain) 4556 PendingLoads.push_back(Load.getValue(1)); 4557 setValue(&I, Load); 4558 } 4559 4560 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4561 SDLoc sdl = getCurSDLoc(); 4562 4563 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4564 const Value *Ptr = I.getArgOperand(0); 4565 SDValue Src0 = getValue(I.getArgOperand(3)); 4566 SDValue Mask = getValue(I.getArgOperand(2)); 4567 4568 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4569 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4570 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4571 ->getMaybeAlignValue() 4572 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4573 4574 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4575 4576 SDValue Root = DAG.getRoot(); 4577 SDValue Base; 4578 SDValue Index; 4579 ISD::MemIndexType IndexType; 4580 SDValue Scale; 4581 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4582 I.getParent(), VT.getScalarStoreSize()); 4583 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4584 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4585 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4586 // TODO: Make MachineMemOperands aware of scalable 4587 // vectors. 4588 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4589 4590 if (!UniformBase) { 4591 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4592 Index = getValue(Ptr); 4593 IndexType = ISD::SIGNED_SCALED; 4594 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4595 } 4596 4597 EVT IdxVT = Index.getValueType(); 4598 EVT EltTy = IdxVT.getVectorElementType(); 4599 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4600 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4601 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4602 } 4603 4604 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4605 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4606 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4607 4608 PendingLoads.push_back(Gather.getValue(1)); 4609 setValue(&I, Gather); 4610 } 4611 4612 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4613 SDLoc dl = getCurSDLoc(); 4614 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4615 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4616 SyncScope::ID SSID = I.getSyncScopeID(); 4617 4618 SDValue InChain = getRoot(); 4619 4620 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4621 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4622 4623 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4624 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4625 4626 MachineFunction &MF = DAG.getMachineFunction(); 4627 MachineMemOperand *MMO = MF.getMachineMemOperand( 4628 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4629 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4630 FailureOrdering); 4631 4632 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4633 dl, MemVT, VTs, InChain, 4634 getValue(I.getPointerOperand()), 4635 getValue(I.getCompareOperand()), 4636 getValue(I.getNewValOperand()), MMO); 4637 4638 SDValue OutChain = L.getValue(2); 4639 4640 setValue(&I, L); 4641 DAG.setRoot(OutChain); 4642 } 4643 4644 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4645 SDLoc dl = getCurSDLoc(); 4646 ISD::NodeType NT; 4647 switch (I.getOperation()) { 4648 default: llvm_unreachable("Unknown atomicrmw operation"); 4649 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4650 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4651 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4652 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4653 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4654 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4655 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4656 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4657 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4658 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4659 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4660 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4661 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4662 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4663 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4664 } 4665 AtomicOrdering Ordering = I.getOrdering(); 4666 SyncScope::ID SSID = I.getSyncScopeID(); 4667 4668 SDValue InChain = getRoot(); 4669 4670 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4671 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4672 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4673 4674 MachineFunction &MF = DAG.getMachineFunction(); 4675 MachineMemOperand *MMO = MF.getMachineMemOperand( 4676 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4677 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4678 4679 SDValue L = 4680 DAG.getAtomic(NT, dl, MemVT, InChain, 4681 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4682 MMO); 4683 4684 SDValue OutChain = L.getValue(1); 4685 4686 setValue(&I, L); 4687 DAG.setRoot(OutChain); 4688 } 4689 4690 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4691 SDLoc dl = getCurSDLoc(); 4692 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4693 SDValue Ops[3]; 4694 Ops[0] = getRoot(); 4695 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4696 TLI.getFenceOperandTy(DAG.getDataLayout())); 4697 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4698 TLI.getFenceOperandTy(DAG.getDataLayout())); 4699 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4700 setValue(&I, N); 4701 DAG.setRoot(N); 4702 } 4703 4704 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4705 SDLoc dl = getCurSDLoc(); 4706 AtomicOrdering Order = I.getOrdering(); 4707 SyncScope::ID SSID = I.getSyncScopeID(); 4708 4709 SDValue InChain = getRoot(); 4710 4711 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4712 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4713 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4714 4715 if (!TLI.supportsUnalignedAtomics() && 4716 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4717 report_fatal_error("Cannot generate unaligned atomic load"); 4718 4719 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4720 4721 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4722 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4723 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4724 4725 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4726 4727 SDValue Ptr = getValue(I.getPointerOperand()); 4728 4729 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4730 // TODO: Once this is better exercised by tests, it should be merged with 4731 // the normal path for loads to prevent future divergence. 4732 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4733 if (MemVT != VT) 4734 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4735 4736 setValue(&I, L); 4737 SDValue OutChain = L.getValue(1); 4738 if (!I.isUnordered()) 4739 DAG.setRoot(OutChain); 4740 else 4741 PendingLoads.push_back(OutChain); 4742 return; 4743 } 4744 4745 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4746 Ptr, MMO); 4747 4748 SDValue OutChain = L.getValue(1); 4749 if (MemVT != VT) 4750 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4751 4752 setValue(&I, L); 4753 DAG.setRoot(OutChain); 4754 } 4755 4756 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4757 SDLoc dl = getCurSDLoc(); 4758 4759 AtomicOrdering Ordering = I.getOrdering(); 4760 SyncScope::ID SSID = I.getSyncScopeID(); 4761 4762 SDValue InChain = getRoot(); 4763 4764 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4765 EVT MemVT = 4766 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4767 4768 if (!TLI.supportsUnalignedAtomics() && 4769 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4770 report_fatal_error("Cannot generate unaligned atomic store"); 4771 4772 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4773 4774 MachineFunction &MF = DAG.getMachineFunction(); 4775 MachineMemOperand *MMO = MF.getMachineMemOperand( 4776 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4777 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4778 4779 SDValue Val = getValue(I.getValueOperand()); 4780 if (Val.getValueType() != MemVT) 4781 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4782 SDValue Ptr = getValue(I.getPointerOperand()); 4783 4784 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4785 // TODO: Once this is better exercised by tests, it should be merged with 4786 // the normal path for stores to prevent future divergence. 4787 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4788 setValue(&I, S); 4789 DAG.setRoot(S); 4790 return; 4791 } 4792 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4793 Ptr, Val, MMO); 4794 4795 setValue(&I, OutChain); 4796 DAG.setRoot(OutChain); 4797 } 4798 4799 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4800 /// node. 4801 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4802 unsigned Intrinsic) { 4803 // Ignore the callsite's attributes. A specific call site may be marked with 4804 // readnone, but the lowering code will expect the chain based on the 4805 // definition. 4806 const Function *F = I.getCalledFunction(); 4807 bool HasChain = !F->doesNotAccessMemory(); 4808 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4809 4810 // Build the operand list. 4811 SmallVector<SDValue, 8> Ops; 4812 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4813 if (OnlyLoad) { 4814 // We don't need to serialize loads against other loads. 4815 Ops.push_back(DAG.getRoot()); 4816 } else { 4817 Ops.push_back(getRoot()); 4818 } 4819 } 4820 4821 // Info is set by getTgtMemIntrinsic 4822 TargetLowering::IntrinsicInfo Info; 4823 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4824 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4825 DAG.getMachineFunction(), 4826 Intrinsic); 4827 4828 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4829 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4830 Info.opc == ISD::INTRINSIC_W_CHAIN) 4831 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4832 TLI.getPointerTy(DAG.getDataLayout()))); 4833 4834 // Add all operands of the call to the operand list. 4835 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4836 const Value *Arg = I.getArgOperand(i); 4837 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4838 Ops.push_back(getValue(Arg)); 4839 continue; 4840 } 4841 4842 // Use TargetConstant instead of a regular constant for immarg. 4843 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4844 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4845 assert(CI->getBitWidth() <= 64 && 4846 "large intrinsic immediates not handled"); 4847 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4848 } else { 4849 Ops.push_back( 4850 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4851 } 4852 } 4853 4854 SmallVector<EVT, 4> ValueVTs; 4855 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4856 4857 if (HasChain) 4858 ValueVTs.push_back(MVT::Other); 4859 4860 SDVTList VTs = DAG.getVTList(ValueVTs); 4861 4862 // Propagate fast-math-flags from IR to node(s). 4863 SDNodeFlags Flags; 4864 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4865 Flags.copyFMF(*FPMO); 4866 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4867 4868 // Create the node. 4869 SDValue Result; 4870 // In some cases, custom collection of operands from CallInst I may be needed. 4871 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4872 if (IsTgtIntrinsic) { 4873 // This is target intrinsic that touches memory 4874 Result = 4875 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4876 MachinePointerInfo(Info.ptrVal, Info.offset), 4877 Info.align, Info.flags, Info.size, 4878 I.getAAMetadata()); 4879 } else if (!HasChain) { 4880 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4881 } else if (!I.getType()->isVoidTy()) { 4882 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4883 } else { 4884 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4885 } 4886 4887 if (HasChain) { 4888 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4889 if (OnlyLoad) 4890 PendingLoads.push_back(Chain); 4891 else 4892 DAG.setRoot(Chain); 4893 } 4894 4895 if (!I.getType()->isVoidTy()) { 4896 if (!isa<VectorType>(I.getType())) 4897 Result = lowerRangeToAssertZExt(DAG, I, Result); 4898 4899 MaybeAlign Alignment = I.getRetAlign(); 4900 if (!Alignment) 4901 Alignment = F->getAttributes().getRetAlignment(); 4902 // Insert `assertalign` node if there's an alignment. 4903 if (InsertAssertAlign && Alignment) { 4904 Result = 4905 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4906 } 4907 4908 setValue(&I, Result); 4909 } 4910 } 4911 4912 /// GetSignificand - Get the significand and build it into a floating-point 4913 /// number with exponent of 1: 4914 /// 4915 /// Op = (Op & 0x007fffff) | 0x3f800000; 4916 /// 4917 /// where Op is the hexadecimal representation of floating point value. 4918 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4919 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4920 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4921 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4922 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4923 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4924 } 4925 4926 /// GetExponent - Get the exponent: 4927 /// 4928 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4929 /// 4930 /// where Op is the hexadecimal representation of floating point value. 4931 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4932 const TargetLowering &TLI, const SDLoc &dl) { 4933 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4934 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4935 SDValue t1 = DAG.getNode( 4936 ISD::SRL, dl, MVT::i32, t0, 4937 DAG.getConstant(23, dl, 4938 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 4939 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4940 DAG.getConstant(127, dl, MVT::i32)); 4941 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4942 } 4943 4944 /// getF32Constant - Get 32-bit floating point constant. 4945 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4946 const SDLoc &dl) { 4947 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4948 MVT::f32); 4949 } 4950 4951 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4952 SelectionDAG &DAG) { 4953 // TODO: What fast-math-flags should be set on the floating-point nodes? 4954 4955 // IntegerPartOfX = ((int32_t)(t0); 4956 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4957 4958 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4959 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4960 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4961 4962 // IntegerPartOfX <<= 23; 4963 IntegerPartOfX = 4964 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4965 DAG.getConstant(23, dl, 4966 DAG.getTargetLoweringInfo().getShiftAmountTy( 4967 MVT::i32, DAG.getDataLayout()))); 4968 4969 SDValue TwoToFractionalPartOfX; 4970 if (LimitFloatPrecision <= 6) { 4971 // For floating-point precision of 6: 4972 // 4973 // TwoToFractionalPartOfX = 4974 // 0.997535578f + 4975 // (0.735607626f + 0.252464424f * x) * x; 4976 // 4977 // error 0.0144103317, which is 6 bits 4978 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4979 getF32Constant(DAG, 0x3e814304, dl)); 4980 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4981 getF32Constant(DAG, 0x3f3c50c8, dl)); 4982 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4983 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4984 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4985 } else if (LimitFloatPrecision <= 12) { 4986 // For floating-point precision of 12: 4987 // 4988 // TwoToFractionalPartOfX = 4989 // 0.999892986f + 4990 // (0.696457318f + 4991 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4992 // 4993 // error 0.000107046256, which is 13 to 14 bits 4994 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4995 getF32Constant(DAG, 0x3da235e3, dl)); 4996 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4997 getF32Constant(DAG, 0x3e65b8f3, dl)); 4998 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4999 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5000 getF32Constant(DAG, 0x3f324b07, dl)); 5001 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5002 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5003 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5004 } else { // LimitFloatPrecision <= 18 5005 // For floating-point precision of 18: 5006 // 5007 // TwoToFractionalPartOfX = 5008 // 0.999999982f + 5009 // (0.693148872f + 5010 // (0.240227044f + 5011 // (0.554906021e-1f + 5012 // (0.961591928e-2f + 5013 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5014 // error 2.47208000*10^(-7), which is better than 18 bits 5015 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5016 getF32Constant(DAG, 0x3924b03e, dl)); 5017 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5018 getF32Constant(DAG, 0x3ab24b87, dl)); 5019 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5020 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5021 getF32Constant(DAG, 0x3c1d8c17, dl)); 5022 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5023 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5024 getF32Constant(DAG, 0x3d634a1d, dl)); 5025 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5026 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5027 getF32Constant(DAG, 0x3e75fe14, dl)); 5028 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5029 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5030 getF32Constant(DAG, 0x3f317234, dl)); 5031 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5032 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5033 getF32Constant(DAG, 0x3f800000, dl)); 5034 } 5035 5036 // Add the exponent into the result in integer domain. 5037 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5038 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5039 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5040 } 5041 5042 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5043 /// limited-precision mode. 5044 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5045 const TargetLowering &TLI, SDNodeFlags Flags) { 5046 if (Op.getValueType() == MVT::f32 && 5047 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5048 5049 // Put the exponent in the right bit position for later addition to the 5050 // final result: 5051 // 5052 // t0 = Op * log2(e) 5053 5054 // TODO: What fast-math-flags should be set here? 5055 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5056 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5057 return getLimitedPrecisionExp2(t0, dl, DAG); 5058 } 5059 5060 // No special expansion. 5061 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5062 } 5063 5064 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5065 /// limited-precision mode. 5066 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5067 const TargetLowering &TLI, SDNodeFlags Flags) { 5068 // TODO: What fast-math-flags should be set on the floating-point nodes? 5069 5070 if (Op.getValueType() == MVT::f32 && 5071 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5072 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5073 5074 // Scale the exponent by log(2). 5075 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5076 SDValue LogOfExponent = 5077 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5078 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5079 5080 // Get the significand and build it into a floating-point number with 5081 // exponent of 1. 5082 SDValue X = GetSignificand(DAG, Op1, dl); 5083 5084 SDValue LogOfMantissa; 5085 if (LimitFloatPrecision <= 6) { 5086 // For floating-point precision of 6: 5087 // 5088 // LogofMantissa = 5089 // -1.1609546f + 5090 // (1.4034025f - 0.23903021f * x) * x; 5091 // 5092 // error 0.0034276066, which is better than 8 bits 5093 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5094 getF32Constant(DAG, 0xbe74c456, dl)); 5095 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5096 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5097 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5098 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5099 getF32Constant(DAG, 0x3f949a29, dl)); 5100 } else if (LimitFloatPrecision <= 12) { 5101 // For floating-point precision of 12: 5102 // 5103 // LogOfMantissa = 5104 // -1.7417939f + 5105 // (2.8212026f + 5106 // (-1.4699568f + 5107 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5108 // 5109 // error 0.000061011436, which is 14 bits 5110 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5111 getF32Constant(DAG, 0xbd67b6d6, dl)); 5112 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5113 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5114 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5115 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5116 getF32Constant(DAG, 0x3fbc278b, dl)); 5117 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5118 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5119 getF32Constant(DAG, 0x40348e95, dl)); 5120 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5121 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5122 getF32Constant(DAG, 0x3fdef31a, dl)); 5123 } else { // LimitFloatPrecision <= 18 5124 // For floating-point precision of 18: 5125 // 5126 // LogOfMantissa = 5127 // -2.1072184f + 5128 // (4.2372794f + 5129 // (-3.7029485f + 5130 // (2.2781945f + 5131 // (-0.87823314f + 5132 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5133 // 5134 // error 0.0000023660568, which is better than 18 bits 5135 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5136 getF32Constant(DAG, 0xbc91e5ac, dl)); 5137 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5138 getF32Constant(DAG, 0x3e4350aa, dl)); 5139 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5140 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5141 getF32Constant(DAG, 0x3f60d3e3, dl)); 5142 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5143 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5144 getF32Constant(DAG, 0x4011cdf0, dl)); 5145 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5146 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5147 getF32Constant(DAG, 0x406cfd1c, dl)); 5148 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5149 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5150 getF32Constant(DAG, 0x408797cb, dl)); 5151 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5152 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5153 getF32Constant(DAG, 0x4006dcab, dl)); 5154 } 5155 5156 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5157 } 5158 5159 // No special expansion. 5160 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5161 } 5162 5163 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5164 /// limited-precision mode. 5165 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5166 const TargetLowering &TLI, SDNodeFlags Flags) { 5167 // TODO: What fast-math-flags should be set on the floating-point nodes? 5168 5169 if (Op.getValueType() == MVT::f32 && 5170 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5171 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5172 5173 // Get the exponent. 5174 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5175 5176 // Get the significand and build it into a floating-point number with 5177 // exponent of 1. 5178 SDValue X = GetSignificand(DAG, Op1, dl); 5179 5180 // Different possible minimax approximations of significand in 5181 // floating-point for various degrees of accuracy over [1,2]. 5182 SDValue Log2ofMantissa; 5183 if (LimitFloatPrecision <= 6) { 5184 // For floating-point precision of 6: 5185 // 5186 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5187 // 5188 // error 0.0049451742, which is more than 7 bits 5189 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5190 getF32Constant(DAG, 0xbeb08fe0, dl)); 5191 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5192 getF32Constant(DAG, 0x40019463, dl)); 5193 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5194 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5195 getF32Constant(DAG, 0x3fd6633d, dl)); 5196 } else if (LimitFloatPrecision <= 12) { 5197 // For floating-point precision of 12: 5198 // 5199 // Log2ofMantissa = 5200 // -2.51285454f + 5201 // (4.07009056f + 5202 // (-2.12067489f + 5203 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5204 // 5205 // error 0.0000876136000, which is better than 13 bits 5206 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5207 getF32Constant(DAG, 0xbda7262e, dl)); 5208 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5209 getF32Constant(DAG, 0x3f25280b, dl)); 5210 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5211 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5212 getF32Constant(DAG, 0x4007b923, dl)); 5213 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5214 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5215 getF32Constant(DAG, 0x40823e2f, dl)); 5216 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5217 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5218 getF32Constant(DAG, 0x4020d29c, dl)); 5219 } else { // LimitFloatPrecision <= 18 5220 // For floating-point precision of 18: 5221 // 5222 // Log2ofMantissa = 5223 // -3.0400495f + 5224 // (6.1129976f + 5225 // (-5.3420409f + 5226 // (3.2865683f + 5227 // (-1.2669343f + 5228 // (0.27515199f - 5229 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5230 // 5231 // error 0.0000018516, which is better than 18 bits 5232 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5233 getF32Constant(DAG, 0xbcd2769e, dl)); 5234 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5235 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5236 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5237 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5238 getF32Constant(DAG, 0x3fa22ae7, dl)); 5239 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5240 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5241 getF32Constant(DAG, 0x40525723, dl)); 5242 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5243 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5244 getF32Constant(DAG, 0x40aaf200, dl)); 5245 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5246 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5247 getF32Constant(DAG, 0x40c39dad, dl)); 5248 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5249 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5250 getF32Constant(DAG, 0x4042902c, dl)); 5251 } 5252 5253 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5254 } 5255 5256 // No special expansion. 5257 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5258 } 5259 5260 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5261 /// limited-precision mode. 5262 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5263 const TargetLowering &TLI, SDNodeFlags Flags) { 5264 // TODO: What fast-math-flags should be set on the floating-point nodes? 5265 5266 if (Op.getValueType() == MVT::f32 && 5267 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5268 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5269 5270 // Scale the exponent by log10(2) [0.30102999f]. 5271 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5272 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5273 getF32Constant(DAG, 0x3e9a209a, dl)); 5274 5275 // Get the significand and build it into a floating-point number with 5276 // exponent of 1. 5277 SDValue X = GetSignificand(DAG, Op1, dl); 5278 5279 SDValue Log10ofMantissa; 5280 if (LimitFloatPrecision <= 6) { 5281 // For floating-point precision of 6: 5282 // 5283 // Log10ofMantissa = 5284 // -0.50419619f + 5285 // (0.60948995f - 0.10380950f * x) * x; 5286 // 5287 // error 0.0014886165, which is 6 bits 5288 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5289 getF32Constant(DAG, 0xbdd49a13, dl)); 5290 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5291 getF32Constant(DAG, 0x3f1c0789, dl)); 5292 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5293 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5294 getF32Constant(DAG, 0x3f011300, dl)); 5295 } else if (LimitFloatPrecision <= 12) { 5296 // For floating-point precision of 12: 5297 // 5298 // Log10ofMantissa = 5299 // -0.64831180f + 5300 // (0.91751397f + 5301 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5302 // 5303 // error 0.00019228036, which is better than 12 bits 5304 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5305 getF32Constant(DAG, 0x3d431f31, dl)); 5306 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5307 getF32Constant(DAG, 0x3ea21fb2, dl)); 5308 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5309 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5310 getF32Constant(DAG, 0x3f6ae232, dl)); 5311 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5312 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5313 getF32Constant(DAG, 0x3f25f7c3, dl)); 5314 } else { // LimitFloatPrecision <= 18 5315 // For floating-point precision of 18: 5316 // 5317 // Log10ofMantissa = 5318 // -0.84299375f + 5319 // (1.5327582f + 5320 // (-1.0688956f + 5321 // (0.49102474f + 5322 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5323 // 5324 // error 0.0000037995730, which is better than 18 bits 5325 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5326 getF32Constant(DAG, 0x3c5d51ce, dl)); 5327 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5328 getF32Constant(DAG, 0x3e00685a, dl)); 5329 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5330 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5331 getF32Constant(DAG, 0x3efb6798, dl)); 5332 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5333 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5334 getF32Constant(DAG, 0x3f88d192, dl)); 5335 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5336 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5337 getF32Constant(DAG, 0x3fc4316c, dl)); 5338 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5339 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5340 getF32Constant(DAG, 0x3f57ce70, dl)); 5341 } 5342 5343 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5344 } 5345 5346 // No special expansion. 5347 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5348 } 5349 5350 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5351 /// limited-precision mode. 5352 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5353 const TargetLowering &TLI, SDNodeFlags Flags) { 5354 if (Op.getValueType() == MVT::f32 && 5355 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5356 return getLimitedPrecisionExp2(Op, dl, DAG); 5357 5358 // No special expansion. 5359 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5360 } 5361 5362 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5363 /// limited-precision mode with x == 10.0f. 5364 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5365 SelectionDAG &DAG, const TargetLowering &TLI, 5366 SDNodeFlags Flags) { 5367 bool IsExp10 = false; 5368 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5369 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5370 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5371 APFloat Ten(10.0f); 5372 IsExp10 = LHSC->isExactlyValue(Ten); 5373 } 5374 } 5375 5376 // TODO: What fast-math-flags should be set on the FMUL node? 5377 if (IsExp10) { 5378 // Put the exponent in the right bit position for later addition to the 5379 // final result: 5380 // 5381 // #define LOG2OF10 3.3219281f 5382 // t0 = Op * LOG2OF10; 5383 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5384 getF32Constant(DAG, 0x40549a78, dl)); 5385 return getLimitedPrecisionExp2(t0, dl, DAG); 5386 } 5387 5388 // No special expansion. 5389 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5390 } 5391 5392 /// ExpandPowI - Expand a llvm.powi intrinsic. 5393 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5394 SelectionDAG &DAG) { 5395 // If RHS is a constant, we can expand this out to a multiplication tree if 5396 // it's beneficial on the target, otherwise we end up lowering to a call to 5397 // __powidf2 (for example). 5398 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5399 unsigned Val = RHSC->getSExtValue(); 5400 5401 // powi(x, 0) -> 1.0 5402 if (Val == 0) 5403 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5404 5405 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5406 Val, DAG.shouldOptForSize())) { 5407 // Get the exponent as a positive value. 5408 if ((int)Val < 0) 5409 Val = -Val; 5410 // We use the simple binary decomposition method to generate the multiply 5411 // sequence. There are more optimal ways to do this (for example, 5412 // powi(x,15) generates one more multiply than it should), but this has 5413 // the benefit of being both really simple and much better than a libcall. 5414 SDValue Res; // Logically starts equal to 1.0 5415 SDValue CurSquare = LHS; 5416 // TODO: Intrinsics should have fast-math-flags that propagate to these 5417 // nodes. 5418 while (Val) { 5419 if (Val & 1) { 5420 if (Res.getNode()) 5421 Res = 5422 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5423 else 5424 Res = CurSquare; // 1.0*CurSquare. 5425 } 5426 5427 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5428 CurSquare, CurSquare); 5429 Val >>= 1; 5430 } 5431 5432 // If the original was negative, invert the result, producing 1/(x*x*x). 5433 if (RHSC->getSExtValue() < 0) 5434 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5435 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5436 return Res; 5437 } 5438 } 5439 5440 // Otherwise, expand to a libcall. 5441 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5442 } 5443 5444 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5445 SDValue LHS, SDValue RHS, SDValue Scale, 5446 SelectionDAG &DAG, const TargetLowering &TLI) { 5447 EVT VT = LHS.getValueType(); 5448 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5449 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5450 LLVMContext &Ctx = *DAG.getContext(); 5451 5452 // If the type is legal but the operation isn't, this node might survive all 5453 // the way to operation legalization. If we end up there and we do not have 5454 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5455 // node. 5456 5457 // Coax the legalizer into expanding the node during type legalization instead 5458 // by bumping the size by one bit. This will force it to Promote, enabling the 5459 // early expansion and avoiding the need to expand later. 5460 5461 // We don't have to do this if Scale is 0; that can always be expanded, unless 5462 // it's a saturating signed operation. Those can experience true integer 5463 // division overflow, a case which we must avoid. 5464 5465 // FIXME: We wouldn't have to do this (or any of the early 5466 // expansion/promotion) if it was possible to expand a libcall of an 5467 // illegal type during operation legalization. But it's not, so things 5468 // get a bit hacky. 5469 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5470 if ((ScaleInt > 0 || (Saturating && Signed)) && 5471 (TLI.isTypeLegal(VT) || 5472 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5473 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5474 Opcode, VT, ScaleInt); 5475 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5476 EVT PromVT; 5477 if (VT.isScalarInteger()) 5478 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5479 else if (VT.isVector()) { 5480 PromVT = VT.getVectorElementType(); 5481 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5482 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5483 } else 5484 llvm_unreachable("Wrong VT for DIVFIX?"); 5485 if (Signed) { 5486 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5487 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5488 } else { 5489 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5490 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5491 } 5492 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5493 // For saturating operations, we need to shift up the LHS to get the 5494 // proper saturation width, and then shift down again afterwards. 5495 if (Saturating) 5496 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5497 DAG.getConstant(1, DL, ShiftTy)); 5498 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5499 if (Saturating) 5500 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5501 DAG.getConstant(1, DL, ShiftTy)); 5502 return DAG.getZExtOrTrunc(Res, DL, VT); 5503 } 5504 } 5505 5506 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5507 } 5508 5509 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5510 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5511 static void 5512 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5513 const SDValue &N) { 5514 switch (N.getOpcode()) { 5515 case ISD::CopyFromReg: { 5516 SDValue Op = N.getOperand(1); 5517 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5518 Op.getValueType().getSizeInBits()); 5519 return; 5520 } 5521 case ISD::BITCAST: 5522 case ISD::AssertZext: 5523 case ISD::AssertSext: 5524 case ISD::TRUNCATE: 5525 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5526 return; 5527 case ISD::BUILD_PAIR: 5528 case ISD::BUILD_VECTOR: 5529 case ISD::CONCAT_VECTORS: 5530 for (SDValue Op : N->op_values()) 5531 getUnderlyingArgRegs(Regs, Op); 5532 return; 5533 default: 5534 return; 5535 } 5536 } 5537 5538 /// If the DbgValueInst is a dbg_value of a function argument, create the 5539 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5540 /// instruction selection, they will be inserted to the entry BB. 5541 /// We don't currently support this for variadic dbg_values, as they shouldn't 5542 /// appear for function arguments or in the prologue. 5543 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5544 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5545 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5546 const Argument *Arg = dyn_cast<Argument>(V); 5547 if (!Arg) 5548 return false; 5549 5550 MachineFunction &MF = DAG.getMachineFunction(); 5551 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5552 5553 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5554 // we've been asked to pursue. 5555 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5556 bool Indirect) { 5557 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5558 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5559 // pointing at the VReg, which will be patched up later. 5560 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5561 auto MIB = BuildMI(MF, DL, Inst); 5562 MIB.addReg(Reg); 5563 MIB.addImm(0); 5564 MIB.addMetadata(Variable); 5565 auto *NewDIExpr = FragExpr; 5566 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5567 // the DIExpression. 5568 if (Indirect) 5569 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5570 MIB.addMetadata(NewDIExpr); 5571 return MIB; 5572 } else { 5573 // Create a completely standard DBG_VALUE. 5574 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5575 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5576 } 5577 }; 5578 5579 if (Kind == FuncArgumentDbgValueKind::Value) { 5580 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5581 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5582 // the entry block. 5583 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5584 if (!IsInEntryBlock) 5585 return false; 5586 5587 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5588 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5589 // variable that also is a param. 5590 // 5591 // Although, if we are at the top of the entry block already, we can still 5592 // emit using ArgDbgValue. This might catch some situations when the 5593 // dbg.value refers to an argument that isn't used in the entry block, so 5594 // any CopyToReg node would be optimized out and the only way to express 5595 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5596 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5597 // we should only emit as ArgDbgValue if the Variable is an argument to the 5598 // current function, and the dbg.value intrinsic is found in the entry 5599 // block. 5600 bool VariableIsFunctionInputArg = Variable->isParameter() && 5601 !DL->getInlinedAt(); 5602 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5603 if (!IsInPrologue && !VariableIsFunctionInputArg) 5604 return false; 5605 5606 // Here we assume that a function argument on IR level only can be used to 5607 // describe one input parameter on source level. If we for example have 5608 // source code like this 5609 // 5610 // struct A { long x, y; }; 5611 // void foo(struct A a, long b) { 5612 // ... 5613 // b = a.x; 5614 // ... 5615 // } 5616 // 5617 // and IR like this 5618 // 5619 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5620 // entry: 5621 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5622 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5623 // call void @llvm.dbg.value(metadata i32 %b, "b", 5624 // ... 5625 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5626 // ... 5627 // 5628 // then the last dbg.value is describing a parameter "b" using a value that 5629 // is an argument. But since we already has used %a1 to describe a parameter 5630 // we should not handle that last dbg.value here (that would result in an 5631 // incorrect hoisting of the DBG_VALUE to the function entry). 5632 // Notice that we allow one dbg.value per IR level argument, to accommodate 5633 // for the situation with fragments above. 5634 if (VariableIsFunctionInputArg) { 5635 unsigned ArgNo = Arg->getArgNo(); 5636 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5637 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5638 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5639 return false; 5640 FuncInfo.DescribedArgs.set(ArgNo); 5641 } 5642 } 5643 5644 bool IsIndirect = false; 5645 Optional<MachineOperand> Op; 5646 // Some arguments' frame index is recorded during argument lowering. 5647 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5648 if (FI != std::numeric_limits<int>::max()) 5649 Op = MachineOperand::CreateFI(FI); 5650 5651 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5652 if (!Op && N.getNode()) { 5653 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5654 Register Reg; 5655 if (ArgRegsAndSizes.size() == 1) 5656 Reg = ArgRegsAndSizes.front().first; 5657 5658 if (Reg && Reg.isVirtual()) { 5659 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5660 Register PR = RegInfo.getLiveInPhysReg(Reg); 5661 if (PR) 5662 Reg = PR; 5663 } 5664 if (Reg) { 5665 Op = MachineOperand::CreateReg(Reg, false); 5666 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5667 } 5668 } 5669 5670 if (!Op && N.getNode()) { 5671 // Check if frame index is available. 5672 SDValue LCandidate = peekThroughBitcasts(N); 5673 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5674 if (FrameIndexSDNode *FINode = 5675 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5676 Op = MachineOperand::CreateFI(FINode->getIndex()); 5677 } 5678 5679 if (!Op) { 5680 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5681 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5682 SplitRegs) { 5683 unsigned Offset = 0; 5684 for (const auto &RegAndSize : SplitRegs) { 5685 // If the expression is already a fragment, the current register 5686 // offset+size might extend beyond the fragment. In this case, only 5687 // the register bits that are inside the fragment are relevant. 5688 int RegFragmentSizeInBits = RegAndSize.second; 5689 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5690 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5691 // The register is entirely outside the expression fragment, 5692 // so is irrelevant for debug info. 5693 if (Offset >= ExprFragmentSizeInBits) 5694 break; 5695 // The register is partially outside the expression fragment, only 5696 // the low bits within the fragment are relevant for debug info. 5697 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5698 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5699 } 5700 } 5701 5702 auto FragmentExpr = DIExpression::createFragmentExpression( 5703 Expr, Offset, RegFragmentSizeInBits); 5704 Offset += RegAndSize.second; 5705 // If a valid fragment expression cannot be created, the variable's 5706 // correct value cannot be determined and so it is set as Undef. 5707 if (!FragmentExpr) { 5708 SDDbgValue *SDV = DAG.getConstantDbgValue( 5709 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5710 DAG.AddDbgValue(SDV, false); 5711 continue; 5712 } 5713 MachineInstr *NewMI = 5714 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5715 Kind != FuncArgumentDbgValueKind::Value); 5716 FuncInfo.ArgDbgValues.push_back(NewMI); 5717 } 5718 }; 5719 5720 // Check if ValueMap has reg number. 5721 DenseMap<const Value *, Register>::const_iterator 5722 VMI = FuncInfo.ValueMap.find(V); 5723 if (VMI != FuncInfo.ValueMap.end()) { 5724 const auto &TLI = DAG.getTargetLoweringInfo(); 5725 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5726 V->getType(), None); 5727 if (RFV.occupiesMultipleRegs()) { 5728 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5729 return true; 5730 } 5731 5732 Op = MachineOperand::CreateReg(VMI->second, false); 5733 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5734 } else if (ArgRegsAndSizes.size() > 1) { 5735 // This was split due to the calling convention, and no virtual register 5736 // mapping exists for the value. 5737 splitMultiRegDbgValue(ArgRegsAndSizes); 5738 return true; 5739 } 5740 } 5741 5742 if (!Op) 5743 return false; 5744 5745 assert(Variable->isValidLocationForIntrinsic(DL) && 5746 "Expected inlined-at fields to agree"); 5747 MachineInstr *NewMI = nullptr; 5748 5749 if (Op->isReg()) 5750 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5751 else 5752 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5753 Variable, Expr); 5754 5755 // Otherwise, use ArgDbgValues. 5756 FuncInfo.ArgDbgValues.push_back(NewMI); 5757 return true; 5758 } 5759 5760 /// Return the appropriate SDDbgValue based on N. 5761 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5762 DILocalVariable *Variable, 5763 DIExpression *Expr, 5764 const DebugLoc &dl, 5765 unsigned DbgSDNodeOrder) { 5766 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5767 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5768 // stack slot locations. 5769 // 5770 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5771 // debug values here after optimization: 5772 // 5773 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5774 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5775 // 5776 // Both describe the direct values of their associated variables. 5777 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5778 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5779 } 5780 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5781 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5782 } 5783 5784 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5785 switch (Intrinsic) { 5786 case Intrinsic::smul_fix: 5787 return ISD::SMULFIX; 5788 case Intrinsic::umul_fix: 5789 return ISD::UMULFIX; 5790 case Intrinsic::smul_fix_sat: 5791 return ISD::SMULFIXSAT; 5792 case Intrinsic::umul_fix_sat: 5793 return ISD::UMULFIXSAT; 5794 case Intrinsic::sdiv_fix: 5795 return ISD::SDIVFIX; 5796 case Intrinsic::udiv_fix: 5797 return ISD::UDIVFIX; 5798 case Intrinsic::sdiv_fix_sat: 5799 return ISD::SDIVFIXSAT; 5800 case Intrinsic::udiv_fix_sat: 5801 return ISD::UDIVFIXSAT; 5802 default: 5803 llvm_unreachable("Unhandled fixed point intrinsic"); 5804 } 5805 } 5806 5807 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5808 const char *FunctionName) { 5809 assert(FunctionName && "FunctionName must not be nullptr"); 5810 SDValue Callee = DAG.getExternalSymbol( 5811 FunctionName, 5812 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5813 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5814 } 5815 5816 /// Given a @llvm.call.preallocated.setup, return the corresponding 5817 /// preallocated call. 5818 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5819 assert(cast<CallBase>(PreallocatedSetup) 5820 ->getCalledFunction() 5821 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5822 "expected call_preallocated_setup Value"); 5823 for (const auto *U : PreallocatedSetup->users()) { 5824 auto *UseCall = cast<CallBase>(U); 5825 const Function *Fn = UseCall->getCalledFunction(); 5826 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5827 return UseCall; 5828 } 5829 } 5830 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5831 } 5832 5833 /// Lower the call to the specified intrinsic function. 5834 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5835 unsigned Intrinsic) { 5836 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5837 SDLoc sdl = getCurSDLoc(); 5838 DebugLoc dl = getCurDebugLoc(); 5839 SDValue Res; 5840 5841 SDNodeFlags Flags; 5842 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5843 Flags.copyFMF(*FPOp); 5844 5845 switch (Intrinsic) { 5846 default: 5847 // By default, turn this into a target intrinsic node. 5848 visitTargetIntrinsic(I, Intrinsic); 5849 return; 5850 case Intrinsic::vscale: { 5851 match(&I, m_VScale(DAG.getDataLayout())); 5852 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5853 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5854 return; 5855 } 5856 case Intrinsic::vastart: visitVAStart(I); return; 5857 case Intrinsic::vaend: visitVAEnd(I); return; 5858 case Intrinsic::vacopy: visitVACopy(I); return; 5859 case Intrinsic::returnaddress: 5860 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5861 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5862 getValue(I.getArgOperand(0)))); 5863 return; 5864 case Intrinsic::addressofreturnaddress: 5865 setValue(&I, 5866 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5867 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5868 return; 5869 case Intrinsic::sponentry: 5870 setValue(&I, 5871 DAG.getNode(ISD::SPONENTRY, sdl, 5872 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5873 return; 5874 case Intrinsic::frameaddress: 5875 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5876 TLI.getFrameIndexTy(DAG.getDataLayout()), 5877 getValue(I.getArgOperand(0)))); 5878 return; 5879 case Intrinsic::read_volatile_register: 5880 case Intrinsic::read_register: { 5881 Value *Reg = I.getArgOperand(0); 5882 SDValue Chain = getRoot(); 5883 SDValue RegName = 5884 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5885 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5886 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5887 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5888 setValue(&I, Res); 5889 DAG.setRoot(Res.getValue(1)); 5890 return; 5891 } 5892 case Intrinsic::write_register: { 5893 Value *Reg = I.getArgOperand(0); 5894 Value *RegValue = I.getArgOperand(1); 5895 SDValue Chain = getRoot(); 5896 SDValue RegName = 5897 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5898 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5899 RegName, getValue(RegValue))); 5900 return; 5901 } 5902 case Intrinsic::memcpy: { 5903 const auto &MCI = cast<MemCpyInst>(I); 5904 SDValue Op1 = getValue(I.getArgOperand(0)); 5905 SDValue Op2 = getValue(I.getArgOperand(1)); 5906 SDValue Op3 = getValue(I.getArgOperand(2)); 5907 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5908 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5909 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5910 Align Alignment = std::min(DstAlign, SrcAlign); 5911 bool isVol = MCI.isVolatile(); 5912 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5913 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5914 // node. 5915 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5916 SDValue MC = DAG.getMemcpy( 5917 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5918 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 5919 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5920 updateDAGForMaybeTailCall(MC); 5921 return; 5922 } 5923 case Intrinsic::memcpy_inline: { 5924 const auto &MCI = cast<MemCpyInlineInst>(I); 5925 SDValue Dst = getValue(I.getArgOperand(0)); 5926 SDValue Src = getValue(I.getArgOperand(1)); 5927 SDValue Size = getValue(I.getArgOperand(2)); 5928 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5929 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5930 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5931 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5932 Align Alignment = std::min(DstAlign, SrcAlign); 5933 bool isVol = MCI.isVolatile(); 5934 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5935 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5936 // node. 5937 SDValue MC = DAG.getMemcpy( 5938 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5939 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5940 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5941 updateDAGForMaybeTailCall(MC); 5942 return; 5943 } 5944 case Intrinsic::memset: { 5945 const auto &MSI = cast<MemSetInst>(I); 5946 SDValue Op1 = getValue(I.getArgOperand(0)); 5947 SDValue Op2 = getValue(I.getArgOperand(1)); 5948 SDValue Op3 = getValue(I.getArgOperand(2)); 5949 // @llvm.memset defines 0 and 1 to both mean no alignment. 5950 Align Alignment = MSI.getDestAlign().valueOrOne(); 5951 bool isVol = MSI.isVolatile(); 5952 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5953 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5954 SDValue MS = DAG.getMemset( 5955 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 5956 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 5957 updateDAGForMaybeTailCall(MS); 5958 return; 5959 } 5960 case Intrinsic::memset_inline: { 5961 const auto &MSII = cast<MemSetInlineInst>(I); 5962 SDValue Dst = getValue(I.getArgOperand(0)); 5963 SDValue Value = getValue(I.getArgOperand(1)); 5964 SDValue Size = getValue(I.getArgOperand(2)); 5965 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 5966 // @llvm.memset defines 0 and 1 to both mean no alignment. 5967 Align DstAlign = MSII.getDestAlign().valueOrOne(); 5968 bool isVol = MSII.isVolatile(); 5969 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5970 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5971 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 5972 /* AlwaysInline */ true, isTC, 5973 MachinePointerInfo(I.getArgOperand(0)), 5974 I.getAAMetadata()); 5975 updateDAGForMaybeTailCall(MC); 5976 return; 5977 } 5978 case Intrinsic::memmove: { 5979 const auto &MMI = cast<MemMoveInst>(I); 5980 SDValue Op1 = getValue(I.getArgOperand(0)); 5981 SDValue Op2 = getValue(I.getArgOperand(1)); 5982 SDValue Op3 = getValue(I.getArgOperand(2)); 5983 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5984 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5985 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5986 Align Alignment = std::min(DstAlign, SrcAlign); 5987 bool isVol = MMI.isVolatile(); 5988 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5989 // FIXME: Support passing different dest/src alignments to the memmove DAG 5990 // node. 5991 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5992 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5993 isTC, MachinePointerInfo(I.getArgOperand(0)), 5994 MachinePointerInfo(I.getArgOperand(1)), 5995 I.getAAMetadata(), AA); 5996 updateDAGForMaybeTailCall(MM); 5997 return; 5998 } 5999 case Intrinsic::memcpy_element_unordered_atomic: { 6000 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6001 SDValue Dst = getValue(MI.getRawDest()); 6002 SDValue Src = getValue(MI.getRawSource()); 6003 SDValue Length = getValue(MI.getLength()); 6004 6005 Type *LengthTy = MI.getLength()->getType(); 6006 unsigned ElemSz = MI.getElementSizeInBytes(); 6007 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6008 SDValue MC = 6009 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6010 isTC, MachinePointerInfo(MI.getRawDest()), 6011 MachinePointerInfo(MI.getRawSource())); 6012 updateDAGForMaybeTailCall(MC); 6013 return; 6014 } 6015 case Intrinsic::memmove_element_unordered_atomic: { 6016 auto &MI = cast<AtomicMemMoveInst>(I); 6017 SDValue Dst = getValue(MI.getRawDest()); 6018 SDValue Src = getValue(MI.getRawSource()); 6019 SDValue Length = getValue(MI.getLength()); 6020 6021 Type *LengthTy = MI.getLength()->getType(); 6022 unsigned ElemSz = MI.getElementSizeInBytes(); 6023 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6024 SDValue MC = 6025 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6026 isTC, MachinePointerInfo(MI.getRawDest()), 6027 MachinePointerInfo(MI.getRawSource())); 6028 updateDAGForMaybeTailCall(MC); 6029 return; 6030 } 6031 case Intrinsic::memset_element_unordered_atomic: { 6032 auto &MI = cast<AtomicMemSetInst>(I); 6033 SDValue Dst = getValue(MI.getRawDest()); 6034 SDValue Val = getValue(MI.getValue()); 6035 SDValue Length = getValue(MI.getLength()); 6036 6037 Type *LengthTy = MI.getLength()->getType(); 6038 unsigned ElemSz = MI.getElementSizeInBytes(); 6039 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6040 SDValue MC = 6041 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6042 isTC, MachinePointerInfo(MI.getRawDest())); 6043 updateDAGForMaybeTailCall(MC); 6044 return; 6045 } 6046 case Intrinsic::call_preallocated_setup: { 6047 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6048 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6049 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6050 getRoot(), SrcValue); 6051 setValue(&I, Res); 6052 DAG.setRoot(Res); 6053 return; 6054 } 6055 case Intrinsic::call_preallocated_arg: { 6056 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6057 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6058 SDValue Ops[3]; 6059 Ops[0] = getRoot(); 6060 Ops[1] = SrcValue; 6061 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6062 MVT::i32); // arg index 6063 SDValue Res = DAG.getNode( 6064 ISD::PREALLOCATED_ARG, sdl, 6065 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6066 setValue(&I, Res); 6067 DAG.setRoot(Res.getValue(1)); 6068 return; 6069 } 6070 case Intrinsic::dbg_addr: 6071 case Intrinsic::dbg_declare: { 6072 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6073 // they are non-variadic. 6074 const auto &DI = cast<DbgVariableIntrinsic>(I); 6075 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6076 DILocalVariable *Variable = DI.getVariable(); 6077 DIExpression *Expression = DI.getExpression(); 6078 dropDanglingDebugInfo(Variable, Expression); 6079 assert(Variable && "Missing variable"); 6080 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6081 << "\n"); 6082 // Check if address has undef value. 6083 const Value *Address = DI.getVariableLocationOp(0); 6084 if (!Address || isa<UndefValue>(Address) || 6085 (Address->use_empty() && !isa<Argument>(Address))) { 6086 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6087 << " (bad/undef/unused-arg address)\n"); 6088 return; 6089 } 6090 6091 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6092 6093 // Check if this variable can be described by a frame index, typically 6094 // either as a static alloca or a byval parameter. 6095 int FI = std::numeric_limits<int>::max(); 6096 if (const auto *AI = 6097 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6098 if (AI->isStaticAlloca()) { 6099 auto I = FuncInfo.StaticAllocaMap.find(AI); 6100 if (I != FuncInfo.StaticAllocaMap.end()) 6101 FI = I->second; 6102 } 6103 } else if (const auto *Arg = dyn_cast<Argument>( 6104 Address->stripInBoundsConstantOffsets())) { 6105 FI = FuncInfo.getArgumentFrameIndex(Arg); 6106 } 6107 6108 // llvm.dbg.addr is control dependent and always generates indirect 6109 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6110 // the MachineFunction variable table. 6111 if (FI != std::numeric_limits<int>::max()) { 6112 if (Intrinsic == Intrinsic::dbg_addr) { 6113 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6114 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6115 dl, SDNodeOrder); 6116 DAG.AddDbgValue(SDV, isParameter); 6117 } else { 6118 LLVM_DEBUG(dbgs() << "Skipping " << DI 6119 << " (variable info stashed in MF side table)\n"); 6120 } 6121 return; 6122 } 6123 6124 SDValue &N = NodeMap[Address]; 6125 if (!N.getNode() && isa<Argument>(Address)) 6126 // Check unused arguments map. 6127 N = UnusedArgNodeMap[Address]; 6128 SDDbgValue *SDV; 6129 if (N.getNode()) { 6130 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6131 Address = BCI->getOperand(0); 6132 // Parameters are handled specially. 6133 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6134 if (isParameter && FINode) { 6135 // Byval parameter. We have a frame index at this point. 6136 SDV = 6137 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6138 /*IsIndirect*/ true, dl, SDNodeOrder); 6139 } else if (isa<Argument>(Address)) { 6140 // Address is an argument, so try to emit its dbg value using 6141 // virtual register info from the FuncInfo.ValueMap. 6142 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6143 FuncArgumentDbgValueKind::Declare, N); 6144 return; 6145 } else { 6146 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6147 true, dl, SDNodeOrder); 6148 } 6149 DAG.AddDbgValue(SDV, isParameter); 6150 } else { 6151 // If Address is an argument then try to emit its dbg value using 6152 // virtual register info from the FuncInfo.ValueMap. 6153 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6154 FuncArgumentDbgValueKind::Declare, N)) { 6155 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6156 << " (could not emit func-arg dbg_value)\n"); 6157 } 6158 } 6159 return; 6160 } 6161 case Intrinsic::dbg_label: { 6162 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6163 DILabel *Label = DI.getLabel(); 6164 assert(Label && "Missing label"); 6165 6166 SDDbgLabel *SDV; 6167 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6168 DAG.AddDbgLabel(SDV); 6169 return; 6170 } 6171 case Intrinsic::dbg_value: { 6172 const DbgValueInst &DI = cast<DbgValueInst>(I); 6173 assert(DI.getVariable() && "Missing variable"); 6174 6175 DILocalVariable *Variable = DI.getVariable(); 6176 DIExpression *Expression = DI.getExpression(); 6177 dropDanglingDebugInfo(Variable, Expression); 6178 SmallVector<Value *, 4> Values(DI.getValues()); 6179 if (Values.empty()) 6180 return; 6181 6182 if (llvm::is_contained(Values, nullptr)) 6183 return; 6184 6185 bool IsVariadic = DI.hasArgList(); 6186 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6187 SDNodeOrder, IsVariadic)) 6188 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6189 return; 6190 } 6191 6192 case Intrinsic::eh_typeid_for: { 6193 // Find the type id for the given typeinfo. 6194 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6195 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6196 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6197 setValue(&I, Res); 6198 return; 6199 } 6200 6201 case Intrinsic::eh_return_i32: 6202 case Intrinsic::eh_return_i64: 6203 DAG.getMachineFunction().setCallsEHReturn(true); 6204 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6205 MVT::Other, 6206 getControlRoot(), 6207 getValue(I.getArgOperand(0)), 6208 getValue(I.getArgOperand(1)))); 6209 return; 6210 case Intrinsic::eh_unwind_init: 6211 DAG.getMachineFunction().setCallsUnwindInit(true); 6212 return; 6213 case Intrinsic::eh_dwarf_cfa: 6214 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6215 TLI.getPointerTy(DAG.getDataLayout()), 6216 getValue(I.getArgOperand(0)))); 6217 return; 6218 case Intrinsic::eh_sjlj_callsite: { 6219 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6220 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6221 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6222 6223 MMI.setCurrentCallSite(CI->getZExtValue()); 6224 return; 6225 } 6226 case Intrinsic::eh_sjlj_functioncontext: { 6227 // Get and store the index of the function context. 6228 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6229 AllocaInst *FnCtx = 6230 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6231 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6232 MFI.setFunctionContextIndex(FI); 6233 return; 6234 } 6235 case Intrinsic::eh_sjlj_setjmp: { 6236 SDValue Ops[2]; 6237 Ops[0] = getRoot(); 6238 Ops[1] = getValue(I.getArgOperand(0)); 6239 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6240 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6241 setValue(&I, Op.getValue(0)); 6242 DAG.setRoot(Op.getValue(1)); 6243 return; 6244 } 6245 case Intrinsic::eh_sjlj_longjmp: 6246 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6247 getRoot(), getValue(I.getArgOperand(0)))); 6248 return; 6249 case Intrinsic::eh_sjlj_setup_dispatch: 6250 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6251 getRoot())); 6252 return; 6253 case Intrinsic::masked_gather: 6254 visitMaskedGather(I); 6255 return; 6256 case Intrinsic::masked_load: 6257 visitMaskedLoad(I); 6258 return; 6259 case Intrinsic::masked_scatter: 6260 visitMaskedScatter(I); 6261 return; 6262 case Intrinsic::masked_store: 6263 visitMaskedStore(I); 6264 return; 6265 case Intrinsic::masked_expandload: 6266 visitMaskedLoad(I, true /* IsExpanding */); 6267 return; 6268 case Intrinsic::masked_compressstore: 6269 visitMaskedStore(I, true /* IsCompressing */); 6270 return; 6271 case Intrinsic::powi: 6272 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6273 getValue(I.getArgOperand(1)), DAG)); 6274 return; 6275 case Intrinsic::log: 6276 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6277 return; 6278 case Intrinsic::log2: 6279 setValue(&I, 6280 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6281 return; 6282 case Intrinsic::log10: 6283 setValue(&I, 6284 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6285 return; 6286 case Intrinsic::exp: 6287 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6288 return; 6289 case Intrinsic::exp2: 6290 setValue(&I, 6291 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6292 return; 6293 case Intrinsic::pow: 6294 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6295 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6296 return; 6297 case Intrinsic::sqrt: 6298 case Intrinsic::fabs: 6299 case Intrinsic::sin: 6300 case Intrinsic::cos: 6301 case Intrinsic::floor: 6302 case Intrinsic::ceil: 6303 case Intrinsic::trunc: 6304 case Intrinsic::rint: 6305 case Intrinsic::nearbyint: 6306 case Intrinsic::round: 6307 case Intrinsic::roundeven: 6308 case Intrinsic::canonicalize: { 6309 unsigned Opcode; 6310 switch (Intrinsic) { 6311 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6312 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6313 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6314 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6315 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6316 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6317 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6318 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6319 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6320 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6321 case Intrinsic::round: Opcode = ISD::FROUND; break; 6322 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6323 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6324 } 6325 6326 setValue(&I, DAG.getNode(Opcode, sdl, 6327 getValue(I.getArgOperand(0)).getValueType(), 6328 getValue(I.getArgOperand(0)), Flags)); 6329 return; 6330 } 6331 case Intrinsic::lround: 6332 case Intrinsic::llround: 6333 case Intrinsic::lrint: 6334 case Intrinsic::llrint: { 6335 unsigned Opcode; 6336 switch (Intrinsic) { 6337 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6338 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6339 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6340 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6341 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6342 } 6343 6344 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6345 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6346 getValue(I.getArgOperand(0)))); 6347 return; 6348 } 6349 case Intrinsic::minnum: 6350 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6351 getValue(I.getArgOperand(0)).getValueType(), 6352 getValue(I.getArgOperand(0)), 6353 getValue(I.getArgOperand(1)), Flags)); 6354 return; 6355 case Intrinsic::maxnum: 6356 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6357 getValue(I.getArgOperand(0)).getValueType(), 6358 getValue(I.getArgOperand(0)), 6359 getValue(I.getArgOperand(1)), Flags)); 6360 return; 6361 case Intrinsic::minimum: 6362 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6363 getValue(I.getArgOperand(0)).getValueType(), 6364 getValue(I.getArgOperand(0)), 6365 getValue(I.getArgOperand(1)), Flags)); 6366 return; 6367 case Intrinsic::maximum: 6368 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6369 getValue(I.getArgOperand(0)).getValueType(), 6370 getValue(I.getArgOperand(0)), 6371 getValue(I.getArgOperand(1)), Flags)); 6372 return; 6373 case Intrinsic::copysign: 6374 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6375 getValue(I.getArgOperand(0)).getValueType(), 6376 getValue(I.getArgOperand(0)), 6377 getValue(I.getArgOperand(1)), Flags)); 6378 return; 6379 case Intrinsic::arithmetic_fence: { 6380 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6381 getValue(I.getArgOperand(0)).getValueType(), 6382 getValue(I.getArgOperand(0)), Flags)); 6383 return; 6384 } 6385 case Intrinsic::fma: 6386 setValue(&I, DAG.getNode( 6387 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6388 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6389 getValue(I.getArgOperand(2)), Flags)); 6390 return; 6391 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6392 case Intrinsic::INTRINSIC: 6393 #include "llvm/IR/ConstrainedOps.def" 6394 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6395 return; 6396 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6397 #include "llvm/IR/VPIntrinsics.def" 6398 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6399 return; 6400 case Intrinsic::fptrunc_round: { 6401 // Get the last argument, the metadata and convert it to an integer in the 6402 // call 6403 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6404 Optional<RoundingMode> RoundMode = 6405 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6406 6407 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6408 6409 // Propagate fast-math-flags from IR to node(s). 6410 SDNodeFlags Flags; 6411 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6412 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6413 6414 SDValue Result; 6415 Result = DAG.getNode( 6416 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6417 DAG.getTargetConstant((int)*RoundMode, sdl, 6418 TLI.getPointerTy(DAG.getDataLayout()))); 6419 setValue(&I, Result); 6420 6421 return; 6422 } 6423 case Intrinsic::fmuladd: { 6424 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6425 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6426 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6427 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6428 getValue(I.getArgOperand(0)).getValueType(), 6429 getValue(I.getArgOperand(0)), 6430 getValue(I.getArgOperand(1)), 6431 getValue(I.getArgOperand(2)), Flags)); 6432 } else { 6433 // TODO: Intrinsic calls should have fast-math-flags. 6434 SDValue Mul = DAG.getNode( 6435 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6436 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6437 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6438 getValue(I.getArgOperand(0)).getValueType(), 6439 Mul, getValue(I.getArgOperand(2)), Flags); 6440 setValue(&I, Add); 6441 } 6442 return; 6443 } 6444 case Intrinsic::convert_to_fp16: 6445 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6446 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6447 getValue(I.getArgOperand(0)), 6448 DAG.getTargetConstant(0, sdl, 6449 MVT::i32)))); 6450 return; 6451 case Intrinsic::convert_from_fp16: 6452 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6453 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6454 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6455 getValue(I.getArgOperand(0))))); 6456 return; 6457 case Intrinsic::fptosi_sat: { 6458 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6459 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6460 getValue(I.getArgOperand(0)), 6461 DAG.getValueType(VT.getScalarType()))); 6462 return; 6463 } 6464 case Intrinsic::fptoui_sat: { 6465 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6466 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6467 getValue(I.getArgOperand(0)), 6468 DAG.getValueType(VT.getScalarType()))); 6469 return; 6470 } 6471 case Intrinsic::set_rounding: 6472 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6473 {getRoot(), getValue(I.getArgOperand(0))}); 6474 setValue(&I, Res); 6475 DAG.setRoot(Res.getValue(0)); 6476 return; 6477 case Intrinsic::is_fpclass: { 6478 const DataLayout DLayout = DAG.getDataLayout(); 6479 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6480 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6481 unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6482 MachineFunction &MF = DAG.getMachineFunction(); 6483 const Function &F = MF.getFunction(); 6484 SDValue Op = getValue(I.getArgOperand(0)); 6485 SDNodeFlags Flags; 6486 Flags.setNoFPExcept( 6487 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6488 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6489 // expansion can use illegal types. Making expansion early allows 6490 // legalizing these types prior to selection. 6491 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6492 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6493 setValue(&I, Result); 6494 return; 6495 } 6496 6497 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6498 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6499 setValue(&I, V); 6500 return; 6501 } 6502 case Intrinsic::pcmarker: { 6503 SDValue Tmp = getValue(I.getArgOperand(0)); 6504 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6505 return; 6506 } 6507 case Intrinsic::readcyclecounter: { 6508 SDValue Op = getRoot(); 6509 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6510 DAG.getVTList(MVT::i64, MVT::Other), Op); 6511 setValue(&I, Res); 6512 DAG.setRoot(Res.getValue(1)); 6513 return; 6514 } 6515 case Intrinsic::bitreverse: 6516 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6517 getValue(I.getArgOperand(0)).getValueType(), 6518 getValue(I.getArgOperand(0)))); 6519 return; 6520 case Intrinsic::bswap: 6521 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6522 getValue(I.getArgOperand(0)).getValueType(), 6523 getValue(I.getArgOperand(0)))); 6524 return; 6525 case Intrinsic::cttz: { 6526 SDValue Arg = getValue(I.getArgOperand(0)); 6527 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6528 EVT Ty = Arg.getValueType(); 6529 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6530 sdl, Ty, Arg)); 6531 return; 6532 } 6533 case Intrinsic::ctlz: { 6534 SDValue Arg = getValue(I.getArgOperand(0)); 6535 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6536 EVT Ty = Arg.getValueType(); 6537 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6538 sdl, Ty, Arg)); 6539 return; 6540 } 6541 case Intrinsic::ctpop: { 6542 SDValue Arg = getValue(I.getArgOperand(0)); 6543 EVT Ty = Arg.getValueType(); 6544 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6545 return; 6546 } 6547 case Intrinsic::fshl: 6548 case Intrinsic::fshr: { 6549 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6550 SDValue X = getValue(I.getArgOperand(0)); 6551 SDValue Y = getValue(I.getArgOperand(1)); 6552 SDValue Z = getValue(I.getArgOperand(2)); 6553 EVT VT = X.getValueType(); 6554 6555 if (X == Y) { 6556 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6557 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6558 } else { 6559 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6560 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6561 } 6562 return; 6563 } 6564 case Intrinsic::sadd_sat: { 6565 SDValue Op1 = getValue(I.getArgOperand(0)); 6566 SDValue Op2 = getValue(I.getArgOperand(1)); 6567 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6568 return; 6569 } 6570 case Intrinsic::uadd_sat: { 6571 SDValue Op1 = getValue(I.getArgOperand(0)); 6572 SDValue Op2 = getValue(I.getArgOperand(1)); 6573 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6574 return; 6575 } 6576 case Intrinsic::ssub_sat: { 6577 SDValue Op1 = getValue(I.getArgOperand(0)); 6578 SDValue Op2 = getValue(I.getArgOperand(1)); 6579 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6580 return; 6581 } 6582 case Intrinsic::usub_sat: { 6583 SDValue Op1 = getValue(I.getArgOperand(0)); 6584 SDValue Op2 = getValue(I.getArgOperand(1)); 6585 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6586 return; 6587 } 6588 case Intrinsic::sshl_sat: { 6589 SDValue Op1 = getValue(I.getArgOperand(0)); 6590 SDValue Op2 = getValue(I.getArgOperand(1)); 6591 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6592 return; 6593 } 6594 case Intrinsic::ushl_sat: { 6595 SDValue Op1 = getValue(I.getArgOperand(0)); 6596 SDValue Op2 = getValue(I.getArgOperand(1)); 6597 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6598 return; 6599 } 6600 case Intrinsic::smul_fix: 6601 case Intrinsic::umul_fix: 6602 case Intrinsic::smul_fix_sat: 6603 case Intrinsic::umul_fix_sat: { 6604 SDValue Op1 = getValue(I.getArgOperand(0)); 6605 SDValue Op2 = getValue(I.getArgOperand(1)); 6606 SDValue Op3 = getValue(I.getArgOperand(2)); 6607 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6608 Op1.getValueType(), Op1, Op2, Op3)); 6609 return; 6610 } 6611 case Intrinsic::sdiv_fix: 6612 case Intrinsic::udiv_fix: 6613 case Intrinsic::sdiv_fix_sat: 6614 case Intrinsic::udiv_fix_sat: { 6615 SDValue Op1 = getValue(I.getArgOperand(0)); 6616 SDValue Op2 = getValue(I.getArgOperand(1)); 6617 SDValue Op3 = getValue(I.getArgOperand(2)); 6618 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6619 Op1, Op2, Op3, DAG, TLI)); 6620 return; 6621 } 6622 case Intrinsic::smax: { 6623 SDValue Op1 = getValue(I.getArgOperand(0)); 6624 SDValue Op2 = getValue(I.getArgOperand(1)); 6625 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6626 return; 6627 } 6628 case Intrinsic::smin: { 6629 SDValue Op1 = getValue(I.getArgOperand(0)); 6630 SDValue Op2 = getValue(I.getArgOperand(1)); 6631 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6632 return; 6633 } 6634 case Intrinsic::umax: { 6635 SDValue Op1 = getValue(I.getArgOperand(0)); 6636 SDValue Op2 = getValue(I.getArgOperand(1)); 6637 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6638 return; 6639 } 6640 case Intrinsic::umin: { 6641 SDValue Op1 = getValue(I.getArgOperand(0)); 6642 SDValue Op2 = getValue(I.getArgOperand(1)); 6643 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6644 return; 6645 } 6646 case Intrinsic::abs: { 6647 // TODO: Preserve "int min is poison" arg in SDAG? 6648 SDValue Op1 = getValue(I.getArgOperand(0)); 6649 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6650 return; 6651 } 6652 case Intrinsic::stacksave: { 6653 SDValue Op = getRoot(); 6654 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6655 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6656 setValue(&I, Res); 6657 DAG.setRoot(Res.getValue(1)); 6658 return; 6659 } 6660 case Intrinsic::stackrestore: 6661 Res = getValue(I.getArgOperand(0)); 6662 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6663 return; 6664 case Intrinsic::get_dynamic_area_offset: { 6665 SDValue Op = getRoot(); 6666 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6667 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6668 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6669 // target. 6670 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6671 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6672 " intrinsic!"); 6673 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6674 Op); 6675 DAG.setRoot(Op); 6676 setValue(&I, Res); 6677 return; 6678 } 6679 case Intrinsic::stackguard: { 6680 MachineFunction &MF = DAG.getMachineFunction(); 6681 const Module &M = *MF.getFunction().getParent(); 6682 SDValue Chain = getRoot(); 6683 if (TLI.useLoadStackGuardNode()) { 6684 Res = getLoadStackGuard(DAG, sdl, Chain); 6685 } else { 6686 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6687 const Value *Global = TLI.getSDagStackGuard(M); 6688 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6689 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6690 MachinePointerInfo(Global, 0), Align, 6691 MachineMemOperand::MOVolatile); 6692 } 6693 if (TLI.useStackGuardXorFP()) 6694 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6695 DAG.setRoot(Chain); 6696 setValue(&I, Res); 6697 return; 6698 } 6699 case Intrinsic::stackprotector: { 6700 // Emit code into the DAG to store the stack guard onto the stack. 6701 MachineFunction &MF = DAG.getMachineFunction(); 6702 MachineFrameInfo &MFI = MF.getFrameInfo(); 6703 SDValue Src, Chain = getRoot(); 6704 6705 if (TLI.useLoadStackGuardNode()) 6706 Src = getLoadStackGuard(DAG, sdl, Chain); 6707 else 6708 Src = getValue(I.getArgOperand(0)); // The guard's value. 6709 6710 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6711 6712 int FI = FuncInfo.StaticAllocaMap[Slot]; 6713 MFI.setStackProtectorIndex(FI); 6714 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6715 6716 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6717 6718 // Store the stack protector onto the stack. 6719 Res = DAG.getStore( 6720 Chain, sdl, Src, FIN, 6721 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6722 MaybeAlign(), MachineMemOperand::MOVolatile); 6723 setValue(&I, Res); 6724 DAG.setRoot(Res); 6725 return; 6726 } 6727 case Intrinsic::objectsize: 6728 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6729 6730 case Intrinsic::is_constant: 6731 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6732 6733 case Intrinsic::annotation: 6734 case Intrinsic::ptr_annotation: 6735 case Intrinsic::launder_invariant_group: 6736 case Intrinsic::strip_invariant_group: 6737 // Drop the intrinsic, but forward the value 6738 setValue(&I, getValue(I.getOperand(0))); 6739 return; 6740 6741 case Intrinsic::assume: 6742 case Intrinsic::experimental_noalias_scope_decl: 6743 case Intrinsic::var_annotation: 6744 case Intrinsic::sideeffect: 6745 // Discard annotate attributes, noalias scope declarations, assumptions, and 6746 // artificial side-effects. 6747 return; 6748 6749 case Intrinsic::codeview_annotation: { 6750 // Emit a label associated with this metadata. 6751 MachineFunction &MF = DAG.getMachineFunction(); 6752 MCSymbol *Label = 6753 MF.getMMI().getContext().createTempSymbol("annotation", true); 6754 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6755 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6756 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6757 DAG.setRoot(Res); 6758 return; 6759 } 6760 6761 case Intrinsic::init_trampoline: { 6762 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6763 6764 SDValue Ops[6]; 6765 Ops[0] = getRoot(); 6766 Ops[1] = getValue(I.getArgOperand(0)); 6767 Ops[2] = getValue(I.getArgOperand(1)); 6768 Ops[3] = getValue(I.getArgOperand(2)); 6769 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6770 Ops[5] = DAG.getSrcValue(F); 6771 6772 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6773 6774 DAG.setRoot(Res); 6775 return; 6776 } 6777 case Intrinsic::adjust_trampoline: 6778 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6779 TLI.getPointerTy(DAG.getDataLayout()), 6780 getValue(I.getArgOperand(0)))); 6781 return; 6782 case Intrinsic::gcroot: { 6783 assert(DAG.getMachineFunction().getFunction().hasGC() && 6784 "only valid in functions with gc specified, enforced by Verifier"); 6785 assert(GFI && "implied by previous"); 6786 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6787 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6788 6789 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6790 GFI->addStackRoot(FI->getIndex(), TypeMap); 6791 return; 6792 } 6793 case Intrinsic::gcread: 6794 case Intrinsic::gcwrite: 6795 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6796 case Intrinsic::flt_rounds: 6797 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6798 setValue(&I, Res); 6799 DAG.setRoot(Res.getValue(1)); 6800 return; 6801 6802 case Intrinsic::expect: 6803 // Just replace __builtin_expect(exp, c) with EXP. 6804 setValue(&I, getValue(I.getArgOperand(0))); 6805 return; 6806 6807 case Intrinsic::ubsantrap: 6808 case Intrinsic::debugtrap: 6809 case Intrinsic::trap: { 6810 StringRef TrapFuncName = 6811 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6812 if (TrapFuncName.empty()) { 6813 switch (Intrinsic) { 6814 case Intrinsic::trap: 6815 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6816 break; 6817 case Intrinsic::debugtrap: 6818 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6819 break; 6820 case Intrinsic::ubsantrap: 6821 DAG.setRoot(DAG.getNode( 6822 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6823 DAG.getTargetConstant( 6824 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6825 MVT::i32))); 6826 break; 6827 default: llvm_unreachable("unknown trap intrinsic"); 6828 } 6829 return; 6830 } 6831 TargetLowering::ArgListTy Args; 6832 if (Intrinsic == Intrinsic::ubsantrap) { 6833 Args.push_back(TargetLoweringBase::ArgListEntry()); 6834 Args[0].Val = I.getArgOperand(0); 6835 Args[0].Node = getValue(Args[0].Val); 6836 Args[0].Ty = Args[0].Val->getType(); 6837 } 6838 6839 TargetLowering::CallLoweringInfo CLI(DAG); 6840 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6841 CallingConv::C, I.getType(), 6842 DAG.getExternalSymbol(TrapFuncName.data(), 6843 TLI.getPointerTy(DAG.getDataLayout())), 6844 std::move(Args)); 6845 6846 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6847 DAG.setRoot(Result.second); 6848 return; 6849 } 6850 6851 case Intrinsic::uadd_with_overflow: 6852 case Intrinsic::sadd_with_overflow: 6853 case Intrinsic::usub_with_overflow: 6854 case Intrinsic::ssub_with_overflow: 6855 case Intrinsic::umul_with_overflow: 6856 case Intrinsic::smul_with_overflow: { 6857 ISD::NodeType Op; 6858 switch (Intrinsic) { 6859 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6860 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6861 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6862 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6863 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6864 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6865 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6866 } 6867 SDValue Op1 = getValue(I.getArgOperand(0)); 6868 SDValue Op2 = getValue(I.getArgOperand(1)); 6869 6870 EVT ResultVT = Op1.getValueType(); 6871 EVT OverflowVT = MVT::i1; 6872 if (ResultVT.isVector()) 6873 OverflowVT = EVT::getVectorVT( 6874 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6875 6876 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6877 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6878 return; 6879 } 6880 case Intrinsic::prefetch: { 6881 SDValue Ops[5]; 6882 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6883 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6884 Ops[0] = DAG.getRoot(); 6885 Ops[1] = getValue(I.getArgOperand(0)); 6886 Ops[2] = getValue(I.getArgOperand(1)); 6887 Ops[3] = getValue(I.getArgOperand(2)); 6888 Ops[4] = getValue(I.getArgOperand(3)); 6889 SDValue Result = DAG.getMemIntrinsicNode( 6890 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6891 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6892 /* align */ None, Flags); 6893 6894 // Chain the prefetch in parallell with any pending loads, to stay out of 6895 // the way of later optimizations. 6896 PendingLoads.push_back(Result); 6897 Result = getRoot(); 6898 DAG.setRoot(Result); 6899 return; 6900 } 6901 case Intrinsic::lifetime_start: 6902 case Intrinsic::lifetime_end: { 6903 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6904 // Stack coloring is not enabled in O0, discard region information. 6905 if (TM.getOptLevel() == CodeGenOpt::None) 6906 return; 6907 6908 const int64_t ObjectSize = 6909 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6910 Value *const ObjectPtr = I.getArgOperand(1); 6911 SmallVector<const Value *, 4> Allocas; 6912 getUnderlyingObjects(ObjectPtr, Allocas); 6913 6914 for (const Value *Alloca : Allocas) { 6915 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6916 6917 // Could not find an Alloca. 6918 if (!LifetimeObject) 6919 continue; 6920 6921 // First check that the Alloca is static, otherwise it won't have a 6922 // valid frame index. 6923 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6924 if (SI == FuncInfo.StaticAllocaMap.end()) 6925 return; 6926 6927 const int FrameIndex = SI->second; 6928 int64_t Offset; 6929 if (GetPointerBaseWithConstantOffset( 6930 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6931 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6932 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6933 Offset); 6934 DAG.setRoot(Res); 6935 } 6936 return; 6937 } 6938 case Intrinsic::pseudoprobe: { 6939 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6940 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6941 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6942 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6943 DAG.setRoot(Res); 6944 return; 6945 } 6946 case Intrinsic::invariant_start: 6947 // Discard region information. 6948 setValue(&I, 6949 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6950 return; 6951 case Intrinsic::invariant_end: 6952 // Discard region information. 6953 return; 6954 case Intrinsic::clear_cache: 6955 /// FunctionName may be null. 6956 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6957 lowerCallToExternalSymbol(I, FunctionName); 6958 return; 6959 case Intrinsic::donothing: 6960 case Intrinsic::seh_try_begin: 6961 case Intrinsic::seh_scope_begin: 6962 case Intrinsic::seh_try_end: 6963 case Intrinsic::seh_scope_end: 6964 // ignore 6965 return; 6966 case Intrinsic::experimental_stackmap: 6967 visitStackmap(I); 6968 return; 6969 case Intrinsic::experimental_patchpoint_void: 6970 case Intrinsic::experimental_patchpoint_i64: 6971 visitPatchpoint(I); 6972 return; 6973 case Intrinsic::experimental_gc_statepoint: 6974 LowerStatepoint(cast<GCStatepointInst>(I)); 6975 return; 6976 case Intrinsic::experimental_gc_result: 6977 visitGCResult(cast<GCResultInst>(I)); 6978 return; 6979 case Intrinsic::experimental_gc_relocate: 6980 visitGCRelocate(cast<GCRelocateInst>(I)); 6981 return; 6982 case Intrinsic::instrprof_cover: 6983 llvm_unreachable("instrprof failed to lower a cover"); 6984 case Intrinsic::instrprof_increment: 6985 llvm_unreachable("instrprof failed to lower an increment"); 6986 case Intrinsic::instrprof_value_profile: 6987 llvm_unreachable("instrprof failed to lower a value profiling call"); 6988 case Intrinsic::localescape: { 6989 MachineFunction &MF = DAG.getMachineFunction(); 6990 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6991 6992 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6993 // is the same on all targets. 6994 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 6995 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6996 if (isa<ConstantPointerNull>(Arg)) 6997 continue; // Skip null pointers. They represent a hole in index space. 6998 AllocaInst *Slot = cast<AllocaInst>(Arg); 6999 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7000 "can only escape static allocas"); 7001 int FI = FuncInfo.StaticAllocaMap[Slot]; 7002 MCSymbol *FrameAllocSym = 7003 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7004 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7005 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7006 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7007 .addSym(FrameAllocSym) 7008 .addFrameIndex(FI); 7009 } 7010 7011 return; 7012 } 7013 7014 case Intrinsic::localrecover: { 7015 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7016 MachineFunction &MF = DAG.getMachineFunction(); 7017 7018 // Get the symbol that defines the frame offset. 7019 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7020 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7021 unsigned IdxVal = 7022 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7023 MCSymbol *FrameAllocSym = 7024 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7025 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7026 7027 Value *FP = I.getArgOperand(1); 7028 SDValue FPVal = getValue(FP); 7029 EVT PtrVT = FPVal.getValueType(); 7030 7031 // Create a MCSymbol for the label to avoid any target lowering 7032 // that would make this PC relative. 7033 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7034 SDValue OffsetVal = 7035 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7036 7037 // Add the offset to the FP. 7038 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7039 setValue(&I, Add); 7040 7041 return; 7042 } 7043 7044 case Intrinsic::eh_exceptionpointer: 7045 case Intrinsic::eh_exceptioncode: { 7046 // Get the exception pointer vreg, copy from it, and resize it to fit. 7047 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7048 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7049 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7050 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7051 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7052 if (Intrinsic == Intrinsic::eh_exceptioncode) 7053 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7054 setValue(&I, N); 7055 return; 7056 } 7057 case Intrinsic::xray_customevent: { 7058 // Here we want to make sure that the intrinsic behaves as if it has a 7059 // specific calling convention, and only for x86_64. 7060 // FIXME: Support other platforms later. 7061 const auto &Triple = DAG.getTarget().getTargetTriple(); 7062 if (Triple.getArch() != Triple::x86_64) 7063 return; 7064 7065 SmallVector<SDValue, 8> Ops; 7066 7067 // We want to say that we always want the arguments in registers. 7068 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7069 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7070 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7071 SDValue Chain = getRoot(); 7072 Ops.push_back(LogEntryVal); 7073 Ops.push_back(StrSizeVal); 7074 Ops.push_back(Chain); 7075 7076 // We need to enforce the calling convention for the callsite, so that 7077 // argument ordering is enforced correctly, and that register allocation can 7078 // see that some registers may be assumed clobbered and have to preserve 7079 // them across calls to the intrinsic. 7080 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7081 sdl, NodeTys, Ops); 7082 SDValue patchableNode = SDValue(MN, 0); 7083 DAG.setRoot(patchableNode); 7084 setValue(&I, patchableNode); 7085 return; 7086 } 7087 case Intrinsic::xray_typedevent: { 7088 // Here we want to make sure that the intrinsic behaves as if it has a 7089 // specific calling convention, and only for x86_64. 7090 // FIXME: Support other platforms later. 7091 const auto &Triple = DAG.getTarget().getTargetTriple(); 7092 if (Triple.getArch() != Triple::x86_64) 7093 return; 7094 7095 SmallVector<SDValue, 8> Ops; 7096 7097 // We want to say that we always want the arguments in registers. 7098 // It's unclear to me how manipulating the selection DAG here forces callers 7099 // to provide arguments in registers instead of on the stack. 7100 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7101 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7102 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7103 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7104 SDValue Chain = getRoot(); 7105 Ops.push_back(LogTypeId); 7106 Ops.push_back(LogEntryVal); 7107 Ops.push_back(StrSizeVal); 7108 Ops.push_back(Chain); 7109 7110 // We need to enforce the calling convention for the callsite, so that 7111 // argument ordering is enforced correctly, and that register allocation can 7112 // see that some registers may be assumed clobbered and have to preserve 7113 // them across calls to the intrinsic. 7114 MachineSDNode *MN = DAG.getMachineNode( 7115 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7116 SDValue patchableNode = SDValue(MN, 0); 7117 DAG.setRoot(patchableNode); 7118 setValue(&I, patchableNode); 7119 return; 7120 } 7121 case Intrinsic::experimental_deoptimize: 7122 LowerDeoptimizeCall(&I); 7123 return; 7124 case Intrinsic::experimental_stepvector: 7125 visitStepVector(I); 7126 return; 7127 case Intrinsic::vector_reduce_fadd: 7128 case Intrinsic::vector_reduce_fmul: 7129 case Intrinsic::vector_reduce_add: 7130 case Intrinsic::vector_reduce_mul: 7131 case Intrinsic::vector_reduce_and: 7132 case Intrinsic::vector_reduce_or: 7133 case Intrinsic::vector_reduce_xor: 7134 case Intrinsic::vector_reduce_smax: 7135 case Intrinsic::vector_reduce_smin: 7136 case Intrinsic::vector_reduce_umax: 7137 case Intrinsic::vector_reduce_umin: 7138 case Intrinsic::vector_reduce_fmax: 7139 case Intrinsic::vector_reduce_fmin: 7140 visitVectorReduce(I, Intrinsic); 7141 return; 7142 7143 case Intrinsic::icall_branch_funnel: { 7144 SmallVector<SDValue, 16> Ops; 7145 Ops.push_back(getValue(I.getArgOperand(0))); 7146 7147 int64_t Offset; 7148 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7149 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7150 if (!Base) 7151 report_fatal_error( 7152 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7153 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7154 7155 struct BranchFunnelTarget { 7156 int64_t Offset; 7157 SDValue Target; 7158 }; 7159 SmallVector<BranchFunnelTarget, 8> Targets; 7160 7161 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7162 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7163 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7164 if (ElemBase != Base) 7165 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7166 "to the same GlobalValue"); 7167 7168 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7169 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7170 if (!GA) 7171 report_fatal_error( 7172 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7173 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7174 GA->getGlobal(), sdl, Val.getValueType(), 7175 GA->getOffset())}); 7176 } 7177 llvm::sort(Targets, 7178 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7179 return T1.Offset < T2.Offset; 7180 }); 7181 7182 for (auto &T : Targets) { 7183 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7184 Ops.push_back(T.Target); 7185 } 7186 7187 Ops.push_back(DAG.getRoot()); // Chain 7188 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7189 MVT::Other, Ops), 7190 0); 7191 DAG.setRoot(N); 7192 setValue(&I, N); 7193 HasTailCall = true; 7194 return; 7195 } 7196 7197 case Intrinsic::wasm_landingpad_index: 7198 // Information this intrinsic contained has been transferred to 7199 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7200 // delete it now. 7201 return; 7202 7203 case Intrinsic::aarch64_settag: 7204 case Intrinsic::aarch64_settag_zero: { 7205 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7206 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7207 SDValue Val = TSI.EmitTargetCodeForSetTag( 7208 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7209 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7210 ZeroMemory); 7211 DAG.setRoot(Val); 7212 setValue(&I, Val); 7213 return; 7214 } 7215 case Intrinsic::ptrmask: { 7216 SDValue Ptr = getValue(I.getOperand(0)); 7217 SDValue Const = getValue(I.getOperand(1)); 7218 7219 EVT PtrVT = Ptr.getValueType(); 7220 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7221 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7222 return; 7223 } 7224 case Intrinsic::threadlocal_address: { 7225 setValue(&I, getValue(I.getOperand(0))); 7226 return; 7227 } 7228 case Intrinsic::get_active_lane_mask: { 7229 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7230 SDValue Index = getValue(I.getOperand(0)); 7231 EVT ElementVT = Index.getValueType(); 7232 7233 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7234 visitTargetIntrinsic(I, Intrinsic); 7235 return; 7236 } 7237 7238 SDValue TripCount = getValue(I.getOperand(1)); 7239 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7240 7241 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7242 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7243 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7244 SDValue VectorInduction = DAG.getNode( 7245 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7246 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7247 VectorTripCount, ISD::CondCode::SETULT); 7248 setValue(&I, SetCC); 7249 return; 7250 } 7251 case Intrinsic::vector_insert: { 7252 SDValue Vec = getValue(I.getOperand(0)); 7253 SDValue SubVec = getValue(I.getOperand(1)); 7254 SDValue Index = getValue(I.getOperand(2)); 7255 7256 // The intrinsic's index type is i64, but the SDNode requires an index type 7257 // suitable for the target. Convert the index as required. 7258 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7259 if (Index.getValueType() != VectorIdxTy) 7260 Index = DAG.getVectorIdxConstant( 7261 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7262 7263 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7264 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7265 Index)); 7266 return; 7267 } 7268 case Intrinsic::vector_extract: { 7269 SDValue Vec = getValue(I.getOperand(0)); 7270 SDValue Index = getValue(I.getOperand(1)); 7271 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7272 7273 // The intrinsic's index type is i64, but the SDNode requires an index type 7274 // suitable for the target. Convert the index as required. 7275 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7276 if (Index.getValueType() != VectorIdxTy) 7277 Index = DAG.getVectorIdxConstant( 7278 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7279 7280 setValue(&I, 7281 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7282 return; 7283 } 7284 case Intrinsic::experimental_vector_reverse: 7285 visitVectorReverse(I); 7286 return; 7287 case Intrinsic::experimental_vector_splice: 7288 visitVectorSplice(I); 7289 return; 7290 } 7291 } 7292 7293 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7294 const ConstrainedFPIntrinsic &FPI) { 7295 SDLoc sdl = getCurSDLoc(); 7296 7297 // We do not need to serialize constrained FP intrinsics against 7298 // each other or against (nonvolatile) loads, so they can be 7299 // chained like loads. 7300 SDValue Chain = DAG.getRoot(); 7301 SmallVector<SDValue, 4> Opers; 7302 Opers.push_back(Chain); 7303 if (FPI.isUnaryOp()) { 7304 Opers.push_back(getValue(FPI.getArgOperand(0))); 7305 } else if (FPI.isTernaryOp()) { 7306 Opers.push_back(getValue(FPI.getArgOperand(0))); 7307 Opers.push_back(getValue(FPI.getArgOperand(1))); 7308 Opers.push_back(getValue(FPI.getArgOperand(2))); 7309 } else { 7310 Opers.push_back(getValue(FPI.getArgOperand(0))); 7311 Opers.push_back(getValue(FPI.getArgOperand(1))); 7312 } 7313 7314 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7315 assert(Result.getNode()->getNumValues() == 2); 7316 7317 // Push node to the appropriate list so that future instructions can be 7318 // chained up correctly. 7319 SDValue OutChain = Result.getValue(1); 7320 switch (EB) { 7321 case fp::ExceptionBehavior::ebIgnore: 7322 // The only reason why ebIgnore nodes still need to be chained is that 7323 // they might depend on the current rounding mode, and therefore must 7324 // not be moved across instruction that may change that mode. 7325 [[fallthrough]]; 7326 case fp::ExceptionBehavior::ebMayTrap: 7327 // These must not be moved across calls or instructions that may change 7328 // floating-point exception masks. 7329 PendingConstrainedFP.push_back(OutChain); 7330 break; 7331 case fp::ExceptionBehavior::ebStrict: 7332 // These must not be moved across calls or instructions that may change 7333 // floating-point exception masks or read floating-point exception flags. 7334 // In addition, they cannot be optimized out even if unused. 7335 PendingConstrainedFPStrict.push_back(OutChain); 7336 break; 7337 } 7338 }; 7339 7340 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7341 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7342 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7343 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7344 7345 SDNodeFlags Flags; 7346 if (EB == fp::ExceptionBehavior::ebIgnore) 7347 Flags.setNoFPExcept(true); 7348 7349 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7350 Flags.copyFMF(*FPOp); 7351 7352 unsigned Opcode; 7353 switch (FPI.getIntrinsicID()) { 7354 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7355 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7356 case Intrinsic::INTRINSIC: \ 7357 Opcode = ISD::STRICT_##DAGN; \ 7358 break; 7359 #include "llvm/IR/ConstrainedOps.def" 7360 case Intrinsic::experimental_constrained_fmuladd: { 7361 Opcode = ISD::STRICT_FMA; 7362 // Break fmuladd into fmul and fadd. 7363 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7364 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7365 Opers.pop_back(); 7366 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7367 pushOutChain(Mul, EB); 7368 Opcode = ISD::STRICT_FADD; 7369 Opers.clear(); 7370 Opers.push_back(Mul.getValue(1)); 7371 Opers.push_back(Mul.getValue(0)); 7372 Opers.push_back(getValue(FPI.getArgOperand(2))); 7373 } 7374 break; 7375 } 7376 } 7377 7378 // A few strict DAG nodes carry additional operands that are not 7379 // set up by the default code above. 7380 switch (Opcode) { 7381 default: break; 7382 case ISD::STRICT_FP_ROUND: 7383 Opers.push_back( 7384 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7385 break; 7386 case ISD::STRICT_FSETCC: 7387 case ISD::STRICT_FSETCCS: { 7388 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7389 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7390 if (TM.Options.NoNaNsFPMath) 7391 Condition = getFCmpCodeWithoutNaN(Condition); 7392 Opers.push_back(DAG.getCondCode(Condition)); 7393 break; 7394 } 7395 } 7396 7397 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7398 pushOutChain(Result, EB); 7399 7400 SDValue FPResult = Result.getValue(0); 7401 setValue(&FPI, FPResult); 7402 } 7403 7404 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7405 Optional<unsigned> ResOPC; 7406 switch (VPIntrin.getIntrinsicID()) { 7407 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7408 case Intrinsic::VPID: \ 7409 ResOPC = ISD::VPSD; \ 7410 break; 7411 #include "llvm/IR/VPIntrinsics.def" 7412 } 7413 7414 if (!ResOPC) 7415 llvm_unreachable( 7416 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7417 7418 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7419 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7420 if (VPIntrin.getFastMathFlags().allowReassoc()) 7421 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7422 : ISD::VP_REDUCE_FMUL; 7423 } 7424 7425 return *ResOPC; 7426 } 7427 7428 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT, 7429 SmallVector<SDValue, 7> &OpValues) { 7430 SDLoc DL = getCurSDLoc(); 7431 Value *PtrOperand = VPIntrin.getArgOperand(0); 7432 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7433 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7434 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7435 SDValue LD; 7436 bool AddToChain = true; 7437 // Do not serialize variable-length loads of constant memory with 7438 // anything. 7439 if (!Alignment) 7440 Alignment = DAG.getEVTAlign(VT); 7441 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7442 AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7443 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7444 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7445 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7446 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7447 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7448 MMO, false /*IsExpanding */); 7449 if (AddToChain) 7450 PendingLoads.push_back(LD.getValue(1)); 7451 setValue(&VPIntrin, LD); 7452 } 7453 7454 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT, 7455 SmallVector<SDValue, 7> &OpValues) { 7456 SDLoc DL = getCurSDLoc(); 7457 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7458 Value *PtrOperand = VPIntrin.getArgOperand(0); 7459 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7460 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7461 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7462 SDValue LD; 7463 if (!Alignment) 7464 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7465 unsigned AS = 7466 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7467 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7468 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7469 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7470 SDValue Base, Index, Scale; 7471 ISD::MemIndexType IndexType; 7472 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7473 this, VPIntrin.getParent(), 7474 VT.getScalarStoreSize()); 7475 if (!UniformBase) { 7476 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7477 Index = getValue(PtrOperand); 7478 IndexType = ISD::SIGNED_SCALED; 7479 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7480 } 7481 EVT IdxVT = Index.getValueType(); 7482 EVT EltTy = IdxVT.getVectorElementType(); 7483 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7484 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7485 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7486 } 7487 LD = DAG.getGatherVP( 7488 DAG.getVTList(VT, MVT::Other), VT, DL, 7489 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7490 IndexType); 7491 PendingLoads.push_back(LD.getValue(1)); 7492 setValue(&VPIntrin, LD); 7493 } 7494 7495 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin, 7496 SmallVector<SDValue, 7> &OpValues) { 7497 SDLoc DL = getCurSDLoc(); 7498 Value *PtrOperand = VPIntrin.getArgOperand(1); 7499 EVT VT = OpValues[0].getValueType(); 7500 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7501 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7502 SDValue ST; 7503 if (!Alignment) 7504 Alignment = DAG.getEVTAlign(VT); 7505 SDValue Ptr = OpValues[1]; 7506 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7507 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7508 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7509 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7510 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7511 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7512 /* IsTruncating */ false, /*IsCompressing*/ false); 7513 DAG.setRoot(ST); 7514 setValue(&VPIntrin, ST); 7515 } 7516 7517 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin, 7518 SmallVector<SDValue, 7> &OpValues) { 7519 SDLoc DL = getCurSDLoc(); 7520 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7521 Value *PtrOperand = VPIntrin.getArgOperand(1); 7522 EVT VT = OpValues[0].getValueType(); 7523 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7524 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7525 SDValue ST; 7526 if (!Alignment) 7527 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7528 unsigned AS = 7529 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7530 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7531 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7532 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7533 SDValue Base, Index, Scale; 7534 ISD::MemIndexType IndexType; 7535 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7536 this, VPIntrin.getParent(), 7537 VT.getScalarStoreSize()); 7538 if (!UniformBase) { 7539 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7540 Index = getValue(PtrOperand); 7541 IndexType = ISD::SIGNED_SCALED; 7542 Scale = 7543 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7544 } 7545 EVT IdxVT = Index.getValueType(); 7546 EVT EltTy = IdxVT.getVectorElementType(); 7547 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7548 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7549 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7550 } 7551 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7552 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7553 OpValues[2], OpValues[3]}, 7554 MMO, IndexType); 7555 DAG.setRoot(ST); 7556 setValue(&VPIntrin, ST); 7557 } 7558 7559 void SelectionDAGBuilder::visitVPStridedLoad( 7560 const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) { 7561 SDLoc DL = getCurSDLoc(); 7562 Value *PtrOperand = VPIntrin.getArgOperand(0); 7563 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7564 if (!Alignment) 7565 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7566 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7567 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7568 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7569 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7570 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7571 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7572 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7573 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7574 7575 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7576 OpValues[2], OpValues[3], MMO, 7577 false /*IsExpanding*/); 7578 7579 if (AddToChain) 7580 PendingLoads.push_back(LD.getValue(1)); 7581 setValue(&VPIntrin, LD); 7582 } 7583 7584 void SelectionDAGBuilder::visitVPStridedStore( 7585 const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) { 7586 SDLoc DL = getCurSDLoc(); 7587 Value *PtrOperand = VPIntrin.getArgOperand(1); 7588 EVT VT = OpValues[0].getValueType(); 7589 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7590 if (!Alignment) 7591 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7592 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7593 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7594 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7595 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7596 7597 SDValue ST = DAG.getStridedStoreVP( 7598 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7599 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7600 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7601 /*IsCompressing*/ false); 7602 7603 DAG.setRoot(ST); 7604 setValue(&VPIntrin, ST); 7605 } 7606 7607 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7608 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7609 SDLoc DL = getCurSDLoc(); 7610 7611 ISD::CondCode Condition; 7612 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7613 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7614 if (IsFP) { 7615 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7616 // flags, but calls that don't return floating-point types can't be 7617 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7618 Condition = getFCmpCondCode(CondCode); 7619 if (TM.Options.NoNaNsFPMath) 7620 Condition = getFCmpCodeWithoutNaN(Condition); 7621 } else { 7622 Condition = getICmpCondCode(CondCode); 7623 } 7624 7625 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7626 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7627 // #2 is the condition code 7628 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7629 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7630 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7631 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7632 "Unexpected target EVL type"); 7633 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7634 7635 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7636 VPIntrin.getType()); 7637 setValue(&VPIntrin, 7638 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7639 } 7640 7641 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7642 const VPIntrinsic &VPIntrin) { 7643 SDLoc DL = getCurSDLoc(); 7644 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7645 7646 auto IID = VPIntrin.getIntrinsicID(); 7647 7648 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7649 return visitVPCmp(*CmpI); 7650 7651 SmallVector<EVT, 4> ValueVTs; 7652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7653 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7654 SDVTList VTs = DAG.getVTList(ValueVTs); 7655 7656 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7657 7658 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7659 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7660 "Unexpected target EVL type"); 7661 7662 // Request operands. 7663 SmallVector<SDValue, 7> OpValues; 7664 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7665 auto Op = getValue(VPIntrin.getArgOperand(I)); 7666 if (I == EVLParamPos) 7667 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7668 OpValues.push_back(Op); 7669 } 7670 7671 switch (Opcode) { 7672 default: { 7673 SDNodeFlags SDFlags; 7674 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7675 SDFlags.copyFMF(*FPMO); 7676 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7677 setValue(&VPIntrin, Result); 7678 break; 7679 } 7680 case ISD::VP_LOAD: 7681 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7682 break; 7683 case ISD::VP_GATHER: 7684 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7685 break; 7686 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7687 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7688 break; 7689 case ISD::VP_STORE: 7690 visitVPStore(VPIntrin, OpValues); 7691 break; 7692 case ISD::VP_SCATTER: 7693 visitVPScatter(VPIntrin, OpValues); 7694 break; 7695 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7696 visitVPStridedStore(VPIntrin, OpValues); 7697 break; 7698 case ISD::VP_FMULADD: { 7699 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7700 SDNodeFlags SDFlags; 7701 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7702 SDFlags.copyFMF(*FPMO); 7703 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7704 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7705 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7706 } else { 7707 SDValue Mul = DAG.getNode( 7708 ISD::VP_FMUL, DL, VTs, 7709 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7710 SDValue Add = 7711 DAG.getNode(ISD::VP_FADD, DL, VTs, 7712 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7713 setValue(&VPIntrin, Add); 7714 } 7715 break; 7716 } 7717 } 7718 } 7719 7720 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7721 const BasicBlock *EHPadBB, 7722 MCSymbol *&BeginLabel) { 7723 MachineFunction &MF = DAG.getMachineFunction(); 7724 MachineModuleInfo &MMI = MF.getMMI(); 7725 7726 // Insert a label before the invoke call to mark the try range. This can be 7727 // used to detect deletion of the invoke via the MachineModuleInfo. 7728 BeginLabel = MMI.getContext().createTempSymbol(); 7729 7730 // For SjLj, keep track of which landing pads go with which invokes 7731 // so as to maintain the ordering of pads in the LSDA. 7732 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7733 if (CallSiteIndex) { 7734 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7735 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7736 7737 // Now that the call site is handled, stop tracking it. 7738 MMI.setCurrentCallSite(0); 7739 } 7740 7741 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7742 } 7743 7744 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7745 const BasicBlock *EHPadBB, 7746 MCSymbol *BeginLabel) { 7747 assert(BeginLabel && "BeginLabel should've been set"); 7748 7749 MachineFunction &MF = DAG.getMachineFunction(); 7750 MachineModuleInfo &MMI = MF.getMMI(); 7751 7752 // Insert a label at the end of the invoke call to mark the try range. This 7753 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7754 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7755 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7756 7757 // Inform MachineModuleInfo of range. 7758 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7759 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7760 // actually use outlined funclets and their LSDA info style. 7761 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7762 assert(II && "II should've been set"); 7763 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7764 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7765 } else if (!isScopedEHPersonality(Pers)) { 7766 assert(EHPadBB); 7767 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7768 } 7769 7770 return Chain; 7771 } 7772 7773 std::pair<SDValue, SDValue> 7774 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7775 const BasicBlock *EHPadBB) { 7776 MCSymbol *BeginLabel = nullptr; 7777 7778 if (EHPadBB) { 7779 // Both PendingLoads and PendingExports must be flushed here; 7780 // this call might not return. 7781 (void)getRoot(); 7782 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7783 CLI.setChain(getRoot()); 7784 } 7785 7786 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7787 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7788 7789 assert((CLI.IsTailCall || Result.second.getNode()) && 7790 "Non-null chain expected with non-tail call!"); 7791 assert((Result.second.getNode() || !Result.first.getNode()) && 7792 "Null value expected with tail call!"); 7793 7794 if (!Result.second.getNode()) { 7795 // As a special case, a null chain means that a tail call has been emitted 7796 // and the DAG root is already updated. 7797 HasTailCall = true; 7798 7799 // Since there's no actual continuation from this block, nothing can be 7800 // relying on us setting vregs for them. 7801 PendingExports.clear(); 7802 } else { 7803 DAG.setRoot(Result.second); 7804 } 7805 7806 if (EHPadBB) { 7807 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7808 BeginLabel)); 7809 } 7810 7811 return Result; 7812 } 7813 7814 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7815 bool isTailCall, 7816 bool isMustTailCall, 7817 const BasicBlock *EHPadBB) { 7818 auto &DL = DAG.getDataLayout(); 7819 FunctionType *FTy = CB.getFunctionType(); 7820 Type *RetTy = CB.getType(); 7821 7822 TargetLowering::ArgListTy Args; 7823 Args.reserve(CB.arg_size()); 7824 7825 const Value *SwiftErrorVal = nullptr; 7826 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7827 7828 if (isTailCall) { 7829 // Avoid emitting tail calls in functions with the disable-tail-calls 7830 // attribute. 7831 auto *Caller = CB.getParent()->getParent(); 7832 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7833 "true" && !isMustTailCall) 7834 isTailCall = false; 7835 7836 // We can't tail call inside a function with a swifterror argument. Lowering 7837 // does not support this yet. It would have to move into the swifterror 7838 // register before the call. 7839 if (TLI.supportSwiftError() && 7840 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7841 isTailCall = false; 7842 } 7843 7844 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7845 TargetLowering::ArgListEntry Entry; 7846 const Value *V = *I; 7847 7848 // Skip empty types 7849 if (V->getType()->isEmptyTy()) 7850 continue; 7851 7852 SDValue ArgNode = getValue(V); 7853 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7854 7855 Entry.setAttributes(&CB, I - CB.arg_begin()); 7856 7857 // Use swifterror virtual register as input to the call. 7858 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7859 SwiftErrorVal = V; 7860 // We find the virtual register for the actual swifterror argument. 7861 // Instead of using the Value, we use the virtual register instead. 7862 Entry.Node = 7863 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7864 EVT(TLI.getPointerTy(DL))); 7865 } 7866 7867 Args.push_back(Entry); 7868 7869 // If we have an explicit sret argument that is an Instruction, (i.e., it 7870 // might point to function-local memory), we can't meaningfully tail-call. 7871 if (Entry.IsSRet && isa<Instruction>(V)) 7872 isTailCall = false; 7873 } 7874 7875 // If call site has a cfguardtarget operand bundle, create and add an 7876 // additional ArgListEntry. 7877 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7878 TargetLowering::ArgListEntry Entry; 7879 Value *V = Bundle->Inputs[0]; 7880 SDValue ArgNode = getValue(V); 7881 Entry.Node = ArgNode; 7882 Entry.Ty = V->getType(); 7883 Entry.IsCFGuardTarget = true; 7884 Args.push_back(Entry); 7885 } 7886 7887 // Check if target-independent constraints permit a tail call here. 7888 // Target-dependent constraints are checked within TLI->LowerCallTo. 7889 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7890 isTailCall = false; 7891 7892 // Disable tail calls if there is an swifterror argument. Targets have not 7893 // been updated to support tail calls. 7894 if (TLI.supportSwiftError() && SwiftErrorVal) 7895 isTailCall = false; 7896 7897 ConstantInt *CFIType = nullptr; 7898 if (CB.isIndirectCall()) { 7899 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 7900 if (!TLI.supportKCFIBundles()) 7901 report_fatal_error( 7902 "Target doesn't support calls with kcfi operand bundles."); 7903 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 7904 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 7905 } 7906 } 7907 7908 TargetLowering::CallLoweringInfo CLI(DAG); 7909 CLI.setDebugLoc(getCurSDLoc()) 7910 .setChain(getRoot()) 7911 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7912 .setTailCall(isTailCall) 7913 .setConvergent(CB.isConvergent()) 7914 .setIsPreallocated( 7915 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 7916 .setCFIType(CFIType); 7917 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7918 7919 if (Result.first.getNode()) { 7920 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7921 setValue(&CB, Result.first); 7922 } 7923 7924 // The last element of CLI.InVals has the SDValue for swifterror return. 7925 // Here we copy it to a virtual register and update SwiftErrorMap for 7926 // book-keeping. 7927 if (SwiftErrorVal && TLI.supportSwiftError()) { 7928 // Get the last element of InVals. 7929 SDValue Src = CLI.InVals.back(); 7930 Register VReg = 7931 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7932 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7933 DAG.setRoot(CopyNode); 7934 } 7935 } 7936 7937 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7938 SelectionDAGBuilder &Builder) { 7939 // Check to see if this load can be trivially constant folded, e.g. if the 7940 // input is from a string literal. 7941 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7942 // Cast pointer to the type we really want to load. 7943 Type *LoadTy = 7944 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7945 if (LoadVT.isVector()) 7946 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7947 7948 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7949 PointerType::getUnqual(LoadTy)); 7950 7951 if (const Constant *LoadCst = 7952 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 7953 LoadTy, Builder.DAG.getDataLayout())) 7954 return Builder.getValue(LoadCst); 7955 } 7956 7957 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7958 // still constant memory, the input chain can be the entry node. 7959 SDValue Root; 7960 bool ConstantMemory = false; 7961 7962 // Do not serialize (non-volatile) loads of constant memory with anything. 7963 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7964 Root = Builder.DAG.getEntryNode(); 7965 ConstantMemory = true; 7966 } else { 7967 // Do not serialize non-volatile loads against each other. 7968 Root = Builder.DAG.getRoot(); 7969 } 7970 7971 SDValue Ptr = Builder.getValue(PtrVal); 7972 SDValue LoadVal = 7973 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7974 MachinePointerInfo(PtrVal), Align(1)); 7975 7976 if (!ConstantMemory) 7977 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7978 return LoadVal; 7979 } 7980 7981 /// Record the value for an instruction that produces an integer result, 7982 /// converting the type where necessary. 7983 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7984 SDValue Value, 7985 bool IsSigned) { 7986 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7987 I.getType(), true); 7988 if (IsSigned) 7989 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7990 else 7991 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7992 setValue(&I, Value); 7993 } 7994 7995 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7996 /// true and lower it. Otherwise return false, and it will be lowered like a 7997 /// normal call. 7998 /// The caller already checked that \p I calls the appropriate LibFunc with a 7999 /// correct prototype. 8000 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8001 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8002 const Value *Size = I.getArgOperand(2); 8003 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8004 if (CSize && CSize->getZExtValue() == 0) { 8005 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8006 I.getType(), true); 8007 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8008 return true; 8009 } 8010 8011 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8012 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8013 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8014 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8015 if (Res.first.getNode()) { 8016 processIntegerCallValue(I, Res.first, true); 8017 PendingLoads.push_back(Res.second); 8018 return true; 8019 } 8020 8021 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8022 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8023 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8024 return false; 8025 8026 // If the target has a fast compare for the given size, it will return a 8027 // preferred load type for that size. Require that the load VT is legal and 8028 // that the target supports unaligned loads of that type. Otherwise, return 8029 // INVALID. 8030 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8031 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8032 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8033 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8034 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8035 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8036 // TODO: Check alignment of src and dest ptrs. 8037 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8038 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8039 if (!TLI.isTypeLegal(LVT) || 8040 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8041 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8042 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8043 } 8044 8045 return LVT; 8046 }; 8047 8048 // This turns into unaligned loads. We only do this if the target natively 8049 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8050 // we'll only produce a small number of byte loads. 8051 MVT LoadVT; 8052 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8053 switch (NumBitsToCompare) { 8054 default: 8055 return false; 8056 case 16: 8057 LoadVT = MVT::i16; 8058 break; 8059 case 32: 8060 LoadVT = MVT::i32; 8061 break; 8062 case 64: 8063 case 128: 8064 case 256: 8065 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8066 break; 8067 } 8068 8069 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8070 return false; 8071 8072 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8073 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8074 8075 // Bitcast to a wide integer type if the loads are vectors. 8076 if (LoadVT.isVector()) { 8077 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8078 LoadL = DAG.getBitcast(CmpVT, LoadL); 8079 LoadR = DAG.getBitcast(CmpVT, LoadR); 8080 } 8081 8082 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8083 processIntegerCallValue(I, Cmp, false); 8084 return true; 8085 } 8086 8087 /// See if we can lower a memchr call into an optimized form. If so, return 8088 /// true and lower it. Otherwise return false, and it will be lowered like a 8089 /// normal call. 8090 /// The caller already checked that \p I calls the appropriate LibFunc with a 8091 /// correct prototype. 8092 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8093 const Value *Src = I.getArgOperand(0); 8094 const Value *Char = I.getArgOperand(1); 8095 const Value *Length = I.getArgOperand(2); 8096 8097 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8098 std::pair<SDValue, SDValue> Res = 8099 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8100 getValue(Src), getValue(Char), getValue(Length), 8101 MachinePointerInfo(Src)); 8102 if (Res.first.getNode()) { 8103 setValue(&I, Res.first); 8104 PendingLoads.push_back(Res.second); 8105 return true; 8106 } 8107 8108 return false; 8109 } 8110 8111 /// See if we can lower a mempcpy call into an optimized form. If so, return 8112 /// true and lower it. Otherwise return false, and it will be lowered like a 8113 /// normal call. 8114 /// The caller already checked that \p I calls the appropriate LibFunc with a 8115 /// correct prototype. 8116 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8117 SDValue Dst = getValue(I.getArgOperand(0)); 8118 SDValue Src = getValue(I.getArgOperand(1)); 8119 SDValue Size = getValue(I.getArgOperand(2)); 8120 8121 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8122 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8123 // DAG::getMemcpy needs Alignment to be defined. 8124 Align Alignment = std::min(DstAlign, SrcAlign); 8125 8126 bool isVol = false; 8127 SDLoc sdl = getCurSDLoc(); 8128 8129 // In the mempcpy context we need to pass in a false value for isTailCall 8130 // because the return pointer needs to be adjusted by the size of 8131 // the copied memory. 8132 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 8133 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 8134 /*isTailCall=*/false, 8135 MachinePointerInfo(I.getArgOperand(0)), 8136 MachinePointerInfo(I.getArgOperand(1)), 8137 I.getAAMetadata()); 8138 assert(MC.getNode() != nullptr && 8139 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8140 DAG.setRoot(MC); 8141 8142 // Check if Size needs to be truncated or extended. 8143 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8144 8145 // Adjust return pointer to point just past the last dst byte. 8146 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8147 Dst, Size); 8148 setValue(&I, DstPlusSize); 8149 return true; 8150 } 8151 8152 /// See if we can lower a strcpy call into an optimized form. If so, return 8153 /// true and lower it, otherwise return false and it will be lowered like a 8154 /// normal call. 8155 /// The caller already checked that \p I calls the appropriate LibFunc with a 8156 /// correct prototype. 8157 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8158 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8159 8160 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8161 std::pair<SDValue, SDValue> Res = 8162 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8163 getValue(Arg0), getValue(Arg1), 8164 MachinePointerInfo(Arg0), 8165 MachinePointerInfo(Arg1), isStpcpy); 8166 if (Res.first.getNode()) { 8167 setValue(&I, Res.first); 8168 DAG.setRoot(Res.second); 8169 return true; 8170 } 8171 8172 return false; 8173 } 8174 8175 /// See if we can lower a strcmp call into an optimized form. If so, return 8176 /// true and lower it, otherwise return false and it will be lowered like a 8177 /// normal call. 8178 /// The caller already checked that \p I calls the appropriate LibFunc with a 8179 /// correct prototype. 8180 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8181 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8182 8183 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8184 std::pair<SDValue, SDValue> Res = 8185 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8186 getValue(Arg0), getValue(Arg1), 8187 MachinePointerInfo(Arg0), 8188 MachinePointerInfo(Arg1)); 8189 if (Res.first.getNode()) { 8190 processIntegerCallValue(I, Res.first, true); 8191 PendingLoads.push_back(Res.second); 8192 return true; 8193 } 8194 8195 return false; 8196 } 8197 8198 /// See if we can lower a strlen call into an optimized form. If so, return 8199 /// true and lower it, otherwise return false and it will be lowered like a 8200 /// normal call. 8201 /// The caller already checked that \p I calls the appropriate LibFunc with a 8202 /// correct prototype. 8203 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8204 const Value *Arg0 = I.getArgOperand(0); 8205 8206 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8207 std::pair<SDValue, SDValue> Res = 8208 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8209 getValue(Arg0), MachinePointerInfo(Arg0)); 8210 if (Res.first.getNode()) { 8211 processIntegerCallValue(I, Res.first, false); 8212 PendingLoads.push_back(Res.second); 8213 return true; 8214 } 8215 8216 return false; 8217 } 8218 8219 /// See if we can lower a strnlen call into an optimized form. If so, return 8220 /// true and lower it, otherwise return false and it will be lowered like a 8221 /// normal call. 8222 /// The caller already checked that \p I calls the appropriate LibFunc with a 8223 /// correct prototype. 8224 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8225 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8226 8227 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8228 std::pair<SDValue, SDValue> Res = 8229 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8230 getValue(Arg0), getValue(Arg1), 8231 MachinePointerInfo(Arg0)); 8232 if (Res.first.getNode()) { 8233 processIntegerCallValue(I, Res.first, false); 8234 PendingLoads.push_back(Res.second); 8235 return true; 8236 } 8237 8238 return false; 8239 } 8240 8241 /// See if we can lower a unary floating-point operation into an SDNode with 8242 /// the specified Opcode. If so, return true and lower it, otherwise return 8243 /// false and it will be lowered like a normal call. 8244 /// The caller already checked that \p I calls the appropriate LibFunc with a 8245 /// correct prototype. 8246 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8247 unsigned Opcode) { 8248 // We already checked this call's prototype; verify it doesn't modify errno. 8249 if (!I.onlyReadsMemory()) 8250 return false; 8251 8252 SDNodeFlags Flags; 8253 Flags.copyFMF(cast<FPMathOperator>(I)); 8254 8255 SDValue Tmp = getValue(I.getArgOperand(0)); 8256 setValue(&I, 8257 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8258 return true; 8259 } 8260 8261 /// See if we can lower a binary floating-point operation into an SDNode with 8262 /// the specified Opcode. If so, return true and lower it. Otherwise return 8263 /// false, and it will be lowered like a normal call. 8264 /// The caller already checked that \p I calls the appropriate LibFunc with a 8265 /// correct prototype. 8266 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8267 unsigned Opcode) { 8268 // We already checked this call's prototype; verify it doesn't modify errno. 8269 if (!I.onlyReadsMemory()) 8270 return false; 8271 8272 SDNodeFlags Flags; 8273 Flags.copyFMF(cast<FPMathOperator>(I)); 8274 8275 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8276 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8277 EVT VT = Tmp0.getValueType(); 8278 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8279 return true; 8280 } 8281 8282 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8283 // Handle inline assembly differently. 8284 if (I.isInlineAsm()) { 8285 visitInlineAsm(I); 8286 return; 8287 } 8288 8289 if (Function *F = I.getCalledFunction()) { 8290 diagnoseDontCall(I); 8291 8292 if (F->isDeclaration()) { 8293 // Is this an LLVM intrinsic or a target-specific intrinsic? 8294 unsigned IID = F->getIntrinsicID(); 8295 if (!IID) 8296 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8297 IID = II->getIntrinsicID(F); 8298 8299 if (IID) { 8300 visitIntrinsicCall(I, IID); 8301 return; 8302 } 8303 } 8304 8305 // Check for well-known libc/libm calls. If the function is internal, it 8306 // can't be a library call. Don't do the check if marked as nobuiltin for 8307 // some reason or the call site requires strict floating point semantics. 8308 LibFunc Func; 8309 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8310 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8311 LibInfo->hasOptimizedCodeGen(Func)) { 8312 switch (Func) { 8313 default: break; 8314 case LibFunc_bcmp: 8315 if (visitMemCmpBCmpCall(I)) 8316 return; 8317 break; 8318 case LibFunc_copysign: 8319 case LibFunc_copysignf: 8320 case LibFunc_copysignl: 8321 // We already checked this call's prototype; verify it doesn't modify 8322 // errno. 8323 if (I.onlyReadsMemory()) { 8324 SDValue LHS = getValue(I.getArgOperand(0)); 8325 SDValue RHS = getValue(I.getArgOperand(1)); 8326 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8327 LHS.getValueType(), LHS, RHS)); 8328 return; 8329 } 8330 break; 8331 case LibFunc_fabs: 8332 case LibFunc_fabsf: 8333 case LibFunc_fabsl: 8334 if (visitUnaryFloatCall(I, ISD::FABS)) 8335 return; 8336 break; 8337 case LibFunc_fmin: 8338 case LibFunc_fminf: 8339 case LibFunc_fminl: 8340 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8341 return; 8342 break; 8343 case LibFunc_fmax: 8344 case LibFunc_fmaxf: 8345 case LibFunc_fmaxl: 8346 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8347 return; 8348 break; 8349 case LibFunc_sin: 8350 case LibFunc_sinf: 8351 case LibFunc_sinl: 8352 if (visitUnaryFloatCall(I, ISD::FSIN)) 8353 return; 8354 break; 8355 case LibFunc_cos: 8356 case LibFunc_cosf: 8357 case LibFunc_cosl: 8358 if (visitUnaryFloatCall(I, ISD::FCOS)) 8359 return; 8360 break; 8361 case LibFunc_sqrt: 8362 case LibFunc_sqrtf: 8363 case LibFunc_sqrtl: 8364 case LibFunc_sqrt_finite: 8365 case LibFunc_sqrtf_finite: 8366 case LibFunc_sqrtl_finite: 8367 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8368 return; 8369 break; 8370 case LibFunc_floor: 8371 case LibFunc_floorf: 8372 case LibFunc_floorl: 8373 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8374 return; 8375 break; 8376 case LibFunc_nearbyint: 8377 case LibFunc_nearbyintf: 8378 case LibFunc_nearbyintl: 8379 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8380 return; 8381 break; 8382 case LibFunc_ceil: 8383 case LibFunc_ceilf: 8384 case LibFunc_ceill: 8385 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8386 return; 8387 break; 8388 case LibFunc_rint: 8389 case LibFunc_rintf: 8390 case LibFunc_rintl: 8391 if (visitUnaryFloatCall(I, ISD::FRINT)) 8392 return; 8393 break; 8394 case LibFunc_round: 8395 case LibFunc_roundf: 8396 case LibFunc_roundl: 8397 if (visitUnaryFloatCall(I, ISD::FROUND)) 8398 return; 8399 break; 8400 case LibFunc_trunc: 8401 case LibFunc_truncf: 8402 case LibFunc_truncl: 8403 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8404 return; 8405 break; 8406 case LibFunc_log2: 8407 case LibFunc_log2f: 8408 case LibFunc_log2l: 8409 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8410 return; 8411 break; 8412 case LibFunc_exp2: 8413 case LibFunc_exp2f: 8414 case LibFunc_exp2l: 8415 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8416 return; 8417 break; 8418 case LibFunc_memcmp: 8419 if (visitMemCmpBCmpCall(I)) 8420 return; 8421 break; 8422 case LibFunc_mempcpy: 8423 if (visitMemPCpyCall(I)) 8424 return; 8425 break; 8426 case LibFunc_memchr: 8427 if (visitMemChrCall(I)) 8428 return; 8429 break; 8430 case LibFunc_strcpy: 8431 if (visitStrCpyCall(I, false)) 8432 return; 8433 break; 8434 case LibFunc_stpcpy: 8435 if (visitStrCpyCall(I, true)) 8436 return; 8437 break; 8438 case LibFunc_strcmp: 8439 if (visitStrCmpCall(I)) 8440 return; 8441 break; 8442 case LibFunc_strlen: 8443 if (visitStrLenCall(I)) 8444 return; 8445 break; 8446 case LibFunc_strnlen: 8447 if (visitStrNLenCall(I)) 8448 return; 8449 break; 8450 } 8451 } 8452 } 8453 8454 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8455 // have to do anything here to lower funclet bundles. 8456 // CFGuardTarget bundles are lowered in LowerCallTo. 8457 assert(!I.hasOperandBundlesOtherThan( 8458 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8459 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8460 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8461 "Cannot lower calls with arbitrary operand bundles!"); 8462 8463 SDValue Callee = getValue(I.getCalledOperand()); 8464 8465 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8466 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8467 else 8468 // Check if we can potentially perform a tail call. More detailed checking 8469 // is be done within LowerCallTo, after more information about the call is 8470 // known. 8471 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8472 } 8473 8474 namespace { 8475 8476 /// AsmOperandInfo - This contains information for each constraint that we are 8477 /// lowering. 8478 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8479 public: 8480 /// CallOperand - If this is the result output operand or a clobber 8481 /// this is null, otherwise it is the incoming operand to the CallInst. 8482 /// This gets modified as the asm is processed. 8483 SDValue CallOperand; 8484 8485 /// AssignedRegs - If this is a register or register class operand, this 8486 /// contains the set of register corresponding to the operand. 8487 RegsForValue AssignedRegs; 8488 8489 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8490 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8491 } 8492 8493 /// Whether or not this operand accesses memory 8494 bool hasMemory(const TargetLowering &TLI) const { 8495 // Indirect operand accesses access memory. 8496 if (isIndirect) 8497 return true; 8498 8499 for (const auto &Code : Codes) 8500 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8501 return true; 8502 8503 return false; 8504 } 8505 }; 8506 8507 8508 } // end anonymous namespace 8509 8510 /// Make sure that the output operand \p OpInfo and its corresponding input 8511 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8512 /// out). 8513 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8514 SDISelAsmOperandInfo &MatchingOpInfo, 8515 SelectionDAG &DAG) { 8516 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8517 return; 8518 8519 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8520 const auto &TLI = DAG.getTargetLoweringInfo(); 8521 8522 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8523 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8524 OpInfo.ConstraintVT); 8525 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8526 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8527 MatchingOpInfo.ConstraintVT); 8528 if ((OpInfo.ConstraintVT.isInteger() != 8529 MatchingOpInfo.ConstraintVT.isInteger()) || 8530 (MatchRC.second != InputRC.second)) { 8531 // FIXME: error out in a more elegant fashion 8532 report_fatal_error("Unsupported asm: input constraint" 8533 " with a matching output constraint of" 8534 " incompatible type!"); 8535 } 8536 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8537 } 8538 8539 /// Get a direct memory input to behave well as an indirect operand. 8540 /// This may introduce stores, hence the need for a \p Chain. 8541 /// \return The (possibly updated) chain. 8542 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8543 SDISelAsmOperandInfo &OpInfo, 8544 SelectionDAG &DAG) { 8545 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8546 8547 // If we don't have an indirect input, put it in the constpool if we can, 8548 // otherwise spill it to a stack slot. 8549 // TODO: This isn't quite right. We need to handle these according to 8550 // the addressing mode that the constraint wants. Also, this may take 8551 // an additional register for the computation and we don't want that 8552 // either. 8553 8554 // If the operand is a float, integer, or vector constant, spill to a 8555 // constant pool entry to get its address. 8556 const Value *OpVal = OpInfo.CallOperandVal; 8557 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8558 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8559 OpInfo.CallOperand = DAG.getConstantPool( 8560 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8561 return Chain; 8562 } 8563 8564 // Otherwise, create a stack slot and emit a store to it before the asm. 8565 Type *Ty = OpVal->getType(); 8566 auto &DL = DAG.getDataLayout(); 8567 uint64_t TySize = DL.getTypeAllocSize(Ty); 8568 MachineFunction &MF = DAG.getMachineFunction(); 8569 int SSFI = MF.getFrameInfo().CreateStackObject( 8570 TySize, DL.getPrefTypeAlign(Ty), false); 8571 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8572 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8573 MachinePointerInfo::getFixedStack(MF, SSFI), 8574 TLI.getMemValueType(DL, Ty)); 8575 OpInfo.CallOperand = StackSlot; 8576 8577 return Chain; 8578 } 8579 8580 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8581 /// specified operand. We prefer to assign virtual registers, to allow the 8582 /// register allocator to handle the assignment process. However, if the asm 8583 /// uses features that we can't model on machineinstrs, we have SDISel do the 8584 /// allocation. This produces generally horrible, but correct, code. 8585 /// 8586 /// OpInfo describes the operand 8587 /// RefOpInfo describes the matching operand if any, the operand otherwise 8588 static llvm::Optional<unsigned> 8589 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8590 SDISelAsmOperandInfo &OpInfo, 8591 SDISelAsmOperandInfo &RefOpInfo) { 8592 LLVMContext &Context = *DAG.getContext(); 8593 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8594 8595 MachineFunction &MF = DAG.getMachineFunction(); 8596 SmallVector<unsigned, 4> Regs; 8597 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8598 8599 // No work to do for memory/address operands. 8600 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8601 OpInfo.ConstraintType == TargetLowering::C_Address) 8602 return None; 8603 8604 // If this is a constraint for a single physreg, or a constraint for a 8605 // register class, find it. 8606 unsigned AssignedReg; 8607 const TargetRegisterClass *RC; 8608 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8609 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8610 // RC is unset only on failure. Return immediately. 8611 if (!RC) 8612 return None; 8613 8614 // Get the actual register value type. This is important, because the user 8615 // may have asked for (e.g.) the AX register in i32 type. We need to 8616 // remember that AX is actually i16 to get the right extension. 8617 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8618 8619 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8620 // If this is an FP operand in an integer register (or visa versa), or more 8621 // generally if the operand value disagrees with the register class we plan 8622 // to stick it in, fix the operand type. 8623 // 8624 // If this is an input value, the bitcast to the new type is done now. 8625 // Bitcast for output value is done at the end of visitInlineAsm(). 8626 if ((OpInfo.Type == InlineAsm::isOutput || 8627 OpInfo.Type == InlineAsm::isInput) && 8628 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8629 // Try to convert to the first EVT that the reg class contains. If the 8630 // types are identical size, use a bitcast to convert (e.g. two differing 8631 // vector types). Note: output bitcast is done at the end of 8632 // visitInlineAsm(). 8633 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8634 // Exclude indirect inputs while they are unsupported because the code 8635 // to perform the load is missing and thus OpInfo.CallOperand still 8636 // refers to the input address rather than the pointed-to value. 8637 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8638 OpInfo.CallOperand = 8639 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8640 OpInfo.ConstraintVT = RegVT; 8641 // If the operand is an FP value and we want it in integer registers, 8642 // use the corresponding integer type. This turns an f64 value into 8643 // i64, which can be passed with two i32 values on a 32-bit machine. 8644 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8645 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8646 if (OpInfo.Type == InlineAsm::isInput) 8647 OpInfo.CallOperand = 8648 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8649 OpInfo.ConstraintVT = VT; 8650 } 8651 } 8652 } 8653 8654 // No need to allocate a matching input constraint since the constraint it's 8655 // matching to has already been allocated. 8656 if (OpInfo.isMatchingInputConstraint()) 8657 return None; 8658 8659 EVT ValueVT = OpInfo.ConstraintVT; 8660 if (OpInfo.ConstraintVT == MVT::Other) 8661 ValueVT = RegVT; 8662 8663 // Initialize NumRegs. 8664 unsigned NumRegs = 1; 8665 if (OpInfo.ConstraintVT != MVT::Other) 8666 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8667 8668 // If this is a constraint for a specific physical register, like {r17}, 8669 // assign it now. 8670 8671 // If this associated to a specific register, initialize iterator to correct 8672 // place. If virtual, make sure we have enough registers 8673 8674 // Initialize iterator if necessary 8675 TargetRegisterClass::iterator I = RC->begin(); 8676 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8677 8678 // Do not check for single registers. 8679 if (AssignedReg) { 8680 I = std::find(I, RC->end(), AssignedReg); 8681 if (I == RC->end()) { 8682 // RC does not contain the selected register, which indicates a 8683 // mismatch between the register and the required type/bitwidth. 8684 return {AssignedReg}; 8685 } 8686 } 8687 8688 for (; NumRegs; --NumRegs, ++I) { 8689 assert(I != RC->end() && "Ran out of registers to allocate!"); 8690 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8691 Regs.push_back(R); 8692 } 8693 8694 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8695 return None; 8696 } 8697 8698 static unsigned 8699 findMatchingInlineAsmOperand(unsigned OperandNo, 8700 const std::vector<SDValue> &AsmNodeOperands) { 8701 // Scan until we find the definition we already emitted of this operand. 8702 unsigned CurOp = InlineAsm::Op_FirstOperand; 8703 for (; OperandNo; --OperandNo) { 8704 // Advance to the next operand. 8705 unsigned OpFlag = 8706 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8707 assert((InlineAsm::isRegDefKind(OpFlag) || 8708 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8709 InlineAsm::isMemKind(OpFlag)) && 8710 "Skipped past definitions?"); 8711 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8712 } 8713 return CurOp; 8714 } 8715 8716 namespace { 8717 8718 class ExtraFlags { 8719 unsigned Flags = 0; 8720 8721 public: 8722 explicit ExtraFlags(const CallBase &Call) { 8723 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8724 if (IA->hasSideEffects()) 8725 Flags |= InlineAsm::Extra_HasSideEffects; 8726 if (IA->isAlignStack()) 8727 Flags |= InlineAsm::Extra_IsAlignStack; 8728 if (Call.isConvergent()) 8729 Flags |= InlineAsm::Extra_IsConvergent; 8730 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8731 } 8732 8733 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8734 // Ideally, we would only check against memory constraints. However, the 8735 // meaning of an Other constraint can be target-specific and we can't easily 8736 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8737 // for Other constraints as well. 8738 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8739 OpInfo.ConstraintType == TargetLowering::C_Other) { 8740 if (OpInfo.Type == InlineAsm::isInput) 8741 Flags |= InlineAsm::Extra_MayLoad; 8742 else if (OpInfo.Type == InlineAsm::isOutput) 8743 Flags |= InlineAsm::Extra_MayStore; 8744 else if (OpInfo.Type == InlineAsm::isClobber) 8745 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8746 } 8747 } 8748 8749 unsigned get() const { return Flags; } 8750 }; 8751 8752 } // end anonymous namespace 8753 8754 static bool isFunction(SDValue Op) { 8755 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 8756 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8757 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 8758 8759 // In normal "call dllimport func" instruction (non-inlineasm) it force 8760 // indirect access by specifing call opcode. And usually specially print 8761 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 8762 // not do in this way now. (In fact, this is similar with "Data Access" 8763 // action). So here we ignore dllimport function. 8764 if (Fn && !Fn->hasDLLImportStorageClass()) 8765 return true; 8766 } 8767 } 8768 return false; 8769 } 8770 8771 /// visitInlineAsm - Handle a call to an InlineAsm object. 8772 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8773 const BasicBlock *EHPadBB) { 8774 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8775 8776 /// ConstraintOperands - Information about all of the constraints. 8777 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8778 8779 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8780 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8781 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8782 8783 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8784 // AsmDialect, MayLoad, MayStore). 8785 bool HasSideEffect = IA->hasSideEffects(); 8786 ExtraFlags ExtraInfo(Call); 8787 8788 for (auto &T : TargetConstraints) { 8789 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8790 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8791 8792 if (OpInfo.CallOperandVal) 8793 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8794 8795 if (!HasSideEffect) 8796 HasSideEffect = OpInfo.hasMemory(TLI); 8797 8798 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8799 // FIXME: Could we compute this on OpInfo rather than T? 8800 8801 // Compute the constraint code and ConstraintType to use. 8802 TLI.ComputeConstraintToUse(T, SDValue()); 8803 8804 if (T.ConstraintType == TargetLowering::C_Immediate && 8805 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8806 // We've delayed emitting a diagnostic like the "n" constraint because 8807 // inlining could cause an integer showing up. 8808 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8809 "' expects an integer constant " 8810 "expression"); 8811 8812 ExtraInfo.update(T); 8813 } 8814 8815 // We won't need to flush pending loads if this asm doesn't touch 8816 // memory and is nonvolatile. 8817 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8818 8819 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8820 if (EmitEHLabels) { 8821 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8822 } 8823 bool IsCallBr = isa<CallBrInst>(Call); 8824 8825 if (IsCallBr || EmitEHLabels) { 8826 // If this is a callbr or invoke we need to flush pending exports since 8827 // inlineasm_br and invoke are terminators. 8828 // We need to do this before nodes are glued to the inlineasm_br node. 8829 Chain = getControlRoot(); 8830 } 8831 8832 MCSymbol *BeginLabel = nullptr; 8833 if (EmitEHLabels) { 8834 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8835 } 8836 8837 int OpNo = -1; 8838 SmallVector<StringRef> AsmStrs; 8839 IA->collectAsmStrs(AsmStrs); 8840 8841 // Second pass over the constraints: compute which constraint option to use. 8842 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8843 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 8844 OpNo++; 8845 8846 // If this is an output operand with a matching input operand, look up the 8847 // matching input. If their types mismatch, e.g. one is an integer, the 8848 // other is floating point, or their sizes are different, flag it as an 8849 // error. 8850 if (OpInfo.hasMatchingInput()) { 8851 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8852 patchMatchingInput(OpInfo, Input, DAG); 8853 } 8854 8855 // Compute the constraint code and ConstraintType to use. 8856 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8857 8858 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 8859 OpInfo.Type == InlineAsm::isClobber) || 8860 OpInfo.ConstraintType == TargetLowering::C_Address) 8861 continue; 8862 8863 // In Linux PIC model, there are 4 cases about value/label addressing: 8864 // 8865 // 1: Function call or Label jmp inside the module. 8866 // 2: Data access (such as global variable, static variable) inside module. 8867 // 3: Function call or Label jmp outside the module. 8868 // 4: Data access (such as global variable) outside the module. 8869 // 8870 // Due to current llvm inline asm architecture designed to not "recognize" 8871 // the asm code, there are quite troubles for us to treat mem addressing 8872 // differently for same value/adress used in different instuctions. 8873 // For example, in pic model, call a func may in plt way or direclty 8874 // pc-related, but lea/mov a function adress may use got. 8875 // 8876 // Here we try to "recognize" function call for the case 1 and case 3 in 8877 // inline asm. And try to adjust the constraint for them. 8878 // 8879 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 8880 // label, so here we don't handle jmp function label now, but we need to 8881 // enhance it (especilly in PIC model) if we meet meaningful requirements. 8882 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 8883 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 8884 TM.getCodeModel() != CodeModel::Large) { 8885 OpInfo.isIndirect = false; 8886 OpInfo.ConstraintType = TargetLowering::C_Address; 8887 } 8888 8889 // If this is a memory input, and if the operand is not indirect, do what we 8890 // need to provide an address for the memory input. 8891 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8892 !OpInfo.isIndirect) { 8893 assert((OpInfo.isMultipleAlternative || 8894 (OpInfo.Type == InlineAsm::isInput)) && 8895 "Can only indirectify direct input operands!"); 8896 8897 // Memory operands really want the address of the value. 8898 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8899 8900 // There is no longer a Value* corresponding to this operand. 8901 OpInfo.CallOperandVal = nullptr; 8902 8903 // It is now an indirect operand. 8904 OpInfo.isIndirect = true; 8905 } 8906 8907 } 8908 8909 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8910 std::vector<SDValue> AsmNodeOperands; 8911 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8912 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8913 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8914 8915 // If we have a !srcloc metadata node associated with it, we want to attach 8916 // this to the ultimately generated inline asm machineinstr. To do this, we 8917 // pass in the third operand as this (potentially null) inline asm MDNode. 8918 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8919 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8920 8921 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8922 // bits as operand 3. 8923 AsmNodeOperands.push_back(DAG.getTargetConstant( 8924 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8925 8926 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8927 // this, assign virtual and physical registers for inputs and otput. 8928 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8929 // Assign Registers. 8930 SDISelAsmOperandInfo &RefOpInfo = 8931 OpInfo.isMatchingInputConstraint() 8932 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8933 : OpInfo; 8934 const auto RegError = 8935 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8936 if (RegError) { 8937 const MachineFunction &MF = DAG.getMachineFunction(); 8938 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8939 const char *RegName = TRI.getName(RegError.value()); 8940 emitInlineAsmError(Call, "register '" + Twine(RegName) + 8941 "' allocated for constraint '" + 8942 Twine(OpInfo.ConstraintCode) + 8943 "' does not match required type"); 8944 return; 8945 } 8946 8947 auto DetectWriteToReservedRegister = [&]() { 8948 const MachineFunction &MF = DAG.getMachineFunction(); 8949 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8950 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8951 if (Register::isPhysicalRegister(Reg) && 8952 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8953 const char *RegName = TRI.getName(Reg); 8954 emitInlineAsmError(Call, "write to reserved register '" + 8955 Twine(RegName) + "'"); 8956 return true; 8957 } 8958 } 8959 return false; 8960 }; 8961 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 8962 (OpInfo.Type == InlineAsm::isInput && 8963 !OpInfo.isMatchingInputConstraint())) && 8964 "Only address as input operand is allowed."); 8965 8966 switch (OpInfo.Type) { 8967 case InlineAsm::isOutput: 8968 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8969 unsigned ConstraintID = 8970 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8971 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8972 "Failed to convert memory constraint code to constraint id."); 8973 8974 // Add information to the INLINEASM node to know about this output. 8975 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8976 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8977 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8978 MVT::i32)); 8979 AsmNodeOperands.push_back(OpInfo.CallOperand); 8980 } else { 8981 // Otherwise, this outputs to a register (directly for C_Register / 8982 // C_RegisterClass, and a target-defined fashion for 8983 // C_Immediate/C_Other). Find a register that we can use. 8984 if (OpInfo.AssignedRegs.Regs.empty()) { 8985 emitInlineAsmError( 8986 Call, "couldn't allocate output register for constraint '" + 8987 Twine(OpInfo.ConstraintCode) + "'"); 8988 return; 8989 } 8990 8991 if (DetectWriteToReservedRegister()) 8992 return; 8993 8994 // Add information to the INLINEASM node to know that this register is 8995 // set. 8996 OpInfo.AssignedRegs.AddInlineAsmOperands( 8997 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8998 : InlineAsm::Kind_RegDef, 8999 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9000 } 9001 break; 9002 9003 case InlineAsm::isInput: 9004 case InlineAsm::isLabel: { 9005 SDValue InOperandVal = OpInfo.CallOperand; 9006 9007 if (OpInfo.isMatchingInputConstraint()) { 9008 // If this is required to match an output register we have already set, 9009 // just use its register. 9010 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9011 AsmNodeOperands); 9012 unsigned OpFlag = 9013 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9014 if (InlineAsm::isRegDefKind(OpFlag) || 9015 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9016 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9017 if (OpInfo.isIndirect) { 9018 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9019 emitInlineAsmError(Call, "inline asm not supported yet: " 9020 "don't know how to handle tied " 9021 "indirect register inputs"); 9022 return; 9023 } 9024 9025 SmallVector<unsigned, 4> Regs; 9026 MachineFunction &MF = DAG.getMachineFunction(); 9027 MachineRegisterInfo &MRI = MF.getRegInfo(); 9028 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9029 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9030 Register TiedReg = R->getReg(); 9031 MVT RegVT = R->getSimpleValueType(0); 9032 const TargetRegisterClass *RC = 9033 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9034 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9035 : TRI.getMinimalPhysRegClass(TiedReg); 9036 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9037 for (unsigned i = 0; i != NumRegs; ++i) 9038 Regs.push_back(MRI.createVirtualRegister(RC)); 9039 9040 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9041 9042 SDLoc dl = getCurSDLoc(); 9043 // Use the produced MatchedRegs object to 9044 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 9045 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9046 true, OpInfo.getMatchedOperand(), dl, 9047 DAG, AsmNodeOperands); 9048 break; 9049 } 9050 9051 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9052 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9053 "Unexpected number of operands"); 9054 // Add information to the INLINEASM node to know about this input. 9055 // See InlineAsm.h isUseOperandTiedToDef. 9056 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9057 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9058 OpInfo.getMatchedOperand()); 9059 AsmNodeOperands.push_back(DAG.getTargetConstant( 9060 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9061 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9062 break; 9063 } 9064 9065 // Treat indirect 'X' constraint as memory. 9066 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9067 OpInfo.isIndirect) 9068 OpInfo.ConstraintType = TargetLowering::C_Memory; 9069 9070 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9071 OpInfo.ConstraintType == TargetLowering::C_Other) { 9072 std::vector<SDValue> Ops; 9073 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9074 Ops, DAG); 9075 if (Ops.empty()) { 9076 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9077 if (isa<ConstantSDNode>(InOperandVal)) { 9078 emitInlineAsmError(Call, "value out of range for constraint '" + 9079 Twine(OpInfo.ConstraintCode) + "'"); 9080 return; 9081 } 9082 9083 emitInlineAsmError(Call, 9084 "invalid operand for inline asm constraint '" + 9085 Twine(OpInfo.ConstraintCode) + "'"); 9086 return; 9087 } 9088 9089 // Add information to the INLINEASM node to know about this input. 9090 unsigned ResOpType = 9091 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9092 AsmNodeOperands.push_back(DAG.getTargetConstant( 9093 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9094 llvm::append_range(AsmNodeOperands, Ops); 9095 break; 9096 } 9097 9098 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9099 assert((OpInfo.isIndirect || 9100 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9101 "Operand must be indirect to be a mem!"); 9102 assert(InOperandVal.getValueType() == 9103 TLI.getPointerTy(DAG.getDataLayout()) && 9104 "Memory operands expect pointer values"); 9105 9106 unsigned ConstraintID = 9107 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9108 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9109 "Failed to convert memory constraint code to constraint id."); 9110 9111 // Add information to the INLINEASM node to know about this input. 9112 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9113 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9114 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9115 getCurSDLoc(), 9116 MVT::i32)); 9117 AsmNodeOperands.push_back(InOperandVal); 9118 break; 9119 } 9120 9121 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9122 assert(InOperandVal.getValueType() == 9123 TLI.getPointerTy(DAG.getDataLayout()) && 9124 "Address operands expect pointer values"); 9125 9126 unsigned ConstraintID = 9127 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9128 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9129 "Failed to convert memory constraint code to constraint id."); 9130 9131 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9132 9133 SDValue AsmOp = InOperandVal; 9134 if (isFunction(InOperandVal)) { 9135 auto *GA = dyn_cast<GlobalAddressSDNode>(InOperandVal); 9136 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9137 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9138 InOperandVal.getValueType(), 9139 GA->getOffset()); 9140 } 9141 9142 // Add information to the INLINEASM node to know about this input. 9143 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9144 9145 AsmNodeOperands.push_back( 9146 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9147 9148 AsmNodeOperands.push_back(AsmOp); 9149 break; 9150 } 9151 9152 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9153 OpInfo.ConstraintType == TargetLowering::C_Register) && 9154 "Unknown constraint type!"); 9155 9156 // TODO: Support this. 9157 if (OpInfo.isIndirect) { 9158 emitInlineAsmError( 9159 Call, "Don't know how to handle indirect register inputs yet " 9160 "for constraint '" + 9161 Twine(OpInfo.ConstraintCode) + "'"); 9162 return; 9163 } 9164 9165 // Copy the input into the appropriate registers. 9166 if (OpInfo.AssignedRegs.Regs.empty()) { 9167 emitInlineAsmError(Call, 9168 "couldn't allocate input reg for constraint '" + 9169 Twine(OpInfo.ConstraintCode) + "'"); 9170 return; 9171 } 9172 9173 if (DetectWriteToReservedRegister()) 9174 return; 9175 9176 SDLoc dl = getCurSDLoc(); 9177 9178 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 9179 &Call); 9180 9181 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9182 dl, DAG, AsmNodeOperands); 9183 break; 9184 } 9185 case InlineAsm::isClobber: 9186 // Add the clobbered value to the operand list, so that the register 9187 // allocator is aware that the physreg got clobbered. 9188 if (!OpInfo.AssignedRegs.Regs.empty()) 9189 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9190 false, 0, getCurSDLoc(), DAG, 9191 AsmNodeOperands); 9192 break; 9193 } 9194 } 9195 9196 // Finish up input operands. Set the input chain and add the flag last. 9197 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9198 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 9199 9200 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9201 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9202 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9203 Flag = Chain.getValue(1); 9204 9205 // Do additional work to generate outputs. 9206 9207 SmallVector<EVT, 1> ResultVTs; 9208 SmallVector<SDValue, 1> ResultValues; 9209 SmallVector<SDValue, 8> OutChains; 9210 9211 llvm::Type *CallResultType = Call.getType(); 9212 ArrayRef<Type *> ResultTypes; 9213 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9214 ResultTypes = StructResult->elements(); 9215 else if (!CallResultType->isVoidTy()) 9216 ResultTypes = makeArrayRef(CallResultType); 9217 9218 auto CurResultType = ResultTypes.begin(); 9219 auto handleRegAssign = [&](SDValue V) { 9220 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9221 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9222 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9223 ++CurResultType; 9224 // If the type of the inline asm call site return value is different but has 9225 // same size as the type of the asm output bitcast it. One example of this 9226 // is for vectors with different width / number of elements. This can 9227 // happen for register classes that can contain multiple different value 9228 // types. The preg or vreg allocated may not have the same VT as was 9229 // expected. 9230 // 9231 // This can also happen for a return value that disagrees with the register 9232 // class it is put in, eg. a double in a general-purpose register on a 9233 // 32-bit machine. 9234 if (ResultVT != V.getValueType() && 9235 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9236 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9237 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9238 V.getValueType().isInteger()) { 9239 // If a result value was tied to an input value, the computed result 9240 // may have a wider width than the expected result. Extract the 9241 // relevant portion. 9242 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9243 } 9244 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9245 ResultVTs.push_back(ResultVT); 9246 ResultValues.push_back(V); 9247 }; 9248 9249 // Deal with output operands. 9250 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9251 if (OpInfo.Type == InlineAsm::isOutput) { 9252 SDValue Val; 9253 // Skip trivial output operands. 9254 if (OpInfo.AssignedRegs.Regs.empty()) 9255 continue; 9256 9257 switch (OpInfo.ConstraintType) { 9258 case TargetLowering::C_Register: 9259 case TargetLowering::C_RegisterClass: 9260 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9261 Chain, &Flag, &Call); 9262 break; 9263 case TargetLowering::C_Immediate: 9264 case TargetLowering::C_Other: 9265 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 9266 OpInfo, DAG); 9267 break; 9268 case TargetLowering::C_Memory: 9269 break; // Already handled. 9270 case TargetLowering::C_Address: 9271 break; // Silence warning. 9272 case TargetLowering::C_Unknown: 9273 assert(false && "Unexpected unknown constraint"); 9274 } 9275 9276 // Indirect output manifest as stores. Record output chains. 9277 if (OpInfo.isIndirect) { 9278 const Value *Ptr = OpInfo.CallOperandVal; 9279 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9280 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9281 MachinePointerInfo(Ptr)); 9282 OutChains.push_back(Store); 9283 } else { 9284 // generate CopyFromRegs to associated registers. 9285 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9286 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9287 for (const SDValue &V : Val->op_values()) 9288 handleRegAssign(V); 9289 } else 9290 handleRegAssign(Val); 9291 } 9292 } 9293 } 9294 9295 // Set results. 9296 if (!ResultValues.empty()) { 9297 assert(CurResultType == ResultTypes.end() && 9298 "Mismatch in number of ResultTypes"); 9299 assert(ResultValues.size() == ResultTypes.size() && 9300 "Mismatch in number of output operands in asm result"); 9301 9302 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9303 DAG.getVTList(ResultVTs), ResultValues); 9304 setValue(&Call, V); 9305 } 9306 9307 // Collect store chains. 9308 if (!OutChains.empty()) 9309 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9310 9311 if (EmitEHLabels) { 9312 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9313 } 9314 9315 // Only Update Root if inline assembly has a memory effect. 9316 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9317 EmitEHLabels) 9318 DAG.setRoot(Chain); 9319 } 9320 9321 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9322 const Twine &Message) { 9323 LLVMContext &Ctx = *DAG.getContext(); 9324 Ctx.emitError(&Call, Message); 9325 9326 // Make sure we leave the DAG in a valid state 9327 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9328 SmallVector<EVT, 1> ValueVTs; 9329 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9330 9331 if (ValueVTs.empty()) 9332 return; 9333 9334 SmallVector<SDValue, 1> Ops; 9335 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9336 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9337 9338 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9339 } 9340 9341 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9342 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9343 MVT::Other, getRoot(), 9344 getValue(I.getArgOperand(0)), 9345 DAG.getSrcValue(I.getArgOperand(0)))); 9346 } 9347 9348 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9349 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9350 const DataLayout &DL = DAG.getDataLayout(); 9351 SDValue V = DAG.getVAArg( 9352 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9353 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9354 DL.getABITypeAlign(I.getType()).value()); 9355 DAG.setRoot(V.getValue(1)); 9356 9357 if (I.getType()->isPointerTy()) 9358 V = DAG.getPtrExtOrTrunc( 9359 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9360 setValue(&I, V); 9361 } 9362 9363 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9364 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9365 MVT::Other, getRoot(), 9366 getValue(I.getArgOperand(0)), 9367 DAG.getSrcValue(I.getArgOperand(0)))); 9368 } 9369 9370 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9371 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9372 MVT::Other, getRoot(), 9373 getValue(I.getArgOperand(0)), 9374 getValue(I.getArgOperand(1)), 9375 DAG.getSrcValue(I.getArgOperand(0)), 9376 DAG.getSrcValue(I.getArgOperand(1)))); 9377 } 9378 9379 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9380 const Instruction &I, 9381 SDValue Op) { 9382 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9383 if (!Range) 9384 return Op; 9385 9386 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9387 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9388 return Op; 9389 9390 APInt Lo = CR.getUnsignedMin(); 9391 if (!Lo.isMinValue()) 9392 return Op; 9393 9394 APInt Hi = CR.getUnsignedMax(); 9395 unsigned Bits = std::max(Hi.getActiveBits(), 9396 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9397 9398 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9399 9400 SDLoc SL = getCurSDLoc(); 9401 9402 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9403 DAG.getValueType(SmallVT)); 9404 unsigned NumVals = Op.getNode()->getNumValues(); 9405 if (NumVals == 1) 9406 return ZExt; 9407 9408 SmallVector<SDValue, 4> Ops; 9409 9410 Ops.push_back(ZExt); 9411 for (unsigned I = 1; I != NumVals; ++I) 9412 Ops.push_back(Op.getValue(I)); 9413 9414 return DAG.getMergeValues(Ops, SL); 9415 } 9416 9417 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9418 /// the call being lowered. 9419 /// 9420 /// This is a helper for lowering intrinsics that follow a target calling 9421 /// convention or require stack pointer adjustment. Only a subset of the 9422 /// intrinsic's operands need to participate in the calling convention. 9423 void SelectionDAGBuilder::populateCallLoweringInfo( 9424 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9425 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9426 bool IsPatchPoint) { 9427 TargetLowering::ArgListTy Args; 9428 Args.reserve(NumArgs); 9429 9430 // Populate the argument list. 9431 // Attributes for args start at offset 1, after the return attribute. 9432 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9433 ArgI != ArgE; ++ArgI) { 9434 const Value *V = Call->getOperand(ArgI); 9435 9436 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9437 9438 TargetLowering::ArgListEntry Entry; 9439 Entry.Node = getValue(V); 9440 Entry.Ty = V->getType(); 9441 Entry.setAttributes(Call, ArgI); 9442 Args.push_back(Entry); 9443 } 9444 9445 CLI.setDebugLoc(getCurSDLoc()) 9446 .setChain(getRoot()) 9447 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9448 .setDiscardResult(Call->use_empty()) 9449 .setIsPatchPoint(IsPatchPoint) 9450 .setIsPreallocated( 9451 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9452 } 9453 9454 /// Add a stack map intrinsic call's live variable operands to a stackmap 9455 /// or patchpoint target node's operand list. 9456 /// 9457 /// Constants are converted to TargetConstants purely as an optimization to 9458 /// avoid constant materialization and register allocation. 9459 /// 9460 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9461 /// generate addess computation nodes, and so FinalizeISel can convert the 9462 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9463 /// address materialization and register allocation, but may also be required 9464 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9465 /// alloca in the entry block, then the runtime may assume that the alloca's 9466 /// StackMap location can be read immediately after compilation and that the 9467 /// location is valid at any point during execution (this is similar to the 9468 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9469 /// only available in a register, then the runtime would need to trap when 9470 /// execution reaches the StackMap in order to read the alloca's location. 9471 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9472 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9473 SelectionDAGBuilder &Builder) { 9474 SelectionDAG &DAG = Builder.DAG; 9475 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9476 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9477 9478 // Things on the stack are pointer-typed, meaning that they are already 9479 // legal and can be emitted directly to target nodes. 9480 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9481 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9482 } else { 9483 // Otherwise emit a target independent node to be legalised. 9484 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9485 } 9486 } 9487 } 9488 9489 /// Lower llvm.experimental.stackmap. 9490 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9491 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9492 // [live variables...]) 9493 9494 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9495 9496 SDValue Chain, InFlag, Callee; 9497 SmallVector<SDValue, 32> Ops; 9498 9499 SDLoc DL = getCurSDLoc(); 9500 Callee = getValue(CI.getCalledOperand()); 9501 9502 // The stackmap intrinsic only records the live variables (the arguments 9503 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9504 // intrinsic, this won't be lowered to a function call. This means we don't 9505 // have to worry about calling conventions and target specific lowering code. 9506 // Instead we perform the call lowering right here. 9507 // 9508 // chain, flag = CALLSEQ_START(chain, 0, 0) 9509 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9510 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9511 // 9512 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9513 InFlag = Chain.getValue(1); 9514 9515 // Add the STACKMAP operands, starting with DAG house-keeping. 9516 Ops.push_back(Chain); 9517 Ops.push_back(InFlag); 9518 9519 // Add the <id>, <numShadowBytes> operands. 9520 // 9521 // These do not require legalisation, and can be emitted directly to target 9522 // constant nodes. 9523 SDValue ID = getValue(CI.getArgOperand(0)); 9524 assert(ID.getValueType() == MVT::i64); 9525 SDValue IDConst = DAG.getTargetConstant( 9526 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9527 Ops.push_back(IDConst); 9528 9529 SDValue Shad = getValue(CI.getArgOperand(1)); 9530 assert(Shad.getValueType() == MVT::i32); 9531 SDValue ShadConst = DAG.getTargetConstant( 9532 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9533 Ops.push_back(ShadConst); 9534 9535 // Add the live variables. 9536 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9537 9538 // Create the STACKMAP node. 9539 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9540 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9541 InFlag = Chain.getValue(1); 9542 9543 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL); 9544 9545 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9546 9547 // Set the root to the target-lowered call chain. 9548 DAG.setRoot(Chain); 9549 9550 // Inform the Frame Information that we have a stackmap in this function. 9551 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9552 } 9553 9554 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9555 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9556 const BasicBlock *EHPadBB) { 9557 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9558 // i32 <numBytes>, 9559 // i8* <target>, 9560 // i32 <numArgs>, 9561 // [Args...], 9562 // [live variables...]) 9563 9564 CallingConv::ID CC = CB.getCallingConv(); 9565 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9566 bool HasDef = !CB.getType()->isVoidTy(); 9567 SDLoc dl = getCurSDLoc(); 9568 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9569 9570 // Handle immediate and symbolic callees. 9571 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9572 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9573 /*isTarget=*/true); 9574 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9575 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9576 SDLoc(SymbolicCallee), 9577 SymbolicCallee->getValueType(0)); 9578 9579 // Get the real number of arguments participating in the call <numArgs> 9580 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9581 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9582 9583 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9584 // Intrinsics include all meta-operands up to but not including CC. 9585 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9586 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9587 "Not enough arguments provided to the patchpoint intrinsic"); 9588 9589 // For AnyRegCC the arguments are lowered later on manually. 9590 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9591 Type *ReturnTy = 9592 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9593 9594 TargetLowering::CallLoweringInfo CLI(DAG); 9595 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9596 ReturnTy, true); 9597 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9598 9599 SDNode *CallEnd = Result.second.getNode(); 9600 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9601 CallEnd = CallEnd->getOperand(0).getNode(); 9602 9603 /// Get a call instruction from the call sequence chain. 9604 /// Tail calls are not allowed. 9605 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9606 "Expected a callseq node."); 9607 SDNode *Call = CallEnd->getOperand(0).getNode(); 9608 bool HasGlue = Call->getGluedNode(); 9609 9610 // Replace the target specific call node with the patchable intrinsic. 9611 SmallVector<SDValue, 8> Ops; 9612 9613 // Push the chain. 9614 Ops.push_back(*(Call->op_begin())); 9615 9616 // Optionally, push the glue (if any). 9617 if (HasGlue) 9618 Ops.push_back(*(Call->op_end() - 1)); 9619 9620 // Push the register mask info. 9621 if (HasGlue) 9622 Ops.push_back(*(Call->op_end() - 2)); 9623 else 9624 Ops.push_back(*(Call->op_end() - 1)); 9625 9626 // Add the <id> and <numBytes> constants. 9627 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9628 Ops.push_back(DAG.getTargetConstant( 9629 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9630 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9631 Ops.push_back(DAG.getTargetConstant( 9632 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9633 MVT::i32)); 9634 9635 // Add the callee. 9636 Ops.push_back(Callee); 9637 9638 // Adjust <numArgs> to account for any arguments that have been passed on the 9639 // stack instead. 9640 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9641 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9642 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9643 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9644 9645 // Add the calling convention 9646 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9647 9648 // Add the arguments we omitted previously. The register allocator should 9649 // place these in any free register. 9650 if (IsAnyRegCC) 9651 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9652 Ops.push_back(getValue(CB.getArgOperand(i))); 9653 9654 // Push the arguments from the call instruction. 9655 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9656 Ops.append(Call->op_begin() + 2, e); 9657 9658 // Push live variables for the stack map. 9659 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9660 9661 SDVTList NodeTys; 9662 if (IsAnyRegCC && HasDef) { 9663 // Create the return types based on the intrinsic definition 9664 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9665 SmallVector<EVT, 3> ValueVTs; 9666 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9667 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9668 9669 // There is always a chain and a glue type at the end 9670 ValueVTs.push_back(MVT::Other); 9671 ValueVTs.push_back(MVT::Glue); 9672 NodeTys = DAG.getVTList(ValueVTs); 9673 } else 9674 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9675 9676 // Replace the target specific call node with a PATCHPOINT node. 9677 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9678 9679 // Update the NodeMap. 9680 if (HasDef) { 9681 if (IsAnyRegCC) 9682 setValue(&CB, SDValue(PPV.getNode(), 0)); 9683 else 9684 setValue(&CB, Result.first); 9685 } 9686 9687 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9688 // call sequence. Furthermore the location of the chain and glue can change 9689 // when the AnyReg calling convention is used and the intrinsic returns a 9690 // value. 9691 if (IsAnyRegCC && HasDef) { 9692 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9693 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9694 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9695 } else 9696 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9697 DAG.DeleteNode(Call); 9698 9699 // Inform the Frame Information that we have a patchpoint in this function. 9700 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9701 } 9702 9703 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9704 unsigned Intrinsic) { 9705 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9706 SDValue Op1 = getValue(I.getArgOperand(0)); 9707 SDValue Op2; 9708 if (I.arg_size() > 1) 9709 Op2 = getValue(I.getArgOperand(1)); 9710 SDLoc dl = getCurSDLoc(); 9711 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9712 SDValue Res; 9713 SDNodeFlags SDFlags; 9714 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9715 SDFlags.copyFMF(*FPMO); 9716 9717 switch (Intrinsic) { 9718 case Intrinsic::vector_reduce_fadd: 9719 if (SDFlags.hasAllowReassociation()) 9720 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9721 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9722 SDFlags); 9723 else 9724 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9725 break; 9726 case Intrinsic::vector_reduce_fmul: 9727 if (SDFlags.hasAllowReassociation()) 9728 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9729 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9730 SDFlags); 9731 else 9732 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9733 break; 9734 case Intrinsic::vector_reduce_add: 9735 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9736 break; 9737 case Intrinsic::vector_reduce_mul: 9738 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9739 break; 9740 case Intrinsic::vector_reduce_and: 9741 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9742 break; 9743 case Intrinsic::vector_reduce_or: 9744 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9745 break; 9746 case Intrinsic::vector_reduce_xor: 9747 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9748 break; 9749 case Intrinsic::vector_reduce_smax: 9750 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9751 break; 9752 case Intrinsic::vector_reduce_smin: 9753 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9754 break; 9755 case Intrinsic::vector_reduce_umax: 9756 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9757 break; 9758 case Intrinsic::vector_reduce_umin: 9759 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9760 break; 9761 case Intrinsic::vector_reduce_fmax: 9762 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9763 break; 9764 case Intrinsic::vector_reduce_fmin: 9765 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9766 break; 9767 default: 9768 llvm_unreachable("Unhandled vector reduce intrinsic"); 9769 } 9770 setValue(&I, Res); 9771 } 9772 9773 /// Returns an AttributeList representing the attributes applied to the return 9774 /// value of the given call. 9775 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9776 SmallVector<Attribute::AttrKind, 2> Attrs; 9777 if (CLI.RetSExt) 9778 Attrs.push_back(Attribute::SExt); 9779 if (CLI.RetZExt) 9780 Attrs.push_back(Attribute::ZExt); 9781 if (CLI.IsInReg) 9782 Attrs.push_back(Attribute::InReg); 9783 9784 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9785 Attrs); 9786 } 9787 9788 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9789 /// implementation, which just calls LowerCall. 9790 /// FIXME: When all targets are 9791 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9792 std::pair<SDValue, SDValue> 9793 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9794 // Handle the incoming return values from the call. 9795 CLI.Ins.clear(); 9796 Type *OrigRetTy = CLI.RetTy; 9797 SmallVector<EVT, 4> RetTys; 9798 SmallVector<uint64_t, 4> Offsets; 9799 auto &DL = CLI.DAG.getDataLayout(); 9800 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9801 9802 if (CLI.IsPostTypeLegalization) { 9803 // If we are lowering a libcall after legalization, split the return type. 9804 SmallVector<EVT, 4> OldRetTys; 9805 SmallVector<uint64_t, 4> OldOffsets; 9806 RetTys.swap(OldRetTys); 9807 Offsets.swap(OldOffsets); 9808 9809 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9810 EVT RetVT = OldRetTys[i]; 9811 uint64_t Offset = OldOffsets[i]; 9812 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9813 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9814 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9815 RetTys.append(NumRegs, RegisterVT); 9816 for (unsigned j = 0; j != NumRegs; ++j) 9817 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9818 } 9819 } 9820 9821 SmallVector<ISD::OutputArg, 4> Outs; 9822 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9823 9824 bool CanLowerReturn = 9825 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9826 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9827 9828 SDValue DemoteStackSlot; 9829 int DemoteStackIdx = -100; 9830 if (!CanLowerReturn) { 9831 // FIXME: equivalent assert? 9832 // assert(!CS.hasInAllocaArgument() && 9833 // "sret demotion is incompatible with inalloca"); 9834 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9835 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9836 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9837 DemoteStackIdx = 9838 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9839 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9840 DL.getAllocaAddrSpace()); 9841 9842 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9843 ArgListEntry Entry; 9844 Entry.Node = DemoteStackSlot; 9845 Entry.Ty = StackSlotPtrType; 9846 Entry.IsSExt = false; 9847 Entry.IsZExt = false; 9848 Entry.IsInReg = false; 9849 Entry.IsSRet = true; 9850 Entry.IsNest = false; 9851 Entry.IsByVal = false; 9852 Entry.IsByRef = false; 9853 Entry.IsReturned = false; 9854 Entry.IsSwiftSelf = false; 9855 Entry.IsSwiftAsync = false; 9856 Entry.IsSwiftError = false; 9857 Entry.IsCFGuardTarget = false; 9858 Entry.Alignment = Alignment; 9859 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9860 CLI.NumFixedArgs += 1; 9861 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9862 9863 // sret demotion isn't compatible with tail-calls, since the sret argument 9864 // points into the callers stack frame. 9865 CLI.IsTailCall = false; 9866 } else { 9867 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9868 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9869 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9870 ISD::ArgFlagsTy Flags; 9871 if (NeedsRegBlock) { 9872 Flags.setInConsecutiveRegs(); 9873 if (I == RetTys.size() - 1) 9874 Flags.setInConsecutiveRegsLast(); 9875 } 9876 EVT VT = RetTys[I]; 9877 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9878 CLI.CallConv, VT); 9879 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9880 CLI.CallConv, VT); 9881 for (unsigned i = 0; i != NumRegs; ++i) { 9882 ISD::InputArg MyFlags; 9883 MyFlags.Flags = Flags; 9884 MyFlags.VT = RegisterVT; 9885 MyFlags.ArgVT = VT; 9886 MyFlags.Used = CLI.IsReturnValueUsed; 9887 if (CLI.RetTy->isPointerTy()) { 9888 MyFlags.Flags.setPointer(); 9889 MyFlags.Flags.setPointerAddrSpace( 9890 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9891 } 9892 if (CLI.RetSExt) 9893 MyFlags.Flags.setSExt(); 9894 if (CLI.RetZExt) 9895 MyFlags.Flags.setZExt(); 9896 if (CLI.IsInReg) 9897 MyFlags.Flags.setInReg(); 9898 CLI.Ins.push_back(MyFlags); 9899 } 9900 } 9901 } 9902 9903 // We push in swifterror return as the last element of CLI.Ins. 9904 ArgListTy &Args = CLI.getArgs(); 9905 if (supportSwiftError()) { 9906 for (const ArgListEntry &Arg : Args) { 9907 if (Arg.IsSwiftError) { 9908 ISD::InputArg MyFlags; 9909 MyFlags.VT = getPointerTy(DL); 9910 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9911 MyFlags.Flags.setSwiftError(); 9912 CLI.Ins.push_back(MyFlags); 9913 } 9914 } 9915 } 9916 9917 // Handle all of the outgoing arguments. 9918 CLI.Outs.clear(); 9919 CLI.OutVals.clear(); 9920 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9921 SmallVector<EVT, 4> ValueVTs; 9922 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9923 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9924 Type *FinalType = Args[i].Ty; 9925 if (Args[i].IsByVal) 9926 FinalType = Args[i].IndirectType; 9927 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9928 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 9929 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9930 ++Value) { 9931 EVT VT = ValueVTs[Value]; 9932 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9933 SDValue Op = SDValue(Args[i].Node.getNode(), 9934 Args[i].Node.getResNo() + Value); 9935 ISD::ArgFlagsTy Flags; 9936 9937 // Certain targets (such as MIPS), may have a different ABI alignment 9938 // for a type depending on the context. Give the target a chance to 9939 // specify the alignment it wants. 9940 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9941 Flags.setOrigAlign(OriginalAlignment); 9942 9943 if (Args[i].Ty->isPointerTy()) { 9944 Flags.setPointer(); 9945 Flags.setPointerAddrSpace( 9946 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9947 } 9948 if (Args[i].IsZExt) 9949 Flags.setZExt(); 9950 if (Args[i].IsSExt) 9951 Flags.setSExt(); 9952 if (Args[i].IsInReg) { 9953 // If we are using vectorcall calling convention, a structure that is 9954 // passed InReg - is surely an HVA 9955 if (CLI.CallConv == CallingConv::X86_VectorCall && 9956 isa<StructType>(FinalType)) { 9957 // The first value of a structure is marked 9958 if (0 == Value) 9959 Flags.setHvaStart(); 9960 Flags.setHva(); 9961 } 9962 // Set InReg Flag 9963 Flags.setInReg(); 9964 } 9965 if (Args[i].IsSRet) 9966 Flags.setSRet(); 9967 if (Args[i].IsSwiftSelf) 9968 Flags.setSwiftSelf(); 9969 if (Args[i].IsSwiftAsync) 9970 Flags.setSwiftAsync(); 9971 if (Args[i].IsSwiftError) 9972 Flags.setSwiftError(); 9973 if (Args[i].IsCFGuardTarget) 9974 Flags.setCFGuardTarget(); 9975 if (Args[i].IsByVal) 9976 Flags.setByVal(); 9977 if (Args[i].IsByRef) 9978 Flags.setByRef(); 9979 if (Args[i].IsPreallocated) { 9980 Flags.setPreallocated(); 9981 // Set the byval flag for CCAssignFn callbacks that don't know about 9982 // preallocated. This way we can know how many bytes we should've 9983 // allocated and how many bytes a callee cleanup function will pop. If 9984 // we port preallocated to more targets, we'll have to add custom 9985 // preallocated handling in the various CC lowering callbacks. 9986 Flags.setByVal(); 9987 } 9988 if (Args[i].IsInAlloca) { 9989 Flags.setInAlloca(); 9990 // Set the byval flag for CCAssignFn callbacks that don't know about 9991 // inalloca. This way we can know how many bytes we should've allocated 9992 // and how many bytes a callee cleanup function will pop. If we port 9993 // inalloca to more targets, we'll have to add custom inalloca handling 9994 // in the various CC lowering callbacks. 9995 Flags.setByVal(); 9996 } 9997 Align MemAlign; 9998 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9999 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10000 Flags.setByValSize(FrameSize); 10001 10002 // info is not there but there are cases it cannot get right. 10003 if (auto MA = Args[i].Alignment) 10004 MemAlign = *MA; 10005 else 10006 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10007 } else if (auto MA = Args[i].Alignment) { 10008 MemAlign = *MA; 10009 } else { 10010 MemAlign = OriginalAlignment; 10011 } 10012 Flags.setMemAlign(MemAlign); 10013 if (Args[i].IsNest) 10014 Flags.setNest(); 10015 if (NeedsRegBlock) 10016 Flags.setInConsecutiveRegs(); 10017 10018 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10019 CLI.CallConv, VT); 10020 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10021 CLI.CallConv, VT); 10022 SmallVector<SDValue, 4> Parts(NumParts); 10023 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10024 10025 if (Args[i].IsSExt) 10026 ExtendKind = ISD::SIGN_EXTEND; 10027 else if (Args[i].IsZExt) 10028 ExtendKind = ISD::ZERO_EXTEND; 10029 10030 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10031 // for now. 10032 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10033 CanLowerReturn) { 10034 assert((CLI.RetTy == Args[i].Ty || 10035 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10036 CLI.RetTy->getPointerAddressSpace() == 10037 Args[i].Ty->getPointerAddressSpace())) && 10038 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10039 // Before passing 'returned' to the target lowering code, ensure that 10040 // either the register MVT and the actual EVT are the same size or that 10041 // the return value and argument are extended in the same way; in these 10042 // cases it's safe to pass the argument register value unchanged as the 10043 // return register value (although it's at the target's option whether 10044 // to do so) 10045 // TODO: allow code generation to take advantage of partially preserved 10046 // registers rather than clobbering the entire register when the 10047 // parameter extension method is not compatible with the return 10048 // extension method 10049 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10050 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10051 CLI.RetZExt == Args[i].IsZExt)) 10052 Flags.setReturned(); 10053 } 10054 10055 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10056 CLI.CallConv, ExtendKind); 10057 10058 for (unsigned j = 0; j != NumParts; ++j) { 10059 // if it isn't first piece, alignment must be 1 10060 // For scalable vectors the scalable part is currently handled 10061 // by individual targets, so we just use the known minimum size here. 10062 ISD::OutputArg MyFlags( 10063 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10064 i < CLI.NumFixedArgs, i, 10065 j * Parts[j].getValueType().getStoreSize().getKnownMinSize()); 10066 if (NumParts > 1 && j == 0) 10067 MyFlags.Flags.setSplit(); 10068 else if (j != 0) { 10069 MyFlags.Flags.setOrigAlign(Align(1)); 10070 if (j == NumParts - 1) 10071 MyFlags.Flags.setSplitEnd(); 10072 } 10073 10074 CLI.Outs.push_back(MyFlags); 10075 CLI.OutVals.push_back(Parts[j]); 10076 } 10077 10078 if (NeedsRegBlock && Value == NumValues - 1) 10079 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10080 } 10081 } 10082 10083 SmallVector<SDValue, 4> InVals; 10084 CLI.Chain = LowerCall(CLI, InVals); 10085 10086 // Update CLI.InVals to use outside of this function. 10087 CLI.InVals = InVals; 10088 10089 // Verify that the target's LowerCall behaved as expected. 10090 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10091 "LowerCall didn't return a valid chain!"); 10092 assert((!CLI.IsTailCall || InVals.empty()) && 10093 "LowerCall emitted a return value for a tail call!"); 10094 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10095 "LowerCall didn't emit the correct number of values!"); 10096 10097 // For a tail call, the return value is merely live-out and there aren't 10098 // any nodes in the DAG representing it. Return a special value to 10099 // indicate that a tail call has been emitted and no more Instructions 10100 // should be processed in the current block. 10101 if (CLI.IsTailCall) { 10102 CLI.DAG.setRoot(CLI.Chain); 10103 return std::make_pair(SDValue(), SDValue()); 10104 } 10105 10106 #ifndef NDEBUG 10107 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10108 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10109 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10110 "LowerCall emitted a value with the wrong type!"); 10111 } 10112 #endif 10113 10114 SmallVector<SDValue, 4> ReturnValues; 10115 if (!CanLowerReturn) { 10116 // The instruction result is the result of loading from the 10117 // hidden sret parameter. 10118 SmallVector<EVT, 1> PVTs; 10119 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10120 10121 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10122 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10123 EVT PtrVT = PVTs[0]; 10124 10125 unsigned NumValues = RetTys.size(); 10126 ReturnValues.resize(NumValues); 10127 SmallVector<SDValue, 4> Chains(NumValues); 10128 10129 // An aggregate return value cannot wrap around the address space, so 10130 // offsets to its parts don't wrap either. 10131 SDNodeFlags Flags; 10132 Flags.setNoUnsignedWrap(true); 10133 10134 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10135 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10136 for (unsigned i = 0; i < NumValues; ++i) { 10137 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10138 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10139 PtrVT), Flags); 10140 SDValue L = CLI.DAG.getLoad( 10141 RetTys[i], CLI.DL, CLI.Chain, Add, 10142 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10143 DemoteStackIdx, Offsets[i]), 10144 HiddenSRetAlign); 10145 ReturnValues[i] = L; 10146 Chains[i] = L.getValue(1); 10147 } 10148 10149 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10150 } else { 10151 // Collect the legal value parts into potentially illegal values 10152 // that correspond to the original function's return values. 10153 Optional<ISD::NodeType> AssertOp; 10154 if (CLI.RetSExt) 10155 AssertOp = ISD::AssertSext; 10156 else if (CLI.RetZExt) 10157 AssertOp = ISD::AssertZext; 10158 unsigned CurReg = 0; 10159 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10160 EVT VT = RetTys[I]; 10161 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10162 CLI.CallConv, VT); 10163 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10164 CLI.CallConv, VT); 10165 10166 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10167 NumRegs, RegisterVT, VT, nullptr, 10168 CLI.CallConv, AssertOp)); 10169 CurReg += NumRegs; 10170 } 10171 10172 // For a function returning void, there is no return value. We can't create 10173 // such a node, so we just return a null return value in that case. In 10174 // that case, nothing will actually look at the value. 10175 if (ReturnValues.empty()) 10176 return std::make_pair(SDValue(), CLI.Chain); 10177 } 10178 10179 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10180 CLI.DAG.getVTList(RetTys), ReturnValues); 10181 return std::make_pair(Res, CLI.Chain); 10182 } 10183 10184 /// Places new result values for the node in Results (their number 10185 /// and types must exactly match those of the original return values of 10186 /// the node), or leaves Results empty, which indicates that the node is not 10187 /// to be custom lowered after all. 10188 void TargetLowering::LowerOperationWrapper(SDNode *N, 10189 SmallVectorImpl<SDValue> &Results, 10190 SelectionDAG &DAG) const { 10191 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10192 10193 if (!Res.getNode()) 10194 return; 10195 10196 // If the original node has one result, take the return value from 10197 // LowerOperation as is. It might not be result number 0. 10198 if (N->getNumValues() == 1) { 10199 Results.push_back(Res); 10200 return; 10201 } 10202 10203 // If the original node has multiple results, then the return node should 10204 // have the same number of results. 10205 assert((N->getNumValues() == Res->getNumValues()) && 10206 "Lowering returned the wrong number of results!"); 10207 10208 // Places new result values base on N result number. 10209 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10210 Results.push_back(Res.getValue(I)); 10211 } 10212 10213 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10214 llvm_unreachable("LowerOperation not implemented for this target!"); 10215 } 10216 10217 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10218 unsigned Reg, 10219 ISD::NodeType ExtendType) { 10220 SDValue Op = getNonRegisterValue(V); 10221 assert((Op.getOpcode() != ISD::CopyFromReg || 10222 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10223 "Copy from a reg to the same reg!"); 10224 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10225 10226 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10227 // If this is an InlineAsm we have to match the registers required, not the 10228 // notional registers required by the type. 10229 10230 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10231 None); // This is not an ABI copy. 10232 SDValue Chain = DAG.getEntryNode(); 10233 10234 if (ExtendType == ISD::ANY_EXTEND) { 10235 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10236 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10237 ExtendType = PreferredExtendIt->second; 10238 } 10239 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10240 PendingExports.push_back(Chain); 10241 } 10242 10243 #include "llvm/CodeGen/SelectionDAGISel.h" 10244 10245 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10246 /// entry block, return true. This includes arguments used by switches, since 10247 /// the switch may expand into multiple basic blocks. 10248 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10249 // With FastISel active, we may be splitting blocks, so force creation 10250 // of virtual registers for all non-dead arguments. 10251 if (FastISel) 10252 return A->use_empty(); 10253 10254 const BasicBlock &Entry = A->getParent()->front(); 10255 for (const User *U : A->users()) 10256 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10257 return false; // Use not in entry block. 10258 10259 return true; 10260 } 10261 10262 using ArgCopyElisionMapTy = 10263 DenseMap<const Argument *, 10264 std::pair<const AllocaInst *, const StoreInst *>>; 10265 10266 /// Scan the entry block of the function in FuncInfo for arguments that look 10267 /// like copies into a local alloca. Record any copied arguments in 10268 /// ArgCopyElisionCandidates. 10269 static void 10270 findArgumentCopyElisionCandidates(const DataLayout &DL, 10271 FunctionLoweringInfo *FuncInfo, 10272 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10273 // Record the state of every static alloca used in the entry block. Argument 10274 // allocas are all used in the entry block, so we need approximately as many 10275 // entries as we have arguments. 10276 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10277 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10278 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10279 StaticAllocas.reserve(NumArgs * 2); 10280 10281 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10282 if (!V) 10283 return nullptr; 10284 V = V->stripPointerCasts(); 10285 const auto *AI = dyn_cast<AllocaInst>(V); 10286 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10287 return nullptr; 10288 auto Iter = StaticAllocas.insert({AI, Unknown}); 10289 return &Iter.first->second; 10290 }; 10291 10292 // Look for stores of arguments to static allocas. Look through bitcasts and 10293 // GEPs to handle type coercions, as long as the alloca is fully initialized 10294 // by the store. Any non-store use of an alloca escapes it and any subsequent 10295 // unanalyzed store might write it. 10296 // FIXME: Handle structs initialized with multiple stores. 10297 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10298 // Look for stores, and handle non-store uses conservatively. 10299 const auto *SI = dyn_cast<StoreInst>(&I); 10300 if (!SI) { 10301 // We will look through cast uses, so ignore them completely. 10302 if (I.isCast()) 10303 continue; 10304 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10305 // to allocas. 10306 if (I.isDebugOrPseudoInst()) 10307 continue; 10308 // This is an unknown instruction. Assume it escapes or writes to all 10309 // static alloca operands. 10310 for (const Use &U : I.operands()) { 10311 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10312 *Info = StaticAllocaInfo::Clobbered; 10313 } 10314 continue; 10315 } 10316 10317 // If the stored value is a static alloca, mark it as escaped. 10318 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10319 *Info = StaticAllocaInfo::Clobbered; 10320 10321 // Check if the destination is a static alloca. 10322 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10323 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10324 if (!Info) 10325 continue; 10326 const AllocaInst *AI = cast<AllocaInst>(Dst); 10327 10328 // Skip allocas that have been initialized or clobbered. 10329 if (*Info != StaticAllocaInfo::Unknown) 10330 continue; 10331 10332 // Check if the stored value is an argument, and that this store fully 10333 // initializes the alloca. 10334 // If the argument type has padding bits we can't directly forward a pointer 10335 // as the upper bits may contain garbage. 10336 // Don't elide copies from the same argument twice. 10337 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10338 const auto *Arg = dyn_cast<Argument>(Val); 10339 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10340 Arg->getType()->isEmptyTy() || 10341 DL.getTypeStoreSize(Arg->getType()) != 10342 DL.getTypeAllocSize(AI->getAllocatedType()) || 10343 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10344 ArgCopyElisionCandidates.count(Arg)) { 10345 *Info = StaticAllocaInfo::Clobbered; 10346 continue; 10347 } 10348 10349 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10350 << '\n'); 10351 10352 // Mark this alloca and store for argument copy elision. 10353 *Info = StaticAllocaInfo::Elidable; 10354 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10355 10356 // Stop scanning if we've seen all arguments. This will happen early in -O0 10357 // builds, which is useful, because -O0 builds have large entry blocks and 10358 // many allocas. 10359 if (ArgCopyElisionCandidates.size() == NumArgs) 10360 break; 10361 } 10362 } 10363 10364 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10365 /// ArgVal is a load from a suitable fixed stack object. 10366 static void tryToElideArgumentCopy( 10367 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10368 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10369 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10370 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10371 SDValue ArgVal, bool &ArgHasUses) { 10372 // Check if this is a load from a fixed stack object. 10373 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10374 if (!LNode) 10375 return; 10376 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10377 if (!FINode) 10378 return; 10379 10380 // Check that the fixed stack object is the right size and alignment. 10381 // Look at the alignment that the user wrote on the alloca instead of looking 10382 // at the stack object. 10383 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10384 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10385 const AllocaInst *AI = ArgCopyIter->second.first; 10386 int FixedIndex = FINode->getIndex(); 10387 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10388 int OldIndex = AllocaIndex; 10389 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10390 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10391 LLVM_DEBUG( 10392 dbgs() << " argument copy elision failed due to bad fixed stack " 10393 "object size\n"); 10394 return; 10395 } 10396 Align RequiredAlignment = AI->getAlign(); 10397 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10398 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10399 "greater than stack argument alignment (" 10400 << DebugStr(RequiredAlignment) << " vs " 10401 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10402 return; 10403 } 10404 10405 // Perform the elision. Delete the old stack object and replace its only use 10406 // in the variable info map. Mark the stack object as mutable. 10407 LLVM_DEBUG({ 10408 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10409 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10410 << '\n'; 10411 }); 10412 MFI.RemoveStackObject(OldIndex); 10413 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10414 AllocaIndex = FixedIndex; 10415 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10416 Chains.push_back(ArgVal.getValue(1)); 10417 10418 // Avoid emitting code for the store implementing the copy. 10419 const StoreInst *SI = ArgCopyIter->second.second; 10420 ElidedArgCopyInstrs.insert(SI); 10421 10422 // Check for uses of the argument again so that we can avoid exporting ArgVal 10423 // if it is't used by anything other than the store. 10424 for (const Value *U : Arg.users()) { 10425 if (U != SI) { 10426 ArgHasUses = true; 10427 break; 10428 } 10429 } 10430 } 10431 10432 void SelectionDAGISel::LowerArguments(const Function &F) { 10433 SelectionDAG &DAG = SDB->DAG; 10434 SDLoc dl = SDB->getCurSDLoc(); 10435 const DataLayout &DL = DAG.getDataLayout(); 10436 SmallVector<ISD::InputArg, 16> Ins; 10437 10438 // In Naked functions we aren't going to save any registers. 10439 if (F.hasFnAttribute(Attribute::Naked)) 10440 return; 10441 10442 if (!FuncInfo->CanLowerReturn) { 10443 // Put in an sret pointer parameter before all the other parameters. 10444 SmallVector<EVT, 1> ValueVTs; 10445 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10446 F.getReturnType()->getPointerTo( 10447 DAG.getDataLayout().getAllocaAddrSpace()), 10448 ValueVTs); 10449 10450 // NOTE: Assuming that a pointer will never break down to more than one VT 10451 // or one register. 10452 ISD::ArgFlagsTy Flags; 10453 Flags.setSRet(); 10454 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10455 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10456 ISD::InputArg::NoArgIndex, 0); 10457 Ins.push_back(RetArg); 10458 } 10459 10460 // Look for stores of arguments to static allocas. Mark such arguments with a 10461 // flag to ask the target to give us the memory location of that argument if 10462 // available. 10463 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10464 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10465 ArgCopyElisionCandidates); 10466 10467 // Set up the incoming argument description vector. 10468 for (const Argument &Arg : F.args()) { 10469 unsigned ArgNo = Arg.getArgNo(); 10470 SmallVector<EVT, 4> ValueVTs; 10471 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10472 bool isArgValueUsed = !Arg.use_empty(); 10473 unsigned PartBase = 0; 10474 Type *FinalType = Arg.getType(); 10475 if (Arg.hasAttribute(Attribute::ByVal)) 10476 FinalType = Arg.getParamByValType(); 10477 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10478 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10479 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10480 Value != NumValues; ++Value) { 10481 EVT VT = ValueVTs[Value]; 10482 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10483 ISD::ArgFlagsTy Flags; 10484 10485 10486 if (Arg.getType()->isPointerTy()) { 10487 Flags.setPointer(); 10488 Flags.setPointerAddrSpace( 10489 cast<PointerType>(Arg.getType())->getAddressSpace()); 10490 } 10491 if (Arg.hasAttribute(Attribute::ZExt)) 10492 Flags.setZExt(); 10493 if (Arg.hasAttribute(Attribute::SExt)) 10494 Flags.setSExt(); 10495 if (Arg.hasAttribute(Attribute::InReg)) { 10496 // If we are using vectorcall calling convention, a structure that is 10497 // passed InReg - is surely an HVA 10498 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10499 isa<StructType>(Arg.getType())) { 10500 // The first value of a structure is marked 10501 if (0 == Value) 10502 Flags.setHvaStart(); 10503 Flags.setHva(); 10504 } 10505 // Set InReg Flag 10506 Flags.setInReg(); 10507 } 10508 if (Arg.hasAttribute(Attribute::StructRet)) 10509 Flags.setSRet(); 10510 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10511 Flags.setSwiftSelf(); 10512 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10513 Flags.setSwiftAsync(); 10514 if (Arg.hasAttribute(Attribute::SwiftError)) 10515 Flags.setSwiftError(); 10516 if (Arg.hasAttribute(Attribute::ByVal)) 10517 Flags.setByVal(); 10518 if (Arg.hasAttribute(Attribute::ByRef)) 10519 Flags.setByRef(); 10520 if (Arg.hasAttribute(Attribute::InAlloca)) { 10521 Flags.setInAlloca(); 10522 // Set the byval flag for CCAssignFn callbacks that don't know about 10523 // inalloca. This way we can know how many bytes we should've allocated 10524 // and how many bytes a callee cleanup function will pop. If we port 10525 // inalloca to more targets, we'll have to add custom inalloca handling 10526 // in the various CC lowering callbacks. 10527 Flags.setByVal(); 10528 } 10529 if (Arg.hasAttribute(Attribute::Preallocated)) { 10530 Flags.setPreallocated(); 10531 // Set the byval flag for CCAssignFn callbacks that don't know about 10532 // preallocated. This way we can know how many bytes we should've 10533 // allocated and how many bytes a callee cleanup function will pop. If 10534 // we port preallocated to more targets, we'll have to add custom 10535 // preallocated handling in the various CC lowering callbacks. 10536 Flags.setByVal(); 10537 } 10538 10539 // Certain targets (such as MIPS), may have a different ABI alignment 10540 // for a type depending on the context. Give the target a chance to 10541 // specify the alignment it wants. 10542 const Align OriginalAlignment( 10543 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10544 Flags.setOrigAlign(OriginalAlignment); 10545 10546 Align MemAlign; 10547 Type *ArgMemTy = nullptr; 10548 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10549 Flags.isByRef()) { 10550 if (!ArgMemTy) 10551 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10552 10553 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10554 10555 // For in-memory arguments, size and alignment should be passed from FE. 10556 // BE will guess if this info is not there but there are cases it cannot 10557 // get right. 10558 if (auto ParamAlign = Arg.getParamStackAlign()) 10559 MemAlign = *ParamAlign; 10560 else if ((ParamAlign = Arg.getParamAlign())) 10561 MemAlign = *ParamAlign; 10562 else 10563 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10564 if (Flags.isByRef()) 10565 Flags.setByRefSize(MemSize); 10566 else 10567 Flags.setByValSize(MemSize); 10568 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10569 MemAlign = *ParamAlign; 10570 } else { 10571 MemAlign = OriginalAlignment; 10572 } 10573 Flags.setMemAlign(MemAlign); 10574 10575 if (Arg.hasAttribute(Attribute::Nest)) 10576 Flags.setNest(); 10577 if (NeedsRegBlock) 10578 Flags.setInConsecutiveRegs(); 10579 if (ArgCopyElisionCandidates.count(&Arg)) 10580 Flags.setCopyElisionCandidate(); 10581 if (Arg.hasAttribute(Attribute::Returned)) 10582 Flags.setReturned(); 10583 10584 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10585 *CurDAG->getContext(), F.getCallingConv(), VT); 10586 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10587 *CurDAG->getContext(), F.getCallingConv(), VT); 10588 for (unsigned i = 0; i != NumRegs; ++i) { 10589 // For scalable vectors, use the minimum size; individual targets 10590 // are responsible for handling scalable vector arguments and 10591 // return values. 10592 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10593 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10594 if (NumRegs > 1 && i == 0) 10595 MyFlags.Flags.setSplit(); 10596 // if it isn't first piece, alignment must be 1 10597 else if (i > 0) { 10598 MyFlags.Flags.setOrigAlign(Align(1)); 10599 if (i == NumRegs - 1) 10600 MyFlags.Flags.setSplitEnd(); 10601 } 10602 Ins.push_back(MyFlags); 10603 } 10604 if (NeedsRegBlock && Value == NumValues - 1) 10605 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10606 PartBase += VT.getStoreSize().getKnownMinSize(); 10607 } 10608 } 10609 10610 // Call the target to set up the argument values. 10611 SmallVector<SDValue, 8> InVals; 10612 SDValue NewRoot = TLI->LowerFormalArguments( 10613 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10614 10615 // Verify that the target's LowerFormalArguments behaved as expected. 10616 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10617 "LowerFormalArguments didn't return a valid chain!"); 10618 assert(InVals.size() == Ins.size() && 10619 "LowerFormalArguments didn't emit the correct number of values!"); 10620 LLVM_DEBUG({ 10621 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10622 assert(InVals[i].getNode() && 10623 "LowerFormalArguments emitted a null value!"); 10624 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10625 "LowerFormalArguments emitted a value with the wrong type!"); 10626 } 10627 }); 10628 10629 // Update the DAG with the new chain value resulting from argument lowering. 10630 DAG.setRoot(NewRoot); 10631 10632 // Set up the argument values. 10633 unsigned i = 0; 10634 if (!FuncInfo->CanLowerReturn) { 10635 // Create a virtual register for the sret pointer, and put in a copy 10636 // from the sret argument into it. 10637 SmallVector<EVT, 1> ValueVTs; 10638 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10639 F.getReturnType()->getPointerTo( 10640 DAG.getDataLayout().getAllocaAddrSpace()), 10641 ValueVTs); 10642 MVT VT = ValueVTs[0].getSimpleVT(); 10643 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10644 Optional<ISD::NodeType> AssertOp; 10645 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10646 nullptr, F.getCallingConv(), AssertOp); 10647 10648 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10649 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10650 Register SRetReg = 10651 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10652 FuncInfo->DemoteRegister = SRetReg; 10653 NewRoot = 10654 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10655 DAG.setRoot(NewRoot); 10656 10657 // i indexes lowered arguments. Bump it past the hidden sret argument. 10658 ++i; 10659 } 10660 10661 SmallVector<SDValue, 4> Chains; 10662 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10663 for (const Argument &Arg : F.args()) { 10664 SmallVector<SDValue, 4> ArgValues; 10665 SmallVector<EVT, 4> ValueVTs; 10666 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10667 unsigned NumValues = ValueVTs.size(); 10668 if (NumValues == 0) 10669 continue; 10670 10671 bool ArgHasUses = !Arg.use_empty(); 10672 10673 // Elide the copying store if the target loaded this argument from a 10674 // suitable fixed stack object. 10675 if (Ins[i].Flags.isCopyElisionCandidate()) { 10676 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10677 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10678 InVals[i], ArgHasUses); 10679 } 10680 10681 // If this argument is unused then remember its value. It is used to generate 10682 // debugging information. 10683 bool isSwiftErrorArg = 10684 TLI->supportSwiftError() && 10685 Arg.hasAttribute(Attribute::SwiftError); 10686 if (!ArgHasUses && !isSwiftErrorArg) { 10687 SDB->setUnusedArgValue(&Arg, InVals[i]); 10688 10689 // Also remember any frame index for use in FastISel. 10690 if (FrameIndexSDNode *FI = 10691 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10692 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10693 } 10694 10695 for (unsigned Val = 0; Val != NumValues; ++Val) { 10696 EVT VT = ValueVTs[Val]; 10697 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10698 F.getCallingConv(), VT); 10699 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10700 *CurDAG->getContext(), F.getCallingConv(), VT); 10701 10702 // Even an apparent 'unused' swifterror argument needs to be returned. So 10703 // we do generate a copy for it that can be used on return from the 10704 // function. 10705 if (ArgHasUses || isSwiftErrorArg) { 10706 Optional<ISD::NodeType> AssertOp; 10707 if (Arg.hasAttribute(Attribute::SExt)) 10708 AssertOp = ISD::AssertSext; 10709 else if (Arg.hasAttribute(Attribute::ZExt)) 10710 AssertOp = ISD::AssertZext; 10711 10712 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10713 PartVT, VT, nullptr, 10714 F.getCallingConv(), AssertOp)); 10715 } 10716 10717 i += NumParts; 10718 } 10719 10720 // We don't need to do anything else for unused arguments. 10721 if (ArgValues.empty()) 10722 continue; 10723 10724 // Note down frame index. 10725 if (FrameIndexSDNode *FI = 10726 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10727 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10728 10729 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10730 SDB->getCurSDLoc()); 10731 10732 SDB->setValue(&Arg, Res); 10733 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10734 // We want to associate the argument with the frame index, among 10735 // involved operands, that correspond to the lowest address. The 10736 // getCopyFromParts function, called earlier, is swapping the order of 10737 // the operands to BUILD_PAIR depending on endianness. The result of 10738 // that swapping is that the least significant bits of the argument will 10739 // be in the first operand of the BUILD_PAIR node, and the most 10740 // significant bits will be in the second operand. 10741 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10742 if (LoadSDNode *LNode = 10743 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10744 if (FrameIndexSDNode *FI = 10745 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10746 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10747 } 10748 10749 // Analyses past this point are naive and don't expect an assertion. 10750 if (Res.getOpcode() == ISD::AssertZext) 10751 Res = Res.getOperand(0); 10752 10753 // Update the SwiftErrorVRegDefMap. 10754 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10755 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10756 if (Register::isVirtualRegister(Reg)) 10757 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10758 Reg); 10759 } 10760 10761 // If this argument is live outside of the entry block, insert a copy from 10762 // wherever we got it to the vreg that other BB's will reference it as. 10763 if (Res.getOpcode() == ISD::CopyFromReg) { 10764 // If we can, though, try to skip creating an unnecessary vreg. 10765 // FIXME: This isn't very clean... it would be nice to make this more 10766 // general. 10767 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10768 if (Register::isVirtualRegister(Reg)) { 10769 FuncInfo->ValueMap[&Arg] = Reg; 10770 continue; 10771 } 10772 } 10773 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10774 FuncInfo->InitializeRegForValue(&Arg); 10775 SDB->CopyToExportRegsIfNeeded(&Arg); 10776 } 10777 } 10778 10779 if (!Chains.empty()) { 10780 Chains.push_back(NewRoot); 10781 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10782 } 10783 10784 DAG.setRoot(NewRoot); 10785 10786 assert(i == InVals.size() && "Argument register count mismatch!"); 10787 10788 // If any argument copy elisions occurred and we have debug info, update the 10789 // stale frame indices used in the dbg.declare variable info table. 10790 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10791 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10792 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10793 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10794 if (I != ArgCopyElisionFrameIndexMap.end()) 10795 VI.Slot = I->second; 10796 } 10797 } 10798 10799 // Finally, if the target has anything special to do, allow it to do so. 10800 emitFunctionEntryCode(); 10801 } 10802 10803 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10804 /// ensure constants are generated when needed. Remember the virtual registers 10805 /// that need to be added to the Machine PHI nodes as input. We cannot just 10806 /// directly add them, because expansion might result in multiple MBB's for one 10807 /// BB. As such, the start of the BB might correspond to a different MBB than 10808 /// the end. 10809 void 10810 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10811 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10812 const Instruction *TI = LLVMBB->getTerminator(); 10813 10814 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10815 10816 // Check PHI nodes in successors that expect a value to be available from this 10817 // block. 10818 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10819 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10820 if (!isa<PHINode>(SuccBB->begin())) continue; 10821 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10822 10823 // If this terminator has multiple identical successors (common for 10824 // switches), only handle each succ once. 10825 if (!SuccsHandled.insert(SuccMBB).second) 10826 continue; 10827 10828 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10829 10830 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10831 // nodes and Machine PHI nodes, but the incoming operands have not been 10832 // emitted yet. 10833 for (const PHINode &PN : SuccBB->phis()) { 10834 // Ignore dead phi's. 10835 if (PN.use_empty()) 10836 continue; 10837 10838 // Skip empty types 10839 if (PN.getType()->isEmptyTy()) 10840 continue; 10841 10842 unsigned Reg; 10843 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10844 10845 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10846 unsigned &RegOut = ConstantsOut[C]; 10847 if (RegOut == 0) { 10848 RegOut = FuncInfo.CreateRegs(C); 10849 // We need to zero/sign extend ConstantInt phi operands to match 10850 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 10851 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 10852 if (auto *CI = dyn_cast<ConstantInt>(C)) 10853 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 10854 : ISD::ZERO_EXTEND; 10855 CopyValueToVirtualRegister(C, RegOut, ExtendType); 10856 } 10857 Reg = RegOut; 10858 } else { 10859 DenseMap<const Value *, Register>::iterator I = 10860 FuncInfo.ValueMap.find(PHIOp); 10861 if (I != FuncInfo.ValueMap.end()) 10862 Reg = I->second; 10863 else { 10864 assert(isa<AllocaInst>(PHIOp) && 10865 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10866 "Didn't codegen value into a register!??"); 10867 Reg = FuncInfo.CreateRegs(PHIOp); 10868 CopyValueToVirtualRegister(PHIOp, Reg); 10869 } 10870 } 10871 10872 // Remember that this register needs to added to the machine PHI node as 10873 // the input for this MBB. 10874 SmallVector<EVT, 4> ValueVTs; 10875 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10876 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10877 EVT VT = ValueVTs[vti]; 10878 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10879 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10880 FuncInfo.PHINodesToUpdate.push_back( 10881 std::make_pair(&*MBBI++, Reg + i)); 10882 Reg += NumRegisters; 10883 } 10884 } 10885 } 10886 10887 ConstantsOut.clear(); 10888 } 10889 10890 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10891 MachineFunction::iterator I(MBB); 10892 if (++I == FuncInfo.MF->end()) 10893 return nullptr; 10894 return &*I; 10895 } 10896 10897 /// During lowering new call nodes can be created (such as memset, etc.). 10898 /// Those will become new roots of the current DAG, but complications arise 10899 /// when they are tail calls. In such cases, the call lowering will update 10900 /// the root, but the builder still needs to know that a tail call has been 10901 /// lowered in order to avoid generating an additional return. 10902 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10903 // If the node is null, we do have a tail call. 10904 if (MaybeTC.getNode() != nullptr) 10905 DAG.setRoot(MaybeTC); 10906 else 10907 HasTailCall = true; 10908 } 10909 10910 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10911 MachineBasicBlock *SwitchMBB, 10912 MachineBasicBlock *DefaultMBB) { 10913 MachineFunction *CurMF = FuncInfo.MF; 10914 MachineBasicBlock *NextMBB = nullptr; 10915 MachineFunction::iterator BBI(W.MBB); 10916 if (++BBI != FuncInfo.MF->end()) 10917 NextMBB = &*BBI; 10918 10919 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10920 10921 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10922 10923 if (Size == 2 && W.MBB == SwitchMBB) { 10924 // If any two of the cases has the same destination, and if one value 10925 // is the same as the other, but has one bit unset that the other has set, 10926 // use bit manipulation to do two compares at once. For example: 10927 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10928 // TODO: This could be extended to merge any 2 cases in switches with 3 10929 // cases. 10930 // TODO: Handle cases where W.CaseBB != SwitchBB. 10931 CaseCluster &Small = *W.FirstCluster; 10932 CaseCluster &Big = *W.LastCluster; 10933 10934 if (Small.Low == Small.High && Big.Low == Big.High && 10935 Small.MBB == Big.MBB) { 10936 const APInt &SmallValue = Small.Low->getValue(); 10937 const APInt &BigValue = Big.Low->getValue(); 10938 10939 // Check that there is only one bit different. 10940 APInt CommonBit = BigValue ^ SmallValue; 10941 if (CommonBit.isPowerOf2()) { 10942 SDValue CondLHS = getValue(Cond); 10943 EVT VT = CondLHS.getValueType(); 10944 SDLoc DL = getCurSDLoc(); 10945 10946 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10947 DAG.getConstant(CommonBit, DL, VT)); 10948 SDValue Cond = DAG.getSetCC( 10949 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10950 ISD::SETEQ); 10951 10952 // Update successor info. 10953 // Both Small and Big will jump to Small.BB, so we sum up the 10954 // probabilities. 10955 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10956 if (BPI) 10957 addSuccessorWithProb( 10958 SwitchMBB, DefaultMBB, 10959 // The default destination is the first successor in IR. 10960 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10961 else 10962 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10963 10964 // Insert the true branch. 10965 SDValue BrCond = 10966 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10967 DAG.getBasicBlock(Small.MBB)); 10968 // Insert the false branch. 10969 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10970 DAG.getBasicBlock(DefaultMBB)); 10971 10972 DAG.setRoot(BrCond); 10973 return; 10974 } 10975 } 10976 } 10977 10978 if (TM.getOptLevel() != CodeGenOpt::None) { 10979 // Here, we order cases by probability so the most likely case will be 10980 // checked first. However, two clusters can have the same probability in 10981 // which case their relative ordering is non-deterministic. So we use Low 10982 // as a tie-breaker as clusters are guaranteed to never overlap. 10983 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10984 [](const CaseCluster &a, const CaseCluster &b) { 10985 return a.Prob != b.Prob ? 10986 a.Prob > b.Prob : 10987 a.Low->getValue().slt(b.Low->getValue()); 10988 }); 10989 10990 // Rearrange the case blocks so that the last one falls through if possible 10991 // without changing the order of probabilities. 10992 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10993 --I; 10994 if (I->Prob > W.LastCluster->Prob) 10995 break; 10996 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10997 std::swap(*I, *W.LastCluster); 10998 break; 10999 } 11000 } 11001 } 11002 11003 // Compute total probability. 11004 BranchProbability DefaultProb = W.DefaultProb; 11005 BranchProbability UnhandledProbs = DefaultProb; 11006 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11007 UnhandledProbs += I->Prob; 11008 11009 MachineBasicBlock *CurMBB = W.MBB; 11010 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11011 bool FallthroughUnreachable = false; 11012 MachineBasicBlock *Fallthrough; 11013 if (I == W.LastCluster) { 11014 // For the last cluster, fall through to the default destination. 11015 Fallthrough = DefaultMBB; 11016 FallthroughUnreachable = isa<UnreachableInst>( 11017 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11018 } else { 11019 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11020 CurMF->insert(BBI, Fallthrough); 11021 // Put Cond in a virtual register to make it available from the new blocks. 11022 ExportFromCurrentBlock(Cond); 11023 } 11024 UnhandledProbs -= I->Prob; 11025 11026 switch (I->Kind) { 11027 case CC_JumpTable: { 11028 // FIXME: Optimize away range check based on pivot comparisons. 11029 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11030 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11031 11032 // The jump block hasn't been inserted yet; insert it here. 11033 MachineBasicBlock *JumpMBB = JT->MBB; 11034 CurMF->insert(BBI, JumpMBB); 11035 11036 auto JumpProb = I->Prob; 11037 auto FallthroughProb = UnhandledProbs; 11038 11039 // If the default statement is a target of the jump table, we evenly 11040 // distribute the default probability to successors of CurMBB. Also 11041 // update the probability on the edge from JumpMBB to Fallthrough. 11042 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11043 SE = JumpMBB->succ_end(); 11044 SI != SE; ++SI) { 11045 if (*SI == DefaultMBB) { 11046 JumpProb += DefaultProb / 2; 11047 FallthroughProb -= DefaultProb / 2; 11048 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11049 JumpMBB->normalizeSuccProbs(); 11050 break; 11051 } 11052 } 11053 11054 if (FallthroughUnreachable) 11055 JTH->FallthroughUnreachable = true; 11056 11057 if (!JTH->FallthroughUnreachable) 11058 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11059 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11060 CurMBB->normalizeSuccProbs(); 11061 11062 // The jump table header will be inserted in our current block, do the 11063 // range check, and fall through to our fallthrough block. 11064 JTH->HeaderBB = CurMBB; 11065 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11066 11067 // If we're in the right place, emit the jump table header right now. 11068 if (CurMBB == SwitchMBB) { 11069 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11070 JTH->Emitted = true; 11071 } 11072 break; 11073 } 11074 case CC_BitTests: { 11075 // FIXME: Optimize away range check based on pivot comparisons. 11076 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11077 11078 // The bit test blocks haven't been inserted yet; insert them here. 11079 for (BitTestCase &BTC : BTB->Cases) 11080 CurMF->insert(BBI, BTC.ThisBB); 11081 11082 // Fill in fields of the BitTestBlock. 11083 BTB->Parent = CurMBB; 11084 BTB->Default = Fallthrough; 11085 11086 BTB->DefaultProb = UnhandledProbs; 11087 // If the cases in bit test don't form a contiguous range, we evenly 11088 // distribute the probability on the edge to Fallthrough to two 11089 // successors of CurMBB. 11090 if (!BTB->ContiguousRange) { 11091 BTB->Prob += DefaultProb / 2; 11092 BTB->DefaultProb -= DefaultProb / 2; 11093 } 11094 11095 if (FallthroughUnreachable) 11096 BTB->FallthroughUnreachable = true; 11097 11098 // If we're in the right place, emit the bit test header right now. 11099 if (CurMBB == SwitchMBB) { 11100 visitBitTestHeader(*BTB, SwitchMBB); 11101 BTB->Emitted = true; 11102 } 11103 break; 11104 } 11105 case CC_Range: { 11106 const Value *RHS, *LHS, *MHS; 11107 ISD::CondCode CC; 11108 if (I->Low == I->High) { 11109 // Check Cond == I->Low. 11110 CC = ISD::SETEQ; 11111 LHS = Cond; 11112 RHS=I->Low; 11113 MHS = nullptr; 11114 } else { 11115 // Check I->Low <= Cond <= I->High. 11116 CC = ISD::SETLE; 11117 LHS = I->Low; 11118 MHS = Cond; 11119 RHS = I->High; 11120 } 11121 11122 // If Fallthrough is unreachable, fold away the comparison. 11123 if (FallthroughUnreachable) 11124 CC = ISD::SETTRUE; 11125 11126 // The false probability is the sum of all unhandled cases. 11127 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11128 getCurSDLoc(), I->Prob, UnhandledProbs); 11129 11130 if (CurMBB == SwitchMBB) 11131 visitSwitchCase(CB, SwitchMBB); 11132 else 11133 SL->SwitchCases.push_back(CB); 11134 11135 break; 11136 } 11137 } 11138 CurMBB = Fallthrough; 11139 } 11140 } 11141 11142 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11143 CaseClusterIt First, 11144 CaseClusterIt Last) { 11145 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11146 if (X.Prob != CC.Prob) 11147 return X.Prob > CC.Prob; 11148 11149 // Ties are broken by comparing the case value. 11150 return X.Low->getValue().slt(CC.Low->getValue()); 11151 }); 11152 } 11153 11154 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11155 const SwitchWorkListItem &W, 11156 Value *Cond, 11157 MachineBasicBlock *SwitchMBB) { 11158 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11159 "Clusters not sorted?"); 11160 11161 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11162 11163 // Balance the tree based on branch probabilities to create a near-optimal (in 11164 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11165 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11166 CaseClusterIt LastLeft = W.FirstCluster; 11167 CaseClusterIt FirstRight = W.LastCluster; 11168 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11169 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11170 11171 // Move LastLeft and FirstRight towards each other from opposite directions to 11172 // find a partitioning of the clusters which balances the probability on both 11173 // sides. If LeftProb and RightProb are equal, alternate which side is 11174 // taken to ensure 0-probability nodes are distributed evenly. 11175 unsigned I = 0; 11176 while (LastLeft + 1 < FirstRight) { 11177 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11178 LeftProb += (++LastLeft)->Prob; 11179 else 11180 RightProb += (--FirstRight)->Prob; 11181 I++; 11182 } 11183 11184 while (true) { 11185 // Our binary search tree differs from a typical BST in that ours can have up 11186 // to three values in each leaf. The pivot selection above doesn't take that 11187 // into account, which means the tree might require more nodes and be less 11188 // efficient. We compensate for this here. 11189 11190 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11191 unsigned NumRight = W.LastCluster - FirstRight + 1; 11192 11193 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11194 // If one side has less than 3 clusters, and the other has more than 3, 11195 // consider taking a cluster from the other side. 11196 11197 if (NumLeft < NumRight) { 11198 // Consider moving the first cluster on the right to the left side. 11199 CaseCluster &CC = *FirstRight; 11200 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11201 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11202 if (LeftSideRank <= RightSideRank) { 11203 // Moving the cluster to the left does not demote it. 11204 ++LastLeft; 11205 ++FirstRight; 11206 continue; 11207 } 11208 } else { 11209 assert(NumRight < NumLeft); 11210 // Consider moving the last element on the left to the right side. 11211 CaseCluster &CC = *LastLeft; 11212 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11213 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11214 if (RightSideRank <= LeftSideRank) { 11215 // Moving the cluster to the right does not demot it. 11216 --LastLeft; 11217 --FirstRight; 11218 continue; 11219 } 11220 } 11221 } 11222 break; 11223 } 11224 11225 assert(LastLeft + 1 == FirstRight); 11226 assert(LastLeft >= W.FirstCluster); 11227 assert(FirstRight <= W.LastCluster); 11228 11229 // Use the first element on the right as pivot since we will make less-than 11230 // comparisons against it. 11231 CaseClusterIt PivotCluster = FirstRight; 11232 assert(PivotCluster > W.FirstCluster); 11233 assert(PivotCluster <= W.LastCluster); 11234 11235 CaseClusterIt FirstLeft = W.FirstCluster; 11236 CaseClusterIt LastRight = W.LastCluster; 11237 11238 const ConstantInt *Pivot = PivotCluster->Low; 11239 11240 // New blocks will be inserted immediately after the current one. 11241 MachineFunction::iterator BBI(W.MBB); 11242 ++BBI; 11243 11244 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11245 // we can branch to its destination directly if it's squeezed exactly in 11246 // between the known lower bound and Pivot - 1. 11247 MachineBasicBlock *LeftMBB; 11248 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11249 FirstLeft->Low == W.GE && 11250 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11251 LeftMBB = FirstLeft->MBB; 11252 } else { 11253 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11254 FuncInfo.MF->insert(BBI, LeftMBB); 11255 WorkList.push_back( 11256 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11257 // Put Cond in a virtual register to make it available from the new blocks. 11258 ExportFromCurrentBlock(Cond); 11259 } 11260 11261 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11262 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11263 // directly if RHS.High equals the current upper bound. 11264 MachineBasicBlock *RightMBB; 11265 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11266 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11267 RightMBB = FirstRight->MBB; 11268 } else { 11269 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11270 FuncInfo.MF->insert(BBI, RightMBB); 11271 WorkList.push_back( 11272 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11273 // Put Cond in a virtual register to make it available from the new blocks. 11274 ExportFromCurrentBlock(Cond); 11275 } 11276 11277 // Create the CaseBlock record that will be used to lower the branch. 11278 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11279 getCurSDLoc(), LeftProb, RightProb); 11280 11281 if (W.MBB == SwitchMBB) 11282 visitSwitchCase(CB, SwitchMBB); 11283 else 11284 SL->SwitchCases.push_back(CB); 11285 } 11286 11287 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11288 // from the swith statement. 11289 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11290 BranchProbability PeeledCaseProb) { 11291 if (PeeledCaseProb == BranchProbability::getOne()) 11292 return BranchProbability::getZero(); 11293 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11294 11295 uint32_t Numerator = CaseProb.getNumerator(); 11296 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11297 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11298 } 11299 11300 // Try to peel the top probability case if it exceeds the threshold. 11301 // Return current MachineBasicBlock for the switch statement if the peeling 11302 // does not occur. 11303 // If the peeling is performed, return the newly created MachineBasicBlock 11304 // for the peeled switch statement. Also update Clusters to remove the peeled 11305 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11306 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11307 const SwitchInst &SI, CaseClusterVector &Clusters, 11308 BranchProbability &PeeledCaseProb) { 11309 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11310 // Don't perform if there is only one cluster or optimizing for size. 11311 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11312 TM.getOptLevel() == CodeGenOpt::None || 11313 SwitchMBB->getParent()->getFunction().hasMinSize()) 11314 return SwitchMBB; 11315 11316 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11317 unsigned PeeledCaseIndex = 0; 11318 bool SwitchPeeled = false; 11319 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11320 CaseCluster &CC = Clusters[Index]; 11321 if (CC.Prob < TopCaseProb) 11322 continue; 11323 TopCaseProb = CC.Prob; 11324 PeeledCaseIndex = Index; 11325 SwitchPeeled = true; 11326 } 11327 if (!SwitchPeeled) 11328 return SwitchMBB; 11329 11330 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11331 << TopCaseProb << "\n"); 11332 11333 // Record the MBB for the peeled switch statement. 11334 MachineFunction::iterator BBI(SwitchMBB); 11335 ++BBI; 11336 MachineBasicBlock *PeeledSwitchMBB = 11337 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11338 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11339 11340 ExportFromCurrentBlock(SI.getCondition()); 11341 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11342 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11343 nullptr, nullptr, TopCaseProb.getCompl()}; 11344 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11345 11346 Clusters.erase(PeeledCaseIt); 11347 for (CaseCluster &CC : Clusters) { 11348 LLVM_DEBUG( 11349 dbgs() << "Scale the probablity for one cluster, before scaling: " 11350 << CC.Prob << "\n"); 11351 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11352 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11353 } 11354 PeeledCaseProb = TopCaseProb; 11355 return PeeledSwitchMBB; 11356 } 11357 11358 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11359 // Extract cases from the switch. 11360 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11361 CaseClusterVector Clusters; 11362 Clusters.reserve(SI.getNumCases()); 11363 for (auto I : SI.cases()) { 11364 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11365 const ConstantInt *CaseVal = I.getCaseValue(); 11366 BranchProbability Prob = 11367 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11368 : BranchProbability(1, SI.getNumCases() + 1); 11369 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11370 } 11371 11372 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11373 11374 // Cluster adjacent cases with the same destination. We do this at all 11375 // optimization levels because it's cheap to do and will make codegen faster 11376 // if there are many clusters. 11377 sortAndRangeify(Clusters); 11378 11379 // The branch probablity of the peeled case. 11380 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11381 MachineBasicBlock *PeeledSwitchMBB = 11382 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11383 11384 // If there is only the default destination, jump there directly. 11385 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11386 if (Clusters.empty()) { 11387 assert(PeeledSwitchMBB == SwitchMBB); 11388 SwitchMBB->addSuccessor(DefaultMBB); 11389 if (DefaultMBB != NextBlock(SwitchMBB)) { 11390 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11391 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11392 } 11393 return; 11394 } 11395 11396 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11397 SL->findBitTestClusters(Clusters, &SI); 11398 11399 LLVM_DEBUG({ 11400 dbgs() << "Case clusters: "; 11401 for (const CaseCluster &C : Clusters) { 11402 if (C.Kind == CC_JumpTable) 11403 dbgs() << "JT:"; 11404 if (C.Kind == CC_BitTests) 11405 dbgs() << "BT:"; 11406 11407 C.Low->getValue().print(dbgs(), true); 11408 if (C.Low != C.High) { 11409 dbgs() << '-'; 11410 C.High->getValue().print(dbgs(), true); 11411 } 11412 dbgs() << ' '; 11413 } 11414 dbgs() << '\n'; 11415 }); 11416 11417 assert(!Clusters.empty()); 11418 SwitchWorkList WorkList; 11419 CaseClusterIt First = Clusters.begin(); 11420 CaseClusterIt Last = Clusters.end() - 1; 11421 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11422 // Scale the branchprobability for DefaultMBB if the peel occurs and 11423 // DefaultMBB is not replaced. 11424 if (PeeledCaseProb != BranchProbability::getZero() && 11425 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11426 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11427 WorkList.push_back( 11428 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11429 11430 while (!WorkList.empty()) { 11431 SwitchWorkListItem W = WorkList.pop_back_val(); 11432 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11433 11434 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11435 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11436 // For optimized builds, lower large range as a balanced binary tree. 11437 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11438 continue; 11439 } 11440 11441 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11442 } 11443 } 11444 11445 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11446 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11447 auto DL = getCurSDLoc(); 11448 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11449 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11450 } 11451 11452 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11453 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11454 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11455 11456 SDLoc DL = getCurSDLoc(); 11457 SDValue V = getValue(I.getOperand(0)); 11458 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11459 11460 if (VT.isScalableVector()) { 11461 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11462 return; 11463 } 11464 11465 // Use VECTOR_SHUFFLE for the fixed-length vector 11466 // to maintain existing behavior. 11467 SmallVector<int, 8> Mask; 11468 unsigned NumElts = VT.getVectorMinNumElements(); 11469 for (unsigned i = 0; i != NumElts; ++i) 11470 Mask.push_back(NumElts - 1 - i); 11471 11472 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11473 } 11474 11475 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11476 SmallVector<EVT, 4> ValueVTs; 11477 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11478 ValueVTs); 11479 unsigned NumValues = ValueVTs.size(); 11480 if (NumValues == 0) return; 11481 11482 SmallVector<SDValue, 4> Values(NumValues); 11483 SDValue Op = getValue(I.getOperand(0)); 11484 11485 for (unsigned i = 0; i != NumValues; ++i) 11486 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11487 SDValue(Op.getNode(), Op.getResNo() + i)); 11488 11489 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11490 DAG.getVTList(ValueVTs), Values)); 11491 } 11492 11493 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11494 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11495 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11496 11497 SDLoc DL = getCurSDLoc(); 11498 SDValue V1 = getValue(I.getOperand(0)); 11499 SDValue V2 = getValue(I.getOperand(1)); 11500 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11501 11502 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11503 if (VT.isScalableVector()) { 11504 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11505 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11506 DAG.getConstant(Imm, DL, IdxVT))); 11507 return; 11508 } 11509 11510 unsigned NumElts = VT.getVectorNumElements(); 11511 11512 uint64_t Idx = (NumElts + Imm) % NumElts; 11513 11514 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11515 SmallVector<int, 8> Mask; 11516 for (unsigned i = 0; i < NumElts; ++i) 11517 Mask.push_back(Idx + i); 11518 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11519 } 11520