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 parts vector has more elements than the value vector, then we 402 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 403 // Extract the elements we want. 404 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 405 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 406 ValueVT.getVectorElementCount().getKnownMinValue()) && 407 (PartEVT.getVectorElementCount().isScalable() == 408 ValueVT.getVectorElementCount().isScalable()) && 409 "Cannot narrow, it would be a lossy transformation"); 410 PartEVT = 411 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 412 ValueVT.getVectorElementCount()); 413 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 414 DAG.getVectorIdxConstant(0, DL)); 415 if (PartEVT == ValueVT) 416 return Val; 417 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 418 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 419 } 420 421 // Promoted vector extract 422 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 423 } 424 425 // Trivial bitcast if the types are the same size and the destination 426 // vector type is legal. 427 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 428 TLI.isTypeLegal(ValueVT)) 429 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 430 431 if (ValueVT.getVectorNumElements() != 1) { 432 // Certain ABIs require that vectors are passed as integers. For vectors 433 // are the same size, this is an obvious bitcast. 434 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 435 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 436 } else if (ValueVT.bitsLT(PartEVT)) { 437 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 438 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 439 // Drop the extra bits. 440 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 441 return DAG.getBitcast(ValueVT, Val); 442 } 443 444 diagnosePossiblyInvalidConstraint( 445 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 446 return DAG.getUNDEF(ValueVT); 447 } 448 449 // Handle cases such as i8 -> <1 x i1> 450 EVT ValueSVT = ValueVT.getVectorElementType(); 451 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 452 unsigned ValueSize = ValueSVT.getSizeInBits(); 453 if (ValueSize == PartEVT.getSizeInBits()) { 454 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 455 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 456 // It's possible a scalar floating point type gets softened to integer and 457 // then promoted to a larger integer. If PartEVT is the larger integer 458 // we need to truncate it and then bitcast to the FP type. 459 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 460 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 461 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 462 Val = DAG.getBitcast(ValueSVT, Val); 463 } else { 464 Val = ValueVT.isFloatingPoint() 465 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 466 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 467 } 468 } 469 470 return DAG.getBuildVector(ValueVT, DL, Val); 471 } 472 473 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 474 SDValue Val, SDValue *Parts, unsigned NumParts, 475 MVT PartVT, const Value *V, 476 Optional<CallingConv::ID> CallConv); 477 478 /// getCopyToParts - Create a series of nodes that contain the specified value 479 /// split into legal parts. If the parts contain more bits than Val, then, for 480 /// integers, ExtendKind can be used to specify how to generate the extra bits. 481 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 482 SDValue *Parts, unsigned NumParts, MVT PartVT, 483 const Value *V, 484 Optional<CallingConv::ID> CallConv = None, 485 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 486 // Let the target split the parts if it wants to 487 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 488 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 489 CallConv)) 490 return; 491 EVT ValueVT = Val.getValueType(); 492 493 // Handle the vector case separately. 494 if (ValueVT.isVector()) 495 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 496 CallConv); 497 498 unsigned PartBits = PartVT.getSizeInBits(); 499 unsigned OrigNumParts = NumParts; 500 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 501 "Copying to an illegal type!"); 502 503 if (NumParts == 0) 504 return; 505 506 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 507 EVT PartEVT = PartVT; 508 if (PartEVT == ValueVT) { 509 assert(NumParts == 1 && "No-op copy with multiple parts!"); 510 Parts[0] = Val; 511 return; 512 } 513 514 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 515 // If the parts cover more bits than the value has, promote the value. 516 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 517 assert(NumParts == 1 && "Do not know what to promote to!"); 518 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 519 } else { 520 if (ValueVT.isFloatingPoint()) { 521 // FP values need to be bitcast, then extended if they are being put 522 // into a larger container. 523 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 524 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 525 } 526 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 527 ValueVT.isInteger() && 528 "Unknown mismatch!"); 529 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 530 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 531 if (PartVT == MVT::x86mmx) 532 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 533 } 534 } else if (PartBits == ValueVT.getSizeInBits()) { 535 // Different types of the same size. 536 assert(NumParts == 1 && PartEVT != ValueVT); 537 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 538 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 539 // If the parts cover less bits than value has, truncate the value. 540 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 541 ValueVT.isInteger() && 542 "Unknown mismatch!"); 543 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 544 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 545 if (PartVT == MVT::x86mmx) 546 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 547 } 548 549 // The value may have changed - recompute ValueVT. 550 ValueVT = Val.getValueType(); 551 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 552 "Failed to tile the value with PartVT!"); 553 554 if (NumParts == 1) { 555 if (PartEVT != ValueVT) { 556 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 557 "scalar-to-vector conversion failed"); 558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 559 } 560 561 Parts[0] = Val; 562 return; 563 } 564 565 // Expand the value into multiple parts. 566 if (NumParts & (NumParts - 1)) { 567 // The number of parts is not a power of 2. Split off and copy the tail. 568 assert(PartVT.isInteger() && ValueVT.isInteger() && 569 "Do not know what to expand to!"); 570 unsigned RoundParts = 1 << Log2_32(NumParts); 571 unsigned RoundBits = RoundParts * PartBits; 572 unsigned OddParts = NumParts - RoundParts; 573 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 574 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 575 576 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 577 CallConv); 578 579 if (DAG.getDataLayout().isBigEndian()) 580 // The odd parts were reversed by getCopyToParts - unreverse them. 581 std::reverse(Parts + RoundParts, Parts + NumParts); 582 583 NumParts = RoundParts; 584 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 585 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 586 } 587 588 // The number of parts is a power of 2. Repeatedly bisect the value using 589 // EXTRACT_ELEMENT. 590 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 591 EVT::getIntegerVT(*DAG.getContext(), 592 ValueVT.getSizeInBits()), 593 Val); 594 595 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 596 for (unsigned i = 0; i < NumParts; i += StepSize) { 597 unsigned ThisBits = StepSize * PartBits / 2; 598 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 599 SDValue &Part0 = Parts[i]; 600 SDValue &Part1 = Parts[i+StepSize/2]; 601 602 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 603 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 604 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 605 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 606 607 if (ThisBits == PartBits && ThisVT != PartVT) { 608 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 609 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 610 } 611 } 612 } 613 614 if (DAG.getDataLayout().isBigEndian()) 615 std::reverse(Parts, Parts + OrigNumParts); 616 } 617 618 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 619 const SDLoc &DL, EVT PartVT) { 620 if (!PartVT.isVector()) 621 return SDValue(); 622 623 EVT ValueVT = Val.getValueType(); 624 ElementCount PartNumElts = PartVT.getVectorElementCount(); 625 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 626 627 // We only support widening vectors with equivalent element types and 628 // fixed/scalable properties. If a target needs to widen a fixed-length type 629 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 630 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 631 PartNumElts.isScalable() != ValueNumElts.isScalable() || 632 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 633 return SDValue(); 634 635 // Widening a scalable vector to another scalable vector is done by inserting 636 // the vector into a larger undef one. 637 if (PartNumElts.isScalable()) 638 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 639 Val, DAG.getVectorIdxConstant(0, DL)); 640 641 EVT ElementVT = PartVT.getVectorElementType(); 642 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 643 // undef elements. 644 SmallVector<SDValue, 16> Ops; 645 DAG.ExtractVectorElements(Val, Ops); 646 SDValue EltUndef = DAG.getUNDEF(ElementVT); 647 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 648 649 // FIXME: Use CONCAT for 2x -> 4x. 650 return DAG.getBuildVector(PartVT, DL, Ops); 651 } 652 653 /// getCopyToPartsVector - Create a series of nodes that contain the specified 654 /// value split into legal parts. 655 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 656 SDValue Val, SDValue *Parts, unsigned NumParts, 657 MVT PartVT, const Value *V, 658 Optional<CallingConv::ID> CallConv) { 659 EVT ValueVT = Val.getValueType(); 660 assert(ValueVT.isVector() && "Not a vector"); 661 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 662 const bool IsABIRegCopy = CallConv.has_value(); 663 664 if (NumParts == 1) { 665 EVT PartEVT = PartVT; 666 if (PartEVT == ValueVT) { 667 // Nothing to do. 668 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 669 // Bitconvert vector->vector case. 670 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 671 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 672 Val = Widened; 673 } else if (PartVT.isVector() && 674 PartEVT.getVectorElementType().bitsGE( 675 ValueVT.getVectorElementType()) && 676 PartEVT.getVectorElementCount() == 677 ValueVT.getVectorElementCount()) { 678 679 // Promoted vector extract 680 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 681 } else if (PartEVT.isVector() && 682 PartEVT.getVectorElementType() != 683 ValueVT.getVectorElementType() && 684 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 685 TargetLowering::TypeWidenVector) { 686 // Combination of widening and promotion. 687 EVT WidenVT = 688 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 689 PartVT.getVectorElementCount()); 690 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 691 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 692 } else { 693 // Don't extract an integer from a float vector. This can happen if the 694 // FP type gets softened to integer and then promoted. The promotion 695 // prevents it from being picked up by the earlier bitcast case. 696 if (ValueVT.getVectorElementCount().isScalar() && 697 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 698 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 699 DAG.getVectorIdxConstant(0, DL)); 700 } else { 701 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 702 assert(PartVT.getFixedSizeInBits() > ValueSize && 703 "lossy conversion of vector to scalar type"); 704 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 705 Val = DAG.getBitcast(IntermediateType, Val); 706 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 707 } 708 } 709 710 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 711 Parts[0] = Val; 712 return; 713 } 714 715 // Handle a multi-element vector. 716 EVT IntermediateVT; 717 MVT RegisterVT; 718 unsigned NumIntermediates; 719 unsigned NumRegs; 720 if (IsABIRegCopy) { 721 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 722 *DAG.getContext(), CallConv.value(), ValueVT, IntermediateVT, 723 NumIntermediates, RegisterVT); 724 } else { 725 NumRegs = 726 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 727 NumIntermediates, RegisterVT); 728 } 729 730 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 731 NumParts = NumRegs; // Silence a compiler warning. 732 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 733 734 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 735 "Mixing scalable and fixed vectors when copying in parts"); 736 737 Optional<ElementCount> DestEltCnt; 738 739 if (IntermediateVT.isVector()) 740 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 741 else 742 DestEltCnt = ElementCount::getFixed(NumIntermediates); 743 744 EVT BuiltVectorTy = EVT::getVectorVT( 745 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 746 747 if (ValueVT == BuiltVectorTy) { 748 // Nothing to do. 749 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 750 // Bitconvert vector->vector case. 751 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 752 } else { 753 if (BuiltVectorTy.getVectorElementType().bitsGT( 754 ValueVT.getVectorElementType())) { 755 // Integer promotion. 756 ValueVT = EVT::getVectorVT(*DAG.getContext(), 757 BuiltVectorTy.getVectorElementType(), 758 ValueVT.getVectorElementCount()); 759 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 760 } 761 762 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 763 Val = Widened; 764 } 765 } 766 767 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 768 769 // Split the vector into intermediate operands. 770 SmallVector<SDValue, 8> Ops(NumIntermediates); 771 for (unsigned i = 0; i != NumIntermediates; ++i) { 772 if (IntermediateVT.isVector()) { 773 // This does something sensible for scalable vectors - see the 774 // definition of EXTRACT_SUBVECTOR for further details. 775 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 776 Ops[i] = 777 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 778 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 779 } else { 780 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 781 DAG.getVectorIdxConstant(i, DL)); 782 } 783 } 784 785 // Split the intermediate operands into legal parts. 786 if (NumParts == NumIntermediates) { 787 // If the register was not expanded, promote or copy the value, 788 // as appropriate. 789 for (unsigned i = 0; i != NumParts; ++i) 790 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 791 } else if (NumParts > 0) { 792 // If the intermediate type was expanded, split each the value into 793 // legal parts. 794 assert(NumIntermediates != 0 && "division by zero"); 795 assert(NumParts % NumIntermediates == 0 && 796 "Must expand into a divisible number of parts!"); 797 unsigned Factor = NumParts / NumIntermediates; 798 for (unsigned i = 0; i != NumIntermediates; ++i) 799 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 800 CallConv); 801 } 802 } 803 804 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 805 EVT valuevt, Optional<CallingConv::ID> CC) 806 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 807 RegCount(1, regs.size()), CallConv(CC) {} 808 809 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 810 const DataLayout &DL, unsigned Reg, Type *Ty, 811 Optional<CallingConv::ID> CC) { 812 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 813 814 CallConv = CC; 815 816 for (EVT ValueVT : ValueVTs) { 817 unsigned NumRegs = 818 isABIMangled() 819 ? TLI.getNumRegistersForCallingConv(Context, CC.value(), ValueVT) 820 : TLI.getNumRegisters(Context, ValueVT); 821 MVT RegisterVT = 822 isABIMangled() 823 ? TLI.getRegisterTypeForCallingConv(Context, CC.value(), ValueVT) 824 : TLI.getRegisterType(Context, ValueVT); 825 for (unsigned i = 0; i != NumRegs; ++i) 826 Regs.push_back(Reg + i); 827 RegVTs.push_back(RegisterVT); 828 RegCount.push_back(NumRegs); 829 Reg += NumRegs; 830 } 831 } 832 833 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 834 FunctionLoweringInfo &FuncInfo, 835 const SDLoc &dl, SDValue &Chain, 836 SDValue *Flag, const Value *V) const { 837 // A Value with type {} or [0 x %t] needs no registers. 838 if (ValueVTs.empty()) 839 return SDValue(); 840 841 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 842 843 // Assemble the legal parts into the final values. 844 SmallVector<SDValue, 4> Values(ValueVTs.size()); 845 SmallVector<SDValue, 8> Parts; 846 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 847 // Copy the legal parts from the registers. 848 EVT ValueVT = ValueVTs[Value]; 849 unsigned NumRegs = RegCount[Value]; 850 MVT RegisterVT = 851 isABIMangled() ? TLI.getRegisterTypeForCallingConv( 852 *DAG.getContext(), CallConv.value(), RegVTs[Value]) 853 : RegVTs[Value]; 854 855 Parts.resize(NumRegs); 856 for (unsigned i = 0; i != NumRegs; ++i) { 857 SDValue P; 858 if (!Flag) { 859 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 860 } else { 861 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 862 *Flag = P.getValue(2); 863 } 864 865 Chain = P.getValue(1); 866 Parts[i] = P; 867 868 // If the source register was virtual and if we know something about it, 869 // add an assert node. 870 if (!Register::isVirtualRegister(Regs[Part + i]) || 871 !RegisterVT.isInteger()) 872 continue; 873 874 const FunctionLoweringInfo::LiveOutInfo *LOI = 875 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 876 if (!LOI) 877 continue; 878 879 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 880 unsigned NumSignBits = LOI->NumSignBits; 881 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 882 883 if (NumZeroBits == RegSize) { 884 // The current value is a zero. 885 // Explicitly express that as it would be easier for 886 // optimizations to kick in. 887 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 888 continue; 889 } 890 891 // FIXME: We capture more information than the dag can represent. For 892 // now, just use the tightest assertzext/assertsext possible. 893 bool isSExt; 894 EVT FromVT(MVT::Other); 895 if (NumZeroBits) { 896 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 897 isSExt = false; 898 } else if (NumSignBits > 1) { 899 FromVT = 900 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 901 isSExt = true; 902 } else { 903 continue; 904 } 905 // Add an assertion node. 906 assert(FromVT != MVT::Other); 907 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 908 RegisterVT, P, DAG.getValueType(FromVT)); 909 } 910 911 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 912 RegisterVT, ValueVT, V, CallConv); 913 Part += NumRegs; 914 Parts.clear(); 915 } 916 917 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 918 } 919 920 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 921 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 922 const Value *V, 923 ISD::NodeType PreferredExtendType) const { 924 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 925 ISD::NodeType ExtendKind = PreferredExtendType; 926 927 // Get the list of the values's legal parts. 928 unsigned NumRegs = Regs.size(); 929 SmallVector<SDValue, 8> Parts(NumRegs); 930 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 931 unsigned NumParts = RegCount[Value]; 932 933 MVT RegisterVT = 934 isABIMangled() ? TLI.getRegisterTypeForCallingConv( 935 *DAG.getContext(), CallConv.value(), RegVTs[Value]) 936 : RegVTs[Value]; 937 938 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 939 ExtendKind = ISD::ZERO_EXTEND; 940 941 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 942 NumParts, RegisterVT, V, CallConv, ExtendKind); 943 Part += NumParts; 944 } 945 946 // Copy the parts into the registers. 947 SmallVector<SDValue, 8> Chains(NumRegs); 948 for (unsigned i = 0; i != NumRegs; ++i) { 949 SDValue Part; 950 if (!Flag) { 951 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 952 } else { 953 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 954 *Flag = Part.getValue(1); 955 } 956 957 Chains[i] = Part.getValue(0); 958 } 959 960 if (NumRegs == 1 || Flag) 961 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 962 // flagged to it. That is the CopyToReg nodes and the user are considered 963 // a single scheduling unit. If we create a TokenFactor and return it as 964 // chain, then the TokenFactor is both a predecessor (operand) of the 965 // user as well as a successor (the TF operands are flagged to the user). 966 // c1, f1 = CopyToReg 967 // c2, f2 = CopyToReg 968 // c3 = TokenFactor c1, c2 969 // ... 970 // = op c3, ..., f2 971 Chain = Chains[NumRegs-1]; 972 else 973 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 974 } 975 976 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 977 unsigned MatchingIdx, const SDLoc &dl, 978 SelectionDAG &DAG, 979 std::vector<SDValue> &Ops) const { 980 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 981 982 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 983 if (HasMatching) 984 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 985 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 986 // Put the register class of the virtual registers in the flag word. That 987 // way, later passes can recompute register class constraints for inline 988 // assembly as well as normal instructions. 989 // Don't do this for tied operands that can use the regclass information 990 // from the def. 991 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 992 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 993 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 994 } 995 996 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 997 Ops.push_back(Res); 998 999 if (Code == InlineAsm::Kind_Clobber) { 1000 // Clobbers should always have a 1:1 mapping with registers, and may 1001 // reference registers that have illegal (e.g. vector) types. Hence, we 1002 // shouldn't try to apply any sort of splitting logic to them. 1003 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1004 "No 1:1 mapping from clobbers to regs?"); 1005 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1006 (void)SP; 1007 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1008 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1009 assert( 1010 (Regs[I] != SP || 1011 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1012 "If we clobbered the stack pointer, MFI should know about it."); 1013 } 1014 return; 1015 } 1016 1017 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1018 MVT RegisterVT = RegVTs[Value]; 1019 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1020 RegisterVT); 1021 for (unsigned i = 0; i != NumRegs; ++i) { 1022 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1023 unsigned TheReg = Regs[Reg++]; 1024 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1025 } 1026 } 1027 } 1028 1029 SmallVector<std::pair<unsigned, TypeSize>, 4> 1030 RegsForValue::getRegsAndSizes() const { 1031 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1032 unsigned I = 0; 1033 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1034 unsigned RegCount = std::get<0>(CountAndVT); 1035 MVT RegisterVT = std::get<1>(CountAndVT); 1036 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1037 for (unsigned E = I + RegCount; I != E; ++I) 1038 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1039 } 1040 return OutVec; 1041 } 1042 1043 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1044 AssumptionCache *ac, 1045 const TargetLibraryInfo *li) { 1046 AA = aa; 1047 AC = ac; 1048 GFI = gfi; 1049 LibInfo = li; 1050 Context = DAG.getContext(); 1051 LPadToCallSiteMap.clear(); 1052 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1053 } 1054 1055 void SelectionDAGBuilder::clear() { 1056 NodeMap.clear(); 1057 UnusedArgNodeMap.clear(); 1058 PendingLoads.clear(); 1059 PendingExports.clear(); 1060 PendingConstrainedFP.clear(); 1061 PendingConstrainedFPStrict.clear(); 1062 CurInst = nullptr; 1063 HasTailCall = false; 1064 SDNodeOrder = LowestSDNodeOrder; 1065 StatepointLowering.clear(); 1066 } 1067 1068 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1069 DanglingDebugInfoMap.clear(); 1070 } 1071 1072 // Update DAG root to include dependencies on Pending chains. 1073 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1074 SDValue Root = DAG.getRoot(); 1075 1076 if (Pending.empty()) 1077 return Root; 1078 1079 // Add current root to PendingChains, unless we already indirectly 1080 // depend on it. 1081 if (Root.getOpcode() != ISD::EntryToken) { 1082 unsigned i = 0, e = Pending.size(); 1083 for (; i != e; ++i) { 1084 assert(Pending[i].getNode()->getNumOperands() > 1); 1085 if (Pending[i].getNode()->getOperand(0) == Root) 1086 break; // Don't add the root if we already indirectly depend on it. 1087 } 1088 1089 if (i == e) 1090 Pending.push_back(Root); 1091 } 1092 1093 if (Pending.size() == 1) 1094 Root = Pending[0]; 1095 else 1096 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1097 1098 DAG.setRoot(Root); 1099 Pending.clear(); 1100 return Root; 1101 } 1102 1103 SDValue SelectionDAGBuilder::getMemoryRoot() { 1104 return updateRoot(PendingLoads); 1105 } 1106 1107 SDValue SelectionDAGBuilder::getRoot() { 1108 // Chain up all pending constrained intrinsics together with all 1109 // pending loads, by simply appending them to PendingLoads and 1110 // then calling getMemoryRoot(). 1111 PendingLoads.reserve(PendingLoads.size() + 1112 PendingConstrainedFP.size() + 1113 PendingConstrainedFPStrict.size()); 1114 PendingLoads.append(PendingConstrainedFP.begin(), 1115 PendingConstrainedFP.end()); 1116 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1117 PendingConstrainedFPStrict.end()); 1118 PendingConstrainedFP.clear(); 1119 PendingConstrainedFPStrict.clear(); 1120 return getMemoryRoot(); 1121 } 1122 1123 SDValue SelectionDAGBuilder::getControlRoot() { 1124 // We need to emit pending fpexcept.strict constrained intrinsics, 1125 // so append them to the PendingExports list. 1126 PendingExports.append(PendingConstrainedFPStrict.begin(), 1127 PendingConstrainedFPStrict.end()); 1128 PendingConstrainedFPStrict.clear(); 1129 return updateRoot(PendingExports); 1130 } 1131 1132 void SelectionDAGBuilder::visit(const Instruction &I) { 1133 // Set up outgoing PHI node register values before emitting the terminator. 1134 if (I.isTerminator()) { 1135 HandlePHINodesInSuccessorBlocks(I.getParent()); 1136 } 1137 1138 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1139 if (!isa<DbgInfoIntrinsic>(I)) 1140 ++SDNodeOrder; 1141 1142 CurInst = &I; 1143 1144 // Set inserted listener only if required. 1145 bool NodeInserted = false; 1146 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1147 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1148 if (PCSectionsMD) { 1149 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1150 DAG, [&](SDNode *) { NodeInserted = true; }); 1151 } 1152 1153 visit(I.getOpcode(), I); 1154 1155 if (!I.isTerminator() && !HasTailCall && 1156 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1157 CopyToExportRegsIfNeeded(&I); 1158 1159 // Handle metadata. 1160 if (PCSectionsMD) { 1161 auto It = NodeMap.find(&I); 1162 if (It != NodeMap.end()) { 1163 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1164 } else if (NodeInserted) { 1165 // This should not happen; if it does, don't let it go unnoticed so we can 1166 // fix it. Relevant visit*() function is probably missing a setValue(). 1167 errs() << "warning: loosing !pcsections metadata [" 1168 << I.getModule()->getName() << "]\n"; 1169 LLVM_DEBUG(I.dump()); 1170 assert(false); 1171 } 1172 } 1173 1174 CurInst = nullptr; 1175 } 1176 1177 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1178 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1179 } 1180 1181 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1182 // Note: this doesn't use InstVisitor, because it has to work with 1183 // ConstantExpr's in addition to instructions. 1184 switch (Opcode) { 1185 default: llvm_unreachable("Unknown instruction type encountered!"); 1186 // Build the switch statement using the Instruction.def file. 1187 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1188 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1189 #include "llvm/IR/Instruction.def" 1190 } 1191 } 1192 1193 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1194 DebugLoc DL, unsigned Order) { 1195 // We treat variadic dbg_values differently at this stage. 1196 if (DI->hasArgList()) { 1197 // For variadic dbg_values we will now insert an undef. 1198 // FIXME: We can potentially recover these! 1199 SmallVector<SDDbgOperand, 2> Locs; 1200 for (const Value *V : DI->getValues()) { 1201 auto Undef = UndefValue::get(V->getType()); 1202 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1203 } 1204 SDDbgValue *SDV = DAG.getDbgValueList( 1205 DI->getVariable(), DI->getExpression(), Locs, {}, 1206 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1207 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1208 } else { 1209 // TODO: Dangling debug info will eventually either be resolved or produce 1210 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1211 // between the original dbg.value location and its resolved DBG_VALUE, 1212 // which we should ideally fill with an extra Undef DBG_VALUE. 1213 assert(DI->getNumVariableLocationOps() == 1 && 1214 "DbgValueInst without an ArgList should have a single location " 1215 "operand."); 1216 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1217 } 1218 } 1219 1220 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1221 const DIExpression *Expr) { 1222 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1223 const DbgValueInst *DI = DDI.getDI(); 1224 DIVariable *DanglingVariable = DI->getVariable(); 1225 DIExpression *DanglingExpr = DI->getExpression(); 1226 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1227 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1228 return true; 1229 } 1230 return false; 1231 }; 1232 1233 for (auto &DDIMI : DanglingDebugInfoMap) { 1234 DanglingDebugInfoVector &DDIV = DDIMI.second; 1235 1236 // If debug info is to be dropped, run it through final checks to see 1237 // whether it can be salvaged. 1238 for (auto &DDI : DDIV) 1239 if (isMatchingDbgValue(DDI)) 1240 salvageUnresolvedDbgValue(DDI); 1241 1242 erase_if(DDIV, isMatchingDbgValue); 1243 } 1244 } 1245 1246 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1247 // generate the debug data structures now that we've seen its definition. 1248 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1249 SDValue Val) { 1250 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1251 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1252 return; 1253 1254 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1255 for (auto &DDI : DDIV) { 1256 const DbgValueInst *DI = DDI.getDI(); 1257 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1258 assert(DI && "Ill-formed DanglingDebugInfo"); 1259 DebugLoc dl = DDI.getdl(); 1260 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1261 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1262 DILocalVariable *Variable = DI->getVariable(); 1263 DIExpression *Expr = DI->getExpression(); 1264 assert(Variable->isValidLocationForIntrinsic(dl) && 1265 "Expected inlined-at fields to agree"); 1266 SDDbgValue *SDV; 1267 if (Val.getNode()) { 1268 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1269 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1270 // we couldn't resolve it directly when examining the DbgValue intrinsic 1271 // in the first place we should not be more successful here). Unless we 1272 // have some test case that prove this to be correct we should avoid 1273 // calling EmitFuncArgumentDbgValue here. 1274 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, 1275 FuncArgumentDbgValueKind::Value, Val)) { 1276 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1277 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1278 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1279 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1280 // inserted after the definition of Val when emitting the instructions 1281 // after ISel. An alternative could be to teach 1282 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1283 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1284 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1285 << ValSDNodeOrder << "\n"); 1286 SDV = getDbgValue(Val, Variable, Expr, dl, 1287 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1288 DAG.AddDbgValue(SDV, false); 1289 } else 1290 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1291 << "in EmitFuncArgumentDbgValue\n"); 1292 } else { 1293 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1294 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1295 auto SDV = 1296 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1297 DAG.AddDbgValue(SDV, false); 1298 } 1299 } 1300 DDIV.clear(); 1301 } 1302 1303 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1304 // TODO: For the variadic implementation, instead of only checking the fail 1305 // state of `handleDebugValue`, we need know specifically which values were 1306 // invalid, so that we attempt to salvage only those values when processing 1307 // a DIArgList. 1308 assert(!DDI.getDI()->hasArgList() && 1309 "Not implemented for variadic dbg_values"); 1310 Value *V = DDI.getDI()->getValue(0); 1311 DILocalVariable *Var = DDI.getDI()->getVariable(); 1312 DIExpression *Expr = DDI.getDI()->getExpression(); 1313 DebugLoc DL = DDI.getdl(); 1314 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1315 unsigned SDOrder = DDI.getSDNodeOrder(); 1316 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1317 // that DW_OP_stack_value is desired. 1318 assert(isa<DbgValueInst>(DDI.getDI())); 1319 bool StackValue = true; 1320 1321 // Can this Value can be encoded without any further work? 1322 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1323 return; 1324 1325 // Attempt to salvage back through as many instructions as possible. Bail if 1326 // a non-instruction is seen, such as a constant expression or global 1327 // variable. FIXME: Further work could recover those too. 1328 while (isa<Instruction>(V)) { 1329 Instruction &VAsInst = *cast<Instruction>(V); 1330 // Temporary "0", awaiting real implementation. 1331 SmallVector<uint64_t, 16> Ops; 1332 SmallVector<Value *, 4> AdditionalValues; 1333 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1334 AdditionalValues); 1335 // If we cannot salvage any further, and haven't yet found a suitable debug 1336 // expression, bail out. 1337 if (!V) 1338 break; 1339 1340 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1341 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1342 // here for variadic dbg_values, remove that condition. 1343 if (!AdditionalValues.empty()) 1344 break; 1345 1346 // New value and expr now represent this debuginfo. 1347 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1348 1349 // Some kind of simplification occurred: check whether the operand of the 1350 // salvaged debug expression can be encoded in this DAG. 1351 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1352 /*IsVariadic=*/false)) { 1353 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1354 << *DDI.getDI() << "\nBy stripping back to:\n " << *V); 1355 return; 1356 } 1357 } 1358 1359 // This was the final opportunity to salvage this debug information, and it 1360 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1361 // any earlier variable location. 1362 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1363 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1364 DAG.AddDbgValue(SDV, false); 1365 1366 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << *DDI.getDI() 1367 << "\n"); 1368 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1369 << "\n"); 1370 } 1371 1372 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1373 DILocalVariable *Var, 1374 DIExpression *Expr, DebugLoc dl, 1375 DebugLoc InstDL, unsigned Order, 1376 bool IsVariadic) { 1377 if (Values.empty()) 1378 return true; 1379 SmallVector<SDDbgOperand> LocationOps; 1380 SmallVector<SDNode *> Dependencies; 1381 for (const Value *V : Values) { 1382 // Constant value. 1383 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1384 isa<ConstantPointerNull>(V)) { 1385 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1386 continue; 1387 } 1388 1389 // Look through IntToPtr constants. 1390 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1391 if (CE->getOpcode() == Instruction::IntToPtr) { 1392 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1393 continue; 1394 } 1395 1396 // If the Value is a frame index, we can create a FrameIndex debug value 1397 // without relying on the DAG at all. 1398 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1399 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1400 if (SI != FuncInfo.StaticAllocaMap.end()) { 1401 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1402 continue; 1403 } 1404 } 1405 1406 // Do not use getValue() in here; we don't want to generate code at 1407 // this point if it hasn't been done yet. 1408 SDValue N = NodeMap[V]; 1409 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1410 N = UnusedArgNodeMap[V]; 1411 if (N.getNode()) { 1412 // Only emit func arg dbg value for non-variadic dbg.values for now. 1413 if (!IsVariadic && 1414 EmitFuncArgumentDbgValue(V, Var, Expr, dl, 1415 FuncArgumentDbgValueKind::Value, N)) 1416 return true; 1417 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1418 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1419 // describe stack slot locations. 1420 // 1421 // Consider "int x = 0; int *px = &x;". There are two kinds of 1422 // interesting debug values here after optimization: 1423 // 1424 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1425 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1426 // 1427 // Both describe the direct values of their associated variables. 1428 Dependencies.push_back(N.getNode()); 1429 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1430 continue; 1431 } 1432 LocationOps.emplace_back( 1433 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1434 continue; 1435 } 1436 1437 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1438 // Special rules apply for the first dbg.values of parameter variables in a 1439 // function. Identify them by the fact they reference Argument Values, that 1440 // they're parameters, and they are parameters of the current function. We 1441 // need to let them dangle until they get an SDNode. 1442 bool IsParamOfFunc = 1443 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1444 if (IsParamOfFunc) 1445 return false; 1446 1447 // The value is not used in this block yet (or it would have an SDNode). 1448 // We still want the value to appear for the user if possible -- if it has 1449 // an associated VReg, we can refer to that instead. 1450 auto VMI = FuncInfo.ValueMap.find(V); 1451 if (VMI != FuncInfo.ValueMap.end()) { 1452 unsigned Reg = VMI->second; 1453 // If this is a PHI node, it may be split up into several MI PHI nodes 1454 // (in FunctionLoweringInfo::set). 1455 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1456 V->getType(), None); 1457 if (RFV.occupiesMultipleRegs()) { 1458 // FIXME: We could potentially support variadic dbg_values here. 1459 if (IsVariadic) 1460 return false; 1461 unsigned Offset = 0; 1462 unsigned BitsToDescribe = 0; 1463 if (auto VarSize = Var->getSizeInBits()) 1464 BitsToDescribe = *VarSize; 1465 if (auto Fragment = Expr->getFragmentInfo()) 1466 BitsToDescribe = Fragment->SizeInBits; 1467 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1468 // Bail out if all bits are described already. 1469 if (Offset >= BitsToDescribe) 1470 break; 1471 // TODO: handle scalable vectors. 1472 unsigned RegisterSize = RegAndSize.second; 1473 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1474 ? BitsToDescribe - Offset 1475 : RegisterSize; 1476 auto FragmentExpr = DIExpression::createFragmentExpression( 1477 Expr, Offset, FragmentSize); 1478 if (!FragmentExpr) 1479 continue; 1480 SDDbgValue *SDV = DAG.getVRegDbgValue( 1481 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1482 DAG.AddDbgValue(SDV, false); 1483 Offset += RegisterSize; 1484 } 1485 return true; 1486 } 1487 // We can use simple vreg locations for variadic dbg_values as well. 1488 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1489 continue; 1490 } 1491 // We failed to create a SDDbgOperand for V. 1492 return false; 1493 } 1494 1495 // We have created a SDDbgOperand for each Value in Values. 1496 // Should use Order instead of SDNodeOrder? 1497 assert(!LocationOps.empty()); 1498 SDDbgValue *SDV = 1499 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1500 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1501 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1502 return true; 1503 } 1504 1505 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1506 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1507 for (auto &Pair : DanglingDebugInfoMap) 1508 for (auto &DDI : Pair.second) 1509 salvageUnresolvedDbgValue(DDI); 1510 clearDanglingDebugInfo(); 1511 } 1512 1513 /// getCopyFromRegs - If there was virtual register allocated for the value V 1514 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1515 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1516 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1517 SDValue Result; 1518 1519 if (It != FuncInfo.ValueMap.end()) { 1520 Register InReg = It->second; 1521 1522 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1523 DAG.getDataLayout(), InReg, Ty, 1524 None); // This is not an ABI copy. 1525 SDValue Chain = DAG.getEntryNode(); 1526 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1527 V); 1528 resolveDanglingDebugInfo(V, Result); 1529 } 1530 1531 return Result; 1532 } 1533 1534 /// getValue - Return an SDValue for the given Value. 1535 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1536 // If we already have an SDValue for this value, use it. It's important 1537 // to do this first, so that we don't create a CopyFromReg if we already 1538 // have a regular SDValue. 1539 SDValue &N = NodeMap[V]; 1540 if (N.getNode()) return N; 1541 1542 // If there's a virtual register allocated and initialized for this 1543 // value, use it. 1544 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1545 return copyFromReg; 1546 1547 // Otherwise create a new SDValue and remember it. 1548 SDValue Val = getValueImpl(V); 1549 NodeMap[V] = Val; 1550 resolveDanglingDebugInfo(V, Val); 1551 return Val; 1552 } 1553 1554 /// getNonRegisterValue - Return an SDValue for the given Value, but 1555 /// don't look in FuncInfo.ValueMap for a virtual register. 1556 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1557 // If we already have an SDValue for this value, use it. 1558 SDValue &N = NodeMap[V]; 1559 if (N.getNode()) { 1560 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1561 // Remove the debug location from the node as the node is about to be used 1562 // in a location which may differ from the original debug location. This 1563 // is relevant to Constant and ConstantFP nodes because they can appear 1564 // as constant expressions inside PHI nodes. 1565 N->setDebugLoc(DebugLoc()); 1566 } 1567 return N; 1568 } 1569 1570 // Otherwise create a new SDValue and remember it. 1571 SDValue Val = getValueImpl(V); 1572 NodeMap[V] = Val; 1573 resolveDanglingDebugInfo(V, Val); 1574 return Val; 1575 } 1576 1577 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1578 /// Create an SDValue for the given value. 1579 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1580 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1581 1582 if (const Constant *C = dyn_cast<Constant>(V)) { 1583 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1584 1585 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1586 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1587 1588 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1589 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1590 1591 if (isa<ConstantPointerNull>(C)) { 1592 unsigned AS = V->getType()->getPointerAddressSpace(); 1593 return DAG.getConstant(0, getCurSDLoc(), 1594 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1595 } 1596 1597 if (match(C, m_VScale(DAG.getDataLayout()))) 1598 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1599 1600 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1601 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1602 1603 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1604 return DAG.getUNDEF(VT); 1605 1606 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1607 visit(CE->getOpcode(), *CE); 1608 SDValue N1 = NodeMap[V]; 1609 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1610 return N1; 1611 } 1612 1613 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1614 SmallVector<SDValue, 4> Constants; 1615 for (const Use &U : C->operands()) { 1616 SDNode *Val = getValue(U).getNode(); 1617 // If the operand is an empty aggregate, there are no values. 1618 if (!Val) continue; 1619 // Add each leaf value from the operand to the Constants list 1620 // to form a flattened list of all the values. 1621 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1622 Constants.push_back(SDValue(Val, i)); 1623 } 1624 1625 return DAG.getMergeValues(Constants, getCurSDLoc()); 1626 } 1627 1628 if (const ConstantDataSequential *CDS = 1629 dyn_cast<ConstantDataSequential>(C)) { 1630 SmallVector<SDValue, 4> Ops; 1631 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1632 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1633 // Add each leaf value from the operand to the Constants list 1634 // to form a flattened list of all the values. 1635 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1636 Ops.push_back(SDValue(Val, i)); 1637 } 1638 1639 if (isa<ArrayType>(CDS->getType())) 1640 return DAG.getMergeValues(Ops, getCurSDLoc()); 1641 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1642 } 1643 1644 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1645 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1646 "Unknown struct or array constant!"); 1647 1648 SmallVector<EVT, 4> ValueVTs; 1649 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1650 unsigned NumElts = ValueVTs.size(); 1651 if (NumElts == 0) 1652 return SDValue(); // empty struct 1653 SmallVector<SDValue, 4> Constants(NumElts); 1654 for (unsigned i = 0; i != NumElts; ++i) { 1655 EVT EltVT = ValueVTs[i]; 1656 if (isa<UndefValue>(C)) 1657 Constants[i] = DAG.getUNDEF(EltVT); 1658 else if (EltVT.isFloatingPoint()) 1659 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1660 else 1661 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1662 } 1663 1664 return DAG.getMergeValues(Constants, getCurSDLoc()); 1665 } 1666 1667 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1668 return DAG.getBlockAddress(BA, VT); 1669 1670 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1671 return getValue(Equiv->getGlobalValue()); 1672 1673 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1674 return getValue(NC->getGlobalValue()); 1675 1676 VectorType *VecTy = cast<VectorType>(V->getType()); 1677 1678 // Now that we know the number and type of the elements, get that number of 1679 // elements into the Ops array based on what kind of constant it is. 1680 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1681 SmallVector<SDValue, 16> Ops; 1682 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1683 for (unsigned i = 0; i != NumElements; ++i) 1684 Ops.push_back(getValue(CV->getOperand(i))); 1685 1686 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1687 } 1688 1689 if (isa<ConstantAggregateZero>(C)) { 1690 EVT EltVT = 1691 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1692 1693 SDValue Op; 1694 if (EltVT.isFloatingPoint()) 1695 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1696 else 1697 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1698 1699 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1700 } 1701 1702 llvm_unreachable("Unknown vector constant"); 1703 } 1704 1705 // If this is a static alloca, generate it as the frameindex instead of 1706 // computation. 1707 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1708 DenseMap<const AllocaInst*, int>::iterator SI = 1709 FuncInfo.StaticAllocaMap.find(AI); 1710 if (SI != FuncInfo.StaticAllocaMap.end()) 1711 return DAG.getFrameIndex(SI->second, 1712 TLI.getFrameIndexTy(DAG.getDataLayout())); 1713 } 1714 1715 // If this is an instruction which fast-isel has deferred, select it now. 1716 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1717 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1718 1719 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1720 Inst->getType(), None); 1721 SDValue Chain = DAG.getEntryNode(); 1722 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1723 } 1724 1725 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1726 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1727 1728 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1729 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1730 1731 llvm_unreachable("Can't get register for value!"); 1732 } 1733 1734 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1735 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1736 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1737 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1738 bool IsSEH = isAsynchronousEHPersonality(Pers); 1739 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1740 if (!IsSEH) 1741 CatchPadMBB->setIsEHScopeEntry(); 1742 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1743 if (IsMSVCCXX || IsCoreCLR) 1744 CatchPadMBB->setIsEHFuncletEntry(); 1745 } 1746 1747 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1748 // Update machine-CFG edge. 1749 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1750 FuncInfo.MBB->addSuccessor(TargetMBB); 1751 TargetMBB->setIsEHCatchretTarget(true); 1752 DAG.getMachineFunction().setHasEHCatchret(true); 1753 1754 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1755 bool IsSEH = isAsynchronousEHPersonality(Pers); 1756 if (IsSEH) { 1757 // If this is not a fall-through branch or optimizations are switched off, 1758 // emit the branch. 1759 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1760 TM.getOptLevel() == CodeGenOpt::None) 1761 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1762 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1763 return; 1764 } 1765 1766 // Figure out the funclet membership for the catchret's successor. 1767 // This will be used by the FuncletLayout pass to determine how to order the 1768 // BB's. 1769 // A 'catchret' returns to the outer scope's color. 1770 Value *ParentPad = I.getCatchSwitchParentPad(); 1771 const BasicBlock *SuccessorColor; 1772 if (isa<ConstantTokenNone>(ParentPad)) 1773 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1774 else 1775 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1776 assert(SuccessorColor && "No parent funclet for catchret!"); 1777 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1778 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1779 1780 // Create the terminator node. 1781 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1782 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1783 DAG.getBasicBlock(SuccessorColorMBB)); 1784 DAG.setRoot(Ret); 1785 } 1786 1787 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1788 // Don't emit any special code for the cleanuppad instruction. It just marks 1789 // the start of an EH scope/funclet. 1790 FuncInfo.MBB->setIsEHScopeEntry(); 1791 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1792 if (Pers != EHPersonality::Wasm_CXX) { 1793 FuncInfo.MBB->setIsEHFuncletEntry(); 1794 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1795 } 1796 } 1797 1798 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1799 // not match, it is OK to add only the first unwind destination catchpad to the 1800 // successors, because there will be at least one invoke instruction within the 1801 // catch scope that points to the next unwind destination, if one exists, so 1802 // CFGSort cannot mess up with BB sorting order. 1803 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1804 // call within them, and catchpads only consisting of 'catch (...)' have a 1805 // '__cxa_end_catch' call within them, both of which generate invokes in case 1806 // the next unwind destination exists, i.e., the next unwind destination is not 1807 // the caller.) 1808 // 1809 // Having at most one EH pad successor is also simpler and helps later 1810 // transformations. 1811 // 1812 // For example, 1813 // current: 1814 // invoke void @foo to ... unwind label %catch.dispatch 1815 // catch.dispatch: 1816 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1817 // catch.start: 1818 // ... 1819 // ... in this BB or some other child BB dominated by this BB there will be an 1820 // invoke that points to 'next' BB as an unwind destination 1821 // 1822 // next: ; We don't need to add this to 'current' BB's successor 1823 // ... 1824 static void findWasmUnwindDestinations( 1825 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1826 BranchProbability Prob, 1827 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1828 &UnwindDests) { 1829 while (EHPadBB) { 1830 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1831 if (isa<CleanupPadInst>(Pad)) { 1832 // Stop on cleanup pads. 1833 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1834 UnwindDests.back().first->setIsEHScopeEntry(); 1835 break; 1836 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1837 // Add the catchpad handlers to the possible destinations. We don't 1838 // continue to the unwind destination of the catchswitch for wasm. 1839 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1840 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1841 UnwindDests.back().first->setIsEHScopeEntry(); 1842 } 1843 break; 1844 } else { 1845 continue; 1846 } 1847 } 1848 } 1849 1850 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1851 /// many places it could ultimately go. In the IR, we have a single unwind 1852 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1853 /// This function skips over imaginary basic blocks that hold catchswitch 1854 /// instructions, and finds all the "real" machine 1855 /// basic block destinations. As those destinations may not be successors of 1856 /// EHPadBB, here we also calculate the edge probability to those destinations. 1857 /// The passed-in Prob is the edge probability to EHPadBB. 1858 static void findUnwindDestinations( 1859 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1860 BranchProbability Prob, 1861 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1862 &UnwindDests) { 1863 EHPersonality Personality = 1864 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1865 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1866 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1867 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1868 bool IsSEH = isAsynchronousEHPersonality(Personality); 1869 1870 if (IsWasmCXX) { 1871 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1872 assert(UnwindDests.size() <= 1 && 1873 "There should be at most one unwind destination for wasm"); 1874 return; 1875 } 1876 1877 while (EHPadBB) { 1878 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1879 BasicBlock *NewEHPadBB = nullptr; 1880 if (isa<LandingPadInst>(Pad)) { 1881 // Stop on landingpads. They are not funclets. 1882 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1883 break; 1884 } else if (isa<CleanupPadInst>(Pad)) { 1885 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1886 // personalities. 1887 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1888 UnwindDests.back().first->setIsEHScopeEntry(); 1889 UnwindDests.back().first->setIsEHFuncletEntry(); 1890 break; 1891 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1892 // Add the catchpad handlers to the possible destinations. 1893 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1894 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1895 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1896 if (IsMSVCCXX || IsCoreCLR) 1897 UnwindDests.back().first->setIsEHFuncletEntry(); 1898 if (!IsSEH) 1899 UnwindDests.back().first->setIsEHScopeEntry(); 1900 } 1901 NewEHPadBB = CatchSwitch->getUnwindDest(); 1902 } else { 1903 continue; 1904 } 1905 1906 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1907 if (BPI && NewEHPadBB) 1908 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1909 EHPadBB = NewEHPadBB; 1910 } 1911 } 1912 1913 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1914 // Update successor info. 1915 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1916 auto UnwindDest = I.getUnwindDest(); 1917 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1918 BranchProbability UnwindDestProb = 1919 (BPI && UnwindDest) 1920 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1921 : BranchProbability::getZero(); 1922 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1923 for (auto &UnwindDest : UnwindDests) { 1924 UnwindDest.first->setIsEHPad(); 1925 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1926 } 1927 FuncInfo.MBB->normalizeSuccProbs(); 1928 1929 // Create the terminator node. 1930 SDValue Ret = 1931 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1932 DAG.setRoot(Ret); 1933 } 1934 1935 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1936 report_fatal_error("visitCatchSwitch not yet implemented!"); 1937 } 1938 1939 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1940 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1941 auto &DL = DAG.getDataLayout(); 1942 SDValue Chain = getControlRoot(); 1943 SmallVector<ISD::OutputArg, 8> Outs; 1944 SmallVector<SDValue, 8> OutVals; 1945 1946 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1947 // lower 1948 // 1949 // %val = call <ty> @llvm.experimental.deoptimize() 1950 // ret <ty> %val 1951 // 1952 // differently. 1953 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1954 LowerDeoptimizingReturn(); 1955 return; 1956 } 1957 1958 if (!FuncInfo.CanLowerReturn) { 1959 unsigned DemoteReg = FuncInfo.DemoteRegister; 1960 const Function *F = I.getParent()->getParent(); 1961 1962 // Emit a store of the return value through the virtual register. 1963 // Leave Outs empty so that LowerReturn won't try to load return 1964 // registers the usual way. 1965 SmallVector<EVT, 1> PtrValueVTs; 1966 ComputeValueVTs(TLI, DL, 1967 F->getReturnType()->getPointerTo( 1968 DAG.getDataLayout().getAllocaAddrSpace()), 1969 PtrValueVTs); 1970 1971 SDValue RetPtr = 1972 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 1973 SDValue RetOp = getValue(I.getOperand(0)); 1974 1975 SmallVector<EVT, 4> ValueVTs, MemVTs; 1976 SmallVector<uint64_t, 4> Offsets; 1977 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1978 &Offsets); 1979 unsigned NumValues = ValueVTs.size(); 1980 1981 SmallVector<SDValue, 4> Chains(NumValues); 1982 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1983 for (unsigned i = 0; i != NumValues; ++i) { 1984 // An aggregate return value cannot wrap around the address space, so 1985 // offsets to its parts don't wrap either. 1986 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1987 TypeSize::Fixed(Offsets[i])); 1988 1989 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1990 if (MemVTs[i] != ValueVTs[i]) 1991 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1992 Chains[i] = DAG.getStore( 1993 Chain, getCurSDLoc(), Val, 1994 // FIXME: better loc info would be nice. 1995 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1996 commonAlignment(BaseAlign, Offsets[i])); 1997 } 1998 1999 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2000 MVT::Other, Chains); 2001 } else if (I.getNumOperands() != 0) { 2002 SmallVector<EVT, 4> ValueVTs; 2003 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2004 unsigned NumValues = ValueVTs.size(); 2005 if (NumValues) { 2006 SDValue RetOp = getValue(I.getOperand(0)); 2007 2008 const Function *F = I.getParent()->getParent(); 2009 2010 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2011 I.getOperand(0)->getType(), F->getCallingConv(), 2012 /*IsVarArg*/ false, DL); 2013 2014 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2015 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2016 ExtendKind = ISD::SIGN_EXTEND; 2017 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2018 ExtendKind = ISD::ZERO_EXTEND; 2019 2020 LLVMContext &Context = F->getContext(); 2021 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2022 2023 for (unsigned j = 0; j != NumValues; ++j) { 2024 EVT VT = ValueVTs[j]; 2025 2026 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2027 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2028 2029 CallingConv::ID CC = F->getCallingConv(); 2030 2031 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2032 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2033 SmallVector<SDValue, 4> Parts(NumParts); 2034 getCopyToParts(DAG, getCurSDLoc(), 2035 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2036 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2037 2038 // 'inreg' on function refers to return value 2039 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2040 if (RetInReg) 2041 Flags.setInReg(); 2042 2043 if (I.getOperand(0)->getType()->isPointerTy()) { 2044 Flags.setPointer(); 2045 Flags.setPointerAddrSpace( 2046 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2047 } 2048 2049 if (NeedsRegBlock) { 2050 Flags.setInConsecutiveRegs(); 2051 if (j == NumValues - 1) 2052 Flags.setInConsecutiveRegsLast(); 2053 } 2054 2055 // Propagate extension type if any 2056 if (ExtendKind == ISD::SIGN_EXTEND) 2057 Flags.setSExt(); 2058 else if (ExtendKind == ISD::ZERO_EXTEND) 2059 Flags.setZExt(); 2060 2061 for (unsigned i = 0; i < NumParts; ++i) { 2062 Outs.push_back(ISD::OutputArg(Flags, 2063 Parts[i].getValueType().getSimpleVT(), 2064 VT, /*isfixed=*/true, 0, 0)); 2065 OutVals.push_back(Parts[i]); 2066 } 2067 } 2068 } 2069 } 2070 2071 // Push in swifterror virtual register as the last element of Outs. This makes 2072 // sure swifterror virtual register will be returned in the swifterror 2073 // physical register. 2074 const Function *F = I.getParent()->getParent(); 2075 if (TLI.supportSwiftError() && 2076 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2077 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2078 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2079 Flags.setSwiftError(); 2080 Outs.push_back(ISD::OutputArg( 2081 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2082 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2083 // Create SDNode for the swifterror virtual register. 2084 OutVals.push_back( 2085 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2086 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2087 EVT(TLI.getPointerTy(DL)))); 2088 } 2089 2090 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2091 CallingConv::ID CallConv = 2092 DAG.getMachineFunction().getFunction().getCallingConv(); 2093 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2094 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2095 2096 // Verify that the target's LowerReturn behaved as expected. 2097 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2098 "LowerReturn didn't return a valid chain!"); 2099 2100 // Update the DAG with the new chain value resulting from return lowering. 2101 DAG.setRoot(Chain); 2102 } 2103 2104 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2105 /// created for it, emit nodes to copy the value into the virtual 2106 /// registers. 2107 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2108 // Skip empty types 2109 if (V->getType()->isEmptyTy()) 2110 return; 2111 2112 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2113 if (VMI != FuncInfo.ValueMap.end()) { 2114 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2115 CopyValueToVirtualRegister(V, VMI->second); 2116 } 2117 } 2118 2119 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2120 /// the current basic block, add it to ValueMap now so that we'll get a 2121 /// CopyTo/FromReg. 2122 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2123 // No need to export constants. 2124 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2125 2126 // Already exported? 2127 if (FuncInfo.isExportedInst(V)) return; 2128 2129 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2130 CopyValueToVirtualRegister(V, Reg); 2131 } 2132 2133 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2134 const BasicBlock *FromBB) { 2135 // The operands of the setcc have to be in this block. We don't know 2136 // how to export them from some other block. 2137 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2138 // Can export from current BB. 2139 if (VI->getParent() == FromBB) 2140 return true; 2141 2142 // Is already exported, noop. 2143 return FuncInfo.isExportedInst(V); 2144 } 2145 2146 // If this is an argument, we can export it if the BB is the entry block or 2147 // if it is already exported. 2148 if (isa<Argument>(V)) { 2149 if (FromBB->isEntryBlock()) 2150 return true; 2151 2152 // Otherwise, can only export this if it is already exported. 2153 return FuncInfo.isExportedInst(V); 2154 } 2155 2156 // Otherwise, constants can always be exported. 2157 return true; 2158 } 2159 2160 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2161 BranchProbability 2162 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2163 const MachineBasicBlock *Dst) const { 2164 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2165 const BasicBlock *SrcBB = Src->getBasicBlock(); 2166 const BasicBlock *DstBB = Dst->getBasicBlock(); 2167 if (!BPI) { 2168 // If BPI is not available, set the default probability as 1 / N, where N is 2169 // the number of successors. 2170 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2171 return BranchProbability(1, SuccSize); 2172 } 2173 return BPI->getEdgeProbability(SrcBB, DstBB); 2174 } 2175 2176 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2177 MachineBasicBlock *Dst, 2178 BranchProbability Prob) { 2179 if (!FuncInfo.BPI) 2180 Src->addSuccessorWithoutProb(Dst); 2181 else { 2182 if (Prob.isUnknown()) 2183 Prob = getEdgeProbability(Src, Dst); 2184 Src->addSuccessor(Dst, Prob); 2185 } 2186 } 2187 2188 static bool InBlock(const Value *V, const BasicBlock *BB) { 2189 if (const Instruction *I = dyn_cast<Instruction>(V)) 2190 return I->getParent() == BB; 2191 return true; 2192 } 2193 2194 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2195 /// This function emits a branch and is used at the leaves of an OR or an 2196 /// AND operator tree. 2197 void 2198 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2199 MachineBasicBlock *TBB, 2200 MachineBasicBlock *FBB, 2201 MachineBasicBlock *CurBB, 2202 MachineBasicBlock *SwitchBB, 2203 BranchProbability TProb, 2204 BranchProbability FProb, 2205 bool InvertCond) { 2206 const BasicBlock *BB = CurBB->getBasicBlock(); 2207 2208 // If the leaf of the tree is a comparison, merge the condition into 2209 // the caseblock. 2210 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2211 // The operands of the cmp have to be in this block. We don't know 2212 // how to export them from some other block. If this is the first block 2213 // of the sequence, no exporting is needed. 2214 if (CurBB == SwitchBB || 2215 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2216 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2217 ISD::CondCode Condition; 2218 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2219 ICmpInst::Predicate Pred = 2220 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2221 Condition = getICmpCondCode(Pred); 2222 } else { 2223 const FCmpInst *FC = cast<FCmpInst>(Cond); 2224 FCmpInst::Predicate Pred = 2225 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2226 Condition = getFCmpCondCode(Pred); 2227 if (TM.Options.NoNaNsFPMath) 2228 Condition = getFCmpCodeWithoutNaN(Condition); 2229 } 2230 2231 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2232 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2233 SL->SwitchCases.push_back(CB); 2234 return; 2235 } 2236 } 2237 2238 // Create a CaseBlock record representing this branch. 2239 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2240 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2241 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2242 SL->SwitchCases.push_back(CB); 2243 } 2244 2245 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2246 MachineBasicBlock *TBB, 2247 MachineBasicBlock *FBB, 2248 MachineBasicBlock *CurBB, 2249 MachineBasicBlock *SwitchBB, 2250 Instruction::BinaryOps Opc, 2251 BranchProbability TProb, 2252 BranchProbability FProb, 2253 bool InvertCond) { 2254 // Skip over not part of the tree and remember to invert op and operands at 2255 // next level. 2256 Value *NotCond; 2257 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2258 InBlock(NotCond, CurBB->getBasicBlock())) { 2259 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2260 !InvertCond); 2261 return; 2262 } 2263 2264 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2265 const Value *BOpOp0, *BOpOp1; 2266 // Compute the effective opcode for Cond, taking into account whether it needs 2267 // to be inverted, e.g. 2268 // and (not (or A, B)), C 2269 // gets lowered as 2270 // and (and (not A, not B), C) 2271 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2272 if (BOp) { 2273 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2274 ? Instruction::And 2275 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2276 ? Instruction::Or 2277 : (Instruction::BinaryOps)0); 2278 if (InvertCond) { 2279 if (BOpc == Instruction::And) 2280 BOpc = Instruction::Or; 2281 else if (BOpc == Instruction::Or) 2282 BOpc = Instruction::And; 2283 } 2284 } 2285 2286 // If this node is not part of the or/and tree, emit it as a branch. 2287 // Note that all nodes in the tree should have same opcode. 2288 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2289 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2290 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2291 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2292 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2293 TProb, FProb, InvertCond); 2294 return; 2295 } 2296 2297 // Create TmpBB after CurBB. 2298 MachineFunction::iterator BBI(CurBB); 2299 MachineFunction &MF = DAG.getMachineFunction(); 2300 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2301 CurBB->getParent()->insert(++BBI, TmpBB); 2302 2303 if (Opc == Instruction::Or) { 2304 // Codegen X | Y as: 2305 // BB1: 2306 // jmp_if_X TBB 2307 // jmp TmpBB 2308 // TmpBB: 2309 // jmp_if_Y TBB 2310 // jmp FBB 2311 // 2312 2313 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2314 // The requirement is that 2315 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2316 // = TrueProb for original BB. 2317 // Assuming the original probabilities are A and B, one choice is to set 2318 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2319 // A/(1+B) and 2B/(1+B). This choice assumes that 2320 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2321 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2322 // TmpBB, but the math is more complicated. 2323 2324 auto NewTrueProb = TProb / 2; 2325 auto NewFalseProb = TProb / 2 + FProb; 2326 // Emit the LHS condition. 2327 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2328 NewFalseProb, InvertCond); 2329 2330 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2331 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2332 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2333 // Emit the RHS condition into TmpBB. 2334 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2335 Probs[1], InvertCond); 2336 } else { 2337 assert(Opc == Instruction::And && "Unknown merge op!"); 2338 // Codegen X & Y as: 2339 // BB1: 2340 // jmp_if_X TmpBB 2341 // jmp FBB 2342 // TmpBB: 2343 // jmp_if_Y TBB 2344 // jmp FBB 2345 // 2346 // This requires creation of TmpBB after CurBB. 2347 2348 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2349 // The requirement is that 2350 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2351 // = FalseProb for original BB. 2352 // Assuming the original probabilities are A and B, one choice is to set 2353 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2354 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2355 // TrueProb for BB1 * FalseProb for TmpBB. 2356 2357 auto NewTrueProb = TProb + FProb / 2; 2358 auto NewFalseProb = FProb / 2; 2359 // Emit the LHS condition. 2360 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2361 NewFalseProb, InvertCond); 2362 2363 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2364 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2365 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2366 // Emit the RHS condition into TmpBB. 2367 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2368 Probs[1], InvertCond); 2369 } 2370 } 2371 2372 /// If the set of cases should be emitted as a series of branches, return true. 2373 /// If we should emit this as a bunch of and/or'd together conditions, return 2374 /// false. 2375 bool 2376 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2377 if (Cases.size() != 2) return true; 2378 2379 // If this is two comparisons of the same values or'd or and'd together, they 2380 // will get folded into a single comparison, so don't emit two blocks. 2381 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2382 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2383 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2384 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2385 return false; 2386 } 2387 2388 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2389 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2390 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2391 Cases[0].CC == Cases[1].CC && 2392 isa<Constant>(Cases[0].CmpRHS) && 2393 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2394 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2395 return false; 2396 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2397 return false; 2398 } 2399 2400 return true; 2401 } 2402 2403 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2404 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2405 2406 // Update machine-CFG edges. 2407 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2408 2409 if (I.isUnconditional()) { 2410 // Update machine-CFG edges. 2411 BrMBB->addSuccessor(Succ0MBB); 2412 2413 // If this is not a fall-through branch or optimizations are switched off, 2414 // emit the branch. 2415 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2416 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2417 MVT::Other, getControlRoot(), 2418 DAG.getBasicBlock(Succ0MBB))); 2419 2420 return; 2421 } 2422 2423 // If this condition is one of the special cases we handle, do special stuff 2424 // now. 2425 const Value *CondVal = I.getCondition(); 2426 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2427 2428 // If this is a series of conditions that are or'd or and'd together, emit 2429 // this as a sequence of branches instead of setcc's with and/or operations. 2430 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2431 // unpredictable branches, and vector extracts because those jumps are likely 2432 // expensive for any target), this should improve performance. 2433 // For example, instead of something like: 2434 // cmp A, B 2435 // C = seteq 2436 // cmp D, E 2437 // F = setle 2438 // or C, F 2439 // jnz foo 2440 // Emit: 2441 // cmp A, B 2442 // je foo 2443 // cmp D, E 2444 // jle foo 2445 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2446 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2447 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2448 Value *Vec; 2449 const Value *BOp0, *BOp1; 2450 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2451 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2452 Opcode = Instruction::And; 2453 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2454 Opcode = Instruction::Or; 2455 2456 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2457 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2458 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2459 getEdgeProbability(BrMBB, Succ0MBB), 2460 getEdgeProbability(BrMBB, Succ1MBB), 2461 /*InvertCond=*/false); 2462 // If the compares in later blocks need to use values not currently 2463 // exported from this block, export them now. This block should always 2464 // be the first entry. 2465 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2466 2467 // Allow some cases to be rejected. 2468 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2469 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2470 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2471 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2472 } 2473 2474 // Emit the branch for this block. 2475 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2476 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2477 return; 2478 } 2479 2480 // Okay, we decided not to do this, remove any inserted MBB's and clear 2481 // SwitchCases. 2482 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2483 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2484 2485 SL->SwitchCases.clear(); 2486 } 2487 } 2488 2489 // Create a CaseBlock record representing this branch. 2490 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2491 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2492 2493 // Use visitSwitchCase to actually insert the fast branch sequence for this 2494 // cond branch. 2495 visitSwitchCase(CB, BrMBB); 2496 } 2497 2498 /// visitSwitchCase - Emits the necessary code to represent a single node in 2499 /// the binary search tree resulting from lowering a switch instruction. 2500 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2501 MachineBasicBlock *SwitchBB) { 2502 SDValue Cond; 2503 SDValue CondLHS = getValue(CB.CmpLHS); 2504 SDLoc dl = CB.DL; 2505 2506 if (CB.CC == ISD::SETTRUE) { 2507 // Branch or fall through to TrueBB. 2508 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2509 SwitchBB->normalizeSuccProbs(); 2510 if (CB.TrueBB != NextBlock(SwitchBB)) { 2511 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2512 DAG.getBasicBlock(CB.TrueBB))); 2513 } 2514 return; 2515 } 2516 2517 auto &TLI = DAG.getTargetLoweringInfo(); 2518 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2519 2520 // Build the setcc now. 2521 if (!CB.CmpMHS) { 2522 // Fold "(X == true)" to X and "(X == false)" to !X to 2523 // handle common cases produced by branch lowering. 2524 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2525 CB.CC == ISD::SETEQ) 2526 Cond = CondLHS; 2527 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2528 CB.CC == ISD::SETEQ) { 2529 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2530 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2531 } else { 2532 SDValue CondRHS = getValue(CB.CmpRHS); 2533 2534 // If a pointer's DAG type is larger than its memory type then the DAG 2535 // values are zero-extended. This breaks signed comparisons so truncate 2536 // back to the underlying type before doing the compare. 2537 if (CondLHS.getValueType() != MemVT) { 2538 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2539 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2540 } 2541 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2542 } 2543 } else { 2544 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2545 2546 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2547 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2548 2549 SDValue CmpOp = getValue(CB.CmpMHS); 2550 EVT VT = CmpOp.getValueType(); 2551 2552 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2553 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2554 ISD::SETLE); 2555 } else { 2556 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2557 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2558 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2559 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2560 } 2561 } 2562 2563 // Update successor info 2564 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2565 // TrueBB and FalseBB are always different unless the incoming IR is 2566 // degenerate. This only happens when running llc on weird IR. 2567 if (CB.TrueBB != CB.FalseBB) 2568 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2569 SwitchBB->normalizeSuccProbs(); 2570 2571 // If the lhs block is the next block, invert the condition so that we can 2572 // fall through to the lhs instead of the rhs block. 2573 if (CB.TrueBB == NextBlock(SwitchBB)) { 2574 std::swap(CB.TrueBB, CB.FalseBB); 2575 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2576 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2577 } 2578 2579 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2580 MVT::Other, getControlRoot(), Cond, 2581 DAG.getBasicBlock(CB.TrueBB)); 2582 2583 setValue(CurInst, BrCond); 2584 2585 // Insert the false branch. Do this even if it's a fall through branch, 2586 // this makes it easier to do DAG optimizations which require inverting 2587 // the branch condition. 2588 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2589 DAG.getBasicBlock(CB.FalseBB)); 2590 2591 DAG.setRoot(BrCond); 2592 } 2593 2594 /// visitJumpTable - Emit JumpTable node in the current MBB 2595 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2596 // Emit the code for the jump table 2597 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2598 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2599 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2600 JT.Reg, PTy); 2601 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2602 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2603 MVT::Other, Index.getValue(1), 2604 Table, Index); 2605 DAG.setRoot(BrJumpTable); 2606 } 2607 2608 /// visitJumpTableHeader - This function emits necessary code to produce index 2609 /// in the JumpTable from switch case. 2610 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2611 JumpTableHeader &JTH, 2612 MachineBasicBlock *SwitchBB) { 2613 SDLoc dl = getCurSDLoc(); 2614 2615 // Subtract the lowest switch case value from the value being switched on. 2616 SDValue SwitchOp = getValue(JTH.SValue); 2617 EVT VT = SwitchOp.getValueType(); 2618 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2619 DAG.getConstant(JTH.First, dl, VT)); 2620 2621 // The SDNode we just created, which holds the value being switched on minus 2622 // the smallest case value, needs to be copied to a virtual register so it 2623 // can be used as an index into the jump table in a subsequent basic block. 2624 // This value may be smaller or larger than the target's pointer type, and 2625 // therefore require extension or truncating. 2626 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2627 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2628 2629 unsigned JumpTableReg = 2630 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2631 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2632 JumpTableReg, SwitchOp); 2633 JT.Reg = JumpTableReg; 2634 2635 if (!JTH.FallthroughUnreachable) { 2636 // Emit the range check for the jump table, and branch to the default block 2637 // for the switch statement if the value being switched on exceeds the 2638 // largest case in the switch. 2639 SDValue CMP = DAG.getSetCC( 2640 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2641 Sub.getValueType()), 2642 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2643 2644 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2645 MVT::Other, CopyTo, CMP, 2646 DAG.getBasicBlock(JT.Default)); 2647 2648 // Avoid emitting unnecessary branches to the next block. 2649 if (JT.MBB != NextBlock(SwitchBB)) 2650 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2651 DAG.getBasicBlock(JT.MBB)); 2652 2653 DAG.setRoot(BrCond); 2654 } else { 2655 // Avoid emitting unnecessary branches to the next block. 2656 if (JT.MBB != NextBlock(SwitchBB)) 2657 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2658 DAG.getBasicBlock(JT.MBB))); 2659 else 2660 DAG.setRoot(CopyTo); 2661 } 2662 } 2663 2664 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2665 /// variable if there exists one. 2666 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2667 SDValue &Chain) { 2668 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2669 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2670 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2671 MachineFunction &MF = DAG.getMachineFunction(); 2672 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2673 MachineSDNode *Node = 2674 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2675 if (Global) { 2676 MachinePointerInfo MPInfo(Global); 2677 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2678 MachineMemOperand::MODereferenceable; 2679 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2680 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2681 DAG.setNodeMemRefs(Node, {MemRef}); 2682 } 2683 if (PtrTy != PtrMemTy) 2684 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2685 return SDValue(Node, 0); 2686 } 2687 2688 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2689 /// tail spliced into a stack protector check success bb. 2690 /// 2691 /// For a high level explanation of how this fits into the stack protector 2692 /// generation see the comment on the declaration of class 2693 /// StackProtectorDescriptor. 2694 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2695 MachineBasicBlock *ParentBB) { 2696 2697 // First create the loads to the guard/stack slot for the comparison. 2698 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2699 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2700 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2701 2702 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2703 int FI = MFI.getStackProtectorIndex(); 2704 2705 SDValue Guard; 2706 SDLoc dl = getCurSDLoc(); 2707 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2708 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2709 Align Align = 2710 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2711 2712 // Generate code to load the content of the guard slot. 2713 SDValue GuardVal = DAG.getLoad( 2714 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2715 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2716 MachineMemOperand::MOVolatile); 2717 2718 if (TLI.useStackGuardXorFP()) 2719 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2720 2721 // Retrieve guard check function, nullptr if instrumentation is inlined. 2722 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2723 // The target provides a guard check function to validate the guard value. 2724 // Generate a call to that function with the content of the guard slot as 2725 // argument. 2726 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2727 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2728 2729 TargetLowering::ArgListTy Args; 2730 TargetLowering::ArgListEntry Entry; 2731 Entry.Node = GuardVal; 2732 Entry.Ty = FnTy->getParamType(0); 2733 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2734 Entry.IsInReg = true; 2735 Args.push_back(Entry); 2736 2737 TargetLowering::CallLoweringInfo CLI(DAG); 2738 CLI.setDebugLoc(getCurSDLoc()) 2739 .setChain(DAG.getEntryNode()) 2740 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2741 getValue(GuardCheckFn), std::move(Args)); 2742 2743 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2744 DAG.setRoot(Result.second); 2745 return; 2746 } 2747 2748 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2749 // Otherwise, emit a volatile load to retrieve the stack guard value. 2750 SDValue Chain = DAG.getEntryNode(); 2751 if (TLI.useLoadStackGuardNode()) { 2752 Guard = getLoadStackGuard(DAG, dl, Chain); 2753 } else { 2754 const Value *IRGuard = TLI.getSDagStackGuard(M); 2755 SDValue GuardPtr = getValue(IRGuard); 2756 2757 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2758 MachinePointerInfo(IRGuard, 0), Align, 2759 MachineMemOperand::MOVolatile); 2760 } 2761 2762 // Perform the comparison via a getsetcc. 2763 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2764 *DAG.getContext(), 2765 Guard.getValueType()), 2766 Guard, GuardVal, ISD::SETNE); 2767 2768 // If the guard/stackslot do not equal, branch to failure MBB. 2769 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2770 MVT::Other, GuardVal.getOperand(0), 2771 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2772 // Otherwise branch to success MBB. 2773 SDValue Br = DAG.getNode(ISD::BR, dl, 2774 MVT::Other, BrCond, 2775 DAG.getBasicBlock(SPD.getSuccessMBB())); 2776 2777 DAG.setRoot(Br); 2778 } 2779 2780 /// Codegen the failure basic block for a stack protector check. 2781 /// 2782 /// A failure stack protector machine basic block consists simply of a call to 2783 /// __stack_chk_fail(). 2784 /// 2785 /// For a high level explanation of how this fits into the stack protector 2786 /// generation see the comment on the declaration of class 2787 /// StackProtectorDescriptor. 2788 void 2789 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2790 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2791 TargetLowering::MakeLibCallOptions CallOptions; 2792 CallOptions.setDiscardResult(true); 2793 SDValue Chain = 2794 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2795 None, CallOptions, getCurSDLoc()).second; 2796 // On PS4/PS5, the "return address" must still be within the calling 2797 // function, even if it's at the very end, so emit an explicit TRAP here. 2798 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2799 if (TM.getTargetTriple().isPS()) 2800 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2801 // WebAssembly needs an unreachable instruction after a non-returning call, 2802 // because the function return type can be different from __stack_chk_fail's 2803 // return type (void). 2804 if (TM.getTargetTriple().isWasm()) 2805 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2806 2807 DAG.setRoot(Chain); 2808 } 2809 2810 /// visitBitTestHeader - This function emits necessary code to produce value 2811 /// suitable for "bit tests" 2812 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2813 MachineBasicBlock *SwitchBB) { 2814 SDLoc dl = getCurSDLoc(); 2815 2816 // Subtract the minimum value. 2817 SDValue SwitchOp = getValue(B.SValue); 2818 EVT VT = SwitchOp.getValueType(); 2819 SDValue RangeSub = 2820 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2821 2822 // Determine the type of the test operands. 2823 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2824 bool UsePtrType = false; 2825 if (!TLI.isTypeLegal(VT)) { 2826 UsePtrType = true; 2827 } else { 2828 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2829 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2830 // Switch table case range are encoded into series of masks. 2831 // Just use pointer type, it's guaranteed to fit. 2832 UsePtrType = true; 2833 break; 2834 } 2835 } 2836 SDValue Sub = RangeSub; 2837 if (UsePtrType) { 2838 VT = TLI.getPointerTy(DAG.getDataLayout()); 2839 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2840 } 2841 2842 B.RegVT = VT.getSimpleVT(); 2843 B.Reg = FuncInfo.CreateReg(B.RegVT); 2844 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2845 2846 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2847 2848 if (!B.FallthroughUnreachable) 2849 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2850 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2851 SwitchBB->normalizeSuccProbs(); 2852 2853 SDValue Root = CopyTo; 2854 if (!B.FallthroughUnreachable) { 2855 // Conditional branch to the default block. 2856 SDValue RangeCmp = DAG.getSetCC(dl, 2857 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2858 RangeSub.getValueType()), 2859 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2860 ISD::SETUGT); 2861 2862 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2863 DAG.getBasicBlock(B.Default)); 2864 } 2865 2866 // Avoid emitting unnecessary branches to the next block. 2867 if (MBB != NextBlock(SwitchBB)) 2868 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2869 2870 DAG.setRoot(Root); 2871 } 2872 2873 /// visitBitTestCase - this function produces one "bit test" 2874 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2875 MachineBasicBlock* NextMBB, 2876 BranchProbability BranchProbToNext, 2877 unsigned Reg, 2878 BitTestCase &B, 2879 MachineBasicBlock *SwitchBB) { 2880 SDLoc dl = getCurSDLoc(); 2881 MVT VT = BB.RegVT; 2882 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2883 SDValue Cmp; 2884 unsigned PopCount = countPopulation(B.Mask); 2885 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2886 if (PopCount == 1) { 2887 // Testing for a single bit; just compare the shift count with what it 2888 // would need to be to shift a 1 bit in that position. 2889 Cmp = DAG.getSetCC( 2890 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2891 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2892 ISD::SETEQ); 2893 } else if (PopCount == BB.Range) { 2894 // There is only one zero bit in the range, test for it directly. 2895 Cmp = DAG.getSetCC( 2896 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2897 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2898 ISD::SETNE); 2899 } else { 2900 // Make desired shift 2901 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2902 DAG.getConstant(1, dl, VT), ShiftOp); 2903 2904 // Emit bit tests and jumps 2905 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2906 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2907 Cmp = DAG.getSetCC( 2908 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2909 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2910 } 2911 2912 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2913 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2914 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2915 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2916 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2917 // one as they are relative probabilities (and thus work more like weights), 2918 // and hence we need to normalize them to let the sum of them become one. 2919 SwitchBB->normalizeSuccProbs(); 2920 2921 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2922 MVT::Other, getControlRoot(), 2923 Cmp, DAG.getBasicBlock(B.TargetBB)); 2924 2925 // Avoid emitting unnecessary branches to the next block. 2926 if (NextMBB != NextBlock(SwitchBB)) 2927 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2928 DAG.getBasicBlock(NextMBB)); 2929 2930 DAG.setRoot(BrAnd); 2931 } 2932 2933 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2934 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2935 2936 // Retrieve successors. Look through artificial IR level blocks like 2937 // catchswitch for successors. 2938 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2939 const BasicBlock *EHPadBB = I.getSuccessor(1); 2940 2941 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2942 // have to do anything here to lower funclet bundles. 2943 assert(!I.hasOperandBundlesOtherThan( 2944 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2945 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2946 LLVMContext::OB_cfguardtarget, 2947 LLVMContext::OB_clang_arc_attachedcall}) && 2948 "Cannot lower invokes with arbitrary operand bundles yet!"); 2949 2950 const Value *Callee(I.getCalledOperand()); 2951 const Function *Fn = dyn_cast<Function>(Callee); 2952 if (isa<InlineAsm>(Callee)) 2953 visitInlineAsm(I, EHPadBB); 2954 else if (Fn && Fn->isIntrinsic()) { 2955 switch (Fn->getIntrinsicID()) { 2956 default: 2957 llvm_unreachable("Cannot invoke this intrinsic"); 2958 case Intrinsic::donothing: 2959 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2960 case Intrinsic::seh_try_begin: 2961 case Intrinsic::seh_scope_begin: 2962 case Intrinsic::seh_try_end: 2963 case Intrinsic::seh_scope_end: 2964 break; 2965 case Intrinsic::experimental_patchpoint_void: 2966 case Intrinsic::experimental_patchpoint_i64: 2967 visitPatchpoint(I, EHPadBB); 2968 break; 2969 case Intrinsic::experimental_gc_statepoint: 2970 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2971 break; 2972 case Intrinsic::wasm_rethrow: { 2973 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2974 // special because it can be invoked, so we manually lower it to a DAG 2975 // node here. 2976 SmallVector<SDValue, 8> Ops; 2977 Ops.push_back(getRoot()); // inchain 2978 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2979 Ops.push_back( 2980 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2981 TLI.getPointerTy(DAG.getDataLayout()))); 2982 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2983 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2984 break; 2985 } 2986 } 2987 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2988 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2989 // Eventually we will support lowering the @llvm.experimental.deoptimize 2990 // intrinsic, and right now there are no plans to support other intrinsics 2991 // with deopt state. 2992 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2993 } else { 2994 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 2995 } 2996 2997 // If the value of the invoke is used outside of its defining block, make it 2998 // available as a virtual register. 2999 // We already took care of the exported value for the statepoint instruction 3000 // during call to the LowerStatepoint. 3001 if (!isa<GCStatepointInst>(I)) { 3002 CopyToExportRegsIfNeeded(&I); 3003 } 3004 3005 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3006 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3007 BranchProbability EHPadBBProb = 3008 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3009 : BranchProbability::getZero(); 3010 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3011 3012 // Update successor info. 3013 addSuccessorWithProb(InvokeMBB, Return); 3014 for (auto &UnwindDest : UnwindDests) { 3015 UnwindDest.first->setIsEHPad(); 3016 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3017 } 3018 InvokeMBB->normalizeSuccProbs(); 3019 3020 // Drop into normal successor. 3021 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3022 DAG.getBasicBlock(Return))); 3023 } 3024 3025 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3026 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3027 3028 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3029 // have to do anything here to lower funclet bundles. 3030 assert(!I.hasOperandBundlesOtherThan( 3031 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3032 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3033 3034 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3035 visitInlineAsm(I); 3036 CopyToExportRegsIfNeeded(&I); 3037 3038 // Retrieve successors. 3039 SmallPtrSet<BasicBlock *, 8> Dests; 3040 Dests.insert(I.getDefaultDest()); 3041 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3042 3043 // Update successor info. 3044 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3045 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3046 BasicBlock *Dest = I.getIndirectDest(i); 3047 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3048 Target->setIsInlineAsmBrIndirectTarget(); 3049 Target->setMachineBlockAddressTaken(); 3050 Target->setLabelMustBeEmitted(); 3051 // Don't add duplicate machine successors. 3052 if (Dests.insert(Dest).second) 3053 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3054 } 3055 CallBrMBB->normalizeSuccProbs(); 3056 3057 // Drop into default successor. 3058 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3059 MVT::Other, getControlRoot(), 3060 DAG.getBasicBlock(Return))); 3061 } 3062 3063 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3064 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3065 } 3066 3067 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3068 assert(FuncInfo.MBB->isEHPad() && 3069 "Call to landingpad not in landing pad!"); 3070 3071 // If there aren't registers to copy the values into (e.g., during SjLj 3072 // exceptions), then don't bother to create these DAG nodes. 3073 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3074 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3075 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3076 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3077 return; 3078 3079 // If landingpad's return type is token type, we don't create DAG nodes 3080 // for its exception pointer and selector value. The extraction of exception 3081 // pointer or selector value from token type landingpads is not currently 3082 // supported. 3083 if (LP.getType()->isTokenTy()) 3084 return; 3085 3086 SmallVector<EVT, 2> ValueVTs; 3087 SDLoc dl = getCurSDLoc(); 3088 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3089 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3090 3091 // Get the two live-in registers as SDValues. The physregs have already been 3092 // copied into virtual registers. 3093 SDValue Ops[2]; 3094 if (FuncInfo.ExceptionPointerVirtReg) { 3095 Ops[0] = DAG.getZExtOrTrunc( 3096 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3097 FuncInfo.ExceptionPointerVirtReg, 3098 TLI.getPointerTy(DAG.getDataLayout())), 3099 dl, ValueVTs[0]); 3100 } else { 3101 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3102 } 3103 Ops[1] = DAG.getZExtOrTrunc( 3104 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3105 FuncInfo.ExceptionSelectorVirtReg, 3106 TLI.getPointerTy(DAG.getDataLayout())), 3107 dl, ValueVTs[1]); 3108 3109 // Merge into one. 3110 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3111 DAG.getVTList(ValueVTs), Ops); 3112 setValue(&LP, Res); 3113 } 3114 3115 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3116 MachineBasicBlock *Last) { 3117 // Update JTCases. 3118 for (JumpTableBlock &JTB : SL->JTCases) 3119 if (JTB.first.HeaderBB == First) 3120 JTB.first.HeaderBB = Last; 3121 3122 // Update BitTestCases. 3123 for (BitTestBlock &BTB : SL->BitTestCases) 3124 if (BTB.Parent == First) 3125 BTB.Parent = Last; 3126 } 3127 3128 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3129 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3130 3131 // Update machine-CFG edges with unique successors. 3132 SmallSet<BasicBlock*, 32> Done; 3133 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3134 BasicBlock *BB = I.getSuccessor(i); 3135 bool Inserted = Done.insert(BB).second; 3136 if (!Inserted) 3137 continue; 3138 3139 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3140 addSuccessorWithProb(IndirectBrMBB, Succ); 3141 } 3142 IndirectBrMBB->normalizeSuccProbs(); 3143 3144 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3145 MVT::Other, getControlRoot(), 3146 getValue(I.getAddress()))); 3147 } 3148 3149 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3150 if (!DAG.getTarget().Options.TrapUnreachable) 3151 return; 3152 3153 // We may be able to ignore unreachable behind a noreturn call. 3154 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3155 const BasicBlock &BB = *I.getParent(); 3156 if (&I != &BB.front()) { 3157 BasicBlock::const_iterator PredI = 3158 std::prev(BasicBlock::const_iterator(&I)); 3159 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3160 if (Call->doesNotReturn()) 3161 return; 3162 } 3163 } 3164 } 3165 3166 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3167 } 3168 3169 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3170 SDNodeFlags Flags; 3171 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3172 Flags.copyFMF(*FPOp); 3173 3174 SDValue Op = getValue(I.getOperand(0)); 3175 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3176 Op, Flags); 3177 setValue(&I, UnNodeValue); 3178 } 3179 3180 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3181 SDNodeFlags Flags; 3182 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3183 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3184 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3185 } 3186 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3187 Flags.setExact(ExactOp->isExact()); 3188 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3189 Flags.copyFMF(*FPOp); 3190 3191 SDValue Op1 = getValue(I.getOperand(0)); 3192 SDValue Op2 = getValue(I.getOperand(1)); 3193 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3194 Op1, Op2, Flags); 3195 setValue(&I, BinNodeValue); 3196 } 3197 3198 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3199 SDValue Op1 = getValue(I.getOperand(0)); 3200 SDValue Op2 = getValue(I.getOperand(1)); 3201 3202 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3203 Op1.getValueType(), DAG.getDataLayout()); 3204 3205 // Coerce the shift amount to the right type if we can. This exposes the 3206 // truncate or zext to optimization early. 3207 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3208 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3209 "Unexpected shift type"); 3210 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3211 } 3212 3213 bool nuw = false; 3214 bool nsw = false; 3215 bool exact = false; 3216 3217 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3218 3219 if (const OverflowingBinaryOperator *OFBinOp = 3220 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3221 nuw = OFBinOp->hasNoUnsignedWrap(); 3222 nsw = OFBinOp->hasNoSignedWrap(); 3223 } 3224 if (const PossiblyExactOperator *ExactOp = 3225 dyn_cast<const PossiblyExactOperator>(&I)) 3226 exact = ExactOp->isExact(); 3227 } 3228 SDNodeFlags Flags; 3229 Flags.setExact(exact); 3230 Flags.setNoSignedWrap(nsw); 3231 Flags.setNoUnsignedWrap(nuw); 3232 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3233 Flags); 3234 setValue(&I, Res); 3235 } 3236 3237 void SelectionDAGBuilder::visitSDiv(const User &I) { 3238 SDValue Op1 = getValue(I.getOperand(0)); 3239 SDValue Op2 = getValue(I.getOperand(1)); 3240 3241 SDNodeFlags Flags; 3242 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3243 cast<PossiblyExactOperator>(&I)->isExact()); 3244 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3245 Op2, Flags)); 3246 } 3247 3248 void SelectionDAGBuilder::visitICmp(const User &I) { 3249 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3250 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3251 predicate = IC->getPredicate(); 3252 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3253 predicate = ICmpInst::Predicate(IC->getPredicate()); 3254 SDValue Op1 = getValue(I.getOperand(0)); 3255 SDValue Op2 = getValue(I.getOperand(1)); 3256 ISD::CondCode Opcode = getICmpCondCode(predicate); 3257 3258 auto &TLI = DAG.getTargetLoweringInfo(); 3259 EVT MemVT = 3260 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3261 3262 // If a pointer's DAG type is larger than its memory type then the DAG values 3263 // are zero-extended. This breaks signed comparisons so truncate back to the 3264 // underlying type before doing the compare. 3265 if (Op1.getValueType() != MemVT) { 3266 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3267 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3268 } 3269 3270 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3271 I.getType()); 3272 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3273 } 3274 3275 void SelectionDAGBuilder::visitFCmp(const User &I) { 3276 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3277 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3278 predicate = FC->getPredicate(); 3279 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3280 predicate = FCmpInst::Predicate(FC->getPredicate()); 3281 SDValue Op1 = getValue(I.getOperand(0)); 3282 SDValue Op2 = getValue(I.getOperand(1)); 3283 3284 ISD::CondCode Condition = getFCmpCondCode(predicate); 3285 auto *FPMO = cast<FPMathOperator>(&I); 3286 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3287 Condition = getFCmpCodeWithoutNaN(Condition); 3288 3289 SDNodeFlags Flags; 3290 Flags.copyFMF(*FPMO); 3291 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3292 3293 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3294 I.getType()); 3295 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3296 } 3297 3298 // Check if the condition of the select has one use or two users that are both 3299 // selects with the same condition. 3300 static bool hasOnlySelectUsers(const Value *Cond) { 3301 return llvm::all_of(Cond->users(), [](const Value *V) { 3302 return isa<SelectInst>(V); 3303 }); 3304 } 3305 3306 void SelectionDAGBuilder::visitSelect(const User &I) { 3307 SmallVector<EVT, 4> ValueVTs; 3308 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3309 ValueVTs); 3310 unsigned NumValues = ValueVTs.size(); 3311 if (NumValues == 0) return; 3312 3313 SmallVector<SDValue, 4> Values(NumValues); 3314 SDValue Cond = getValue(I.getOperand(0)); 3315 SDValue LHSVal = getValue(I.getOperand(1)); 3316 SDValue RHSVal = getValue(I.getOperand(2)); 3317 SmallVector<SDValue, 1> BaseOps(1, Cond); 3318 ISD::NodeType OpCode = 3319 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3320 3321 bool IsUnaryAbs = false; 3322 bool Negate = false; 3323 3324 SDNodeFlags Flags; 3325 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3326 Flags.copyFMF(*FPOp); 3327 3328 // Min/max matching is only viable if all output VTs are the same. 3329 if (all_equal(ValueVTs)) { 3330 EVT VT = ValueVTs[0]; 3331 LLVMContext &Ctx = *DAG.getContext(); 3332 auto &TLI = DAG.getTargetLoweringInfo(); 3333 3334 // We care about the legality of the operation after it has been type 3335 // legalized. 3336 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3337 VT = TLI.getTypeToTransformTo(Ctx, VT); 3338 3339 // If the vselect is legal, assume we want to leave this as a vector setcc + 3340 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3341 // min/max is legal on the scalar type. 3342 bool UseScalarMinMax = VT.isVector() && 3343 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3344 3345 Value *LHS, *RHS; 3346 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3347 ISD::NodeType Opc = ISD::DELETED_NODE; 3348 switch (SPR.Flavor) { 3349 case SPF_UMAX: Opc = ISD::UMAX; break; 3350 case SPF_UMIN: Opc = ISD::UMIN; break; 3351 case SPF_SMAX: Opc = ISD::SMAX; break; 3352 case SPF_SMIN: Opc = ISD::SMIN; break; 3353 case SPF_FMINNUM: 3354 switch (SPR.NaNBehavior) { 3355 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3356 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3357 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3358 case SPNB_RETURNS_ANY: { 3359 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3360 Opc = ISD::FMINNUM; 3361 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3362 Opc = ISD::FMINIMUM; 3363 else if (UseScalarMinMax) 3364 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3365 ISD::FMINNUM : ISD::FMINIMUM; 3366 break; 3367 } 3368 } 3369 break; 3370 case SPF_FMAXNUM: 3371 switch (SPR.NaNBehavior) { 3372 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3373 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3374 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3375 case SPNB_RETURNS_ANY: 3376 3377 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3378 Opc = ISD::FMAXNUM; 3379 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3380 Opc = ISD::FMAXIMUM; 3381 else if (UseScalarMinMax) 3382 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3383 ISD::FMAXNUM : ISD::FMAXIMUM; 3384 break; 3385 } 3386 break; 3387 case SPF_NABS: 3388 Negate = true; 3389 [[fallthrough]]; 3390 case SPF_ABS: 3391 IsUnaryAbs = true; 3392 Opc = ISD::ABS; 3393 break; 3394 default: break; 3395 } 3396 3397 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3398 (TLI.isOperationLegalOrCustom(Opc, VT) || 3399 (UseScalarMinMax && 3400 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3401 // If the underlying comparison instruction is used by any other 3402 // instruction, the consumed instructions won't be destroyed, so it is 3403 // not profitable to convert to a min/max. 3404 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3405 OpCode = Opc; 3406 LHSVal = getValue(LHS); 3407 RHSVal = getValue(RHS); 3408 BaseOps.clear(); 3409 } 3410 3411 if (IsUnaryAbs) { 3412 OpCode = Opc; 3413 LHSVal = getValue(LHS); 3414 BaseOps.clear(); 3415 } 3416 } 3417 3418 if (IsUnaryAbs) { 3419 for (unsigned i = 0; i != NumValues; ++i) { 3420 SDLoc dl = getCurSDLoc(); 3421 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3422 Values[i] = 3423 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3424 if (Negate) 3425 Values[i] = DAG.getNegative(Values[i], dl, VT); 3426 } 3427 } else { 3428 for (unsigned i = 0; i != NumValues; ++i) { 3429 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3430 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3431 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3432 Values[i] = DAG.getNode( 3433 OpCode, getCurSDLoc(), 3434 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3435 } 3436 } 3437 3438 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3439 DAG.getVTList(ValueVTs), Values)); 3440 } 3441 3442 void SelectionDAGBuilder::visitTrunc(const User &I) { 3443 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3444 SDValue N = getValue(I.getOperand(0)); 3445 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3446 I.getType()); 3447 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3448 } 3449 3450 void SelectionDAGBuilder::visitZExt(const User &I) { 3451 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3452 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3453 SDValue N = getValue(I.getOperand(0)); 3454 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3455 I.getType()); 3456 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3457 } 3458 3459 void SelectionDAGBuilder::visitSExt(const User &I) { 3460 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3461 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3462 SDValue N = getValue(I.getOperand(0)); 3463 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3464 I.getType()); 3465 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3466 } 3467 3468 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3469 // FPTrunc is never a no-op cast, no need to check 3470 SDValue N = getValue(I.getOperand(0)); 3471 SDLoc dl = getCurSDLoc(); 3472 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3473 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3474 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3475 DAG.getTargetConstant( 3476 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3477 } 3478 3479 void SelectionDAGBuilder::visitFPExt(const User &I) { 3480 // FPExt is never a no-op cast, no need to check 3481 SDValue N = getValue(I.getOperand(0)); 3482 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3483 I.getType()); 3484 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3485 } 3486 3487 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3488 // FPToUI is never a no-op cast, no need to check 3489 SDValue N = getValue(I.getOperand(0)); 3490 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3491 I.getType()); 3492 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3493 } 3494 3495 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3496 // FPToSI is never a no-op cast, no need to check 3497 SDValue N = getValue(I.getOperand(0)); 3498 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3499 I.getType()); 3500 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3501 } 3502 3503 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3504 // UIToFP is never a no-op cast, no need to check 3505 SDValue N = getValue(I.getOperand(0)); 3506 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3507 I.getType()); 3508 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3509 } 3510 3511 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3512 // SIToFP is never a no-op cast, no need to check 3513 SDValue N = getValue(I.getOperand(0)); 3514 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3515 I.getType()); 3516 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3517 } 3518 3519 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3520 // What to do depends on the size of the integer and the size of the pointer. 3521 // We can either truncate, zero extend, or no-op, accordingly. 3522 SDValue N = getValue(I.getOperand(0)); 3523 auto &TLI = DAG.getTargetLoweringInfo(); 3524 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3525 I.getType()); 3526 EVT PtrMemVT = 3527 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3528 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3529 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3530 setValue(&I, N); 3531 } 3532 3533 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3534 // What to do depends on the size of the integer and the size of the pointer. 3535 // We can either truncate, zero extend, or no-op, accordingly. 3536 SDValue N = getValue(I.getOperand(0)); 3537 auto &TLI = DAG.getTargetLoweringInfo(); 3538 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3539 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3540 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3541 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3542 setValue(&I, N); 3543 } 3544 3545 void SelectionDAGBuilder::visitBitCast(const User &I) { 3546 SDValue N = getValue(I.getOperand(0)); 3547 SDLoc dl = getCurSDLoc(); 3548 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3549 I.getType()); 3550 3551 // BitCast assures us that source and destination are the same size so this is 3552 // either a BITCAST or a no-op. 3553 if (DestVT != N.getValueType()) 3554 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3555 DestVT, N)); // convert types. 3556 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3557 // might fold any kind of constant expression to an integer constant and that 3558 // is not what we are looking for. Only recognize a bitcast of a genuine 3559 // constant integer as an opaque constant. 3560 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3561 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3562 /*isOpaque*/true)); 3563 else 3564 setValue(&I, N); // noop cast. 3565 } 3566 3567 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3568 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3569 const Value *SV = I.getOperand(0); 3570 SDValue N = getValue(SV); 3571 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3572 3573 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3574 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3575 3576 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3577 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3578 3579 setValue(&I, N); 3580 } 3581 3582 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3583 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3584 SDValue InVec = getValue(I.getOperand(0)); 3585 SDValue InVal = getValue(I.getOperand(1)); 3586 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3587 TLI.getVectorIdxTy(DAG.getDataLayout())); 3588 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3589 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3590 InVec, InVal, InIdx)); 3591 } 3592 3593 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3594 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3595 SDValue InVec = getValue(I.getOperand(0)); 3596 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3597 TLI.getVectorIdxTy(DAG.getDataLayout())); 3598 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3599 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3600 InVec, InIdx)); 3601 } 3602 3603 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3604 SDValue Src1 = getValue(I.getOperand(0)); 3605 SDValue Src2 = getValue(I.getOperand(1)); 3606 ArrayRef<int> Mask; 3607 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3608 Mask = SVI->getShuffleMask(); 3609 else 3610 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3611 SDLoc DL = getCurSDLoc(); 3612 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3613 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3614 EVT SrcVT = Src1.getValueType(); 3615 3616 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3617 VT.isScalableVector()) { 3618 // Canonical splat form of first element of first input vector. 3619 SDValue FirstElt = 3620 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3621 DAG.getVectorIdxConstant(0, DL)); 3622 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3623 return; 3624 } 3625 3626 // For now, we only handle splats for scalable vectors. 3627 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3628 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3629 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3630 3631 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3632 unsigned MaskNumElts = Mask.size(); 3633 3634 if (SrcNumElts == MaskNumElts) { 3635 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3636 return; 3637 } 3638 3639 // Normalize the shuffle vector since mask and vector length don't match. 3640 if (SrcNumElts < MaskNumElts) { 3641 // Mask is longer than the source vectors. We can use concatenate vector to 3642 // make the mask and vectors lengths match. 3643 3644 if (MaskNumElts % SrcNumElts == 0) { 3645 // Mask length is a multiple of the source vector length. 3646 // Check if the shuffle is some kind of concatenation of the input 3647 // vectors. 3648 unsigned NumConcat = MaskNumElts / SrcNumElts; 3649 bool IsConcat = true; 3650 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3651 for (unsigned i = 0; i != MaskNumElts; ++i) { 3652 int Idx = Mask[i]; 3653 if (Idx < 0) 3654 continue; 3655 // Ensure the indices in each SrcVT sized piece are sequential and that 3656 // the same source is used for the whole piece. 3657 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3658 (ConcatSrcs[i / SrcNumElts] >= 0 && 3659 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3660 IsConcat = false; 3661 break; 3662 } 3663 // Remember which source this index came from. 3664 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3665 } 3666 3667 // The shuffle is concatenating multiple vectors together. Just emit 3668 // a CONCAT_VECTORS operation. 3669 if (IsConcat) { 3670 SmallVector<SDValue, 8> ConcatOps; 3671 for (auto Src : ConcatSrcs) { 3672 if (Src < 0) 3673 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3674 else if (Src == 0) 3675 ConcatOps.push_back(Src1); 3676 else 3677 ConcatOps.push_back(Src2); 3678 } 3679 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3680 return; 3681 } 3682 } 3683 3684 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3685 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3686 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3687 PaddedMaskNumElts); 3688 3689 // Pad both vectors with undefs to make them the same length as the mask. 3690 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3691 3692 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3693 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3694 MOps1[0] = Src1; 3695 MOps2[0] = Src2; 3696 3697 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3698 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3699 3700 // Readjust mask for new input vector length. 3701 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3702 for (unsigned i = 0; i != MaskNumElts; ++i) { 3703 int Idx = Mask[i]; 3704 if (Idx >= (int)SrcNumElts) 3705 Idx -= SrcNumElts - PaddedMaskNumElts; 3706 MappedOps[i] = Idx; 3707 } 3708 3709 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3710 3711 // If the concatenated vector was padded, extract a subvector with the 3712 // correct number of elements. 3713 if (MaskNumElts != PaddedMaskNumElts) 3714 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3715 DAG.getVectorIdxConstant(0, DL)); 3716 3717 setValue(&I, Result); 3718 return; 3719 } 3720 3721 if (SrcNumElts > MaskNumElts) { 3722 // Analyze the access pattern of the vector to see if we can extract 3723 // two subvectors and do the shuffle. 3724 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3725 bool CanExtract = true; 3726 for (int Idx : Mask) { 3727 unsigned Input = 0; 3728 if (Idx < 0) 3729 continue; 3730 3731 if (Idx >= (int)SrcNumElts) { 3732 Input = 1; 3733 Idx -= SrcNumElts; 3734 } 3735 3736 // If all the indices come from the same MaskNumElts sized portion of 3737 // the sources we can use extract. Also make sure the extract wouldn't 3738 // extract past the end of the source. 3739 int NewStartIdx = alignDown(Idx, MaskNumElts); 3740 if (NewStartIdx + MaskNumElts > SrcNumElts || 3741 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3742 CanExtract = false; 3743 // Make sure we always update StartIdx as we use it to track if all 3744 // elements are undef. 3745 StartIdx[Input] = NewStartIdx; 3746 } 3747 3748 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3749 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3750 return; 3751 } 3752 if (CanExtract) { 3753 // Extract appropriate subvector and generate a vector shuffle 3754 for (unsigned Input = 0; Input < 2; ++Input) { 3755 SDValue &Src = Input == 0 ? Src1 : Src2; 3756 if (StartIdx[Input] < 0) 3757 Src = DAG.getUNDEF(VT); 3758 else { 3759 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3760 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3761 } 3762 } 3763 3764 // Calculate new mask. 3765 SmallVector<int, 8> MappedOps(Mask); 3766 for (int &Idx : MappedOps) { 3767 if (Idx >= (int)SrcNumElts) 3768 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3769 else if (Idx >= 0) 3770 Idx -= StartIdx[0]; 3771 } 3772 3773 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3774 return; 3775 } 3776 } 3777 3778 // We can't use either concat vectors or extract subvectors so fall back to 3779 // replacing the shuffle with extract and build vector. 3780 // to insert and build vector. 3781 EVT EltVT = VT.getVectorElementType(); 3782 SmallVector<SDValue,8> Ops; 3783 for (int Idx : Mask) { 3784 SDValue Res; 3785 3786 if (Idx < 0) { 3787 Res = DAG.getUNDEF(EltVT); 3788 } else { 3789 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3790 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3791 3792 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3793 DAG.getVectorIdxConstant(Idx, DL)); 3794 } 3795 3796 Ops.push_back(Res); 3797 } 3798 3799 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3800 } 3801 3802 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3803 ArrayRef<unsigned> Indices = I.getIndices(); 3804 const Value *Op0 = I.getOperand(0); 3805 const Value *Op1 = I.getOperand(1); 3806 Type *AggTy = I.getType(); 3807 Type *ValTy = Op1->getType(); 3808 bool IntoUndef = isa<UndefValue>(Op0); 3809 bool FromUndef = isa<UndefValue>(Op1); 3810 3811 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3812 3813 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3814 SmallVector<EVT, 4> AggValueVTs; 3815 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3816 SmallVector<EVT, 4> ValValueVTs; 3817 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3818 3819 unsigned NumAggValues = AggValueVTs.size(); 3820 unsigned NumValValues = ValValueVTs.size(); 3821 SmallVector<SDValue, 4> Values(NumAggValues); 3822 3823 // Ignore an insertvalue that produces an empty object 3824 if (!NumAggValues) { 3825 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3826 return; 3827 } 3828 3829 SDValue Agg = getValue(Op0); 3830 unsigned i = 0; 3831 // Copy the beginning value(s) from the original aggregate. 3832 for (; i != LinearIndex; ++i) 3833 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3834 SDValue(Agg.getNode(), Agg.getResNo() + i); 3835 // Copy values from the inserted value(s). 3836 if (NumValValues) { 3837 SDValue Val = getValue(Op1); 3838 for (; i != LinearIndex + NumValValues; ++i) 3839 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3840 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3841 } 3842 // Copy remaining value(s) from the original aggregate. 3843 for (; i != NumAggValues; ++i) 3844 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3845 SDValue(Agg.getNode(), Agg.getResNo() + i); 3846 3847 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3848 DAG.getVTList(AggValueVTs), Values)); 3849 } 3850 3851 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3852 ArrayRef<unsigned> Indices = I.getIndices(); 3853 const Value *Op0 = I.getOperand(0); 3854 Type *AggTy = Op0->getType(); 3855 Type *ValTy = I.getType(); 3856 bool OutOfUndef = isa<UndefValue>(Op0); 3857 3858 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3859 3860 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3861 SmallVector<EVT, 4> ValValueVTs; 3862 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3863 3864 unsigned NumValValues = ValValueVTs.size(); 3865 3866 // Ignore a extractvalue that produces an empty object 3867 if (!NumValValues) { 3868 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3869 return; 3870 } 3871 3872 SmallVector<SDValue, 4> Values(NumValValues); 3873 3874 SDValue Agg = getValue(Op0); 3875 // Copy out the selected value(s). 3876 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3877 Values[i - LinearIndex] = 3878 OutOfUndef ? 3879 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3880 SDValue(Agg.getNode(), Agg.getResNo() + i); 3881 3882 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3883 DAG.getVTList(ValValueVTs), Values)); 3884 } 3885 3886 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3887 Value *Op0 = I.getOperand(0); 3888 // Note that the pointer operand may be a vector of pointers. Take the scalar 3889 // element which holds a pointer. 3890 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3891 SDValue N = getValue(Op0); 3892 SDLoc dl = getCurSDLoc(); 3893 auto &TLI = DAG.getTargetLoweringInfo(); 3894 3895 // Normalize Vector GEP - all scalar operands should be converted to the 3896 // splat vector. 3897 bool IsVectorGEP = I.getType()->isVectorTy(); 3898 ElementCount VectorElementCount = 3899 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3900 : ElementCount::getFixed(0); 3901 3902 if (IsVectorGEP && !N.getValueType().isVector()) { 3903 LLVMContext &Context = *DAG.getContext(); 3904 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3905 N = DAG.getSplat(VT, dl, N); 3906 } 3907 3908 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3909 GTI != E; ++GTI) { 3910 const Value *Idx = GTI.getOperand(); 3911 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3912 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3913 if (Field) { 3914 // N = N + Offset 3915 uint64_t Offset = 3916 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3917 3918 // In an inbounds GEP with an offset that is nonnegative even when 3919 // interpreted as signed, assume there is no unsigned overflow. 3920 SDNodeFlags Flags; 3921 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3922 Flags.setNoUnsignedWrap(true); 3923 3924 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3925 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3926 } 3927 } else { 3928 // IdxSize is the width of the arithmetic according to IR semantics. 3929 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3930 // (and fix up the result later). 3931 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3932 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3933 TypeSize ElementSize = 3934 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3935 // We intentionally mask away the high bits here; ElementSize may not 3936 // fit in IdxTy. 3937 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3938 bool ElementScalable = ElementSize.isScalable(); 3939 3940 // If this is a scalar constant or a splat vector of constants, 3941 // handle it quickly. 3942 const auto *C = dyn_cast<Constant>(Idx); 3943 if (C && isa<VectorType>(C->getType())) 3944 C = C->getSplatValue(); 3945 3946 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3947 if (CI && CI->isZero()) 3948 continue; 3949 if (CI && !ElementScalable) { 3950 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3951 LLVMContext &Context = *DAG.getContext(); 3952 SDValue OffsVal; 3953 if (IsVectorGEP) 3954 OffsVal = DAG.getConstant( 3955 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3956 else 3957 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3958 3959 // In an inbounds GEP with an offset that is nonnegative even when 3960 // interpreted as signed, assume there is no unsigned overflow. 3961 SDNodeFlags Flags; 3962 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3963 Flags.setNoUnsignedWrap(true); 3964 3965 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3966 3967 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3968 continue; 3969 } 3970 3971 // N = N + Idx * ElementMul; 3972 SDValue IdxN = getValue(Idx); 3973 3974 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3975 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3976 VectorElementCount); 3977 IdxN = DAG.getSplat(VT, dl, IdxN); 3978 } 3979 3980 // If the index is smaller or larger than intptr_t, truncate or extend 3981 // it. 3982 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3983 3984 if (ElementScalable) { 3985 EVT VScaleTy = N.getValueType().getScalarType(); 3986 SDValue VScale = DAG.getNode( 3987 ISD::VSCALE, dl, VScaleTy, 3988 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3989 if (IsVectorGEP) 3990 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3991 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3992 } else { 3993 // If this is a multiply by a power of two, turn it into a shl 3994 // immediately. This is a very common case. 3995 if (ElementMul != 1) { 3996 if (ElementMul.isPowerOf2()) { 3997 unsigned Amt = ElementMul.logBase2(); 3998 IdxN = DAG.getNode(ISD::SHL, dl, 3999 N.getValueType(), IdxN, 4000 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4001 } else { 4002 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4003 IdxN.getValueType()); 4004 IdxN = DAG.getNode(ISD::MUL, dl, 4005 N.getValueType(), IdxN, Scale); 4006 } 4007 } 4008 } 4009 4010 N = DAG.getNode(ISD::ADD, dl, 4011 N.getValueType(), N, IdxN); 4012 } 4013 } 4014 4015 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4016 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4017 if (IsVectorGEP) { 4018 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4019 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4020 } 4021 4022 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4023 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4024 4025 setValue(&I, N); 4026 } 4027 4028 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4029 // If this is a fixed sized alloca in the entry block of the function, 4030 // allocate it statically on the stack. 4031 if (FuncInfo.StaticAllocaMap.count(&I)) 4032 return; // getValue will auto-populate this. 4033 4034 SDLoc dl = getCurSDLoc(); 4035 Type *Ty = I.getAllocatedType(); 4036 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4037 auto &DL = DAG.getDataLayout(); 4038 TypeSize TySize = DL.getTypeAllocSize(Ty); 4039 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4040 4041 SDValue AllocSize = getValue(I.getArraySize()); 4042 4043 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 4044 if (AllocSize.getValueType() != IntPtr) 4045 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4046 4047 if (TySize.isScalable()) 4048 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4049 DAG.getVScale(dl, IntPtr, 4050 APInt(IntPtr.getScalarSizeInBits(), 4051 TySize.getKnownMinValue()))); 4052 else 4053 AllocSize = 4054 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4055 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4056 4057 // Handle alignment. If the requested alignment is less than or equal to 4058 // the stack alignment, ignore it. If the size is greater than or equal to 4059 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4060 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4061 if (*Alignment <= StackAlign) 4062 Alignment = None; 4063 4064 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4065 // Round the size of the allocation up to the stack alignment size 4066 // by add SA-1 to the size. This doesn't overflow because we're computing 4067 // an address inside an alloca. 4068 SDNodeFlags Flags; 4069 Flags.setNoUnsignedWrap(true); 4070 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4071 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4072 4073 // Mask out the low bits for alignment purposes. 4074 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4075 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4076 4077 SDValue Ops[] = { 4078 getRoot(), AllocSize, 4079 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4080 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4081 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4082 setValue(&I, DSA); 4083 DAG.setRoot(DSA.getValue(1)); 4084 4085 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4086 } 4087 4088 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4089 if (I.isAtomic()) 4090 return visitAtomicLoad(I); 4091 4092 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4093 const Value *SV = I.getOperand(0); 4094 if (TLI.supportSwiftError()) { 4095 // Swifterror values can come from either a function parameter with 4096 // swifterror attribute or an alloca with swifterror attribute. 4097 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4098 if (Arg->hasSwiftErrorAttr()) 4099 return visitLoadFromSwiftError(I); 4100 } 4101 4102 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4103 if (Alloca->isSwiftError()) 4104 return visitLoadFromSwiftError(I); 4105 } 4106 } 4107 4108 SDValue Ptr = getValue(SV); 4109 4110 Type *Ty = I.getType(); 4111 SmallVector<EVT, 4> ValueVTs, MemVTs; 4112 SmallVector<uint64_t, 4> Offsets; 4113 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4114 unsigned NumValues = ValueVTs.size(); 4115 if (NumValues == 0) 4116 return; 4117 4118 Align Alignment = I.getAlign(); 4119 AAMDNodes AAInfo = I.getAAMetadata(); 4120 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4121 bool isVolatile = I.isVolatile(); 4122 MachineMemOperand::Flags MMOFlags = 4123 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4124 4125 SDValue Root; 4126 bool ConstantMemory = false; 4127 if (isVolatile) 4128 // Serialize volatile loads with other side effects. 4129 Root = getRoot(); 4130 else if (NumValues > MaxParallelChains) 4131 Root = getMemoryRoot(); 4132 else if (AA && 4133 AA->pointsToConstantMemory(MemoryLocation( 4134 SV, 4135 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4136 AAInfo))) { 4137 // Do not serialize (non-volatile) loads of constant memory with anything. 4138 Root = DAG.getEntryNode(); 4139 ConstantMemory = true; 4140 MMOFlags |= MachineMemOperand::MOInvariant; 4141 } else { 4142 // Do not serialize non-volatile loads against each other. 4143 Root = DAG.getRoot(); 4144 } 4145 4146 if (isDereferenceableAndAlignedPointer(SV, Ty, Alignment, DAG.getDataLayout(), 4147 &I, AC, nullptr, LibInfo)) 4148 MMOFlags |= MachineMemOperand::MODereferenceable; 4149 4150 SDLoc dl = getCurSDLoc(); 4151 4152 if (isVolatile) 4153 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4154 4155 // An aggregate load cannot wrap around the address space, so offsets to its 4156 // parts don't wrap either. 4157 SDNodeFlags Flags; 4158 Flags.setNoUnsignedWrap(true); 4159 4160 SmallVector<SDValue, 4> Values(NumValues); 4161 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4162 EVT PtrVT = Ptr.getValueType(); 4163 4164 unsigned ChainI = 0; 4165 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4166 // Serializing loads here may result in excessive register pressure, and 4167 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4168 // could recover a bit by hoisting nodes upward in the chain by recognizing 4169 // they are side-effect free or do not alias. The optimizer should really 4170 // avoid this case by converting large object/array copies to llvm.memcpy 4171 // (MaxParallelChains should always remain as failsafe). 4172 if (ChainI == MaxParallelChains) { 4173 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4174 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4175 makeArrayRef(Chains.data(), ChainI)); 4176 Root = Chain; 4177 ChainI = 0; 4178 } 4179 SDValue A = DAG.getNode(ISD::ADD, dl, 4180 PtrVT, Ptr, 4181 DAG.getConstant(Offsets[i], dl, PtrVT), 4182 Flags); 4183 4184 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4185 MachinePointerInfo(SV, Offsets[i]), Alignment, 4186 MMOFlags, AAInfo, Ranges); 4187 Chains[ChainI] = L.getValue(1); 4188 4189 if (MemVTs[i] != ValueVTs[i]) 4190 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4191 4192 Values[i] = L; 4193 } 4194 4195 if (!ConstantMemory) { 4196 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4197 makeArrayRef(Chains.data(), ChainI)); 4198 if (isVolatile) 4199 DAG.setRoot(Chain); 4200 else 4201 PendingLoads.push_back(Chain); 4202 } 4203 4204 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4205 DAG.getVTList(ValueVTs), Values)); 4206 } 4207 4208 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4209 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4210 "call visitStoreToSwiftError when backend supports swifterror"); 4211 4212 SmallVector<EVT, 4> ValueVTs; 4213 SmallVector<uint64_t, 4> Offsets; 4214 const Value *SrcV = I.getOperand(0); 4215 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4216 SrcV->getType(), ValueVTs, &Offsets); 4217 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4218 "expect a single EVT for swifterror"); 4219 4220 SDValue Src = getValue(SrcV); 4221 // Create a virtual register, then update the virtual register. 4222 Register VReg = 4223 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4224 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4225 // Chain can be getRoot or getControlRoot. 4226 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4227 SDValue(Src.getNode(), Src.getResNo())); 4228 DAG.setRoot(CopyNode); 4229 } 4230 4231 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4232 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4233 "call visitLoadFromSwiftError when backend supports swifterror"); 4234 4235 assert(!I.isVolatile() && 4236 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4237 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4238 "Support volatile, non temporal, invariant for load_from_swift_error"); 4239 4240 const Value *SV = I.getOperand(0); 4241 Type *Ty = I.getType(); 4242 assert( 4243 (!AA || 4244 !AA->pointsToConstantMemory(MemoryLocation( 4245 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4246 I.getAAMetadata()))) && 4247 "load_from_swift_error should not be constant memory"); 4248 4249 SmallVector<EVT, 4> ValueVTs; 4250 SmallVector<uint64_t, 4> Offsets; 4251 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4252 ValueVTs, &Offsets); 4253 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4254 "expect a single EVT for swifterror"); 4255 4256 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4257 SDValue L = DAG.getCopyFromReg( 4258 getRoot(), getCurSDLoc(), 4259 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4260 4261 setValue(&I, L); 4262 } 4263 4264 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4265 if (I.isAtomic()) 4266 return visitAtomicStore(I); 4267 4268 const Value *SrcV = I.getOperand(0); 4269 const Value *PtrV = I.getOperand(1); 4270 4271 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4272 if (TLI.supportSwiftError()) { 4273 // Swifterror values can come from either a function parameter with 4274 // swifterror attribute or an alloca with swifterror attribute. 4275 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4276 if (Arg->hasSwiftErrorAttr()) 4277 return visitStoreToSwiftError(I); 4278 } 4279 4280 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4281 if (Alloca->isSwiftError()) 4282 return visitStoreToSwiftError(I); 4283 } 4284 } 4285 4286 SmallVector<EVT, 4> ValueVTs, MemVTs; 4287 SmallVector<uint64_t, 4> Offsets; 4288 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4289 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4290 unsigned NumValues = ValueVTs.size(); 4291 if (NumValues == 0) 4292 return; 4293 4294 // Get the lowered operands. Note that we do this after 4295 // checking if NumResults is zero, because with zero results 4296 // the operands won't have values in the map. 4297 SDValue Src = getValue(SrcV); 4298 SDValue Ptr = getValue(PtrV); 4299 4300 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4301 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4302 SDLoc dl = getCurSDLoc(); 4303 Align Alignment = I.getAlign(); 4304 AAMDNodes AAInfo = I.getAAMetadata(); 4305 4306 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4307 4308 // An aggregate load cannot wrap around the address space, so offsets to its 4309 // parts don't wrap either. 4310 SDNodeFlags Flags; 4311 Flags.setNoUnsignedWrap(true); 4312 4313 unsigned ChainI = 0; 4314 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4315 // See visitLoad comments. 4316 if (ChainI == MaxParallelChains) { 4317 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4318 makeArrayRef(Chains.data(), ChainI)); 4319 Root = Chain; 4320 ChainI = 0; 4321 } 4322 SDValue Add = 4323 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4324 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4325 if (MemVTs[i] != ValueVTs[i]) 4326 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4327 SDValue St = 4328 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4329 Alignment, MMOFlags, AAInfo); 4330 Chains[ChainI] = St; 4331 } 4332 4333 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4334 makeArrayRef(Chains.data(), ChainI)); 4335 setValue(&I, StoreNode); 4336 DAG.setRoot(StoreNode); 4337 } 4338 4339 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4340 bool IsCompressing) { 4341 SDLoc sdl = getCurSDLoc(); 4342 4343 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4344 MaybeAlign &Alignment) { 4345 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4346 Src0 = I.getArgOperand(0); 4347 Ptr = I.getArgOperand(1); 4348 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4349 Mask = I.getArgOperand(3); 4350 }; 4351 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4352 MaybeAlign &Alignment) { 4353 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4354 Src0 = I.getArgOperand(0); 4355 Ptr = I.getArgOperand(1); 4356 Mask = I.getArgOperand(2); 4357 Alignment = None; 4358 }; 4359 4360 Value *PtrOperand, *MaskOperand, *Src0Operand; 4361 MaybeAlign Alignment; 4362 if (IsCompressing) 4363 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4364 else 4365 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4366 4367 SDValue Ptr = getValue(PtrOperand); 4368 SDValue Src0 = getValue(Src0Operand); 4369 SDValue Mask = getValue(MaskOperand); 4370 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4371 4372 EVT VT = Src0.getValueType(); 4373 if (!Alignment) 4374 Alignment = DAG.getEVTAlign(VT); 4375 4376 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4377 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4378 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4379 SDValue StoreNode = 4380 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4381 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4382 DAG.setRoot(StoreNode); 4383 setValue(&I, StoreNode); 4384 } 4385 4386 // Get a uniform base for the Gather/Scatter intrinsic. 4387 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4388 // We try to represent it as a base pointer + vector of indices. 4389 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4390 // The first operand of the GEP may be a single pointer or a vector of pointers 4391 // Example: 4392 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4393 // or 4394 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4395 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4396 // 4397 // When the first GEP operand is a single pointer - it is the uniform base we 4398 // are looking for. If first operand of the GEP is a splat vector - we 4399 // extract the splat value and use it as a uniform base. 4400 // In all other cases the function returns 'false'. 4401 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4402 ISD::MemIndexType &IndexType, SDValue &Scale, 4403 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4404 uint64_t ElemSize) { 4405 SelectionDAG& DAG = SDB->DAG; 4406 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4407 const DataLayout &DL = DAG.getDataLayout(); 4408 4409 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4410 4411 // Handle splat constant pointer. 4412 if (auto *C = dyn_cast<Constant>(Ptr)) { 4413 C = C->getSplatValue(); 4414 if (!C) 4415 return false; 4416 4417 Base = SDB->getValue(C); 4418 4419 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4420 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4421 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4422 IndexType = ISD::SIGNED_SCALED; 4423 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4424 return true; 4425 } 4426 4427 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4428 if (!GEP || GEP->getParent() != CurBB) 4429 return false; 4430 4431 if (GEP->getNumOperands() != 2) 4432 return false; 4433 4434 const Value *BasePtr = GEP->getPointerOperand(); 4435 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4436 4437 // Make sure the base is scalar and the index is a vector. 4438 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4439 return false; 4440 4441 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4442 4443 // Target may not support the required addressing mode. 4444 if (ScaleVal != 1 && 4445 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4446 return false; 4447 4448 Base = SDB->getValue(BasePtr); 4449 Index = SDB->getValue(IndexVal); 4450 IndexType = ISD::SIGNED_SCALED; 4451 4452 Scale = 4453 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4454 return true; 4455 } 4456 4457 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4458 SDLoc sdl = getCurSDLoc(); 4459 4460 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4461 const Value *Ptr = I.getArgOperand(1); 4462 SDValue Src0 = getValue(I.getArgOperand(0)); 4463 SDValue Mask = getValue(I.getArgOperand(3)); 4464 EVT VT = Src0.getValueType(); 4465 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4466 ->getMaybeAlignValue() 4467 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4468 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4469 4470 SDValue Base; 4471 SDValue Index; 4472 ISD::MemIndexType IndexType; 4473 SDValue Scale; 4474 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4475 I.getParent(), VT.getScalarStoreSize()); 4476 4477 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4478 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4479 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4480 // TODO: Make MachineMemOperands aware of scalable 4481 // vectors. 4482 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4483 if (!UniformBase) { 4484 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4485 Index = getValue(Ptr); 4486 IndexType = ISD::SIGNED_SCALED; 4487 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4488 } 4489 4490 EVT IdxVT = Index.getValueType(); 4491 EVT EltTy = IdxVT.getVectorElementType(); 4492 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4493 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4494 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4495 } 4496 4497 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4498 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4499 Ops, MMO, IndexType, false); 4500 DAG.setRoot(Scatter); 4501 setValue(&I, Scatter); 4502 } 4503 4504 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4505 SDLoc sdl = getCurSDLoc(); 4506 4507 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4508 MaybeAlign &Alignment) { 4509 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4510 Ptr = I.getArgOperand(0); 4511 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4512 Mask = I.getArgOperand(2); 4513 Src0 = I.getArgOperand(3); 4514 }; 4515 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4516 MaybeAlign &Alignment) { 4517 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4518 Ptr = I.getArgOperand(0); 4519 Alignment = None; 4520 Mask = I.getArgOperand(1); 4521 Src0 = I.getArgOperand(2); 4522 }; 4523 4524 Value *PtrOperand, *MaskOperand, *Src0Operand; 4525 MaybeAlign Alignment; 4526 if (IsExpanding) 4527 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4528 else 4529 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4530 4531 SDValue Ptr = getValue(PtrOperand); 4532 SDValue Src0 = getValue(Src0Operand); 4533 SDValue Mask = getValue(MaskOperand); 4534 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4535 4536 EVT VT = Src0.getValueType(); 4537 if (!Alignment) 4538 Alignment = DAG.getEVTAlign(VT); 4539 4540 AAMDNodes AAInfo = I.getAAMetadata(); 4541 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4542 4543 // Do not serialize masked loads of constant memory with anything. 4544 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4545 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4546 4547 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4548 4549 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4550 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4551 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4552 4553 SDValue Load = 4554 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4555 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4556 if (AddToChain) 4557 PendingLoads.push_back(Load.getValue(1)); 4558 setValue(&I, Load); 4559 } 4560 4561 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4562 SDLoc sdl = getCurSDLoc(); 4563 4564 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4565 const Value *Ptr = I.getArgOperand(0); 4566 SDValue Src0 = getValue(I.getArgOperand(3)); 4567 SDValue Mask = getValue(I.getArgOperand(2)); 4568 4569 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4570 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4571 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4572 ->getMaybeAlignValue() 4573 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4574 4575 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4576 4577 SDValue Root = DAG.getRoot(); 4578 SDValue Base; 4579 SDValue Index; 4580 ISD::MemIndexType IndexType; 4581 SDValue Scale; 4582 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4583 I.getParent(), VT.getScalarStoreSize()); 4584 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4585 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4586 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4587 // TODO: Make MachineMemOperands aware of scalable 4588 // vectors. 4589 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4590 4591 if (!UniformBase) { 4592 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4593 Index = getValue(Ptr); 4594 IndexType = ISD::SIGNED_SCALED; 4595 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4596 } 4597 4598 EVT IdxVT = Index.getValueType(); 4599 EVT EltTy = IdxVT.getVectorElementType(); 4600 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4601 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4602 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4603 } 4604 4605 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4606 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4607 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4608 4609 PendingLoads.push_back(Gather.getValue(1)); 4610 setValue(&I, Gather); 4611 } 4612 4613 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4614 SDLoc dl = getCurSDLoc(); 4615 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4616 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4617 SyncScope::ID SSID = I.getSyncScopeID(); 4618 4619 SDValue InChain = getRoot(); 4620 4621 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4622 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4623 4624 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4625 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4626 4627 MachineFunction &MF = DAG.getMachineFunction(); 4628 MachineMemOperand *MMO = MF.getMachineMemOperand( 4629 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4630 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4631 FailureOrdering); 4632 4633 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4634 dl, MemVT, VTs, InChain, 4635 getValue(I.getPointerOperand()), 4636 getValue(I.getCompareOperand()), 4637 getValue(I.getNewValOperand()), MMO); 4638 4639 SDValue OutChain = L.getValue(2); 4640 4641 setValue(&I, L); 4642 DAG.setRoot(OutChain); 4643 } 4644 4645 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4646 SDLoc dl = getCurSDLoc(); 4647 ISD::NodeType NT; 4648 switch (I.getOperation()) { 4649 default: llvm_unreachable("Unknown atomicrmw operation"); 4650 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4651 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4652 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4653 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4654 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4655 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4656 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4657 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4658 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4659 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4660 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4661 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4662 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4663 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4664 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4665 } 4666 AtomicOrdering Ordering = I.getOrdering(); 4667 SyncScope::ID SSID = I.getSyncScopeID(); 4668 4669 SDValue InChain = getRoot(); 4670 4671 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4672 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4673 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4674 4675 MachineFunction &MF = DAG.getMachineFunction(); 4676 MachineMemOperand *MMO = MF.getMachineMemOperand( 4677 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4678 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4679 4680 SDValue L = 4681 DAG.getAtomic(NT, dl, MemVT, InChain, 4682 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4683 MMO); 4684 4685 SDValue OutChain = L.getValue(1); 4686 4687 setValue(&I, L); 4688 DAG.setRoot(OutChain); 4689 } 4690 4691 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4692 SDLoc dl = getCurSDLoc(); 4693 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4694 SDValue Ops[3]; 4695 Ops[0] = getRoot(); 4696 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4697 TLI.getFenceOperandTy(DAG.getDataLayout())); 4698 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4699 TLI.getFenceOperandTy(DAG.getDataLayout())); 4700 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4701 setValue(&I, N); 4702 DAG.setRoot(N); 4703 } 4704 4705 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4706 SDLoc dl = getCurSDLoc(); 4707 AtomicOrdering Order = I.getOrdering(); 4708 SyncScope::ID SSID = I.getSyncScopeID(); 4709 4710 SDValue InChain = getRoot(); 4711 4712 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4713 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4714 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4715 4716 if (!TLI.supportsUnalignedAtomics() && 4717 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4718 report_fatal_error("Cannot generate unaligned atomic load"); 4719 4720 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4721 4722 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4723 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4724 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4725 4726 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4727 4728 SDValue Ptr = getValue(I.getPointerOperand()); 4729 4730 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4731 // TODO: Once this is better exercised by tests, it should be merged with 4732 // the normal path for loads to prevent future divergence. 4733 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4734 if (MemVT != VT) 4735 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4736 4737 setValue(&I, L); 4738 SDValue OutChain = L.getValue(1); 4739 if (!I.isUnordered()) 4740 DAG.setRoot(OutChain); 4741 else 4742 PendingLoads.push_back(OutChain); 4743 return; 4744 } 4745 4746 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4747 Ptr, MMO); 4748 4749 SDValue OutChain = L.getValue(1); 4750 if (MemVT != VT) 4751 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4752 4753 setValue(&I, L); 4754 DAG.setRoot(OutChain); 4755 } 4756 4757 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4758 SDLoc dl = getCurSDLoc(); 4759 4760 AtomicOrdering Ordering = I.getOrdering(); 4761 SyncScope::ID SSID = I.getSyncScopeID(); 4762 4763 SDValue InChain = getRoot(); 4764 4765 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4766 EVT MemVT = 4767 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4768 4769 if (!TLI.supportsUnalignedAtomics() && 4770 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4771 report_fatal_error("Cannot generate unaligned atomic store"); 4772 4773 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4774 4775 MachineFunction &MF = DAG.getMachineFunction(); 4776 MachineMemOperand *MMO = MF.getMachineMemOperand( 4777 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4778 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4779 4780 SDValue Val = getValue(I.getValueOperand()); 4781 if (Val.getValueType() != MemVT) 4782 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4783 SDValue Ptr = getValue(I.getPointerOperand()); 4784 4785 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4786 // TODO: Once this is better exercised by tests, it should be merged with 4787 // the normal path for stores to prevent future divergence. 4788 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4789 setValue(&I, S); 4790 DAG.setRoot(S); 4791 return; 4792 } 4793 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4794 Ptr, Val, MMO); 4795 4796 setValue(&I, OutChain); 4797 DAG.setRoot(OutChain); 4798 } 4799 4800 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4801 /// node. 4802 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4803 unsigned Intrinsic) { 4804 // Ignore the callsite's attributes. A specific call site may be marked with 4805 // readnone, but the lowering code will expect the chain based on the 4806 // definition. 4807 const Function *F = I.getCalledFunction(); 4808 bool HasChain = !F->doesNotAccessMemory(); 4809 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4810 4811 // Build the operand list. 4812 SmallVector<SDValue, 8> Ops; 4813 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4814 if (OnlyLoad) { 4815 // We don't need to serialize loads against other loads. 4816 Ops.push_back(DAG.getRoot()); 4817 } else { 4818 Ops.push_back(getRoot()); 4819 } 4820 } 4821 4822 // Info is set by getTgtMemIntrinsic 4823 TargetLowering::IntrinsicInfo Info; 4824 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4825 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4826 DAG.getMachineFunction(), 4827 Intrinsic); 4828 4829 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4830 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4831 Info.opc == ISD::INTRINSIC_W_CHAIN) 4832 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4833 TLI.getPointerTy(DAG.getDataLayout()))); 4834 4835 // Add all operands of the call to the operand list. 4836 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4837 const Value *Arg = I.getArgOperand(i); 4838 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4839 Ops.push_back(getValue(Arg)); 4840 continue; 4841 } 4842 4843 // Use TargetConstant instead of a regular constant for immarg. 4844 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4845 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4846 assert(CI->getBitWidth() <= 64 && 4847 "large intrinsic immediates not handled"); 4848 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4849 } else { 4850 Ops.push_back( 4851 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4852 } 4853 } 4854 4855 SmallVector<EVT, 4> ValueVTs; 4856 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4857 4858 if (HasChain) 4859 ValueVTs.push_back(MVT::Other); 4860 4861 SDVTList VTs = DAG.getVTList(ValueVTs); 4862 4863 // Propagate fast-math-flags from IR to node(s). 4864 SDNodeFlags Flags; 4865 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4866 Flags.copyFMF(*FPMO); 4867 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4868 4869 // Create the node. 4870 SDValue Result; 4871 // In some cases, custom collection of operands from CallInst I may be needed. 4872 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4873 if (IsTgtIntrinsic) { 4874 // This is target intrinsic that touches memory 4875 Result = 4876 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4877 MachinePointerInfo(Info.ptrVal, Info.offset), 4878 Info.align, Info.flags, Info.size, 4879 I.getAAMetadata()); 4880 } else if (!HasChain) { 4881 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4882 } else if (!I.getType()->isVoidTy()) { 4883 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4884 } else { 4885 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4886 } 4887 4888 if (HasChain) { 4889 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4890 if (OnlyLoad) 4891 PendingLoads.push_back(Chain); 4892 else 4893 DAG.setRoot(Chain); 4894 } 4895 4896 if (!I.getType()->isVoidTy()) { 4897 if (!isa<VectorType>(I.getType())) 4898 Result = lowerRangeToAssertZExt(DAG, I, Result); 4899 4900 MaybeAlign Alignment = I.getRetAlign(); 4901 if (!Alignment) 4902 Alignment = F->getAttributes().getRetAlignment(); 4903 // Insert `assertalign` node if there's an alignment. 4904 if (InsertAssertAlign && Alignment) { 4905 Result = 4906 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4907 } 4908 4909 setValue(&I, Result); 4910 } 4911 } 4912 4913 /// GetSignificand - Get the significand and build it into a floating-point 4914 /// number with exponent of 1: 4915 /// 4916 /// Op = (Op & 0x007fffff) | 0x3f800000; 4917 /// 4918 /// where Op is the hexadecimal representation of floating point value. 4919 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4920 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4921 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4922 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4923 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4924 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4925 } 4926 4927 /// GetExponent - Get the exponent: 4928 /// 4929 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4930 /// 4931 /// where Op is the hexadecimal representation of floating point value. 4932 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4933 const TargetLowering &TLI, const SDLoc &dl) { 4934 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4935 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4936 SDValue t1 = DAG.getNode( 4937 ISD::SRL, dl, MVT::i32, t0, 4938 DAG.getConstant(23, dl, 4939 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 4940 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4941 DAG.getConstant(127, dl, MVT::i32)); 4942 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4943 } 4944 4945 /// getF32Constant - Get 32-bit floating point constant. 4946 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4947 const SDLoc &dl) { 4948 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4949 MVT::f32); 4950 } 4951 4952 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4953 SelectionDAG &DAG) { 4954 // TODO: What fast-math-flags should be set on the floating-point nodes? 4955 4956 // IntegerPartOfX = ((int32_t)(t0); 4957 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4958 4959 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4960 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4961 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4962 4963 // IntegerPartOfX <<= 23; 4964 IntegerPartOfX = 4965 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4966 DAG.getConstant(23, dl, 4967 DAG.getTargetLoweringInfo().getShiftAmountTy( 4968 MVT::i32, DAG.getDataLayout()))); 4969 4970 SDValue TwoToFractionalPartOfX; 4971 if (LimitFloatPrecision <= 6) { 4972 // For floating-point precision of 6: 4973 // 4974 // TwoToFractionalPartOfX = 4975 // 0.997535578f + 4976 // (0.735607626f + 0.252464424f * x) * x; 4977 // 4978 // error 0.0144103317, which is 6 bits 4979 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4980 getF32Constant(DAG, 0x3e814304, dl)); 4981 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4982 getF32Constant(DAG, 0x3f3c50c8, dl)); 4983 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4984 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4985 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4986 } else if (LimitFloatPrecision <= 12) { 4987 // For floating-point precision of 12: 4988 // 4989 // TwoToFractionalPartOfX = 4990 // 0.999892986f + 4991 // (0.696457318f + 4992 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4993 // 4994 // error 0.000107046256, which is 13 to 14 bits 4995 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4996 getF32Constant(DAG, 0x3da235e3, dl)); 4997 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4998 getF32Constant(DAG, 0x3e65b8f3, dl)); 4999 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5000 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5001 getF32Constant(DAG, 0x3f324b07, dl)); 5002 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5003 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5004 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5005 } else { // LimitFloatPrecision <= 18 5006 // For floating-point precision of 18: 5007 // 5008 // TwoToFractionalPartOfX = 5009 // 0.999999982f + 5010 // (0.693148872f + 5011 // (0.240227044f + 5012 // (0.554906021e-1f + 5013 // (0.961591928e-2f + 5014 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5015 // error 2.47208000*10^(-7), which is better than 18 bits 5016 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5017 getF32Constant(DAG, 0x3924b03e, dl)); 5018 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5019 getF32Constant(DAG, 0x3ab24b87, dl)); 5020 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5021 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5022 getF32Constant(DAG, 0x3c1d8c17, dl)); 5023 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5024 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5025 getF32Constant(DAG, 0x3d634a1d, dl)); 5026 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5027 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5028 getF32Constant(DAG, 0x3e75fe14, dl)); 5029 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5030 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5031 getF32Constant(DAG, 0x3f317234, dl)); 5032 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5033 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5034 getF32Constant(DAG, 0x3f800000, dl)); 5035 } 5036 5037 // Add the exponent into the result in integer domain. 5038 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5039 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5040 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5041 } 5042 5043 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5044 /// limited-precision mode. 5045 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5046 const TargetLowering &TLI, SDNodeFlags Flags) { 5047 if (Op.getValueType() == MVT::f32 && 5048 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5049 5050 // Put the exponent in the right bit position for later addition to the 5051 // final result: 5052 // 5053 // t0 = Op * log2(e) 5054 5055 // TODO: What fast-math-flags should be set here? 5056 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5057 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5058 return getLimitedPrecisionExp2(t0, dl, DAG); 5059 } 5060 5061 // No special expansion. 5062 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5063 } 5064 5065 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5066 /// limited-precision mode. 5067 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5068 const TargetLowering &TLI, SDNodeFlags Flags) { 5069 // TODO: What fast-math-flags should be set on the floating-point nodes? 5070 5071 if (Op.getValueType() == MVT::f32 && 5072 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5073 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5074 5075 // Scale the exponent by log(2). 5076 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5077 SDValue LogOfExponent = 5078 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5079 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5080 5081 // Get the significand and build it into a floating-point number with 5082 // exponent of 1. 5083 SDValue X = GetSignificand(DAG, Op1, dl); 5084 5085 SDValue LogOfMantissa; 5086 if (LimitFloatPrecision <= 6) { 5087 // For floating-point precision of 6: 5088 // 5089 // LogofMantissa = 5090 // -1.1609546f + 5091 // (1.4034025f - 0.23903021f * x) * x; 5092 // 5093 // error 0.0034276066, which is better than 8 bits 5094 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5095 getF32Constant(DAG, 0xbe74c456, dl)); 5096 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5097 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5098 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5099 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5100 getF32Constant(DAG, 0x3f949a29, dl)); 5101 } else if (LimitFloatPrecision <= 12) { 5102 // For floating-point precision of 12: 5103 // 5104 // LogOfMantissa = 5105 // -1.7417939f + 5106 // (2.8212026f + 5107 // (-1.4699568f + 5108 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5109 // 5110 // error 0.000061011436, which is 14 bits 5111 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5112 getF32Constant(DAG, 0xbd67b6d6, dl)); 5113 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5114 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5115 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5116 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5117 getF32Constant(DAG, 0x3fbc278b, dl)); 5118 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5119 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5120 getF32Constant(DAG, 0x40348e95, dl)); 5121 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5122 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5123 getF32Constant(DAG, 0x3fdef31a, dl)); 5124 } else { // LimitFloatPrecision <= 18 5125 // For floating-point precision of 18: 5126 // 5127 // LogOfMantissa = 5128 // -2.1072184f + 5129 // (4.2372794f + 5130 // (-3.7029485f + 5131 // (2.2781945f + 5132 // (-0.87823314f + 5133 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5134 // 5135 // error 0.0000023660568, which is better than 18 bits 5136 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5137 getF32Constant(DAG, 0xbc91e5ac, dl)); 5138 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5139 getF32Constant(DAG, 0x3e4350aa, dl)); 5140 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5141 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5142 getF32Constant(DAG, 0x3f60d3e3, dl)); 5143 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5144 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5145 getF32Constant(DAG, 0x4011cdf0, dl)); 5146 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5147 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5148 getF32Constant(DAG, 0x406cfd1c, dl)); 5149 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5150 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5151 getF32Constant(DAG, 0x408797cb, dl)); 5152 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5153 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5154 getF32Constant(DAG, 0x4006dcab, dl)); 5155 } 5156 5157 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5158 } 5159 5160 // No special expansion. 5161 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5162 } 5163 5164 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5165 /// limited-precision mode. 5166 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5167 const TargetLowering &TLI, SDNodeFlags Flags) { 5168 // TODO: What fast-math-flags should be set on the floating-point nodes? 5169 5170 if (Op.getValueType() == MVT::f32 && 5171 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5172 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5173 5174 // Get the exponent. 5175 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5176 5177 // Get the significand and build it into a floating-point number with 5178 // exponent of 1. 5179 SDValue X = GetSignificand(DAG, Op1, dl); 5180 5181 // Different possible minimax approximations of significand in 5182 // floating-point for various degrees of accuracy over [1,2]. 5183 SDValue Log2ofMantissa; 5184 if (LimitFloatPrecision <= 6) { 5185 // For floating-point precision of 6: 5186 // 5187 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5188 // 5189 // error 0.0049451742, which is more than 7 bits 5190 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5191 getF32Constant(DAG, 0xbeb08fe0, dl)); 5192 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5193 getF32Constant(DAG, 0x40019463, dl)); 5194 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5195 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5196 getF32Constant(DAG, 0x3fd6633d, dl)); 5197 } else if (LimitFloatPrecision <= 12) { 5198 // For floating-point precision of 12: 5199 // 5200 // Log2ofMantissa = 5201 // -2.51285454f + 5202 // (4.07009056f + 5203 // (-2.12067489f + 5204 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5205 // 5206 // error 0.0000876136000, which is better than 13 bits 5207 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5208 getF32Constant(DAG, 0xbda7262e, dl)); 5209 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5210 getF32Constant(DAG, 0x3f25280b, dl)); 5211 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5212 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5213 getF32Constant(DAG, 0x4007b923, dl)); 5214 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5215 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5216 getF32Constant(DAG, 0x40823e2f, dl)); 5217 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5218 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5219 getF32Constant(DAG, 0x4020d29c, dl)); 5220 } else { // LimitFloatPrecision <= 18 5221 // For floating-point precision of 18: 5222 // 5223 // Log2ofMantissa = 5224 // -3.0400495f + 5225 // (6.1129976f + 5226 // (-5.3420409f + 5227 // (3.2865683f + 5228 // (-1.2669343f + 5229 // (0.27515199f - 5230 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5231 // 5232 // error 0.0000018516, which is better than 18 bits 5233 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5234 getF32Constant(DAG, 0xbcd2769e, dl)); 5235 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5236 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5237 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5238 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5239 getF32Constant(DAG, 0x3fa22ae7, dl)); 5240 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5241 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5242 getF32Constant(DAG, 0x40525723, dl)); 5243 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5244 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5245 getF32Constant(DAG, 0x40aaf200, dl)); 5246 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5247 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5248 getF32Constant(DAG, 0x40c39dad, dl)); 5249 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5250 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5251 getF32Constant(DAG, 0x4042902c, dl)); 5252 } 5253 5254 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5255 } 5256 5257 // No special expansion. 5258 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5259 } 5260 5261 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5262 /// limited-precision mode. 5263 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5264 const TargetLowering &TLI, SDNodeFlags Flags) { 5265 // TODO: What fast-math-flags should be set on the floating-point nodes? 5266 5267 if (Op.getValueType() == MVT::f32 && 5268 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5269 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5270 5271 // Scale the exponent by log10(2) [0.30102999f]. 5272 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5273 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5274 getF32Constant(DAG, 0x3e9a209a, dl)); 5275 5276 // Get the significand and build it into a floating-point number with 5277 // exponent of 1. 5278 SDValue X = GetSignificand(DAG, Op1, dl); 5279 5280 SDValue Log10ofMantissa; 5281 if (LimitFloatPrecision <= 6) { 5282 // For floating-point precision of 6: 5283 // 5284 // Log10ofMantissa = 5285 // -0.50419619f + 5286 // (0.60948995f - 0.10380950f * x) * x; 5287 // 5288 // error 0.0014886165, which is 6 bits 5289 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5290 getF32Constant(DAG, 0xbdd49a13, dl)); 5291 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5292 getF32Constant(DAG, 0x3f1c0789, dl)); 5293 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5294 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5295 getF32Constant(DAG, 0x3f011300, dl)); 5296 } else if (LimitFloatPrecision <= 12) { 5297 // For floating-point precision of 12: 5298 // 5299 // Log10ofMantissa = 5300 // -0.64831180f + 5301 // (0.91751397f + 5302 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5303 // 5304 // error 0.00019228036, which is better than 12 bits 5305 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5306 getF32Constant(DAG, 0x3d431f31, dl)); 5307 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5308 getF32Constant(DAG, 0x3ea21fb2, dl)); 5309 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5310 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5311 getF32Constant(DAG, 0x3f6ae232, dl)); 5312 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5313 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5314 getF32Constant(DAG, 0x3f25f7c3, dl)); 5315 } else { // LimitFloatPrecision <= 18 5316 // For floating-point precision of 18: 5317 // 5318 // Log10ofMantissa = 5319 // -0.84299375f + 5320 // (1.5327582f + 5321 // (-1.0688956f + 5322 // (0.49102474f + 5323 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5324 // 5325 // error 0.0000037995730, which is better than 18 bits 5326 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5327 getF32Constant(DAG, 0x3c5d51ce, dl)); 5328 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5329 getF32Constant(DAG, 0x3e00685a, dl)); 5330 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5331 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5332 getF32Constant(DAG, 0x3efb6798, dl)); 5333 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5334 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5335 getF32Constant(DAG, 0x3f88d192, dl)); 5336 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5337 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5338 getF32Constant(DAG, 0x3fc4316c, dl)); 5339 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5340 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5341 getF32Constant(DAG, 0x3f57ce70, dl)); 5342 } 5343 5344 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5345 } 5346 5347 // No special expansion. 5348 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5349 } 5350 5351 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5352 /// limited-precision mode. 5353 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5354 const TargetLowering &TLI, SDNodeFlags Flags) { 5355 if (Op.getValueType() == MVT::f32 && 5356 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5357 return getLimitedPrecisionExp2(Op, dl, DAG); 5358 5359 // No special expansion. 5360 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5361 } 5362 5363 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5364 /// limited-precision mode with x == 10.0f. 5365 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5366 SelectionDAG &DAG, const TargetLowering &TLI, 5367 SDNodeFlags Flags) { 5368 bool IsExp10 = false; 5369 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5370 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5371 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5372 APFloat Ten(10.0f); 5373 IsExp10 = LHSC->isExactlyValue(Ten); 5374 } 5375 } 5376 5377 // TODO: What fast-math-flags should be set on the FMUL node? 5378 if (IsExp10) { 5379 // Put the exponent in the right bit position for later addition to the 5380 // final result: 5381 // 5382 // #define LOG2OF10 3.3219281f 5383 // t0 = Op * LOG2OF10; 5384 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5385 getF32Constant(DAG, 0x40549a78, dl)); 5386 return getLimitedPrecisionExp2(t0, dl, DAG); 5387 } 5388 5389 // No special expansion. 5390 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5391 } 5392 5393 /// ExpandPowI - Expand a llvm.powi intrinsic. 5394 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5395 SelectionDAG &DAG) { 5396 // If RHS is a constant, we can expand this out to a multiplication tree if 5397 // it's beneficial on the target, otherwise we end up lowering to a call to 5398 // __powidf2 (for example). 5399 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5400 unsigned Val = RHSC->getSExtValue(); 5401 5402 // powi(x, 0) -> 1.0 5403 if (Val == 0) 5404 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5405 5406 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5407 Val, DAG.shouldOptForSize())) { 5408 // Get the exponent as a positive value. 5409 if ((int)Val < 0) 5410 Val = -Val; 5411 // We use the simple binary decomposition method to generate the multiply 5412 // sequence. There are more optimal ways to do this (for example, 5413 // powi(x,15) generates one more multiply than it should), but this has 5414 // the benefit of being both really simple and much better than a libcall. 5415 SDValue Res; // Logically starts equal to 1.0 5416 SDValue CurSquare = LHS; 5417 // TODO: Intrinsics should have fast-math-flags that propagate to these 5418 // nodes. 5419 while (Val) { 5420 if (Val & 1) { 5421 if (Res.getNode()) 5422 Res = 5423 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5424 else 5425 Res = CurSquare; // 1.0*CurSquare. 5426 } 5427 5428 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5429 CurSquare, CurSquare); 5430 Val >>= 1; 5431 } 5432 5433 // If the original was negative, invert the result, producing 1/(x*x*x). 5434 if (RHSC->getSExtValue() < 0) 5435 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5436 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5437 return Res; 5438 } 5439 } 5440 5441 // Otherwise, expand to a libcall. 5442 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5443 } 5444 5445 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5446 SDValue LHS, SDValue RHS, SDValue Scale, 5447 SelectionDAG &DAG, const TargetLowering &TLI) { 5448 EVT VT = LHS.getValueType(); 5449 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5450 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5451 LLVMContext &Ctx = *DAG.getContext(); 5452 5453 // If the type is legal but the operation isn't, this node might survive all 5454 // the way to operation legalization. If we end up there and we do not have 5455 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5456 // node. 5457 5458 // Coax the legalizer into expanding the node during type legalization instead 5459 // by bumping the size by one bit. This will force it to Promote, enabling the 5460 // early expansion and avoiding the need to expand later. 5461 5462 // We don't have to do this if Scale is 0; that can always be expanded, unless 5463 // it's a saturating signed operation. Those can experience true integer 5464 // division overflow, a case which we must avoid. 5465 5466 // FIXME: We wouldn't have to do this (or any of the early 5467 // expansion/promotion) if it was possible to expand a libcall of an 5468 // illegal type during operation legalization. But it's not, so things 5469 // get a bit hacky. 5470 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5471 if ((ScaleInt > 0 || (Saturating && Signed)) && 5472 (TLI.isTypeLegal(VT) || 5473 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5474 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5475 Opcode, VT, ScaleInt); 5476 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5477 EVT PromVT; 5478 if (VT.isScalarInteger()) 5479 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5480 else if (VT.isVector()) { 5481 PromVT = VT.getVectorElementType(); 5482 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5483 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5484 } else 5485 llvm_unreachable("Wrong VT for DIVFIX?"); 5486 if (Signed) { 5487 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5488 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5489 } else { 5490 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5491 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5492 } 5493 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5494 // For saturating operations, we need to shift up the LHS to get the 5495 // proper saturation width, and then shift down again afterwards. 5496 if (Saturating) 5497 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5498 DAG.getConstant(1, DL, ShiftTy)); 5499 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5500 if (Saturating) 5501 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5502 DAG.getConstant(1, DL, ShiftTy)); 5503 return DAG.getZExtOrTrunc(Res, DL, VT); 5504 } 5505 } 5506 5507 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5508 } 5509 5510 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5511 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5512 static void 5513 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5514 const SDValue &N) { 5515 switch (N.getOpcode()) { 5516 case ISD::CopyFromReg: { 5517 SDValue Op = N.getOperand(1); 5518 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5519 Op.getValueType().getSizeInBits()); 5520 return; 5521 } 5522 case ISD::BITCAST: 5523 case ISD::AssertZext: 5524 case ISD::AssertSext: 5525 case ISD::TRUNCATE: 5526 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5527 return; 5528 case ISD::BUILD_PAIR: 5529 case ISD::BUILD_VECTOR: 5530 case ISD::CONCAT_VECTORS: 5531 for (SDValue Op : N->op_values()) 5532 getUnderlyingArgRegs(Regs, Op); 5533 return; 5534 default: 5535 return; 5536 } 5537 } 5538 5539 /// If the DbgValueInst is a dbg_value of a function argument, create the 5540 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5541 /// instruction selection, they will be inserted to the entry BB. 5542 /// We don't currently support this for variadic dbg_values, as they shouldn't 5543 /// appear for function arguments or in the prologue. 5544 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5545 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5546 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5547 const Argument *Arg = dyn_cast<Argument>(V); 5548 if (!Arg) 5549 return false; 5550 5551 MachineFunction &MF = DAG.getMachineFunction(); 5552 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5553 5554 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5555 // we've been asked to pursue. 5556 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5557 bool Indirect) { 5558 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5559 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5560 // pointing at the VReg, which will be patched up later. 5561 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5562 auto MIB = BuildMI(MF, DL, Inst); 5563 MIB.addReg(Reg); 5564 MIB.addImm(0); 5565 MIB.addMetadata(Variable); 5566 auto *NewDIExpr = FragExpr; 5567 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5568 // the DIExpression. 5569 if (Indirect) 5570 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5571 MIB.addMetadata(NewDIExpr); 5572 return MIB; 5573 } else { 5574 // Create a completely standard DBG_VALUE. 5575 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5576 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5577 } 5578 }; 5579 5580 if (Kind == FuncArgumentDbgValueKind::Value) { 5581 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5582 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5583 // the entry block. 5584 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5585 if (!IsInEntryBlock) 5586 return false; 5587 5588 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5589 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5590 // variable that also is a param. 5591 // 5592 // Although, if we are at the top of the entry block already, we can still 5593 // emit using ArgDbgValue. This might catch some situations when the 5594 // dbg.value refers to an argument that isn't used in the entry block, so 5595 // any CopyToReg node would be optimized out and the only way to express 5596 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5597 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5598 // we should only emit as ArgDbgValue if the Variable is an argument to the 5599 // current function, and the dbg.value intrinsic is found in the entry 5600 // block. 5601 bool VariableIsFunctionInputArg = Variable->isParameter() && 5602 !DL->getInlinedAt(); 5603 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5604 if (!IsInPrologue && !VariableIsFunctionInputArg) 5605 return false; 5606 5607 // Here we assume that a function argument on IR level only can be used to 5608 // describe one input parameter on source level. If we for example have 5609 // source code like this 5610 // 5611 // struct A { long x, y; }; 5612 // void foo(struct A a, long b) { 5613 // ... 5614 // b = a.x; 5615 // ... 5616 // } 5617 // 5618 // and IR like this 5619 // 5620 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5621 // entry: 5622 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5623 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5624 // call void @llvm.dbg.value(metadata i32 %b, "b", 5625 // ... 5626 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5627 // ... 5628 // 5629 // then the last dbg.value is describing a parameter "b" using a value that 5630 // is an argument. But since we already has used %a1 to describe a parameter 5631 // we should not handle that last dbg.value here (that would result in an 5632 // incorrect hoisting of the DBG_VALUE to the function entry). 5633 // Notice that we allow one dbg.value per IR level argument, to accommodate 5634 // for the situation with fragments above. 5635 if (VariableIsFunctionInputArg) { 5636 unsigned ArgNo = Arg->getArgNo(); 5637 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5638 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5639 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5640 return false; 5641 FuncInfo.DescribedArgs.set(ArgNo); 5642 } 5643 } 5644 5645 bool IsIndirect = false; 5646 Optional<MachineOperand> Op; 5647 // Some arguments' frame index is recorded during argument lowering. 5648 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5649 if (FI != std::numeric_limits<int>::max()) 5650 Op = MachineOperand::CreateFI(FI); 5651 5652 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5653 if (!Op && N.getNode()) { 5654 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5655 Register Reg; 5656 if (ArgRegsAndSizes.size() == 1) 5657 Reg = ArgRegsAndSizes.front().first; 5658 5659 if (Reg && Reg.isVirtual()) { 5660 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5661 Register PR = RegInfo.getLiveInPhysReg(Reg); 5662 if (PR) 5663 Reg = PR; 5664 } 5665 if (Reg) { 5666 Op = MachineOperand::CreateReg(Reg, false); 5667 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5668 } 5669 } 5670 5671 if (!Op && N.getNode()) { 5672 // Check if frame index is available. 5673 SDValue LCandidate = peekThroughBitcasts(N); 5674 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5675 if (FrameIndexSDNode *FINode = 5676 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5677 Op = MachineOperand::CreateFI(FINode->getIndex()); 5678 } 5679 5680 if (!Op) { 5681 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5682 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5683 SplitRegs) { 5684 unsigned Offset = 0; 5685 for (const auto &RegAndSize : SplitRegs) { 5686 // If the expression is already a fragment, the current register 5687 // offset+size might extend beyond the fragment. In this case, only 5688 // the register bits that are inside the fragment are relevant. 5689 int RegFragmentSizeInBits = RegAndSize.second; 5690 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5691 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5692 // The register is entirely outside the expression fragment, 5693 // so is irrelevant for debug info. 5694 if (Offset >= ExprFragmentSizeInBits) 5695 break; 5696 // The register is partially outside the expression fragment, only 5697 // the low bits within the fragment are relevant for debug info. 5698 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5699 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5700 } 5701 } 5702 5703 auto FragmentExpr = DIExpression::createFragmentExpression( 5704 Expr, Offset, RegFragmentSizeInBits); 5705 Offset += RegAndSize.second; 5706 // If a valid fragment expression cannot be created, the variable's 5707 // correct value cannot be determined and so it is set as Undef. 5708 if (!FragmentExpr) { 5709 SDDbgValue *SDV = DAG.getConstantDbgValue( 5710 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5711 DAG.AddDbgValue(SDV, false); 5712 continue; 5713 } 5714 MachineInstr *NewMI = 5715 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5716 Kind != FuncArgumentDbgValueKind::Value); 5717 FuncInfo.ArgDbgValues.push_back(NewMI); 5718 } 5719 }; 5720 5721 // Check if ValueMap has reg number. 5722 DenseMap<const Value *, Register>::const_iterator 5723 VMI = FuncInfo.ValueMap.find(V); 5724 if (VMI != FuncInfo.ValueMap.end()) { 5725 const auto &TLI = DAG.getTargetLoweringInfo(); 5726 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5727 V->getType(), None); 5728 if (RFV.occupiesMultipleRegs()) { 5729 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5730 return true; 5731 } 5732 5733 Op = MachineOperand::CreateReg(VMI->second, false); 5734 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5735 } else if (ArgRegsAndSizes.size() > 1) { 5736 // This was split due to the calling convention, and no virtual register 5737 // mapping exists for the value. 5738 splitMultiRegDbgValue(ArgRegsAndSizes); 5739 return true; 5740 } 5741 } 5742 5743 if (!Op) 5744 return false; 5745 5746 assert(Variable->isValidLocationForIntrinsic(DL) && 5747 "Expected inlined-at fields to agree"); 5748 MachineInstr *NewMI = nullptr; 5749 5750 if (Op->isReg()) 5751 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5752 else 5753 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5754 Variable, Expr); 5755 5756 // Otherwise, use ArgDbgValues. 5757 FuncInfo.ArgDbgValues.push_back(NewMI); 5758 return true; 5759 } 5760 5761 /// Return the appropriate SDDbgValue based on N. 5762 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5763 DILocalVariable *Variable, 5764 DIExpression *Expr, 5765 const DebugLoc &dl, 5766 unsigned DbgSDNodeOrder) { 5767 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5768 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5769 // stack slot locations. 5770 // 5771 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5772 // debug values here after optimization: 5773 // 5774 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5775 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5776 // 5777 // Both describe the direct values of their associated variables. 5778 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5779 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5780 } 5781 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5782 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5783 } 5784 5785 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5786 switch (Intrinsic) { 5787 case Intrinsic::smul_fix: 5788 return ISD::SMULFIX; 5789 case Intrinsic::umul_fix: 5790 return ISD::UMULFIX; 5791 case Intrinsic::smul_fix_sat: 5792 return ISD::SMULFIXSAT; 5793 case Intrinsic::umul_fix_sat: 5794 return ISD::UMULFIXSAT; 5795 case Intrinsic::sdiv_fix: 5796 return ISD::SDIVFIX; 5797 case Intrinsic::udiv_fix: 5798 return ISD::UDIVFIX; 5799 case Intrinsic::sdiv_fix_sat: 5800 return ISD::SDIVFIXSAT; 5801 case Intrinsic::udiv_fix_sat: 5802 return ISD::UDIVFIXSAT; 5803 default: 5804 llvm_unreachable("Unhandled fixed point intrinsic"); 5805 } 5806 } 5807 5808 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5809 const char *FunctionName) { 5810 assert(FunctionName && "FunctionName must not be nullptr"); 5811 SDValue Callee = DAG.getExternalSymbol( 5812 FunctionName, 5813 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5814 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5815 } 5816 5817 /// Given a @llvm.call.preallocated.setup, return the corresponding 5818 /// preallocated call. 5819 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5820 assert(cast<CallBase>(PreallocatedSetup) 5821 ->getCalledFunction() 5822 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5823 "expected call_preallocated_setup Value"); 5824 for (const auto *U : PreallocatedSetup->users()) { 5825 auto *UseCall = cast<CallBase>(U); 5826 const Function *Fn = UseCall->getCalledFunction(); 5827 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5828 return UseCall; 5829 } 5830 } 5831 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5832 } 5833 5834 /// Lower the call to the specified intrinsic function. 5835 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5836 unsigned Intrinsic) { 5837 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5838 SDLoc sdl = getCurSDLoc(); 5839 DebugLoc dl = getCurDebugLoc(); 5840 SDValue Res; 5841 5842 SDNodeFlags Flags; 5843 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5844 Flags.copyFMF(*FPOp); 5845 5846 switch (Intrinsic) { 5847 default: 5848 // By default, turn this into a target intrinsic node. 5849 visitTargetIntrinsic(I, Intrinsic); 5850 return; 5851 case Intrinsic::vscale: { 5852 match(&I, m_VScale(DAG.getDataLayout())); 5853 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5854 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5855 return; 5856 } 5857 case Intrinsic::vastart: visitVAStart(I); return; 5858 case Intrinsic::vaend: visitVAEnd(I); return; 5859 case Intrinsic::vacopy: visitVACopy(I); return; 5860 case Intrinsic::returnaddress: 5861 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5862 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5863 getValue(I.getArgOperand(0)))); 5864 return; 5865 case Intrinsic::addressofreturnaddress: 5866 setValue(&I, 5867 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5868 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5869 return; 5870 case Intrinsic::sponentry: 5871 setValue(&I, 5872 DAG.getNode(ISD::SPONENTRY, sdl, 5873 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5874 return; 5875 case Intrinsic::frameaddress: 5876 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5877 TLI.getFrameIndexTy(DAG.getDataLayout()), 5878 getValue(I.getArgOperand(0)))); 5879 return; 5880 case Intrinsic::read_volatile_register: 5881 case Intrinsic::read_register: { 5882 Value *Reg = I.getArgOperand(0); 5883 SDValue Chain = getRoot(); 5884 SDValue RegName = 5885 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5886 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5887 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5888 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5889 setValue(&I, Res); 5890 DAG.setRoot(Res.getValue(1)); 5891 return; 5892 } 5893 case Intrinsic::write_register: { 5894 Value *Reg = I.getArgOperand(0); 5895 Value *RegValue = I.getArgOperand(1); 5896 SDValue Chain = getRoot(); 5897 SDValue RegName = 5898 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5899 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5900 RegName, getValue(RegValue))); 5901 return; 5902 } 5903 case Intrinsic::memcpy: { 5904 const auto &MCI = cast<MemCpyInst>(I); 5905 SDValue Op1 = getValue(I.getArgOperand(0)); 5906 SDValue Op2 = getValue(I.getArgOperand(1)); 5907 SDValue Op3 = getValue(I.getArgOperand(2)); 5908 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5909 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5910 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5911 Align Alignment = std::min(DstAlign, SrcAlign); 5912 bool isVol = MCI.isVolatile(); 5913 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5914 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5915 // node. 5916 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5917 SDValue MC = DAG.getMemcpy( 5918 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5919 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 5920 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5921 updateDAGForMaybeTailCall(MC); 5922 return; 5923 } 5924 case Intrinsic::memcpy_inline: { 5925 const auto &MCI = cast<MemCpyInlineInst>(I); 5926 SDValue Dst = getValue(I.getArgOperand(0)); 5927 SDValue Src = getValue(I.getArgOperand(1)); 5928 SDValue Size = getValue(I.getArgOperand(2)); 5929 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5930 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5931 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5932 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5933 Align Alignment = std::min(DstAlign, SrcAlign); 5934 bool isVol = MCI.isVolatile(); 5935 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5936 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5937 // node. 5938 SDValue MC = DAG.getMemcpy( 5939 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5940 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5941 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5942 updateDAGForMaybeTailCall(MC); 5943 return; 5944 } 5945 case Intrinsic::memset: { 5946 const auto &MSI = cast<MemSetInst>(I); 5947 SDValue Op1 = getValue(I.getArgOperand(0)); 5948 SDValue Op2 = getValue(I.getArgOperand(1)); 5949 SDValue Op3 = getValue(I.getArgOperand(2)); 5950 // @llvm.memset defines 0 and 1 to both mean no alignment. 5951 Align Alignment = MSI.getDestAlign().valueOrOne(); 5952 bool isVol = MSI.isVolatile(); 5953 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5954 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5955 SDValue MS = DAG.getMemset( 5956 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 5957 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 5958 updateDAGForMaybeTailCall(MS); 5959 return; 5960 } 5961 case Intrinsic::memset_inline: { 5962 const auto &MSII = cast<MemSetInlineInst>(I); 5963 SDValue Dst = getValue(I.getArgOperand(0)); 5964 SDValue Value = getValue(I.getArgOperand(1)); 5965 SDValue Size = getValue(I.getArgOperand(2)); 5966 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 5967 // @llvm.memset defines 0 and 1 to both mean no alignment. 5968 Align DstAlign = MSII.getDestAlign().valueOrOne(); 5969 bool isVol = MSII.isVolatile(); 5970 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5971 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5972 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 5973 /* AlwaysInline */ true, isTC, 5974 MachinePointerInfo(I.getArgOperand(0)), 5975 I.getAAMetadata()); 5976 updateDAGForMaybeTailCall(MC); 5977 return; 5978 } 5979 case Intrinsic::memmove: { 5980 const auto &MMI = cast<MemMoveInst>(I); 5981 SDValue Op1 = getValue(I.getArgOperand(0)); 5982 SDValue Op2 = getValue(I.getArgOperand(1)); 5983 SDValue Op3 = getValue(I.getArgOperand(2)); 5984 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5985 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5986 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5987 Align Alignment = std::min(DstAlign, SrcAlign); 5988 bool isVol = MMI.isVolatile(); 5989 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5990 // FIXME: Support passing different dest/src alignments to the memmove DAG 5991 // node. 5992 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5993 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5994 isTC, MachinePointerInfo(I.getArgOperand(0)), 5995 MachinePointerInfo(I.getArgOperand(1)), 5996 I.getAAMetadata(), AA); 5997 updateDAGForMaybeTailCall(MM); 5998 return; 5999 } 6000 case Intrinsic::memcpy_element_unordered_atomic: { 6001 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6002 SDValue Dst = getValue(MI.getRawDest()); 6003 SDValue Src = getValue(MI.getRawSource()); 6004 SDValue Length = getValue(MI.getLength()); 6005 6006 Type *LengthTy = MI.getLength()->getType(); 6007 unsigned ElemSz = MI.getElementSizeInBytes(); 6008 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6009 SDValue MC = 6010 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6011 isTC, MachinePointerInfo(MI.getRawDest()), 6012 MachinePointerInfo(MI.getRawSource())); 6013 updateDAGForMaybeTailCall(MC); 6014 return; 6015 } 6016 case Intrinsic::memmove_element_unordered_atomic: { 6017 auto &MI = cast<AtomicMemMoveInst>(I); 6018 SDValue Dst = getValue(MI.getRawDest()); 6019 SDValue Src = getValue(MI.getRawSource()); 6020 SDValue Length = getValue(MI.getLength()); 6021 6022 Type *LengthTy = MI.getLength()->getType(); 6023 unsigned ElemSz = MI.getElementSizeInBytes(); 6024 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6025 SDValue MC = 6026 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6027 isTC, MachinePointerInfo(MI.getRawDest()), 6028 MachinePointerInfo(MI.getRawSource())); 6029 updateDAGForMaybeTailCall(MC); 6030 return; 6031 } 6032 case Intrinsic::memset_element_unordered_atomic: { 6033 auto &MI = cast<AtomicMemSetInst>(I); 6034 SDValue Dst = getValue(MI.getRawDest()); 6035 SDValue Val = getValue(MI.getValue()); 6036 SDValue Length = getValue(MI.getLength()); 6037 6038 Type *LengthTy = MI.getLength()->getType(); 6039 unsigned ElemSz = MI.getElementSizeInBytes(); 6040 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6041 SDValue MC = 6042 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6043 isTC, MachinePointerInfo(MI.getRawDest())); 6044 updateDAGForMaybeTailCall(MC); 6045 return; 6046 } 6047 case Intrinsic::call_preallocated_setup: { 6048 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6049 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6050 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6051 getRoot(), SrcValue); 6052 setValue(&I, Res); 6053 DAG.setRoot(Res); 6054 return; 6055 } 6056 case Intrinsic::call_preallocated_arg: { 6057 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6058 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6059 SDValue Ops[3]; 6060 Ops[0] = getRoot(); 6061 Ops[1] = SrcValue; 6062 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6063 MVT::i32); // arg index 6064 SDValue Res = DAG.getNode( 6065 ISD::PREALLOCATED_ARG, sdl, 6066 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6067 setValue(&I, Res); 6068 DAG.setRoot(Res.getValue(1)); 6069 return; 6070 } 6071 case Intrinsic::dbg_addr: 6072 case Intrinsic::dbg_declare: { 6073 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6074 // they are non-variadic. 6075 const auto &DI = cast<DbgVariableIntrinsic>(I); 6076 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6077 DILocalVariable *Variable = DI.getVariable(); 6078 DIExpression *Expression = DI.getExpression(); 6079 dropDanglingDebugInfo(Variable, Expression); 6080 assert(Variable && "Missing variable"); 6081 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6082 << "\n"); 6083 // Check if address has undef value. 6084 const Value *Address = DI.getVariableLocationOp(0); 6085 if (!Address || isa<UndefValue>(Address) || 6086 (Address->use_empty() && !isa<Argument>(Address))) { 6087 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6088 << " (bad/undef/unused-arg address)\n"); 6089 return; 6090 } 6091 6092 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6093 6094 // Check if this variable can be described by a frame index, typically 6095 // either as a static alloca or a byval parameter. 6096 int FI = std::numeric_limits<int>::max(); 6097 if (const auto *AI = 6098 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6099 if (AI->isStaticAlloca()) { 6100 auto I = FuncInfo.StaticAllocaMap.find(AI); 6101 if (I != FuncInfo.StaticAllocaMap.end()) 6102 FI = I->second; 6103 } 6104 } else if (const auto *Arg = dyn_cast<Argument>( 6105 Address->stripInBoundsConstantOffsets())) { 6106 FI = FuncInfo.getArgumentFrameIndex(Arg); 6107 } 6108 6109 // llvm.dbg.addr is control dependent and always generates indirect 6110 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6111 // the MachineFunction variable table. 6112 if (FI != std::numeric_limits<int>::max()) { 6113 if (Intrinsic == Intrinsic::dbg_addr) { 6114 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6115 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6116 dl, SDNodeOrder); 6117 DAG.AddDbgValue(SDV, isParameter); 6118 } else { 6119 LLVM_DEBUG(dbgs() << "Skipping " << DI 6120 << " (variable info stashed in MF side table)\n"); 6121 } 6122 return; 6123 } 6124 6125 SDValue &N = NodeMap[Address]; 6126 if (!N.getNode() && isa<Argument>(Address)) 6127 // Check unused arguments map. 6128 N = UnusedArgNodeMap[Address]; 6129 SDDbgValue *SDV; 6130 if (N.getNode()) { 6131 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6132 Address = BCI->getOperand(0); 6133 // Parameters are handled specially. 6134 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6135 if (isParameter && FINode) { 6136 // Byval parameter. We have a frame index at this point. 6137 SDV = 6138 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6139 /*IsIndirect*/ true, dl, SDNodeOrder); 6140 } else if (isa<Argument>(Address)) { 6141 // Address is an argument, so try to emit its dbg value using 6142 // virtual register info from the FuncInfo.ValueMap. 6143 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6144 FuncArgumentDbgValueKind::Declare, N); 6145 return; 6146 } else { 6147 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6148 true, dl, SDNodeOrder); 6149 } 6150 DAG.AddDbgValue(SDV, isParameter); 6151 } else { 6152 // If Address is an argument then try to emit its dbg value using 6153 // virtual register info from the FuncInfo.ValueMap. 6154 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6155 FuncArgumentDbgValueKind::Declare, N)) { 6156 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6157 << " (could not emit func-arg dbg_value)\n"); 6158 } 6159 } 6160 return; 6161 } 6162 case Intrinsic::dbg_label: { 6163 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6164 DILabel *Label = DI.getLabel(); 6165 assert(Label && "Missing label"); 6166 6167 SDDbgLabel *SDV; 6168 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6169 DAG.AddDbgLabel(SDV); 6170 return; 6171 } 6172 case Intrinsic::dbg_value: { 6173 const DbgValueInst &DI = cast<DbgValueInst>(I); 6174 assert(DI.getVariable() && "Missing variable"); 6175 6176 DILocalVariable *Variable = DI.getVariable(); 6177 DIExpression *Expression = DI.getExpression(); 6178 dropDanglingDebugInfo(Variable, Expression); 6179 SmallVector<Value *, 4> Values(DI.getValues()); 6180 if (Values.empty()) 6181 return; 6182 6183 if (llvm::is_contained(Values, nullptr)) 6184 return; 6185 6186 bool IsVariadic = DI.hasArgList(); 6187 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6188 SDNodeOrder, IsVariadic)) 6189 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6190 return; 6191 } 6192 6193 case Intrinsic::eh_typeid_for: { 6194 // Find the type id for the given typeinfo. 6195 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6196 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6197 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6198 setValue(&I, Res); 6199 return; 6200 } 6201 6202 case Intrinsic::eh_return_i32: 6203 case Intrinsic::eh_return_i64: 6204 DAG.getMachineFunction().setCallsEHReturn(true); 6205 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6206 MVT::Other, 6207 getControlRoot(), 6208 getValue(I.getArgOperand(0)), 6209 getValue(I.getArgOperand(1)))); 6210 return; 6211 case Intrinsic::eh_unwind_init: 6212 DAG.getMachineFunction().setCallsUnwindInit(true); 6213 return; 6214 case Intrinsic::eh_dwarf_cfa: 6215 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6216 TLI.getPointerTy(DAG.getDataLayout()), 6217 getValue(I.getArgOperand(0)))); 6218 return; 6219 case Intrinsic::eh_sjlj_callsite: { 6220 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6221 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6222 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6223 6224 MMI.setCurrentCallSite(CI->getZExtValue()); 6225 return; 6226 } 6227 case Intrinsic::eh_sjlj_functioncontext: { 6228 // Get and store the index of the function context. 6229 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6230 AllocaInst *FnCtx = 6231 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6232 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6233 MFI.setFunctionContextIndex(FI); 6234 return; 6235 } 6236 case Intrinsic::eh_sjlj_setjmp: { 6237 SDValue Ops[2]; 6238 Ops[0] = getRoot(); 6239 Ops[1] = getValue(I.getArgOperand(0)); 6240 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6241 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6242 setValue(&I, Op.getValue(0)); 6243 DAG.setRoot(Op.getValue(1)); 6244 return; 6245 } 6246 case Intrinsic::eh_sjlj_longjmp: 6247 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6248 getRoot(), getValue(I.getArgOperand(0)))); 6249 return; 6250 case Intrinsic::eh_sjlj_setup_dispatch: 6251 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6252 getRoot())); 6253 return; 6254 case Intrinsic::masked_gather: 6255 visitMaskedGather(I); 6256 return; 6257 case Intrinsic::masked_load: 6258 visitMaskedLoad(I); 6259 return; 6260 case Intrinsic::masked_scatter: 6261 visitMaskedScatter(I); 6262 return; 6263 case Intrinsic::masked_store: 6264 visitMaskedStore(I); 6265 return; 6266 case Intrinsic::masked_expandload: 6267 visitMaskedLoad(I, true /* IsExpanding */); 6268 return; 6269 case Intrinsic::masked_compressstore: 6270 visitMaskedStore(I, true /* IsCompressing */); 6271 return; 6272 case Intrinsic::powi: 6273 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6274 getValue(I.getArgOperand(1)), DAG)); 6275 return; 6276 case Intrinsic::log: 6277 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6278 return; 6279 case Intrinsic::log2: 6280 setValue(&I, 6281 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6282 return; 6283 case Intrinsic::log10: 6284 setValue(&I, 6285 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6286 return; 6287 case Intrinsic::exp: 6288 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6289 return; 6290 case Intrinsic::exp2: 6291 setValue(&I, 6292 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6293 return; 6294 case Intrinsic::pow: 6295 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6296 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6297 return; 6298 case Intrinsic::sqrt: 6299 case Intrinsic::fabs: 6300 case Intrinsic::sin: 6301 case Intrinsic::cos: 6302 case Intrinsic::floor: 6303 case Intrinsic::ceil: 6304 case Intrinsic::trunc: 6305 case Intrinsic::rint: 6306 case Intrinsic::nearbyint: 6307 case Intrinsic::round: 6308 case Intrinsic::roundeven: 6309 case Intrinsic::canonicalize: { 6310 unsigned Opcode; 6311 switch (Intrinsic) { 6312 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6313 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6314 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6315 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6316 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6317 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6318 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6319 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6320 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6321 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6322 case Intrinsic::round: Opcode = ISD::FROUND; break; 6323 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6324 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6325 } 6326 6327 setValue(&I, DAG.getNode(Opcode, sdl, 6328 getValue(I.getArgOperand(0)).getValueType(), 6329 getValue(I.getArgOperand(0)), Flags)); 6330 return; 6331 } 6332 case Intrinsic::lround: 6333 case Intrinsic::llround: 6334 case Intrinsic::lrint: 6335 case Intrinsic::llrint: { 6336 unsigned Opcode; 6337 switch (Intrinsic) { 6338 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6339 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6340 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6341 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6342 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6343 } 6344 6345 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6346 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6347 getValue(I.getArgOperand(0)))); 6348 return; 6349 } 6350 case Intrinsic::minnum: 6351 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6352 getValue(I.getArgOperand(0)).getValueType(), 6353 getValue(I.getArgOperand(0)), 6354 getValue(I.getArgOperand(1)), Flags)); 6355 return; 6356 case Intrinsic::maxnum: 6357 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6358 getValue(I.getArgOperand(0)).getValueType(), 6359 getValue(I.getArgOperand(0)), 6360 getValue(I.getArgOperand(1)), Flags)); 6361 return; 6362 case Intrinsic::minimum: 6363 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6364 getValue(I.getArgOperand(0)).getValueType(), 6365 getValue(I.getArgOperand(0)), 6366 getValue(I.getArgOperand(1)), Flags)); 6367 return; 6368 case Intrinsic::maximum: 6369 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6370 getValue(I.getArgOperand(0)).getValueType(), 6371 getValue(I.getArgOperand(0)), 6372 getValue(I.getArgOperand(1)), Flags)); 6373 return; 6374 case Intrinsic::copysign: 6375 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6376 getValue(I.getArgOperand(0)).getValueType(), 6377 getValue(I.getArgOperand(0)), 6378 getValue(I.getArgOperand(1)), Flags)); 6379 return; 6380 case Intrinsic::arithmetic_fence: { 6381 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6382 getValue(I.getArgOperand(0)).getValueType(), 6383 getValue(I.getArgOperand(0)), Flags)); 6384 return; 6385 } 6386 case Intrinsic::fma: 6387 setValue(&I, DAG.getNode( 6388 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6389 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6390 getValue(I.getArgOperand(2)), Flags)); 6391 return; 6392 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6393 case Intrinsic::INTRINSIC: 6394 #include "llvm/IR/ConstrainedOps.def" 6395 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6396 return; 6397 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6398 #include "llvm/IR/VPIntrinsics.def" 6399 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6400 return; 6401 case Intrinsic::fptrunc_round: { 6402 // Get the last argument, the metadata and convert it to an integer in the 6403 // call 6404 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6405 Optional<RoundingMode> RoundMode = 6406 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6407 6408 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6409 6410 // Propagate fast-math-flags from IR to node(s). 6411 SDNodeFlags Flags; 6412 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6413 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6414 6415 SDValue Result; 6416 Result = DAG.getNode( 6417 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6418 DAG.getTargetConstant((int)*RoundMode, sdl, 6419 TLI.getPointerTy(DAG.getDataLayout()))); 6420 setValue(&I, Result); 6421 6422 return; 6423 } 6424 case Intrinsic::fmuladd: { 6425 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6426 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6427 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6428 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6429 getValue(I.getArgOperand(0)).getValueType(), 6430 getValue(I.getArgOperand(0)), 6431 getValue(I.getArgOperand(1)), 6432 getValue(I.getArgOperand(2)), Flags)); 6433 } else { 6434 // TODO: Intrinsic calls should have fast-math-flags. 6435 SDValue Mul = DAG.getNode( 6436 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6437 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6438 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6439 getValue(I.getArgOperand(0)).getValueType(), 6440 Mul, getValue(I.getArgOperand(2)), Flags); 6441 setValue(&I, Add); 6442 } 6443 return; 6444 } 6445 case Intrinsic::convert_to_fp16: 6446 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6447 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6448 getValue(I.getArgOperand(0)), 6449 DAG.getTargetConstant(0, sdl, 6450 MVT::i32)))); 6451 return; 6452 case Intrinsic::convert_from_fp16: 6453 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6454 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6455 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6456 getValue(I.getArgOperand(0))))); 6457 return; 6458 case Intrinsic::fptosi_sat: { 6459 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6460 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6461 getValue(I.getArgOperand(0)), 6462 DAG.getValueType(VT.getScalarType()))); 6463 return; 6464 } 6465 case Intrinsic::fptoui_sat: { 6466 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6467 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6468 getValue(I.getArgOperand(0)), 6469 DAG.getValueType(VT.getScalarType()))); 6470 return; 6471 } 6472 case Intrinsic::set_rounding: 6473 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6474 {getRoot(), getValue(I.getArgOperand(0))}); 6475 setValue(&I, Res); 6476 DAG.setRoot(Res.getValue(0)); 6477 return; 6478 case Intrinsic::is_fpclass: { 6479 const DataLayout DLayout = DAG.getDataLayout(); 6480 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6481 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6482 unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6483 MachineFunction &MF = DAG.getMachineFunction(); 6484 const Function &F = MF.getFunction(); 6485 SDValue Op = getValue(I.getArgOperand(0)); 6486 SDNodeFlags Flags; 6487 Flags.setNoFPExcept( 6488 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6489 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6490 // expansion can use illegal types. Making expansion early allows 6491 // legalizing these types prior to selection. 6492 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6493 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6494 setValue(&I, Result); 6495 return; 6496 } 6497 6498 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6499 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6500 setValue(&I, V); 6501 return; 6502 } 6503 case Intrinsic::pcmarker: { 6504 SDValue Tmp = getValue(I.getArgOperand(0)); 6505 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6506 return; 6507 } 6508 case Intrinsic::readcyclecounter: { 6509 SDValue Op = getRoot(); 6510 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6511 DAG.getVTList(MVT::i64, MVT::Other), Op); 6512 setValue(&I, Res); 6513 DAG.setRoot(Res.getValue(1)); 6514 return; 6515 } 6516 case Intrinsic::bitreverse: 6517 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6518 getValue(I.getArgOperand(0)).getValueType(), 6519 getValue(I.getArgOperand(0)))); 6520 return; 6521 case Intrinsic::bswap: 6522 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6523 getValue(I.getArgOperand(0)).getValueType(), 6524 getValue(I.getArgOperand(0)))); 6525 return; 6526 case Intrinsic::cttz: { 6527 SDValue Arg = getValue(I.getArgOperand(0)); 6528 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6529 EVT Ty = Arg.getValueType(); 6530 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6531 sdl, Ty, Arg)); 6532 return; 6533 } 6534 case Intrinsic::ctlz: { 6535 SDValue Arg = getValue(I.getArgOperand(0)); 6536 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6537 EVT Ty = Arg.getValueType(); 6538 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6539 sdl, Ty, Arg)); 6540 return; 6541 } 6542 case Intrinsic::ctpop: { 6543 SDValue Arg = getValue(I.getArgOperand(0)); 6544 EVT Ty = Arg.getValueType(); 6545 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6546 return; 6547 } 6548 case Intrinsic::fshl: 6549 case Intrinsic::fshr: { 6550 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6551 SDValue X = getValue(I.getArgOperand(0)); 6552 SDValue Y = getValue(I.getArgOperand(1)); 6553 SDValue Z = getValue(I.getArgOperand(2)); 6554 EVT VT = X.getValueType(); 6555 6556 if (X == Y) { 6557 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6558 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6559 } else { 6560 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6561 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6562 } 6563 return; 6564 } 6565 case Intrinsic::sadd_sat: { 6566 SDValue Op1 = getValue(I.getArgOperand(0)); 6567 SDValue Op2 = getValue(I.getArgOperand(1)); 6568 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6569 return; 6570 } 6571 case Intrinsic::uadd_sat: { 6572 SDValue Op1 = getValue(I.getArgOperand(0)); 6573 SDValue Op2 = getValue(I.getArgOperand(1)); 6574 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6575 return; 6576 } 6577 case Intrinsic::ssub_sat: { 6578 SDValue Op1 = getValue(I.getArgOperand(0)); 6579 SDValue Op2 = getValue(I.getArgOperand(1)); 6580 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6581 return; 6582 } 6583 case Intrinsic::usub_sat: { 6584 SDValue Op1 = getValue(I.getArgOperand(0)); 6585 SDValue Op2 = getValue(I.getArgOperand(1)); 6586 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6587 return; 6588 } 6589 case Intrinsic::sshl_sat: { 6590 SDValue Op1 = getValue(I.getArgOperand(0)); 6591 SDValue Op2 = getValue(I.getArgOperand(1)); 6592 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6593 return; 6594 } 6595 case Intrinsic::ushl_sat: { 6596 SDValue Op1 = getValue(I.getArgOperand(0)); 6597 SDValue Op2 = getValue(I.getArgOperand(1)); 6598 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6599 return; 6600 } 6601 case Intrinsic::smul_fix: 6602 case Intrinsic::umul_fix: 6603 case Intrinsic::smul_fix_sat: 6604 case Intrinsic::umul_fix_sat: { 6605 SDValue Op1 = getValue(I.getArgOperand(0)); 6606 SDValue Op2 = getValue(I.getArgOperand(1)); 6607 SDValue Op3 = getValue(I.getArgOperand(2)); 6608 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6609 Op1.getValueType(), Op1, Op2, Op3)); 6610 return; 6611 } 6612 case Intrinsic::sdiv_fix: 6613 case Intrinsic::udiv_fix: 6614 case Intrinsic::sdiv_fix_sat: 6615 case Intrinsic::udiv_fix_sat: { 6616 SDValue Op1 = getValue(I.getArgOperand(0)); 6617 SDValue Op2 = getValue(I.getArgOperand(1)); 6618 SDValue Op3 = getValue(I.getArgOperand(2)); 6619 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6620 Op1, Op2, Op3, DAG, TLI)); 6621 return; 6622 } 6623 case Intrinsic::smax: { 6624 SDValue Op1 = getValue(I.getArgOperand(0)); 6625 SDValue Op2 = getValue(I.getArgOperand(1)); 6626 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6627 return; 6628 } 6629 case Intrinsic::smin: { 6630 SDValue Op1 = getValue(I.getArgOperand(0)); 6631 SDValue Op2 = getValue(I.getArgOperand(1)); 6632 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6633 return; 6634 } 6635 case Intrinsic::umax: { 6636 SDValue Op1 = getValue(I.getArgOperand(0)); 6637 SDValue Op2 = getValue(I.getArgOperand(1)); 6638 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6639 return; 6640 } 6641 case Intrinsic::umin: { 6642 SDValue Op1 = getValue(I.getArgOperand(0)); 6643 SDValue Op2 = getValue(I.getArgOperand(1)); 6644 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6645 return; 6646 } 6647 case Intrinsic::abs: { 6648 // TODO: Preserve "int min is poison" arg in SDAG? 6649 SDValue Op1 = getValue(I.getArgOperand(0)); 6650 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6651 return; 6652 } 6653 case Intrinsic::stacksave: { 6654 SDValue Op = getRoot(); 6655 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6656 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6657 setValue(&I, Res); 6658 DAG.setRoot(Res.getValue(1)); 6659 return; 6660 } 6661 case Intrinsic::stackrestore: 6662 Res = getValue(I.getArgOperand(0)); 6663 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6664 return; 6665 case Intrinsic::get_dynamic_area_offset: { 6666 SDValue Op = getRoot(); 6667 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6668 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6669 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6670 // target. 6671 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6672 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6673 " intrinsic!"); 6674 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6675 Op); 6676 DAG.setRoot(Op); 6677 setValue(&I, Res); 6678 return; 6679 } 6680 case Intrinsic::stackguard: { 6681 MachineFunction &MF = DAG.getMachineFunction(); 6682 const Module &M = *MF.getFunction().getParent(); 6683 SDValue Chain = getRoot(); 6684 if (TLI.useLoadStackGuardNode()) { 6685 Res = getLoadStackGuard(DAG, sdl, Chain); 6686 } else { 6687 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6688 const Value *Global = TLI.getSDagStackGuard(M); 6689 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6690 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6691 MachinePointerInfo(Global, 0), Align, 6692 MachineMemOperand::MOVolatile); 6693 } 6694 if (TLI.useStackGuardXorFP()) 6695 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6696 DAG.setRoot(Chain); 6697 setValue(&I, Res); 6698 return; 6699 } 6700 case Intrinsic::stackprotector: { 6701 // Emit code into the DAG to store the stack guard onto the stack. 6702 MachineFunction &MF = DAG.getMachineFunction(); 6703 MachineFrameInfo &MFI = MF.getFrameInfo(); 6704 SDValue Src, Chain = getRoot(); 6705 6706 if (TLI.useLoadStackGuardNode()) 6707 Src = getLoadStackGuard(DAG, sdl, Chain); 6708 else 6709 Src = getValue(I.getArgOperand(0)); // The guard's value. 6710 6711 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6712 6713 int FI = FuncInfo.StaticAllocaMap[Slot]; 6714 MFI.setStackProtectorIndex(FI); 6715 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6716 6717 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6718 6719 // Store the stack protector onto the stack. 6720 Res = DAG.getStore( 6721 Chain, sdl, Src, FIN, 6722 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6723 MaybeAlign(), MachineMemOperand::MOVolatile); 6724 setValue(&I, Res); 6725 DAG.setRoot(Res); 6726 return; 6727 } 6728 case Intrinsic::objectsize: 6729 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6730 6731 case Intrinsic::is_constant: 6732 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6733 6734 case Intrinsic::annotation: 6735 case Intrinsic::ptr_annotation: 6736 case Intrinsic::launder_invariant_group: 6737 case Intrinsic::strip_invariant_group: 6738 // Drop the intrinsic, but forward the value 6739 setValue(&I, getValue(I.getOperand(0))); 6740 return; 6741 6742 case Intrinsic::assume: 6743 case Intrinsic::experimental_noalias_scope_decl: 6744 case Intrinsic::var_annotation: 6745 case Intrinsic::sideeffect: 6746 // Discard annotate attributes, noalias scope declarations, assumptions, and 6747 // artificial side-effects. 6748 return; 6749 6750 case Intrinsic::codeview_annotation: { 6751 // Emit a label associated with this metadata. 6752 MachineFunction &MF = DAG.getMachineFunction(); 6753 MCSymbol *Label = 6754 MF.getMMI().getContext().createTempSymbol("annotation", true); 6755 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6756 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6757 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6758 DAG.setRoot(Res); 6759 return; 6760 } 6761 6762 case Intrinsic::init_trampoline: { 6763 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6764 6765 SDValue Ops[6]; 6766 Ops[0] = getRoot(); 6767 Ops[1] = getValue(I.getArgOperand(0)); 6768 Ops[2] = getValue(I.getArgOperand(1)); 6769 Ops[3] = getValue(I.getArgOperand(2)); 6770 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6771 Ops[5] = DAG.getSrcValue(F); 6772 6773 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6774 6775 DAG.setRoot(Res); 6776 return; 6777 } 6778 case Intrinsic::adjust_trampoline: 6779 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6780 TLI.getPointerTy(DAG.getDataLayout()), 6781 getValue(I.getArgOperand(0)))); 6782 return; 6783 case Intrinsic::gcroot: { 6784 assert(DAG.getMachineFunction().getFunction().hasGC() && 6785 "only valid in functions with gc specified, enforced by Verifier"); 6786 assert(GFI && "implied by previous"); 6787 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6788 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6789 6790 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6791 GFI->addStackRoot(FI->getIndex(), TypeMap); 6792 return; 6793 } 6794 case Intrinsic::gcread: 6795 case Intrinsic::gcwrite: 6796 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6797 case Intrinsic::flt_rounds: 6798 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6799 setValue(&I, Res); 6800 DAG.setRoot(Res.getValue(1)); 6801 return; 6802 6803 case Intrinsic::expect: 6804 // Just replace __builtin_expect(exp, c) with EXP. 6805 setValue(&I, getValue(I.getArgOperand(0))); 6806 return; 6807 6808 case Intrinsic::ubsantrap: 6809 case Intrinsic::debugtrap: 6810 case Intrinsic::trap: { 6811 StringRef TrapFuncName = 6812 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6813 if (TrapFuncName.empty()) { 6814 switch (Intrinsic) { 6815 case Intrinsic::trap: 6816 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6817 break; 6818 case Intrinsic::debugtrap: 6819 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6820 break; 6821 case Intrinsic::ubsantrap: 6822 DAG.setRoot(DAG.getNode( 6823 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6824 DAG.getTargetConstant( 6825 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6826 MVT::i32))); 6827 break; 6828 default: llvm_unreachable("unknown trap intrinsic"); 6829 } 6830 return; 6831 } 6832 TargetLowering::ArgListTy Args; 6833 if (Intrinsic == Intrinsic::ubsantrap) { 6834 Args.push_back(TargetLoweringBase::ArgListEntry()); 6835 Args[0].Val = I.getArgOperand(0); 6836 Args[0].Node = getValue(Args[0].Val); 6837 Args[0].Ty = Args[0].Val->getType(); 6838 } 6839 6840 TargetLowering::CallLoweringInfo CLI(DAG); 6841 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6842 CallingConv::C, I.getType(), 6843 DAG.getExternalSymbol(TrapFuncName.data(), 6844 TLI.getPointerTy(DAG.getDataLayout())), 6845 std::move(Args)); 6846 6847 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6848 DAG.setRoot(Result.second); 6849 return; 6850 } 6851 6852 case Intrinsic::uadd_with_overflow: 6853 case Intrinsic::sadd_with_overflow: 6854 case Intrinsic::usub_with_overflow: 6855 case Intrinsic::ssub_with_overflow: 6856 case Intrinsic::umul_with_overflow: 6857 case Intrinsic::smul_with_overflow: { 6858 ISD::NodeType Op; 6859 switch (Intrinsic) { 6860 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6861 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6862 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6863 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6864 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6865 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6866 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6867 } 6868 SDValue Op1 = getValue(I.getArgOperand(0)); 6869 SDValue Op2 = getValue(I.getArgOperand(1)); 6870 6871 EVT ResultVT = Op1.getValueType(); 6872 EVT OverflowVT = MVT::i1; 6873 if (ResultVT.isVector()) 6874 OverflowVT = EVT::getVectorVT( 6875 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6876 6877 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6878 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6879 return; 6880 } 6881 case Intrinsic::prefetch: { 6882 SDValue Ops[5]; 6883 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6884 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6885 Ops[0] = DAG.getRoot(); 6886 Ops[1] = getValue(I.getArgOperand(0)); 6887 Ops[2] = getValue(I.getArgOperand(1)); 6888 Ops[3] = getValue(I.getArgOperand(2)); 6889 Ops[4] = getValue(I.getArgOperand(3)); 6890 SDValue Result = DAG.getMemIntrinsicNode( 6891 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6892 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6893 /* align */ None, Flags); 6894 6895 // Chain the prefetch in parallell with any pending loads, to stay out of 6896 // the way of later optimizations. 6897 PendingLoads.push_back(Result); 6898 Result = getRoot(); 6899 DAG.setRoot(Result); 6900 return; 6901 } 6902 case Intrinsic::lifetime_start: 6903 case Intrinsic::lifetime_end: { 6904 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6905 // Stack coloring is not enabled in O0, discard region information. 6906 if (TM.getOptLevel() == CodeGenOpt::None) 6907 return; 6908 6909 const int64_t ObjectSize = 6910 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6911 Value *const ObjectPtr = I.getArgOperand(1); 6912 SmallVector<const Value *, 4> Allocas; 6913 getUnderlyingObjects(ObjectPtr, Allocas); 6914 6915 for (const Value *Alloca : Allocas) { 6916 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6917 6918 // Could not find an Alloca. 6919 if (!LifetimeObject) 6920 continue; 6921 6922 // First check that the Alloca is static, otherwise it won't have a 6923 // valid frame index. 6924 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6925 if (SI == FuncInfo.StaticAllocaMap.end()) 6926 return; 6927 6928 const int FrameIndex = SI->second; 6929 int64_t Offset; 6930 if (GetPointerBaseWithConstantOffset( 6931 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6932 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6933 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6934 Offset); 6935 DAG.setRoot(Res); 6936 } 6937 return; 6938 } 6939 case Intrinsic::pseudoprobe: { 6940 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6941 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6942 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6943 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6944 DAG.setRoot(Res); 6945 return; 6946 } 6947 case Intrinsic::invariant_start: 6948 // Discard region information. 6949 setValue(&I, 6950 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6951 return; 6952 case Intrinsic::invariant_end: 6953 // Discard region information. 6954 return; 6955 case Intrinsic::clear_cache: 6956 /// FunctionName may be null. 6957 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6958 lowerCallToExternalSymbol(I, FunctionName); 6959 return; 6960 case Intrinsic::donothing: 6961 case Intrinsic::seh_try_begin: 6962 case Intrinsic::seh_scope_begin: 6963 case Intrinsic::seh_try_end: 6964 case Intrinsic::seh_scope_end: 6965 // ignore 6966 return; 6967 case Intrinsic::experimental_stackmap: 6968 visitStackmap(I); 6969 return; 6970 case Intrinsic::experimental_patchpoint_void: 6971 case Intrinsic::experimental_patchpoint_i64: 6972 visitPatchpoint(I); 6973 return; 6974 case Intrinsic::experimental_gc_statepoint: 6975 LowerStatepoint(cast<GCStatepointInst>(I)); 6976 return; 6977 case Intrinsic::experimental_gc_result: 6978 visitGCResult(cast<GCResultInst>(I)); 6979 return; 6980 case Intrinsic::experimental_gc_relocate: 6981 visitGCRelocate(cast<GCRelocateInst>(I)); 6982 return; 6983 case Intrinsic::instrprof_cover: 6984 llvm_unreachable("instrprof failed to lower a cover"); 6985 case Intrinsic::instrprof_increment: 6986 llvm_unreachable("instrprof failed to lower an increment"); 6987 case Intrinsic::instrprof_value_profile: 6988 llvm_unreachable("instrprof failed to lower a value profiling call"); 6989 case Intrinsic::localescape: { 6990 MachineFunction &MF = DAG.getMachineFunction(); 6991 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6992 6993 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6994 // is the same on all targets. 6995 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 6996 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6997 if (isa<ConstantPointerNull>(Arg)) 6998 continue; // Skip null pointers. They represent a hole in index space. 6999 AllocaInst *Slot = cast<AllocaInst>(Arg); 7000 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7001 "can only escape static allocas"); 7002 int FI = FuncInfo.StaticAllocaMap[Slot]; 7003 MCSymbol *FrameAllocSym = 7004 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7005 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7006 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7007 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7008 .addSym(FrameAllocSym) 7009 .addFrameIndex(FI); 7010 } 7011 7012 return; 7013 } 7014 7015 case Intrinsic::localrecover: { 7016 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7017 MachineFunction &MF = DAG.getMachineFunction(); 7018 7019 // Get the symbol that defines the frame offset. 7020 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7021 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7022 unsigned IdxVal = 7023 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7024 MCSymbol *FrameAllocSym = 7025 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7026 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7027 7028 Value *FP = I.getArgOperand(1); 7029 SDValue FPVal = getValue(FP); 7030 EVT PtrVT = FPVal.getValueType(); 7031 7032 // Create a MCSymbol for the label to avoid any target lowering 7033 // that would make this PC relative. 7034 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7035 SDValue OffsetVal = 7036 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7037 7038 // Add the offset to the FP. 7039 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7040 setValue(&I, Add); 7041 7042 return; 7043 } 7044 7045 case Intrinsic::eh_exceptionpointer: 7046 case Intrinsic::eh_exceptioncode: { 7047 // Get the exception pointer vreg, copy from it, and resize it to fit. 7048 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7049 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7050 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7051 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7052 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7053 if (Intrinsic == Intrinsic::eh_exceptioncode) 7054 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7055 setValue(&I, N); 7056 return; 7057 } 7058 case Intrinsic::xray_customevent: { 7059 // Here we want to make sure that the intrinsic behaves as if it has a 7060 // specific calling convention, and only for x86_64. 7061 // FIXME: Support other platforms later. 7062 const auto &Triple = DAG.getTarget().getTargetTriple(); 7063 if (Triple.getArch() != Triple::x86_64) 7064 return; 7065 7066 SmallVector<SDValue, 8> Ops; 7067 7068 // We want to say that we always want the arguments in registers. 7069 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7070 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7071 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7072 SDValue Chain = getRoot(); 7073 Ops.push_back(LogEntryVal); 7074 Ops.push_back(StrSizeVal); 7075 Ops.push_back(Chain); 7076 7077 // We need to enforce the calling convention for the callsite, so that 7078 // argument ordering is enforced correctly, and that register allocation can 7079 // see that some registers may be assumed clobbered and have to preserve 7080 // them across calls to the intrinsic. 7081 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7082 sdl, NodeTys, Ops); 7083 SDValue patchableNode = SDValue(MN, 0); 7084 DAG.setRoot(patchableNode); 7085 setValue(&I, patchableNode); 7086 return; 7087 } 7088 case Intrinsic::xray_typedevent: { 7089 // Here we want to make sure that the intrinsic behaves as if it has a 7090 // specific calling convention, and only for x86_64. 7091 // FIXME: Support other platforms later. 7092 const auto &Triple = DAG.getTarget().getTargetTriple(); 7093 if (Triple.getArch() != Triple::x86_64) 7094 return; 7095 7096 SmallVector<SDValue, 8> Ops; 7097 7098 // We want to say that we always want the arguments in registers. 7099 // It's unclear to me how manipulating the selection DAG here forces callers 7100 // to provide arguments in registers instead of on the stack. 7101 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7102 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7103 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7104 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7105 SDValue Chain = getRoot(); 7106 Ops.push_back(LogTypeId); 7107 Ops.push_back(LogEntryVal); 7108 Ops.push_back(StrSizeVal); 7109 Ops.push_back(Chain); 7110 7111 // We need to enforce the calling convention for the callsite, so that 7112 // argument ordering is enforced correctly, and that register allocation can 7113 // see that some registers may be assumed clobbered and have to preserve 7114 // them across calls to the intrinsic. 7115 MachineSDNode *MN = DAG.getMachineNode( 7116 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7117 SDValue patchableNode = SDValue(MN, 0); 7118 DAG.setRoot(patchableNode); 7119 setValue(&I, patchableNode); 7120 return; 7121 } 7122 case Intrinsic::experimental_deoptimize: 7123 LowerDeoptimizeCall(&I); 7124 return; 7125 case Intrinsic::experimental_stepvector: 7126 visitStepVector(I); 7127 return; 7128 case Intrinsic::vector_reduce_fadd: 7129 case Intrinsic::vector_reduce_fmul: 7130 case Intrinsic::vector_reduce_add: 7131 case Intrinsic::vector_reduce_mul: 7132 case Intrinsic::vector_reduce_and: 7133 case Intrinsic::vector_reduce_or: 7134 case Intrinsic::vector_reduce_xor: 7135 case Intrinsic::vector_reduce_smax: 7136 case Intrinsic::vector_reduce_smin: 7137 case Intrinsic::vector_reduce_umax: 7138 case Intrinsic::vector_reduce_umin: 7139 case Intrinsic::vector_reduce_fmax: 7140 case Intrinsic::vector_reduce_fmin: 7141 visitVectorReduce(I, Intrinsic); 7142 return; 7143 7144 case Intrinsic::icall_branch_funnel: { 7145 SmallVector<SDValue, 16> Ops; 7146 Ops.push_back(getValue(I.getArgOperand(0))); 7147 7148 int64_t Offset; 7149 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7150 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7151 if (!Base) 7152 report_fatal_error( 7153 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7154 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7155 7156 struct BranchFunnelTarget { 7157 int64_t Offset; 7158 SDValue Target; 7159 }; 7160 SmallVector<BranchFunnelTarget, 8> Targets; 7161 7162 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7163 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7164 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7165 if (ElemBase != Base) 7166 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7167 "to the same GlobalValue"); 7168 7169 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7170 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7171 if (!GA) 7172 report_fatal_error( 7173 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7174 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7175 GA->getGlobal(), sdl, Val.getValueType(), 7176 GA->getOffset())}); 7177 } 7178 llvm::sort(Targets, 7179 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7180 return T1.Offset < T2.Offset; 7181 }); 7182 7183 for (auto &T : Targets) { 7184 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7185 Ops.push_back(T.Target); 7186 } 7187 7188 Ops.push_back(DAG.getRoot()); // Chain 7189 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7190 MVT::Other, Ops), 7191 0); 7192 DAG.setRoot(N); 7193 setValue(&I, N); 7194 HasTailCall = true; 7195 return; 7196 } 7197 7198 case Intrinsic::wasm_landingpad_index: 7199 // Information this intrinsic contained has been transferred to 7200 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7201 // delete it now. 7202 return; 7203 7204 case Intrinsic::aarch64_settag: 7205 case Intrinsic::aarch64_settag_zero: { 7206 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7207 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7208 SDValue Val = TSI.EmitTargetCodeForSetTag( 7209 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7210 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7211 ZeroMemory); 7212 DAG.setRoot(Val); 7213 setValue(&I, Val); 7214 return; 7215 } 7216 case Intrinsic::ptrmask: { 7217 SDValue Ptr = getValue(I.getOperand(0)); 7218 SDValue Const = getValue(I.getOperand(1)); 7219 7220 EVT PtrVT = Ptr.getValueType(); 7221 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7222 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7223 return; 7224 } 7225 case Intrinsic::threadlocal_address: { 7226 setValue(&I, getValue(I.getOperand(0))); 7227 return; 7228 } 7229 case Intrinsic::get_active_lane_mask: { 7230 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7231 SDValue Index = getValue(I.getOperand(0)); 7232 EVT ElementVT = Index.getValueType(); 7233 7234 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7235 visitTargetIntrinsic(I, Intrinsic); 7236 return; 7237 } 7238 7239 SDValue TripCount = getValue(I.getOperand(1)); 7240 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7241 7242 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7243 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7244 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7245 SDValue VectorInduction = DAG.getNode( 7246 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7247 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7248 VectorTripCount, ISD::CondCode::SETULT); 7249 setValue(&I, SetCC); 7250 return; 7251 } 7252 case Intrinsic::vector_insert: { 7253 SDValue Vec = getValue(I.getOperand(0)); 7254 SDValue SubVec = getValue(I.getOperand(1)); 7255 SDValue Index = getValue(I.getOperand(2)); 7256 7257 // The intrinsic's index type is i64, but the SDNode requires an index type 7258 // suitable for the target. Convert the index as required. 7259 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7260 if (Index.getValueType() != VectorIdxTy) 7261 Index = DAG.getVectorIdxConstant( 7262 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7263 7264 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7265 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7266 Index)); 7267 return; 7268 } 7269 case Intrinsic::vector_extract: { 7270 SDValue Vec = getValue(I.getOperand(0)); 7271 SDValue Index = getValue(I.getOperand(1)); 7272 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7273 7274 // The intrinsic's index type is i64, but the SDNode requires an index type 7275 // suitable for the target. Convert the index as required. 7276 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7277 if (Index.getValueType() != VectorIdxTy) 7278 Index = DAG.getVectorIdxConstant( 7279 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7280 7281 setValue(&I, 7282 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7283 return; 7284 } 7285 case Intrinsic::experimental_vector_reverse: 7286 visitVectorReverse(I); 7287 return; 7288 case Intrinsic::experimental_vector_splice: 7289 visitVectorSplice(I); 7290 return; 7291 } 7292 } 7293 7294 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7295 const ConstrainedFPIntrinsic &FPI) { 7296 SDLoc sdl = getCurSDLoc(); 7297 7298 // We do not need to serialize constrained FP intrinsics against 7299 // each other or against (nonvolatile) loads, so they can be 7300 // chained like loads. 7301 SDValue Chain = DAG.getRoot(); 7302 SmallVector<SDValue, 4> Opers; 7303 Opers.push_back(Chain); 7304 if (FPI.isUnaryOp()) { 7305 Opers.push_back(getValue(FPI.getArgOperand(0))); 7306 } else if (FPI.isTernaryOp()) { 7307 Opers.push_back(getValue(FPI.getArgOperand(0))); 7308 Opers.push_back(getValue(FPI.getArgOperand(1))); 7309 Opers.push_back(getValue(FPI.getArgOperand(2))); 7310 } else { 7311 Opers.push_back(getValue(FPI.getArgOperand(0))); 7312 Opers.push_back(getValue(FPI.getArgOperand(1))); 7313 } 7314 7315 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7316 assert(Result.getNode()->getNumValues() == 2); 7317 7318 // Push node to the appropriate list so that future instructions can be 7319 // chained up correctly. 7320 SDValue OutChain = Result.getValue(1); 7321 switch (EB) { 7322 case fp::ExceptionBehavior::ebIgnore: 7323 // The only reason why ebIgnore nodes still need to be chained is that 7324 // they might depend on the current rounding mode, and therefore must 7325 // not be moved across instruction that may change that mode. 7326 [[fallthrough]]; 7327 case fp::ExceptionBehavior::ebMayTrap: 7328 // These must not be moved across calls or instructions that may change 7329 // floating-point exception masks. 7330 PendingConstrainedFP.push_back(OutChain); 7331 break; 7332 case fp::ExceptionBehavior::ebStrict: 7333 // These must not be moved across calls or instructions that may change 7334 // floating-point exception masks or read floating-point exception flags. 7335 // In addition, they cannot be optimized out even if unused. 7336 PendingConstrainedFPStrict.push_back(OutChain); 7337 break; 7338 } 7339 }; 7340 7341 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7342 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7343 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7344 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7345 7346 SDNodeFlags Flags; 7347 if (EB == fp::ExceptionBehavior::ebIgnore) 7348 Flags.setNoFPExcept(true); 7349 7350 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7351 Flags.copyFMF(*FPOp); 7352 7353 unsigned Opcode; 7354 switch (FPI.getIntrinsicID()) { 7355 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7356 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7357 case Intrinsic::INTRINSIC: \ 7358 Opcode = ISD::STRICT_##DAGN; \ 7359 break; 7360 #include "llvm/IR/ConstrainedOps.def" 7361 case Intrinsic::experimental_constrained_fmuladd: { 7362 Opcode = ISD::STRICT_FMA; 7363 // Break fmuladd into fmul and fadd. 7364 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7365 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7366 Opers.pop_back(); 7367 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7368 pushOutChain(Mul, EB); 7369 Opcode = ISD::STRICT_FADD; 7370 Opers.clear(); 7371 Opers.push_back(Mul.getValue(1)); 7372 Opers.push_back(Mul.getValue(0)); 7373 Opers.push_back(getValue(FPI.getArgOperand(2))); 7374 } 7375 break; 7376 } 7377 } 7378 7379 // A few strict DAG nodes carry additional operands that are not 7380 // set up by the default code above. 7381 switch (Opcode) { 7382 default: break; 7383 case ISD::STRICT_FP_ROUND: 7384 Opers.push_back( 7385 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7386 break; 7387 case ISD::STRICT_FSETCC: 7388 case ISD::STRICT_FSETCCS: { 7389 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7390 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7391 if (TM.Options.NoNaNsFPMath) 7392 Condition = getFCmpCodeWithoutNaN(Condition); 7393 Opers.push_back(DAG.getCondCode(Condition)); 7394 break; 7395 } 7396 } 7397 7398 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7399 pushOutChain(Result, EB); 7400 7401 SDValue FPResult = Result.getValue(0); 7402 setValue(&FPI, FPResult); 7403 } 7404 7405 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7406 Optional<unsigned> ResOPC; 7407 switch (VPIntrin.getIntrinsicID()) { 7408 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7409 case Intrinsic::VPID: \ 7410 ResOPC = ISD::VPSD; \ 7411 break; 7412 #include "llvm/IR/VPIntrinsics.def" 7413 } 7414 7415 if (!ResOPC) 7416 llvm_unreachable( 7417 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7418 7419 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7420 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7421 if (VPIntrin.getFastMathFlags().allowReassoc()) 7422 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7423 : ISD::VP_REDUCE_FMUL; 7424 } 7425 7426 return *ResOPC; 7427 } 7428 7429 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT, 7430 SmallVector<SDValue, 7> &OpValues) { 7431 SDLoc DL = getCurSDLoc(); 7432 Value *PtrOperand = VPIntrin.getArgOperand(0); 7433 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7434 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7435 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7436 SDValue LD; 7437 bool AddToChain = true; 7438 // Do not serialize variable-length loads of constant memory with 7439 // anything. 7440 if (!Alignment) 7441 Alignment = DAG.getEVTAlign(VT); 7442 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7443 AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7444 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7445 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7446 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7447 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7448 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7449 MMO, false /*IsExpanding */); 7450 if (AddToChain) 7451 PendingLoads.push_back(LD.getValue(1)); 7452 setValue(&VPIntrin, LD); 7453 } 7454 7455 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT, 7456 SmallVector<SDValue, 7> &OpValues) { 7457 SDLoc DL = getCurSDLoc(); 7458 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7459 Value *PtrOperand = VPIntrin.getArgOperand(0); 7460 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7461 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7462 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7463 SDValue LD; 7464 if (!Alignment) 7465 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7466 unsigned AS = 7467 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7468 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7469 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7470 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7471 SDValue Base, Index, Scale; 7472 ISD::MemIndexType IndexType; 7473 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7474 this, VPIntrin.getParent(), 7475 VT.getScalarStoreSize()); 7476 if (!UniformBase) { 7477 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7478 Index = getValue(PtrOperand); 7479 IndexType = ISD::SIGNED_SCALED; 7480 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7481 } 7482 EVT IdxVT = Index.getValueType(); 7483 EVT EltTy = IdxVT.getVectorElementType(); 7484 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7485 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7486 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7487 } 7488 LD = DAG.getGatherVP( 7489 DAG.getVTList(VT, MVT::Other), VT, DL, 7490 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7491 IndexType); 7492 PendingLoads.push_back(LD.getValue(1)); 7493 setValue(&VPIntrin, LD); 7494 } 7495 7496 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin, 7497 SmallVector<SDValue, 7> &OpValues) { 7498 SDLoc DL = getCurSDLoc(); 7499 Value *PtrOperand = VPIntrin.getArgOperand(1); 7500 EVT VT = OpValues[0].getValueType(); 7501 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7502 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7503 SDValue ST; 7504 if (!Alignment) 7505 Alignment = DAG.getEVTAlign(VT); 7506 SDValue Ptr = OpValues[1]; 7507 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7508 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7509 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7510 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7511 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7512 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7513 /* IsTruncating */ false, /*IsCompressing*/ false); 7514 DAG.setRoot(ST); 7515 setValue(&VPIntrin, ST); 7516 } 7517 7518 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin, 7519 SmallVector<SDValue, 7> &OpValues) { 7520 SDLoc DL = getCurSDLoc(); 7521 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7522 Value *PtrOperand = VPIntrin.getArgOperand(1); 7523 EVT VT = OpValues[0].getValueType(); 7524 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7525 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7526 SDValue ST; 7527 if (!Alignment) 7528 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7529 unsigned AS = 7530 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7531 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7532 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7533 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7534 SDValue Base, Index, Scale; 7535 ISD::MemIndexType IndexType; 7536 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7537 this, VPIntrin.getParent(), 7538 VT.getScalarStoreSize()); 7539 if (!UniformBase) { 7540 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7541 Index = getValue(PtrOperand); 7542 IndexType = ISD::SIGNED_SCALED; 7543 Scale = 7544 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7545 } 7546 EVT IdxVT = Index.getValueType(); 7547 EVT EltTy = IdxVT.getVectorElementType(); 7548 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7549 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7550 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7551 } 7552 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7553 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7554 OpValues[2], OpValues[3]}, 7555 MMO, IndexType); 7556 DAG.setRoot(ST); 7557 setValue(&VPIntrin, ST); 7558 } 7559 7560 void SelectionDAGBuilder::visitVPStridedLoad( 7561 const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) { 7562 SDLoc DL = getCurSDLoc(); 7563 Value *PtrOperand = VPIntrin.getArgOperand(0); 7564 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7565 if (!Alignment) 7566 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7567 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7568 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7569 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7570 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7571 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7572 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7573 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7574 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7575 7576 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7577 OpValues[2], OpValues[3], MMO, 7578 false /*IsExpanding*/); 7579 7580 if (AddToChain) 7581 PendingLoads.push_back(LD.getValue(1)); 7582 setValue(&VPIntrin, LD); 7583 } 7584 7585 void SelectionDAGBuilder::visitVPStridedStore( 7586 const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) { 7587 SDLoc DL = getCurSDLoc(); 7588 Value *PtrOperand = VPIntrin.getArgOperand(1); 7589 EVT VT = OpValues[0].getValueType(); 7590 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7591 if (!Alignment) 7592 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7593 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7594 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7595 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7596 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7597 7598 SDValue ST = DAG.getStridedStoreVP( 7599 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7600 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7601 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7602 /*IsCompressing*/ false); 7603 7604 DAG.setRoot(ST); 7605 setValue(&VPIntrin, ST); 7606 } 7607 7608 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7609 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7610 SDLoc DL = getCurSDLoc(); 7611 7612 ISD::CondCode Condition; 7613 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7614 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7615 if (IsFP) { 7616 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7617 // flags, but calls that don't return floating-point types can't be 7618 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7619 Condition = getFCmpCondCode(CondCode); 7620 if (TM.Options.NoNaNsFPMath) 7621 Condition = getFCmpCodeWithoutNaN(Condition); 7622 } else { 7623 Condition = getICmpCondCode(CondCode); 7624 } 7625 7626 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7627 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7628 // #2 is the condition code 7629 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7630 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7631 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7632 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7633 "Unexpected target EVL type"); 7634 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7635 7636 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7637 VPIntrin.getType()); 7638 setValue(&VPIntrin, 7639 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7640 } 7641 7642 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7643 const VPIntrinsic &VPIntrin) { 7644 SDLoc DL = getCurSDLoc(); 7645 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7646 7647 auto IID = VPIntrin.getIntrinsicID(); 7648 7649 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7650 return visitVPCmp(*CmpI); 7651 7652 SmallVector<EVT, 4> ValueVTs; 7653 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7654 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7655 SDVTList VTs = DAG.getVTList(ValueVTs); 7656 7657 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7658 7659 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7660 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7661 "Unexpected target EVL type"); 7662 7663 // Request operands. 7664 SmallVector<SDValue, 7> OpValues; 7665 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7666 auto Op = getValue(VPIntrin.getArgOperand(I)); 7667 if (I == EVLParamPos) 7668 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7669 OpValues.push_back(Op); 7670 } 7671 7672 switch (Opcode) { 7673 default: { 7674 SDNodeFlags SDFlags; 7675 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7676 SDFlags.copyFMF(*FPMO); 7677 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7678 setValue(&VPIntrin, Result); 7679 break; 7680 } 7681 case ISD::VP_LOAD: 7682 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7683 break; 7684 case ISD::VP_GATHER: 7685 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7686 break; 7687 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7688 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7689 break; 7690 case ISD::VP_STORE: 7691 visitVPStore(VPIntrin, OpValues); 7692 break; 7693 case ISD::VP_SCATTER: 7694 visitVPScatter(VPIntrin, OpValues); 7695 break; 7696 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7697 visitVPStridedStore(VPIntrin, OpValues); 7698 break; 7699 case ISD::VP_FMULADD: { 7700 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7701 SDNodeFlags SDFlags; 7702 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7703 SDFlags.copyFMF(*FPMO); 7704 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7705 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7706 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7707 } else { 7708 SDValue Mul = DAG.getNode( 7709 ISD::VP_FMUL, DL, VTs, 7710 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7711 SDValue Add = 7712 DAG.getNode(ISD::VP_FADD, DL, VTs, 7713 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7714 setValue(&VPIntrin, Add); 7715 } 7716 break; 7717 } 7718 } 7719 } 7720 7721 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7722 const BasicBlock *EHPadBB, 7723 MCSymbol *&BeginLabel) { 7724 MachineFunction &MF = DAG.getMachineFunction(); 7725 MachineModuleInfo &MMI = MF.getMMI(); 7726 7727 // Insert a label before the invoke call to mark the try range. This can be 7728 // used to detect deletion of the invoke via the MachineModuleInfo. 7729 BeginLabel = MMI.getContext().createTempSymbol(); 7730 7731 // For SjLj, keep track of which landing pads go with which invokes 7732 // so as to maintain the ordering of pads in the LSDA. 7733 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7734 if (CallSiteIndex) { 7735 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7736 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7737 7738 // Now that the call site is handled, stop tracking it. 7739 MMI.setCurrentCallSite(0); 7740 } 7741 7742 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7743 } 7744 7745 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7746 const BasicBlock *EHPadBB, 7747 MCSymbol *BeginLabel) { 7748 assert(BeginLabel && "BeginLabel should've been set"); 7749 7750 MachineFunction &MF = DAG.getMachineFunction(); 7751 MachineModuleInfo &MMI = MF.getMMI(); 7752 7753 // Insert a label at the end of the invoke call to mark the try range. This 7754 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7755 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7756 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7757 7758 // Inform MachineModuleInfo of range. 7759 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7760 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7761 // actually use outlined funclets and their LSDA info style. 7762 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7763 assert(II && "II should've been set"); 7764 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7765 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7766 } else if (!isScopedEHPersonality(Pers)) { 7767 assert(EHPadBB); 7768 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7769 } 7770 7771 return Chain; 7772 } 7773 7774 std::pair<SDValue, SDValue> 7775 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7776 const BasicBlock *EHPadBB) { 7777 MCSymbol *BeginLabel = nullptr; 7778 7779 if (EHPadBB) { 7780 // Both PendingLoads and PendingExports must be flushed here; 7781 // this call might not return. 7782 (void)getRoot(); 7783 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7784 CLI.setChain(getRoot()); 7785 } 7786 7787 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7788 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7789 7790 assert((CLI.IsTailCall || Result.second.getNode()) && 7791 "Non-null chain expected with non-tail call!"); 7792 assert((Result.second.getNode() || !Result.first.getNode()) && 7793 "Null value expected with tail call!"); 7794 7795 if (!Result.second.getNode()) { 7796 // As a special case, a null chain means that a tail call has been emitted 7797 // and the DAG root is already updated. 7798 HasTailCall = true; 7799 7800 // Since there's no actual continuation from this block, nothing can be 7801 // relying on us setting vregs for them. 7802 PendingExports.clear(); 7803 } else { 7804 DAG.setRoot(Result.second); 7805 } 7806 7807 if (EHPadBB) { 7808 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7809 BeginLabel)); 7810 } 7811 7812 return Result; 7813 } 7814 7815 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7816 bool isTailCall, 7817 bool isMustTailCall, 7818 const BasicBlock *EHPadBB) { 7819 auto &DL = DAG.getDataLayout(); 7820 FunctionType *FTy = CB.getFunctionType(); 7821 Type *RetTy = CB.getType(); 7822 7823 TargetLowering::ArgListTy Args; 7824 Args.reserve(CB.arg_size()); 7825 7826 const Value *SwiftErrorVal = nullptr; 7827 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7828 7829 if (isTailCall) { 7830 // Avoid emitting tail calls in functions with the disable-tail-calls 7831 // attribute. 7832 auto *Caller = CB.getParent()->getParent(); 7833 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7834 "true" && !isMustTailCall) 7835 isTailCall = false; 7836 7837 // We can't tail call inside a function with a swifterror argument. Lowering 7838 // does not support this yet. It would have to move into the swifterror 7839 // register before the call. 7840 if (TLI.supportSwiftError() && 7841 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7842 isTailCall = false; 7843 } 7844 7845 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7846 TargetLowering::ArgListEntry Entry; 7847 const Value *V = *I; 7848 7849 // Skip empty types 7850 if (V->getType()->isEmptyTy()) 7851 continue; 7852 7853 SDValue ArgNode = getValue(V); 7854 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7855 7856 Entry.setAttributes(&CB, I - CB.arg_begin()); 7857 7858 // Use swifterror virtual register as input to the call. 7859 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7860 SwiftErrorVal = V; 7861 // We find the virtual register for the actual swifterror argument. 7862 // Instead of using the Value, we use the virtual register instead. 7863 Entry.Node = 7864 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7865 EVT(TLI.getPointerTy(DL))); 7866 } 7867 7868 Args.push_back(Entry); 7869 7870 // If we have an explicit sret argument that is an Instruction, (i.e., it 7871 // might point to function-local memory), we can't meaningfully tail-call. 7872 if (Entry.IsSRet && isa<Instruction>(V)) 7873 isTailCall = false; 7874 } 7875 7876 // If call site has a cfguardtarget operand bundle, create and add an 7877 // additional ArgListEntry. 7878 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7879 TargetLowering::ArgListEntry Entry; 7880 Value *V = Bundle->Inputs[0]; 7881 SDValue ArgNode = getValue(V); 7882 Entry.Node = ArgNode; 7883 Entry.Ty = V->getType(); 7884 Entry.IsCFGuardTarget = true; 7885 Args.push_back(Entry); 7886 } 7887 7888 // Check if target-independent constraints permit a tail call here. 7889 // Target-dependent constraints are checked within TLI->LowerCallTo. 7890 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7891 isTailCall = false; 7892 7893 // Disable tail calls if there is an swifterror argument. Targets have not 7894 // been updated to support tail calls. 7895 if (TLI.supportSwiftError() && SwiftErrorVal) 7896 isTailCall = false; 7897 7898 ConstantInt *CFIType = nullptr; 7899 if (CB.isIndirectCall()) { 7900 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 7901 if (!TLI.supportKCFIBundles()) 7902 report_fatal_error( 7903 "Target doesn't support calls with kcfi operand bundles."); 7904 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 7905 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 7906 } 7907 } 7908 7909 TargetLowering::CallLoweringInfo CLI(DAG); 7910 CLI.setDebugLoc(getCurSDLoc()) 7911 .setChain(getRoot()) 7912 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7913 .setTailCall(isTailCall) 7914 .setConvergent(CB.isConvergent()) 7915 .setIsPreallocated( 7916 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 7917 .setCFIType(CFIType); 7918 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7919 7920 if (Result.first.getNode()) { 7921 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7922 setValue(&CB, Result.first); 7923 } 7924 7925 // The last element of CLI.InVals has the SDValue for swifterror return. 7926 // Here we copy it to a virtual register and update SwiftErrorMap for 7927 // book-keeping. 7928 if (SwiftErrorVal && TLI.supportSwiftError()) { 7929 // Get the last element of InVals. 7930 SDValue Src = CLI.InVals.back(); 7931 Register VReg = 7932 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7933 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7934 DAG.setRoot(CopyNode); 7935 } 7936 } 7937 7938 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7939 SelectionDAGBuilder &Builder) { 7940 // Check to see if this load can be trivially constant folded, e.g. if the 7941 // input is from a string literal. 7942 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7943 // Cast pointer to the type we really want to load. 7944 Type *LoadTy = 7945 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7946 if (LoadVT.isVector()) 7947 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7948 7949 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7950 PointerType::getUnqual(LoadTy)); 7951 7952 if (const Constant *LoadCst = 7953 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 7954 LoadTy, Builder.DAG.getDataLayout())) 7955 return Builder.getValue(LoadCst); 7956 } 7957 7958 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7959 // still constant memory, the input chain can be the entry node. 7960 SDValue Root; 7961 bool ConstantMemory = false; 7962 7963 // Do not serialize (non-volatile) loads of constant memory with anything. 7964 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7965 Root = Builder.DAG.getEntryNode(); 7966 ConstantMemory = true; 7967 } else { 7968 // Do not serialize non-volatile loads against each other. 7969 Root = Builder.DAG.getRoot(); 7970 } 7971 7972 SDValue Ptr = Builder.getValue(PtrVal); 7973 SDValue LoadVal = 7974 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7975 MachinePointerInfo(PtrVal), Align(1)); 7976 7977 if (!ConstantMemory) 7978 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7979 return LoadVal; 7980 } 7981 7982 /// Record the value for an instruction that produces an integer result, 7983 /// converting the type where necessary. 7984 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7985 SDValue Value, 7986 bool IsSigned) { 7987 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7988 I.getType(), true); 7989 if (IsSigned) 7990 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7991 else 7992 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7993 setValue(&I, Value); 7994 } 7995 7996 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7997 /// true and lower it. Otherwise return false, and it will be lowered like a 7998 /// normal call. 7999 /// The caller already checked that \p I calls the appropriate LibFunc with a 8000 /// correct prototype. 8001 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8002 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8003 const Value *Size = I.getArgOperand(2); 8004 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8005 if (CSize && CSize->getZExtValue() == 0) { 8006 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8007 I.getType(), true); 8008 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8009 return true; 8010 } 8011 8012 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8013 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8014 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8015 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8016 if (Res.first.getNode()) { 8017 processIntegerCallValue(I, Res.first, true); 8018 PendingLoads.push_back(Res.second); 8019 return true; 8020 } 8021 8022 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8023 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8024 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8025 return false; 8026 8027 // If the target has a fast compare for the given size, it will return a 8028 // preferred load type for that size. Require that the load VT is legal and 8029 // that the target supports unaligned loads of that type. Otherwise, return 8030 // INVALID. 8031 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8032 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8033 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8034 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8035 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8036 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8037 // TODO: Check alignment of src and dest ptrs. 8038 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8039 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8040 if (!TLI.isTypeLegal(LVT) || 8041 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8042 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8043 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8044 } 8045 8046 return LVT; 8047 }; 8048 8049 // This turns into unaligned loads. We only do this if the target natively 8050 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8051 // we'll only produce a small number of byte loads. 8052 MVT LoadVT; 8053 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8054 switch (NumBitsToCompare) { 8055 default: 8056 return false; 8057 case 16: 8058 LoadVT = MVT::i16; 8059 break; 8060 case 32: 8061 LoadVT = MVT::i32; 8062 break; 8063 case 64: 8064 case 128: 8065 case 256: 8066 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8067 break; 8068 } 8069 8070 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8071 return false; 8072 8073 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8074 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8075 8076 // Bitcast to a wide integer type if the loads are vectors. 8077 if (LoadVT.isVector()) { 8078 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8079 LoadL = DAG.getBitcast(CmpVT, LoadL); 8080 LoadR = DAG.getBitcast(CmpVT, LoadR); 8081 } 8082 8083 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8084 processIntegerCallValue(I, Cmp, false); 8085 return true; 8086 } 8087 8088 /// See if we can lower a memchr call into an optimized form. If so, return 8089 /// true and lower it. Otherwise return false, and it will be lowered like a 8090 /// normal call. 8091 /// The caller already checked that \p I calls the appropriate LibFunc with a 8092 /// correct prototype. 8093 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8094 const Value *Src = I.getArgOperand(0); 8095 const Value *Char = I.getArgOperand(1); 8096 const Value *Length = I.getArgOperand(2); 8097 8098 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8099 std::pair<SDValue, SDValue> Res = 8100 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8101 getValue(Src), getValue(Char), getValue(Length), 8102 MachinePointerInfo(Src)); 8103 if (Res.first.getNode()) { 8104 setValue(&I, Res.first); 8105 PendingLoads.push_back(Res.second); 8106 return true; 8107 } 8108 8109 return false; 8110 } 8111 8112 /// See if we can lower a mempcpy call into an optimized form. If so, return 8113 /// true and lower it. Otherwise return false, and it will be lowered like a 8114 /// normal call. 8115 /// The caller already checked that \p I calls the appropriate LibFunc with a 8116 /// correct prototype. 8117 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8118 SDValue Dst = getValue(I.getArgOperand(0)); 8119 SDValue Src = getValue(I.getArgOperand(1)); 8120 SDValue Size = getValue(I.getArgOperand(2)); 8121 8122 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8123 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8124 // DAG::getMemcpy needs Alignment to be defined. 8125 Align Alignment = std::min(DstAlign, SrcAlign); 8126 8127 bool isVol = false; 8128 SDLoc sdl = getCurSDLoc(); 8129 8130 // In the mempcpy context we need to pass in a false value for isTailCall 8131 // because the return pointer needs to be adjusted by the size of 8132 // the copied memory. 8133 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 8134 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 8135 /*isTailCall=*/false, 8136 MachinePointerInfo(I.getArgOperand(0)), 8137 MachinePointerInfo(I.getArgOperand(1)), 8138 I.getAAMetadata()); 8139 assert(MC.getNode() != nullptr && 8140 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8141 DAG.setRoot(MC); 8142 8143 // Check if Size needs to be truncated or extended. 8144 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8145 8146 // Adjust return pointer to point just past the last dst byte. 8147 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8148 Dst, Size); 8149 setValue(&I, DstPlusSize); 8150 return true; 8151 } 8152 8153 /// See if we can lower a strcpy call into an optimized form. If so, return 8154 /// true and lower it, otherwise return false and it will be lowered like a 8155 /// normal call. 8156 /// The caller already checked that \p I calls the appropriate LibFunc with a 8157 /// correct prototype. 8158 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8159 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8160 8161 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8162 std::pair<SDValue, SDValue> Res = 8163 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8164 getValue(Arg0), getValue(Arg1), 8165 MachinePointerInfo(Arg0), 8166 MachinePointerInfo(Arg1), isStpcpy); 8167 if (Res.first.getNode()) { 8168 setValue(&I, Res.first); 8169 DAG.setRoot(Res.second); 8170 return true; 8171 } 8172 8173 return false; 8174 } 8175 8176 /// See if we can lower a strcmp call into an optimized form. If so, return 8177 /// true and lower it, otherwise return false and it will be lowered like a 8178 /// normal call. 8179 /// The caller already checked that \p I calls the appropriate LibFunc with a 8180 /// correct prototype. 8181 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8182 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8183 8184 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8185 std::pair<SDValue, SDValue> Res = 8186 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8187 getValue(Arg0), getValue(Arg1), 8188 MachinePointerInfo(Arg0), 8189 MachinePointerInfo(Arg1)); 8190 if (Res.first.getNode()) { 8191 processIntegerCallValue(I, Res.first, true); 8192 PendingLoads.push_back(Res.second); 8193 return true; 8194 } 8195 8196 return false; 8197 } 8198 8199 /// See if we can lower a strlen call into an optimized form. If so, return 8200 /// true and lower it, otherwise return false and it will be lowered like a 8201 /// normal call. 8202 /// The caller already checked that \p I calls the appropriate LibFunc with a 8203 /// correct prototype. 8204 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8205 const Value *Arg0 = I.getArgOperand(0); 8206 8207 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8208 std::pair<SDValue, SDValue> Res = 8209 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8210 getValue(Arg0), MachinePointerInfo(Arg0)); 8211 if (Res.first.getNode()) { 8212 processIntegerCallValue(I, Res.first, false); 8213 PendingLoads.push_back(Res.second); 8214 return true; 8215 } 8216 8217 return false; 8218 } 8219 8220 /// See if we can lower a strnlen call into an optimized form. If so, return 8221 /// true and lower it, otherwise return false and it will be lowered like a 8222 /// normal call. 8223 /// The caller already checked that \p I calls the appropriate LibFunc with a 8224 /// correct prototype. 8225 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8226 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8227 8228 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8229 std::pair<SDValue, SDValue> Res = 8230 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8231 getValue(Arg0), getValue(Arg1), 8232 MachinePointerInfo(Arg0)); 8233 if (Res.first.getNode()) { 8234 processIntegerCallValue(I, Res.first, false); 8235 PendingLoads.push_back(Res.second); 8236 return true; 8237 } 8238 8239 return false; 8240 } 8241 8242 /// See if we can lower a unary floating-point operation into an SDNode with 8243 /// the specified Opcode. If so, return true and lower it, otherwise return 8244 /// false and it will be lowered like a normal call. 8245 /// The caller already checked that \p I calls the appropriate LibFunc with a 8246 /// correct prototype. 8247 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8248 unsigned Opcode) { 8249 // We already checked this call's prototype; verify it doesn't modify errno. 8250 if (!I.onlyReadsMemory()) 8251 return false; 8252 8253 SDNodeFlags Flags; 8254 Flags.copyFMF(cast<FPMathOperator>(I)); 8255 8256 SDValue Tmp = getValue(I.getArgOperand(0)); 8257 setValue(&I, 8258 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8259 return true; 8260 } 8261 8262 /// See if we can lower a binary floating-point operation into an SDNode with 8263 /// the specified Opcode. If so, return true and lower it. Otherwise return 8264 /// false, and it will be lowered like a normal call. 8265 /// The caller already checked that \p I calls the appropriate LibFunc with a 8266 /// correct prototype. 8267 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8268 unsigned Opcode) { 8269 // We already checked this call's prototype; verify it doesn't modify errno. 8270 if (!I.onlyReadsMemory()) 8271 return false; 8272 8273 SDNodeFlags Flags; 8274 Flags.copyFMF(cast<FPMathOperator>(I)); 8275 8276 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8277 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8278 EVT VT = Tmp0.getValueType(); 8279 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8280 return true; 8281 } 8282 8283 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8284 // Handle inline assembly differently. 8285 if (I.isInlineAsm()) { 8286 visitInlineAsm(I); 8287 return; 8288 } 8289 8290 if (Function *F = I.getCalledFunction()) { 8291 diagnoseDontCall(I); 8292 8293 if (F->isDeclaration()) { 8294 // Is this an LLVM intrinsic or a target-specific intrinsic? 8295 unsigned IID = F->getIntrinsicID(); 8296 if (!IID) 8297 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8298 IID = II->getIntrinsicID(F); 8299 8300 if (IID) { 8301 visitIntrinsicCall(I, IID); 8302 return; 8303 } 8304 } 8305 8306 // Check for well-known libc/libm calls. If the function is internal, it 8307 // can't be a library call. Don't do the check if marked as nobuiltin for 8308 // some reason or the call site requires strict floating point semantics. 8309 LibFunc Func; 8310 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8311 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8312 LibInfo->hasOptimizedCodeGen(Func)) { 8313 switch (Func) { 8314 default: break; 8315 case LibFunc_bcmp: 8316 if (visitMemCmpBCmpCall(I)) 8317 return; 8318 break; 8319 case LibFunc_copysign: 8320 case LibFunc_copysignf: 8321 case LibFunc_copysignl: 8322 // We already checked this call's prototype; verify it doesn't modify 8323 // errno. 8324 if (I.onlyReadsMemory()) { 8325 SDValue LHS = getValue(I.getArgOperand(0)); 8326 SDValue RHS = getValue(I.getArgOperand(1)); 8327 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8328 LHS.getValueType(), LHS, RHS)); 8329 return; 8330 } 8331 break; 8332 case LibFunc_fabs: 8333 case LibFunc_fabsf: 8334 case LibFunc_fabsl: 8335 if (visitUnaryFloatCall(I, ISD::FABS)) 8336 return; 8337 break; 8338 case LibFunc_fmin: 8339 case LibFunc_fminf: 8340 case LibFunc_fminl: 8341 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8342 return; 8343 break; 8344 case LibFunc_fmax: 8345 case LibFunc_fmaxf: 8346 case LibFunc_fmaxl: 8347 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8348 return; 8349 break; 8350 case LibFunc_sin: 8351 case LibFunc_sinf: 8352 case LibFunc_sinl: 8353 if (visitUnaryFloatCall(I, ISD::FSIN)) 8354 return; 8355 break; 8356 case LibFunc_cos: 8357 case LibFunc_cosf: 8358 case LibFunc_cosl: 8359 if (visitUnaryFloatCall(I, ISD::FCOS)) 8360 return; 8361 break; 8362 case LibFunc_sqrt: 8363 case LibFunc_sqrtf: 8364 case LibFunc_sqrtl: 8365 case LibFunc_sqrt_finite: 8366 case LibFunc_sqrtf_finite: 8367 case LibFunc_sqrtl_finite: 8368 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8369 return; 8370 break; 8371 case LibFunc_floor: 8372 case LibFunc_floorf: 8373 case LibFunc_floorl: 8374 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8375 return; 8376 break; 8377 case LibFunc_nearbyint: 8378 case LibFunc_nearbyintf: 8379 case LibFunc_nearbyintl: 8380 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8381 return; 8382 break; 8383 case LibFunc_ceil: 8384 case LibFunc_ceilf: 8385 case LibFunc_ceill: 8386 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8387 return; 8388 break; 8389 case LibFunc_rint: 8390 case LibFunc_rintf: 8391 case LibFunc_rintl: 8392 if (visitUnaryFloatCall(I, ISD::FRINT)) 8393 return; 8394 break; 8395 case LibFunc_round: 8396 case LibFunc_roundf: 8397 case LibFunc_roundl: 8398 if (visitUnaryFloatCall(I, ISD::FROUND)) 8399 return; 8400 break; 8401 case LibFunc_trunc: 8402 case LibFunc_truncf: 8403 case LibFunc_truncl: 8404 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8405 return; 8406 break; 8407 case LibFunc_log2: 8408 case LibFunc_log2f: 8409 case LibFunc_log2l: 8410 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8411 return; 8412 break; 8413 case LibFunc_exp2: 8414 case LibFunc_exp2f: 8415 case LibFunc_exp2l: 8416 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8417 return; 8418 break; 8419 case LibFunc_memcmp: 8420 if (visitMemCmpBCmpCall(I)) 8421 return; 8422 break; 8423 case LibFunc_mempcpy: 8424 if (visitMemPCpyCall(I)) 8425 return; 8426 break; 8427 case LibFunc_memchr: 8428 if (visitMemChrCall(I)) 8429 return; 8430 break; 8431 case LibFunc_strcpy: 8432 if (visitStrCpyCall(I, false)) 8433 return; 8434 break; 8435 case LibFunc_stpcpy: 8436 if (visitStrCpyCall(I, true)) 8437 return; 8438 break; 8439 case LibFunc_strcmp: 8440 if (visitStrCmpCall(I)) 8441 return; 8442 break; 8443 case LibFunc_strlen: 8444 if (visitStrLenCall(I)) 8445 return; 8446 break; 8447 case LibFunc_strnlen: 8448 if (visitStrNLenCall(I)) 8449 return; 8450 break; 8451 } 8452 } 8453 } 8454 8455 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8456 // have to do anything here to lower funclet bundles. 8457 // CFGuardTarget bundles are lowered in LowerCallTo. 8458 assert(!I.hasOperandBundlesOtherThan( 8459 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8460 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8461 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8462 "Cannot lower calls with arbitrary operand bundles!"); 8463 8464 SDValue Callee = getValue(I.getCalledOperand()); 8465 8466 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8467 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8468 else 8469 // Check if we can potentially perform a tail call. More detailed checking 8470 // is be done within LowerCallTo, after more information about the call is 8471 // known. 8472 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8473 } 8474 8475 namespace { 8476 8477 /// AsmOperandInfo - This contains information for each constraint that we are 8478 /// lowering. 8479 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8480 public: 8481 /// CallOperand - If this is the result output operand or a clobber 8482 /// this is null, otherwise it is the incoming operand to the CallInst. 8483 /// This gets modified as the asm is processed. 8484 SDValue CallOperand; 8485 8486 /// AssignedRegs - If this is a register or register class operand, this 8487 /// contains the set of register corresponding to the operand. 8488 RegsForValue AssignedRegs; 8489 8490 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8491 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8492 } 8493 8494 /// Whether or not this operand accesses memory 8495 bool hasMemory(const TargetLowering &TLI) const { 8496 // Indirect operand accesses access memory. 8497 if (isIndirect) 8498 return true; 8499 8500 for (const auto &Code : Codes) 8501 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8502 return true; 8503 8504 return false; 8505 } 8506 }; 8507 8508 8509 } // end anonymous namespace 8510 8511 /// Make sure that the output operand \p OpInfo and its corresponding input 8512 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8513 /// out). 8514 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8515 SDISelAsmOperandInfo &MatchingOpInfo, 8516 SelectionDAG &DAG) { 8517 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8518 return; 8519 8520 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8521 const auto &TLI = DAG.getTargetLoweringInfo(); 8522 8523 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8524 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8525 OpInfo.ConstraintVT); 8526 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8527 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8528 MatchingOpInfo.ConstraintVT); 8529 if ((OpInfo.ConstraintVT.isInteger() != 8530 MatchingOpInfo.ConstraintVT.isInteger()) || 8531 (MatchRC.second != InputRC.second)) { 8532 // FIXME: error out in a more elegant fashion 8533 report_fatal_error("Unsupported asm: input constraint" 8534 " with a matching output constraint of" 8535 " incompatible type!"); 8536 } 8537 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8538 } 8539 8540 /// Get a direct memory input to behave well as an indirect operand. 8541 /// This may introduce stores, hence the need for a \p Chain. 8542 /// \return The (possibly updated) chain. 8543 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8544 SDISelAsmOperandInfo &OpInfo, 8545 SelectionDAG &DAG) { 8546 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8547 8548 // If we don't have an indirect input, put it in the constpool if we can, 8549 // otherwise spill it to a stack slot. 8550 // TODO: This isn't quite right. We need to handle these according to 8551 // the addressing mode that the constraint wants. Also, this may take 8552 // an additional register for the computation and we don't want that 8553 // either. 8554 8555 // If the operand is a float, integer, or vector constant, spill to a 8556 // constant pool entry to get its address. 8557 const Value *OpVal = OpInfo.CallOperandVal; 8558 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8559 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8560 OpInfo.CallOperand = DAG.getConstantPool( 8561 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8562 return Chain; 8563 } 8564 8565 // Otherwise, create a stack slot and emit a store to it before the asm. 8566 Type *Ty = OpVal->getType(); 8567 auto &DL = DAG.getDataLayout(); 8568 uint64_t TySize = DL.getTypeAllocSize(Ty); 8569 MachineFunction &MF = DAG.getMachineFunction(); 8570 int SSFI = MF.getFrameInfo().CreateStackObject( 8571 TySize, DL.getPrefTypeAlign(Ty), false); 8572 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8573 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8574 MachinePointerInfo::getFixedStack(MF, SSFI), 8575 TLI.getMemValueType(DL, Ty)); 8576 OpInfo.CallOperand = StackSlot; 8577 8578 return Chain; 8579 } 8580 8581 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8582 /// specified operand. We prefer to assign virtual registers, to allow the 8583 /// register allocator to handle the assignment process. However, if the asm 8584 /// uses features that we can't model on machineinstrs, we have SDISel do the 8585 /// allocation. This produces generally horrible, but correct, code. 8586 /// 8587 /// OpInfo describes the operand 8588 /// RefOpInfo describes the matching operand if any, the operand otherwise 8589 static llvm::Optional<unsigned> 8590 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8591 SDISelAsmOperandInfo &OpInfo, 8592 SDISelAsmOperandInfo &RefOpInfo) { 8593 LLVMContext &Context = *DAG.getContext(); 8594 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8595 8596 MachineFunction &MF = DAG.getMachineFunction(); 8597 SmallVector<unsigned, 4> Regs; 8598 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8599 8600 // No work to do for memory/address operands. 8601 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8602 OpInfo.ConstraintType == TargetLowering::C_Address) 8603 return None; 8604 8605 // If this is a constraint for a single physreg, or a constraint for a 8606 // register class, find it. 8607 unsigned AssignedReg; 8608 const TargetRegisterClass *RC; 8609 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8610 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8611 // RC is unset only on failure. Return immediately. 8612 if (!RC) 8613 return None; 8614 8615 // Get the actual register value type. This is important, because the user 8616 // may have asked for (e.g.) the AX register in i32 type. We need to 8617 // remember that AX is actually i16 to get the right extension. 8618 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8619 8620 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8621 // If this is an FP operand in an integer register (or visa versa), or more 8622 // generally if the operand value disagrees with the register class we plan 8623 // to stick it in, fix the operand type. 8624 // 8625 // If this is an input value, the bitcast to the new type is done now. 8626 // Bitcast for output value is done at the end of visitInlineAsm(). 8627 if ((OpInfo.Type == InlineAsm::isOutput || 8628 OpInfo.Type == InlineAsm::isInput) && 8629 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8630 // Try to convert to the first EVT that the reg class contains. If the 8631 // types are identical size, use a bitcast to convert (e.g. two differing 8632 // vector types). Note: output bitcast is done at the end of 8633 // visitInlineAsm(). 8634 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8635 // Exclude indirect inputs while they are unsupported because the code 8636 // to perform the load is missing and thus OpInfo.CallOperand still 8637 // refers to the input address rather than the pointed-to value. 8638 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8639 OpInfo.CallOperand = 8640 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8641 OpInfo.ConstraintVT = RegVT; 8642 // If the operand is an FP value and we want it in integer registers, 8643 // use the corresponding integer type. This turns an f64 value into 8644 // i64, which can be passed with two i32 values on a 32-bit machine. 8645 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8646 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8647 if (OpInfo.Type == InlineAsm::isInput) 8648 OpInfo.CallOperand = 8649 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8650 OpInfo.ConstraintVT = VT; 8651 } 8652 } 8653 } 8654 8655 // No need to allocate a matching input constraint since the constraint it's 8656 // matching to has already been allocated. 8657 if (OpInfo.isMatchingInputConstraint()) 8658 return None; 8659 8660 EVT ValueVT = OpInfo.ConstraintVT; 8661 if (OpInfo.ConstraintVT == MVT::Other) 8662 ValueVT = RegVT; 8663 8664 // Initialize NumRegs. 8665 unsigned NumRegs = 1; 8666 if (OpInfo.ConstraintVT != MVT::Other) 8667 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8668 8669 // If this is a constraint for a specific physical register, like {r17}, 8670 // assign it now. 8671 8672 // If this associated to a specific register, initialize iterator to correct 8673 // place. If virtual, make sure we have enough registers 8674 8675 // Initialize iterator if necessary 8676 TargetRegisterClass::iterator I = RC->begin(); 8677 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8678 8679 // Do not check for single registers. 8680 if (AssignedReg) { 8681 I = std::find(I, RC->end(), AssignedReg); 8682 if (I == RC->end()) { 8683 // RC does not contain the selected register, which indicates a 8684 // mismatch between the register and the required type/bitwidth. 8685 return {AssignedReg}; 8686 } 8687 } 8688 8689 for (; NumRegs; --NumRegs, ++I) { 8690 assert(I != RC->end() && "Ran out of registers to allocate!"); 8691 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8692 Regs.push_back(R); 8693 } 8694 8695 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8696 return None; 8697 } 8698 8699 static unsigned 8700 findMatchingInlineAsmOperand(unsigned OperandNo, 8701 const std::vector<SDValue> &AsmNodeOperands) { 8702 // Scan until we find the definition we already emitted of this operand. 8703 unsigned CurOp = InlineAsm::Op_FirstOperand; 8704 for (; OperandNo; --OperandNo) { 8705 // Advance to the next operand. 8706 unsigned OpFlag = 8707 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8708 assert((InlineAsm::isRegDefKind(OpFlag) || 8709 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8710 InlineAsm::isMemKind(OpFlag)) && 8711 "Skipped past definitions?"); 8712 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8713 } 8714 return CurOp; 8715 } 8716 8717 namespace { 8718 8719 class ExtraFlags { 8720 unsigned Flags = 0; 8721 8722 public: 8723 explicit ExtraFlags(const CallBase &Call) { 8724 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8725 if (IA->hasSideEffects()) 8726 Flags |= InlineAsm::Extra_HasSideEffects; 8727 if (IA->isAlignStack()) 8728 Flags |= InlineAsm::Extra_IsAlignStack; 8729 if (Call.isConvergent()) 8730 Flags |= InlineAsm::Extra_IsConvergent; 8731 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8732 } 8733 8734 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8735 // Ideally, we would only check against memory constraints. However, the 8736 // meaning of an Other constraint can be target-specific and we can't easily 8737 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8738 // for Other constraints as well. 8739 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8740 OpInfo.ConstraintType == TargetLowering::C_Other) { 8741 if (OpInfo.Type == InlineAsm::isInput) 8742 Flags |= InlineAsm::Extra_MayLoad; 8743 else if (OpInfo.Type == InlineAsm::isOutput) 8744 Flags |= InlineAsm::Extra_MayStore; 8745 else if (OpInfo.Type == InlineAsm::isClobber) 8746 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8747 } 8748 } 8749 8750 unsigned get() const { return Flags; } 8751 }; 8752 8753 } // end anonymous namespace 8754 8755 static bool isFunction(SDValue Op) { 8756 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 8757 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8758 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 8759 8760 // In normal "call dllimport func" instruction (non-inlineasm) it force 8761 // indirect access by specifing call opcode. And usually specially print 8762 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 8763 // not do in this way now. (In fact, this is similar with "Data Access" 8764 // action). So here we ignore dllimport function. 8765 if (Fn && !Fn->hasDLLImportStorageClass()) 8766 return true; 8767 } 8768 } 8769 return false; 8770 } 8771 8772 /// visitInlineAsm - Handle a call to an InlineAsm object. 8773 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8774 const BasicBlock *EHPadBB) { 8775 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8776 8777 /// ConstraintOperands - Information about all of the constraints. 8778 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8779 8780 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8781 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8782 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8783 8784 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8785 // AsmDialect, MayLoad, MayStore). 8786 bool HasSideEffect = IA->hasSideEffects(); 8787 ExtraFlags ExtraInfo(Call); 8788 8789 for (auto &T : TargetConstraints) { 8790 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8791 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8792 8793 if (OpInfo.CallOperandVal) 8794 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8795 8796 if (!HasSideEffect) 8797 HasSideEffect = OpInfo.hasMemory(TLI); 8798 8799 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8800 // FIXME: Could we compute this on OpInfo rather than T? 8801 8802 // Compute the constraint code and ConstraintType to use. 8803 TLI.ComputeConstraintToUse(T, SDValue()); 8804 8805 if (T.ConstraintType == TargetLowering::C_Immediate && 8806 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8807 // We've delayed emitting a diagnostic like the "n" constraint because 8808 // inlining could cause an integer showing up. 8809 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8810 "' expects an integer constant " 8811 "expression"); 8812 8813 ExtraInfo.update(T); 8814 } 8815 8816 // We won't need to flush pending loads if this asm doesn't touch 8817 // memory and is nonvolatile. 8818 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8819 8820 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8821 if (EmitEHLabels) { 8822 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8823 } 8824 bool IsCallBr = isa<CallBrInst>(Call); 8825 8826 if (IsCallBr || EmitEHLabels) { 8827 // If this is a callbr or invoke we need to flush pending exports since 8828 // inlineasm_br and invoke are terminators. 8829 // We need to do this before nodes are glued to the inlineasm_br node. 8830 Chain = getControlRoot(); 8831 } 8832 8833 MCSymbol *BeginLabel = nullptr; 8834 if (EmitEHLabels) { 8835 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8836 } 8837 8838 int OpNo = -1; 8839 SmallVector<StringRef> AsmStrs; 8840 IA->collectAsmStrs(AsmStrs); 8841 8842 // Second pass over the constraints: compute which constraint option to use. 8843 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8844 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 8845 OpNo++; 8846 8847 // If this is an output operand with a matching input operand, look up the 8848 // matching input. If their types mismatch, e.g. one is an integer, the 8849 // other is floating point, or their sizes are different, flag it as an 8850 // error. 8851 if (OpInfo.hasMatchingInput()) { 8852 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8853 patchMatchingInput(OpInfo, Input, DAG); 8854 } 8855 8856 // Compute the constraint code and ConstraintType to use. 8857 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8858 8859 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 8860 OpInfo.Type == InlineAsm::isClobber) || 8861 OpInfo.ConstraintType == TargetLowering::C_Address) 8862 continue; 8863 8864 // In Linux PIC model, there are 4 cases about value/label addressing: 8865 // 8866 // 1: Function call or Label jmp inside the module. 8867 // 2: Data access (such as global variable, static variable) inside module. 8868 // 3: Function call or Label jmp outside the module. 8869 // 4: Data access (such as global variable) outside the module. 8870 // 8871 // Due to current llvm inline asm architecture designed to not "recognize" 8872 // the asm code, there are quite troubles for us to treat mem addressing 8873 // differently for same value/adress used in different instuctions. 8874 // For example, in pic model, call a func may in plt way or direclty 8875 // pc-related, but lea/mov a function adress may use got. 8876 // 8877 // Here we try to "recognize" function call for the case 1 and case 3 in 8878 // inline asm. And try to adjust the constraint for them. 8879 // 8880 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 8881 // label, so here we don't handle jmp function label now, but we need to 8882 // enhance it (especilly in PIC model) if we meet meaningful requirements. 8883 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 8884 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 8885 TM.getCodeModel() != CodeModel::Large) { 8886 OpInfo.isIndirect = false; 8887 OpInfo.ConstraintType = TargetLowering::C_Address; 8888 } 8889 8890 // If this is a memory input, and if the operand is not indirect, do what we 8891 // need to provide an address for the memory input. 8892 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8893 !OpInfo.isIndirect) { 8894 assert((OpInfo.isMultipleAlternative || 8895 (OpInfo.Type == InlineAsm::isInput)) && 8896 "Can only indirectify direct input operands!"); 8897 8898 // Memory operands really want the address of the value. 8899 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8900 8901 // There is no longer a Value* corresponding to this operand. 8902 OpInfo.CallOperandVal = nullptr; 8903 8904 // It is now an indirect operand. 8905 OpInfo.isIndirect = true; 8906 } 8907 8908 } 8909 8910 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8911 std::vector<SDValue> AsmNodeOperands; 8912 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8913 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8914 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8915 8916 // If we have a !srcloc metadata node associated with it, we want to attach 8917 // this to the ultimately generated inline asm machineinstr. To do this, we 8918 // pass in the third operand as this (potentially null) inline asm MDNode. 8919 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8920 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8921 8922 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8923 // bits as operand 3. 8924 AsmNodeOperands.push_back(DAG.getTargetConstant( 8925 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8926 8927 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8928 // this, assign virtual and physical registers for inputs and otput. 8929 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8930 // Assign Registers. 8931 SDISelAsmOperandInfo &RefOpInfo = 8932 OpInfo.isMatchingInputConstraint() 8933 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8934 : OpInfo; 8935 const auto RegError = 8936 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8937 if (RegError) { 8938 const MachineFunction &MF = DAG.getMachineFunction(); 8939 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8940 const char *RegName = TRI.getName(RegError.value()); 8941 emitInlineAsmError(Call, "register '" + Twine(RegName) + 8942 "' allocated for constraint '" + 8943 Twine(OpInfo.ConstraintCode) + 8944 "' does not match required type"); 8945 return; 8946 } 8947 8948 auto DetectWriteToReservedRegister = [&]() { 8949 const MachineFunction &MF = DAG.getMachineFunction(); 8950 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8951 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8952 if (Register::isPhysicalRegister(Reg) && 8953 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8954 const char *RegName = TRI.getName(Reg); 8955 emitInlineAsmError(Call, "write to reserved register '" + 8956 Twine(RegName) + "'"); 8957 return true; 8958 } 8959 } 8960 return false; 8961 }; 8962 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 8963 (OpInfo.Type == InlineAsm::isInput && 8964 !OpInfo.isMatchingInputConstraint())) && 8965 "Only address as input operand is allowed."); 8966 8967 switch (OpInfo.Type) { 8968 case InlineAsm::isOutput: 8969 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8970 unsigned ConstraintID = 8971 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8972 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8973 "Failed to convert memory constraint code to constraint id."); 8974 8975 // Add information to the INLINEASM node to know about this output. 8976 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8977 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8978 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8979 MVT::i32)); 8980 AsmNodeOperands.push_back(OpInfo.CallOperand); 8981 } else { 8982 // Otherwise, this outputs to a register (directly for C_Register / 8983 // C_RegisterClass, and a target-defined fashion for 8984 // C_Immediate/C_Other). Find a register that we can use. 8985 if (OpInfo.AssignedRegs.Regs.empty()) { 8986 emitInlineAsmError( 8987 Call, "couldn't allocate output register for constraint '" + 8988 Twine(OpInfo.ConstraintCode) + "'"); 8989 return; 8990 } 8991 8992 if (DetectWriteToReservedRegister()) 8993 return; 8994 8995 // Add information to the INLINEASM node to know that this register is 8996 // set. 8997 OpInfo.AssignedRegs.AddInlineAsmOperands( 8998 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8999 : InlineAsm::Kind_RegDef, 9000 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9001 } 9002 break; 9003 9004 case InlineAsm::isInput: 9005 case InlineAsm::isLabel: { 9006 SDValue InOperandVal = OpInfo.CallOperand; 9007 9008 if (OpInfo.isMatchingInputConstraint()) { 9009 // If this is required to match an output register we have already set, 9010 // just use its register. 9011 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9012 AsmNodeOperands); 9013 unsigned OpFlag = 9014 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9015 if (InlineAsm::isRegDefKind(OpFlag) || 9016 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9017 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9018 if (OpInfo.isIndirect) { 9019 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9020 emitInlineAsmError(Call, "inline asm not supported yet: " 9021 "don't know how to handle tied " 9022 "indirect register inputs"); 9023 return; 9024 } 9025 9026 SmallVector<unsigned, 4> Regs; 9027 MachineFunction &MF = DAG.getMachineFunction(); 9028 MachineRegisterInfo &MRI = MF.getRegInfo(); 9029 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9030 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9031 Register TiedReg = R->getReg(); 9032 MVT RegVT = R->getSimpleValueType(0); 9033 const TargetRegisterClass *RC = 9034 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9035 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9036 : TRI.getMinimalPhysRegClass(TiedReg); 9037 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9038 for (unsigned i = 0; i != NumRegs; ++i) 9039 Regs.push_back(MRI.createVirtualRegister(RC)); 9040 9041 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9042 9043 SDLoc dl = getCurSDLoc(); 9044 // Use the produced MatchedRegs object to 9045 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 9046 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9047 true, OpInfo.getMatchedOperand(), dl, 9048 DAG, AsmNodeOperands); 9049 break; 9050 } 9051 9052 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9053 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9054 "Unexpected number of operands"); 9055 // Add information to the INLINEASM node to know about this input. 9056 // See InlineAsm.h isUseOperandTiedToDef. 9057 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9058 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9059 OpInfo.getMatchedOperand()); 9060 AsmNodeOperands.push_back(DAG.getTargetConstant( 9061 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9062 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9063 break; 9064 } 9065 9066 // Treat indirect 'X' constraint as memory. 9067 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9068 OpInfo.isIndirect) 9069 OpInfo.ConstraintType = TargetLowering::C_Memory; 9070 9071 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9072 OpInfo.ConstraintType == TargetLowering::C_Other) { 9073 std::vector<SDValue> Ops; 9074 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9075 Ops, DAG); 9076 if (Ops.empty()) { 9077 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9078 if (isa<ConstantSDNode>(InOperandVal)) { 9079 emitInlineAsmError(Call, "value out of range for constraint '" + 9080 Twine(OpInfo.ConstraintCode) + "'"); 9081 return; 9082 } 9083 9084 emitInlineAsmError(Call, 9085 "invalid operand for inline asm constraint '" + 9086 Twine(OpInfo.ConstraintCode) + "'"); 9087 return; 9088 } 9089 9090 // Add information to the INLINEASM node to know about this input. 9091 unsigned ResOpType = 9092 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9093 AsmNodeOperands.push_back(DAG.getTargetConstant( 9094 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9095 llvm::append_range(AsmNodeOperands, Ops); 9096 break; 9097 } 9098 9099 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9100 assert((OpInfo.isIndirect || 9101 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9102 "Operand must be indirect to be a mem!"); 9103 assert(InOperandVal.getValueType() == 9104 TLI.getPointerTy(DAG.getDataLayout()) && 9105 "Memory operands expect pointer values"); 9106 9107 unsigned ConstraintID = 9108 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9109 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9110 "Failed to convert memory constraint code to constraint id."); 9111 9112 // Add information to the INLINEASM node to know about this input. 9113 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9114 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9115 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9116 getCurSDLoc(), 9117 MVT::i32)); 9118 AsmNodeOperands.push_back(InOperandVal); 9119 break; 9120 } 9121 9122 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9123 assert(InOperandVal.getValueType() == 9124 TLI.getPointerTy(DAG.getDataLayout()) && 9125 "Address operands expect pointer values"); 9126 9127 unsigned ConstraintID = 9128 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9129 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9130 "Failed to convert memory constraint code to constraint id."); 9131 9132 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9133 9134 SDValue AsmOp = InOperandVal; 9135 if (isFunction(InOperandVal)) { 9136 auto *GA = dyn_cast<GlobalAddressSDNode>(InOperandVal); 9137 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9138 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9139 InOperandVal.getValueType(), 9140 GA->getOffset()); 9141 } 9142 9143 // Add information to the INLINEASM node to know about this input. 9144 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9145 9146 AsmNodeOperands.push_back( 9147 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9148 9149 AsmNodeOperands.push_back(AsmOp); 9150 break; 9151 } 9152 9153 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9154 OpInfo.ConstraintType == TargetLowering::C_Register) && 9155 "Unknown constraint type!"); 9156 9157 // TODO: Support this. 9158 if (OpInfo.isIndirect) { 9159 emitInlineAsmError( 9160 Call, "Don't know how to handle indirect register inputs yet " 9161 "for constraint '" + 9162 Twine(OpInfo.ConstraintCode) + "'"); 9163 return; 9164 } 9165 9166 // Copy the input into the appropriate registers. 9167 if (OpInfo.AssignedRegs.Regs.empty()) { 9168 emitInlineAsmError(Call, 9169 "couldn't allocate input reg for constraint '" + 9170 Twine(OpInfo.ConstraintCode) + "'"); 9171 return; 9172 } 9173 9174 if (DetectWriteToReservedRegister()) 9175 return; 9176 9177 SDLoc dl = getCurSDLoc(); 9178 9179 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 9180 &Call); 9181 9182 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9183 dl, DAG, AsmNodeOperands); 9184 break; 9185 } 9186 case InlineAsm::isClobber: 9187 // Add the clobbered value to the operand list, so that the register 9188 // allocator is aware that the physreg got clobbered. 9189 if (!OpInfo.AssignedRegs.Regs.empty()) 9190 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9191 false, 0, getCurSDLoc(), DAG, 9192 AsmNodeOperands); 9193 break; 9194 } 9195 } 9196 9197 // Finish up input operands. Set the input chain and add the flag last. 9198 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9199 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 9200 9201 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9202 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9203 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9204 Flag = Chain.getValue(1); 9205 9206 // Do additional work to generate outputs. 9207 9208 SmallVector<EVT, 1> ResultVTs; 9209 SmallVector<SDValue, 1> ResultValues; 9210 SmallVector<SDValue, 8> OutChains; 9211 9212 llvm::Type *CallResultType = Call.getType(); 9213 ArrayRef<Type *> ResultTypes; 9214 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9215 ResultTypes = StructResult->elements(); 9216 else if (!CallResultType->isVoidTy()) 9217 ResultTypes = makeArrayRef(CallResultType); 9218 9219 auto CurResultType = ResultTypes.begin(); 9220 auto handleRegAssign = [&](SDValue V) { 9221 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9222 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9223 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9224 ++CurResultType; 9225 // If the type of the inline asm call site return value is different but has 9226 // same size as the type of the asm output bitcast it. One example of this 9227 // is for vectors with different width / number of elements. This can 9228 // happen for register classes that can contain multiple different value 9229 // types. The preg or vreg allocated may not have the same VT as was 9230 // expected. 9231 // 9232 // This can also happen for a return value that disagrees with the register 9233 // class it is put in, eg. a double in a general-purpose register on a 9234 // 32-bit machine. 9235 if (ResultVT != V.getValueType() && 9236 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9237 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9238 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9239 V.getValueType().isInteger()) { 9240 // If a result value was tied to an input value, the computed result 9241 // may have a wider width than the expected result. Extract the 9242 // relevant portion. 9243 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9244 } 9245 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9246 ResultVTs.push_back(ResultVT); 9247 ResultValues.push_back(V); 9248 }; 9249 9250 // Deal with output operands. 9251 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9252 if (OpInfo.Type == InlineAsm::isOutput) { 9253 SDValue Val; 9254 // Skip trivial output operands. 9255 if (OpInfo.AssignedRegs.Regs.empty()) 9256 continue; 9257 9258 switch (OpInfo.ConstraintType) { 9259 case TargetLowering::C_Register: 9260 case TargetLowering::C_RegisterClass: 9261 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9262 Chain, &Flag, &Call); 9263 break; 9264 case TargetLowering::C_Immediate: 9265 case TargetLowering::C_Other: 9266 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 9267 OpInfo, DAG); 9268 break; 9269 case TargetLowering::C_Memory: 9270 break; // Already handled. 9271 case TargetLowering::C_Address: 9272 break; // Silence warning. 9273 case TargetLowering::C_Unknown: 9274 assert(false && "Unexpected unknown constraint"); 9275 } 9276 9277 // Indirect output manifest as stores. Record output chains. 9278 if (OpInfo.isIndirect) { 9279 const Value *Ptr = OpInfo.CallOperandVal; 9280 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9281 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9282 MachinePointerInfo(Ptr)); 9283 OutChains.push_back(Store); 9284 } else { 9285 // generate CopyFromRegs to associated registers. 9286 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9287 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9288 for (const SDValue &V : Val->op_values()) 9289 handleRegAssign(V); 9290 } else 9291 handleRegAssign(Val); 9292 } 9293 } 9294 } 9295 9296 // Set results. 9297 if (!ResultValues.empty()) { 9298 assert(CurResultType == ResultTypes.end() && 9299 "Mismatch in number of ResultTypes"); 9300 assert(ResultValues.size() == ResultTypes.size() && 9301 "Mismatch in number of output operands in asm result"); 9302 9303 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9304 DAG.getVTList(ResultVTs), ResultValues); 9305 setValue(&Call, V); 9306 } 9307 9308 // Collect store chains. 9309 if (!OutChains.empty()) 9310 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9311 9312 if (EmitEHLabels) { 9313 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9314 } 9315 9316 // Only Update Root if inline assembly has a memory effect. 9317 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9318 EmitEHLabels) 9319 DAG.setRoot(Chain); 9320 } 9321 9322 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9323 const Twine &Message) { 9324 LLVMContext &Ctx = *DAG.getContext(); 9325 Ctx.emitError(&Call, Message); 9326 9327 // Make sure we leave the DAG in a valid state 9328 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9329 SmallVector<EVT, 1> ValueVTs; 9330 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9331 9332 if (ValueVTs.empty()) 9333 return; 9334 9335 SmallVector<SDValue, 1> Ops; 9336 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9337 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9338 9339 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9340 } 9341 9342 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9343 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9344 MVT::Other, getRoot(), 9345 getValue(I.getArgOperand(0)), 9346 DAG.getSrcValue(I.getArgOperand(0)))); 9347 } 9348 9349 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9350 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9351 const DataLayout &DL = DAG.getDataLayout(); 9352 SDValue V = DAG.getVAArg( 9353 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9354 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9355 DL.getABITypeAlign(I.getType()).value()); 9356 DAG.setRoot(V.getValue(1)); 9357 9358 if (I.getType()->isPointerTy()) 9359 V = DAG.getPtrExtOrTrunc( 9360 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9361 setValue(&I, V); 9362 } 9363 9364 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9365 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9366 MVT::Other, getRoot(), 9367 getValue(I.getArgOperand(0)), 9368 DAG.getSrcValue(I.getArgOperand(0)))); 9369 } 9370 9371 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9372 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9373 MVT::Other, getRoot(), 9374 getValue(I.getArgOperand(0)), 9375 getValue(I.getArgOperand(1)), 9376 DAG.getSrcValue(I.getArgOperand(0)), 9377 DAG.getSrcValue(I.getArgOperand(1)))); 9378 } 9379 9380 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9381 const Instruction &I, 9382 SDValue Op) { 9383 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9384 if (!Range) 9385 return Op; 9386 9387 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9388 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9389 return Op; 9390 9391 APInt Lo = CR.getUnsignedMin(); 9392 if (!Lo.isMinValue()) 9393 return Op; 9394 9395 APInt Hi = CR.getUnsignedMax(); 9396 unsigned Bits = std::max(Hi.getActiveBits(), 9397 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9398 9399 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9400 9401 SDLoc SL = getCurSDLoc(); 9402 9403 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9404 DAG.getValueType(SmallVT)); 9405 unsigned NumVals = Op.getNode()->getNumValues(); 9406 if (NumVals == 1) 9407 return ZExt; 9408 9409 SmallVector<SDValue, 4> Ops; 9410 9411 Ops.push_back(ZExt); 9412 for (unsigned I = 1; I != NumVals; ++I) 9413 Ops.push_back(Op.getValue(I)); 9414 9415 return DAG.getMergeValues(Ops, SL); 9416 } 9417 9418 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9419 /// the call being lowered. 9420 /// 9421 /// This is a helper for lowering intrinsics that follow a target calling 9422 /// convention or require stack pointer adjustment. Only a subset of the 9423 /// intrinsic's operands need to participate in the calling convention. 9424 void SelectionDAGBuilder::populateCallLoweringInfo( 9425 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9426 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9427 bool IsPatchPoint) { 9428 TargetLowering::ArgListTy Args; 9429 Args.reserve(NumArgs); 9430 9431 // Populate the argument list. 9432 // Attributes for args start at offset 1, after the return attribute. 9433 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9434 ArgI != ArgE; ++ArgI) { 9435 const Value *V = Call->getOperand(ArgI); 9436 9437 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9438 9439 TargetLowering::ArgListEntry Entry; 9440 Entry.Node = getValue(V); 9441 Entry.Ty = V->getType(); 9442 Entry.setAttributes(Call, ArgI); 9443 Args.push_back(Entry); 9444 } 9445 9446 CLI.setDebugLoc(getCurSDLoc()) 9447 .setChain(getRoot()) 9448 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9449 .setDiscardResult(Call->use_empty()) 9450 .setIsPatchPoint(IsPatchPoint) 9451 .setIsPreallocated( 9452 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9453 } 9454 9455 /// Add a stack map intrinsic call's live variable operands to a stackmap 9456 /// or patchpoint target node's operand list. 9457 /// 9458 /// Constants are converted to TargetConstants purely as an optimization to 9459 /// avoid constant materialization and register allocation. 9460 /// 9461 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9462 /// generate addess computation nodes, and so FinalizeISel can convert the 9463 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9464 /// address materialization and register allocation, but may also be required 9465 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9466 /// alloca in the entry block, then the runtime may assume that the alloca's 9467 /// StackMap location can be read immediately after compilation and that the 9468 /// location is valid at any point during execution (this is similar to the 9469 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9470 /// only available in a register, then the runtime would need to trap when 9471 /// execution reaches the StackMap in order to read the alloca's location. 9472 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9473 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9474 SelectionDAGBuilder &Builder) { 9475 SelectionDAG &DAG = Builder.DAG; 9476 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9477 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9478 9479 // Things on the stack are pointer-typed, meaning that they are already 9480 // legal and can be emitted directly to target nodes. 9481 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9482 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9483 } else { 9484 // Otherwise emit a target independent node to be legalised. 9485 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9486 } 9487 } 9488 } 9489 9490 /// Lower llvm.experimental.stackmap. 9491 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9492 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9493 // [live variables...]) 9494 9495 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9496 9497 SDValue Chain, InFlag, Callee; 9498 SmallVector<SDValue, 32> Ops; 9499 9500 SDLoc DL = getCurSDLoc(); 9501 Callee = getValue(CI.getCalledOperand()); 9502 9503 // The stackmap intrinsic only records the live variables (the arguments 9504 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9505 // intrinsic, this won't be lowered to a function call. This means we don't 9506 // have to worry about calling conventions and target specific lowering code. 9507 // Instead we perform the call lowering right here. 9508 // 9509 // chain, flag = CALLSEQ_START(chain, 0, 0) 9510 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9511 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9512 // 9513 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9514 InFlag = Chain.getValue(1); 9515 9516 // Add the STACKMAP operands, starting with DAG house-keeping. 9517 Ops.push_back(Chain); 9518 Ops.push_back(InFlag); 9519 9520 // Add the <id>, <numShadowBytes> operands. 9521 // 9522 // These do not require legalisation, and can be emitted directly to target 9523 // constant nodes. 9524 SDValue ID = getValue(CI.getArgOperand(0)); 9525 assert(ID.getValueType() == MVT::i64); 9526 SDValue IDConst = DAG.getTargetConstant( 9527 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9528 Ops.push_back(IDConst); 9529 9530 SDValue Shad = getValue(CI.getArgOperand(1)); 9531 assert(Shad.getValueType() == MVT::i32); 9532 SDValue ShadConst = DAG.getTargetConstant( 9533 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9534 Ops.push_back(ShadConst); 9535 9536 // Add the live variables. 9537 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9538 9539 // Create the STACKMAP node. 9540 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9541 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9542 InFlag = Chain.getValue(1); 9543 9544 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL); 9545 9546 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9547 9548 // Set the root to the target-lowered call chain. 9549 DAG.setRoot(Chain); 9550 9551 // Inform the Frame Information that we have a stackmap in this function. 9552 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9553 } 9554 9555 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9556 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9557 const BasicBlock *EHPadBB) { 9558 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9559 // i32 <numBytes>, 9560 // i8* <target>, 9561 // i32 <numArgs>, 9562 // [Args...], 9563 // [live variables...]) 9564 9565 CallingConv::ID CC = CB.getCallingConv(); 9566 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9567 bool HasDef = !CB.getType()->isVoidTy(); 9568 SDLoc dl = getCurSDLoc(); 9569 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9570 9571 // Handle immediate and symbolic callees. 9572 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9573 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9574 /*isTarget=*/true); 9575 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9576 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9577 SDLoc(SymbolicCallee), 9578 SymbolicCallee->getValueType(0)); 9579 9580 // Get the real number of arguments participating in the call <numArgs> 9581 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9582 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9583 9584 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9585 // Intrinsics include all meta-operands up to but not including CC. 9586 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9587 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9588 "Not enough arguments provided to the patchpoint intrinsic"); 9589 9590 // For AnyRegCC the arguments are lowered later on manually. 9591 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9592 Type *ReturnTy = 9593 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9594 9595 TargetLowering::CallLoweringInfo CLI(DAG); 9596 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9597 ReturnTy, true); 9598 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9599 9600 SDNode *CallEnd = Result.second.getNode(); 9601 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9602 CallEnd = CallEnd->getOperand(0).getNode(); 9603 9604 /// Get a call instruction from the call sequence chain. 9605 /// Tail calls are not allowed. 9606 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9607 "Expected a callseq node."); 9608 SDNode *Call = CallEnd->getOperand(0).getNode(); 9609 bool HasGlue = Call->getGluedNode(); 9610 9611 // Replace the target specific call node with the patchable intrinsic. 9612 SmallVector<SDValue, 8> Ops; 9613 9614 // Push the chain. 9615 Ops.push_back(*(Call->op_begin())); 9616 9617 // Optionally, push the glue (if any). 9618 if (HasGlue) 9619 Ops.push_back(*(Call->op_end() - 1)); 9620 9621 // Push the register mask info. 9622 if (HasGlue) 9623 Ops.push_back(*(Call->op_end() - 2)); 9624 else 9625 Ops.push_back(*(Call->op_end() - 1)); 9626 9627 // Add the <id> and <numBytes> constants. 9628 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9629 Ops.push_back(DAG.getTargetConstant( 9630 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9631 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9632 Ops.push_back(DAG.getTargetConstant( 9633 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9634 MVT::i32)); 9635 9636 // Add the callee. 9637 Ops.push_back(Callee); 9638 9639 // Adjust <numArgs> to account for any arguments that have been passed on the 9640 // stack instead. 9641 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9642 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9643 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9644 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9645 9646 // Add the calling convention 9647 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9648 9649 // Add the arguments we omitted previously. The register allocator should 9650 // place these in any free register. 9651 if (IsAnyRegCC) 9652 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9653 Ops.push_back(getValue(CB.getArgOperand(i))); 9654 9655 // Push the arguments from the call instruction. 9656 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9657 Ops.append(Call->op_begin() + 2, e); 9658 9659 // Push live variables for the stack map. 9660 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9661 9662 SDVTList NodeTys; 9663 if (IsAnyRegCC && HasDef) { 9664 // Create the return types based on the intrinsic definition 9665 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9666 SmallVector<EVT, 3> ValueVTs; 9667 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9668 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9669 9670 // There is always a chain and a glue type at the end 9671 ValueVTs.push_back(MVT::Other); 9672 ValueVTs.push_back(MVT::Glue); 9673 NodeTys = DAG.getVTList(ValueVTs); 9674 } else 9675 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9676 9677 // Replace the target specific call node with a PATCHPOINT node. 9678 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9679 9680 // Update the NodeMap. 9681 if (HasDef) { 9682 if (IsAnyRegCC) 9683 setValue(&CB, SDValue(PPV.getNode(), 0)); 9684 else 9685 setValue(&CB, Result.first); 9686 } 9687 9688 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9689 // call sequence. Furthermore the location of the chain and glue can change 9690 // when the AnyReg calling convention is used and the intrinsic returns a 9691 // value. 9692 if (IsAnyRegCC && HasDef) { 9693 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9694 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9695 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9696 } else 9697 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9698 DAG.DeleteNode(Call); 9699 9700 // Inform the Frame Information that we have a patchpoint in this function. 9701 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9702 } 9703 9704 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9705 unsigned Intrinsic) { 9706 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9707 SDValue Op1 = getValue(I.getArgOperand(0)); 9708 SDValue Op2; 9709 if (I.arg_size() > 1) 9710 Op2 = getValue(I.getArgOperand(1)); 9711 SDLoc dl = getCurSDLoc(); 9712 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9713 SDValue Res; 9714 SDNodeFlags SDFlags; 9715 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9716 SDFlags.copyFMF(*FPMO); 9717 9718 switch (Intrinsic) { 9719 case Intrinsic::vector_reduce_fadd: 9720 if (SDFlags.hasAllowReassociation()) 9721 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9722 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9723 SDFlags); 9724 else 9725 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9726 break; 9727 case Intrinsic::vector_reduce_fmul: 9728 if (SDFlags.hasAllowReassociation()) 9729 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9730 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9731 SDFlags); 9732 else 9733 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9734 break; 9735 case Intrinsic::vector_reduce_add: 9736 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9737 break; 9738 case Intrinsic::vector_reduce_mul: 9739 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9740 break; 9741 case Intrinsic::vector_reduce_and: 9742 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9743 break; 9744 case Intrinsic::vector_reduce_or: 9745 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9746 break; 9747 case Intrinsic::vector_reduce_xor: 9748 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9749 break; 9750 case Intrinsic::vector_reduce_smax: 9751 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9752 break; 9753 case Intrinsic::vector_reduce_smin: 9754 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9755 break; 9756 case Intrinsic::vector_reduce_umax: 9757 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9758 break; 9759 case Intrinsic::vector_reduce_umin: 9760 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9761 break; 9762 case Intrinsic::vector_reduce_fmax: 9763 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9764 break; 9765 case Intrinsic::vector_reduce_fmin: 9766 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9767 break; 9768 default: 9769 llvm_unreachable("Unhandled vector reduce intrinsic"); 9770 } 9771 setValue(&I, Res); 9772 } 9773 9774 /// Returns an AttributeList representing the attributes applied to the return 9775 /// value of the given call. 9776 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9777 SmallVector<Attribute::AttrKind, 2> Attrs; 9778 if (CLI.RetSExt) 9779 Attrs.push_back(Attribute::SExt); 9780 if (CLI.RetZExt) 9781 Attrs.push_back(Attribute::ZExt); 9782 if (CLI.IsInReg) 9783 Attrs.push_back(Attribute::InReg); 9784 9785 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9786 Attrs); 9787 } 9788 9789 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9790 /// implementation, which just calls LowerCall. 9791 /// FIXME: When all targets are 9792 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9793 std::pair<SDValue, SDValue> 9794 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9795 // Handle the incoming return values from the call. 9796 CLI.Ins.clear(); 9797 Type *OrigRetTy = CLI.RetTy; 9798 SmallVector<EVT, 4> RetTys; 9799 SmallVector<uint64_t, 4> Offsets; 9800 auto &DL = CLI.DAG.getDataLayout(); 9801 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9802 9803 if (CLI.IsPostTypeLegalization) { 9804 // If we are lowering a libcall after legalization, split the return type. 9805 SmallVector<EVT, 4> OldRetTys; 9806 SmallVector<uint64_t, 4> OldOffsets; 9807 RetTys.swap(OldRetTys); 9808 Offsets.swap(OldOffsets); 9809 9810 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9811 EVT RetVT = OldRetTys[i]; 9812 uint64_t Offset = OldOffsets[i]; 9813 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9814 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9815 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9816 RetTys.append(NumRegs, RegisterVT); 9817 for (unsigned j = 0; j != NumRegs; ++j) 9818 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9819 } 9820 } 9821 9822 SmallVector<ISD::OutputArg, 4> Outs; 9823 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9824 9825 bool CanLowerReturn = 9826 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9827 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9828 9829 SDValue DemoteStackSlot; 9830 int DemoteStackIdx = -100; 9831 if (!CanLowerReturn) { 9832 // FIXME: equivalent assert? 9833 // assert(!CS.hasInAllocaArgument() && 9834 // "sret demotion is incompatible with inalloca"); 9835 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9836 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9837 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9838 DemoteStackIdx = 9839 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9840 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9841 DL.getAllocaAddrSpace()); 9842 9843 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9844 ArgListEntry Entry; 9845 Entry.Node = DemoteStackSlot; 9846 Entry.Ty = StackSlotPtrType; 9847 Entry.IsSExt = false; 9848 Entry.IsZExt = false; 9849 Entry.IsInReg = false; 9850 Entry.IsSRet = true; 9851 Entry.IsNest = false; 9852 Entry.IsByVal = false; 9853 Entry.IsByRef = false; 9854 Entry.IsReturned = false; 9855 Entry.IsSwiftSelf = false; 9856 Entry.IsSwiftAsync = false; 9857 Entry.IsSwiftError = false; 9858 Entry.IsCFGuardTarget = false; 9859 Entry.Alignment = Alignment; 9860 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9861 CLI.NumFixedArgs += 1; 9862 CLI.getArgs()[0].IndirectType = CLI.RetTy; 9863 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9864 9865 // sret demotion isn't compatible with tail-calls, since the sret argument 9866 // points into the callers stack frame. 9867 CLI.IsTailCall = false; 9868 } else { 9869 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9870 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9871 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9872 ISD::ArgFlagsTy Flags; 9873 if (NeedsRegBlock) { 9874 Flags.setInConsecutiveRegs(); 9875 if (I == RetTys.size() - 1) 9876 Flags.setInConsecutiveRegsLast(); 9877 } 9878 EVT VT = RetTys[I]; 9879 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9880 CLI.CallConv, VT); 9881 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9882 CLI.CallConv, VT); 9883 for (unsigned i = 0; i != NumRegs; ++i) { 9884 ISD::InputArg MyFlags; 9885 MyFlags.Flags = Flags; 9886 MyFlags.VT = RegisterVT; 9887 MyFlags.ArgVT = VT; 9888 MyFlags.Used = CLI.IsReturnValueUsed; 9889 if (CLI.RetTy->isPointerTy()) { 9890 MyFlags.Flags.setPointer(); 9891 MyFlags.Flags.setPointerAddrSpace( 9892 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9893 } 9894 if (CLI.RetSExt) 9895 MyFlags.Flags.setSExt(); 9896 if (CLI.RetZExt) 9897 MyFlags.Flags.setZExt(); 9898 if (CLI.IsInReg) 9899 MyFlags.Flags.setInReg(); 9900 CLI.Ins.push_back(MyFlags); 9901 } 9902 } 9903 } 9904 9905 // We push in swifterror return as the last element of CLI.Ins. 9906 ArgListTy &Args = CLI.getArgs(); 9907 if (supportSwiftError()) { 9908 for (const ArgListEntry &Arg : Args) { 9909 if (Arg.IsSwiftError) { 9910 ISD::InputArg MyFlags; 9911 MyFlags.VT = getPointerTy(DL); 9912 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9913 MyFlags.Flags.setSwiftError(); 9914 CLI.Ins.push_back(MyFlags); 9915 } 9916 } 9917 } 9918 9919 // Handle all of the outgoing arguments. 9920 CLI.Outs.clear(); 9921 CLI.OutVals.clear(); 9922 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9923 SmallVector<EVT, 4> ValueVTs; 9924 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9925 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9926 Type *FinalType = Args[i].Ty; 9927 if (Args[i].IsByVal) 9928 FinalType = Args[i].IndirectType; 9929 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9930 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 9931 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9932 ++Value) { 9933 EVT VT = ValueVTs[Value]; 9934 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9935 SDValue Op = SDValue(Args[i].Node.getNode(), 9936 Args[i].Node.getResNo() + Value); 9937 ISD::ArgFlagsTy Flags; 9938 9939 // Certain targets (such as MIPS), may have a different ABI alignment 9940 // for a type depending on the context. Give the target a chance to 9941 // specify the alignment it wants. 9942 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9943 Flags.setOrigAlign(OriginalAlignment); 9944 9945 if (Args[i].Ty->isPointerTy()) { 9946 Flags.setPointer(); 9947 Flags.setPointerAddrSpace( 9948 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9949 } 9950 if (Args[i].IsZExt) 9951 Flags.setZExt(); 9952 if (Args[i].IsSExt) 9953 Flags.setSExt(); 9954 if (Args[i].IsInReg) { 9955 // If we are using vectorcall calling convention, a structure that is 9956 // passed InReg - is surely an HVA 9957 if (CLI.CallConv == CallingConv::X86_VectorCall && 9958 isa<StructType>(FinalType)) { 9959 // The first value of a structure is marked 9960 if (0 == Value) 9961 Flags.setHvaStart(); 9962 Flags.setHva(); 9963 } 9964 // Set InReg Flag 9965 Flags.setInReg(); 9966 } 9967 if (Args[i].IsSRet) 9968 Flags.setSRet(); 9969 if (Args[i].IsSwiftSelf) 9970 Flags.setSwiftSelf(); 9971 if (Args[i].IsSwiftAsync) 9972 Flags.setSwiftAsync(); 9973 if (Args[i].IsSwiftError) 9974 Flags.setSwiftError(); 9975 if (Args[i].IsCFGuardTarget) 9976 Flags.setCFGuardTarget(); 9977 if (Args[i].IsByVal) 9978 Flags.setByVal(); 9979 if (Args[i].IsByRef) 9980 Flags.setByRef(); 9981 if (Args[i].IsPreallocated) { 9982 Flags.setPreallocated(); 9983 // Set the byval flag for CCAssignFn callbacks that don't know about 9984 // preallocated. This way we can know how many bytes we should've 9985 // allocated and how many bytes a callee cleanup function will pop. If 9986 // we port preallocated to more targets, we'll have to add custom 9987 // preallocated handling in the various CC lowering callbacks. 9988 Flags.setByVal(); 9989 } 9990 if (Args[i].IsInAlloca) { 9991 Flags.setInAlloca(); 9992 // Set the byval flag for CCAssignFn callbacks that don't know about 9993 // inalloca. This way we can know how many bytes we should've allocated 9994 // and how many bytes a callee cleanup function will pop. If we port 9995 // inalloca to more targets, we'll have to add custom inalloca handling 9996 // in the various CC lowering callbacks. 9997 Flags.setByVal(); 9998 } 9999 Align MemAlign; 10000 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10001 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10002 Flags.setByValSize(FrameSize); 10003 10004 // info is not there but there are cases it cannot get right. 10005 if (auto MA = Args[i].Alignment) 10006 MemAlign = *MA; 10007 else 10008 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10009 } else if (auto MA = Args[i].Alignment) { 10010 MemAlign = *MA; 10011 } else { 10012 MemAlign = OriginalAlignment; 10013 } 10014 Flags.setMemAlign(MemAlign); 10015 if (Args[i].IsNest) 10016 Flags.setNest(); 10017 if (NeedsRegBlock) 10018 Flags.setInConsecutiveRegs(); 10019 10020 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10021 CLI.CallConv, VT); 10022 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10023 CLI.CallConv, VT); 10024 SmallVector<SDValue, 4> Parts(NumParts); 10025 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10026 10027 if (Args[i].IsSExt) 10028 ExtendKind = ISD::SIGN_EXTEND; 10029 else if (Args[i].IsZExt) 10030 ExtendKind = ISD::ZERO_EXTEND; 10031 10032 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10033 // for now. 10034 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10035 CanLowerReturn) { 10036 assert((CLI.RetTy == Args[i].Ty || 10037 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10038 CLI.RetTy->getPointerAddressSpace() == 10039 Args[i].Ty->getPointerAddressSpace())) && 10040 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10041 // Before passing 'returned' to the target lowering code, ensure that 10042 // either the register MVT and the actual EVT are the same size or that 10043 // the return value and argument are extended in the same way; in these 10044 // cases it's safe to pass the argument register value unchanged as the 10045 // return register value (although it's at the target's option whether 10046 // to do so) 10047 // TODO: allow code generation to take advantage of partially preserved 10048 // registers rather than clobbering the entire register when the 10049 // parameter extension method is not compatible with the return 10050 // extension method 10051 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10052 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10053 CLI.RetZExt == Args[i].IsZExt)) 10054 Flags.setReturned(); 10055 } 10056 10057 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10058 CLI.CallConv, ExtendKind); 10059 10060 for (unsigned j = 0; j != NumParts; ++j) { 10061 // if it isn't first piece, alignment must be 1 10062 // For scalable vectors the scalable part is currently handled 10063 // by individual targets, so we just use the known minimum size here. 10064 ISD::OutputArg MyFlags( 10065 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10066 i < CLI.NumFixedArgs, i, 10067 j * Parts[j].getValueType().getStoreSize().getKnownMinSize()); 10068 if (NumParts > 1 && j == 0) 10069 MyFlags.Flags.setSplit(); 10070 else if (j != 0) { 10071 MyFlags.Flags.setOrigAlign(Align(1)); 10072 if (j == NumParts - 1) 10073 MyFlags.Flags.setSplitEnd(); 10074 } 10075 10076 CLI.Outs.push_back(MyFlags); 10077 CLI.OutVals.push_back(Parts[j]); 10078 } 10079 10080 if (NeedsRegBlock && Value == NumValues - 1) 10081 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10082 } 10083 } 10084 10085 SmallVector<SDValue, 4> InVals; 10086 CLI.Chain = LowerCall(CLI, InVals); 10087 10088 // Update CLI.InVals to use outside of this function. 10089 CLI.InVals = InVals; 10090 10091 // Verify that the target's LowerCall behaved as expected. 10092 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10093 "LowerCall didn't return a valid chain!"); 10094 assert((!CLI.IsTailCall || InVals.empty()) && 10095 "LowerCall emitted a return value for a tail call!"); 10096 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10097 "LowerCall didn't emit the correct number of values!"); 10098 10099 // For a tail call, the return value is merely live-out and there aren't 10100 // any nodes in the DAG representing it. Return a special value to 10101 // indicate that a tail call has been emitted and no more Instructions 10102 // should be processed in the current block. 10103 if (CLI.IsTailCall) { 10104 CLI.DAG.setRoot(CLI.Chain); 10105 return std::make_pair(SDValue(), SDValue()); 10106 } 10107 10108 #ifndef NDEBUG 10109 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10110 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10111 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10112 "LowerCall emitted a value with the wrong type!"); 10113 } 10114 #endif 10115 10116 SmallVector<SDValue, 4> ReturnValues; 10117 if (!CanLowerReturn) { 10118 // The instruction result is the result of loading from the 10119 // hidden sret parameter. 10120 SmallVector<EVT, 1> PVTs; 10121 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10122 10123 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10124 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10125 EVT PtrVT = PVTs[0]; 10126 10127 unsigned NumValues = RetTys.size(); 10128 ReturnValues.resize(NumValues); 10129 SmallVector<SDValue, 4> Chains(NumValues); 10130 10131 // An aggregate return value cannot wrap around the address space, so 10132 // offsets to its parts don't wrap either. 10133 SDNodeFlags Flags; 10134 Flags.setNoUnsignedWrap(true); 10135 10136 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10137 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10138 for (unsigned i = 0; i < NumValues; ++i) { 10139 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10140 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10141 PtrVT), Flags); 10142 SDValue L = CLI.DAG.getLoad( 10143 RetTys[i], CLI.DL, CLI.Chain, Add, 10144 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10145 DemoteStackIdx, Offsets[i]), 10146 HiddenSRetAlign); 10147 ReturnValues[i] = L; 10148 Chains[i] = L.getValue(1); 10149 } 10150 10151 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10152 } else { 10153 // Collect the legal value parts into potentially illegal values 10154 // that correspond to the original function's return values. 10155 Optional<ISD::NodeType> AssertOp; 10156 if (CLI.RetSExt) 10157 AssertOp = ISD::AssertSext; 10158 else if (CLI.RetZExt) 10159 AssertOp = ISD::AssertZext; 10160 unsigned CurReg = 0; 10161 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10162 EVT VT = RetTys[I]; 10163 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10164 CLI.CallConv, VT); 10165 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10166 CLI.CallConv, VT); 10167 10168 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10169 NumRegs, RegisterVT, VT, nullptr, 10170 CLI.CallConv, AssertOp)); 10171 CurReg += NumRegs; 10172 } 10173 10174 // For a function returning void, there is no return value. We can't create 10175 // such a node, so we just return a null return value in that case. In 10176 // that case, nothing will actually look at the value. 10177 if (ReturnValues.empty()) 10178 return std::make_pair(SDValue(), CLI.Chain); 10179 } 10180 10181 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10182 CLI.DAG.getVTList(RetTys), ReturnValues); 10183 return std::make_pair(Res, CLI.Chain); 10184 } 10185 10186 /// Places new result values for the node in Results (their number 10187 /// and types must exactly match those of the original return values of 10188 /// the node), or leaves Results empty, which indicates that the node is not 10189 /// to be custom lowered after all. 10190 void TargetLowering::LowerOperationWrapper(SDNode *N, 10191 SmallVectorImpl<SDValue> &Results, 10192 SelectionDAG &DAG) const { 10193 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10194 10195 if (!Res.getNode()) 10196 return; 10197 10198 // If the original node has one result, take the return value from 10199 // LowerOperation as is. It might not be result number 0. 10200 if (N->getNumValues() == 1) { 10201 Results.push_back(Res); 10202 return; 10203 } 10204 10205 // If the original node has multiple results, then the return node should 10206 // have the same number of results. 10207 assert((N->getNumValues() == Res->getNumValues()) && 10208 "Lowering returned the wrong number of results!"); 10209 10210 // Places new result values base on N result number. 10211 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10212 Results.push_back(Res.getValue(I)); 10213 } 10214 10215 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10216 llvm_unreachable("LowerOperation not implemented for this target!"); 10217 } 10218 10219 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10220 unsigned Reg, 10221 ISD::NodeType ExtendType) { 10222 SDValue Op = getNonRegisterValue(V); 10223 assert((Op.getOpcode() != ISD::CopyFromReg || 10224 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10225 "Copy from a reg to the same reg!"); 10226 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10227 10228 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10229 // If this is an InlineAsm we have to match the registers required, not the 10230 // notional registers required by the type. 10231 10232 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10233 None); // This is not an ABI copy. 10234 SDValue Chain = DAG.getEntryNode(); 10235 10236 if (ExtendType == ISD::ANY_EXTEND) { 10237 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10238 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10239 ExtendType = PreferredExtendIt->second; 10240 } 10241 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10242 PendingExports.push_back(Chain); 10243 } 10244 10245 #include "llvm/CodeGen/SelectionDAGISel.h" 10246 10247 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10248 /// entry block, return true. This includes arguments used by switches, since 10249 /// the switch may expand into multiple basic blocks. 10250 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10251 // With FastISel active, we may be splitting blocks, so force creation 10252 // of virtual registers for all non-dead arguments. 10253 if (FastISel) 10254 return A->use_empty(); 10255 10256 const BasicBlock &Entry = A->getParent()->front(); 10257 for (const User *U : A->users()) 10258 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10259 return false; // Use not in entry block. 10260 10261 return true; 10262 } 10263 10264 using ArgCopyElisionMapTy = 10265 DenseMap<const Argument *, 10266 std::pair<const AllocaInst *, const StoreInst *>>; 10267 10268 /// Scan the entry block of the function in FuncInfo for arguments that look 10269 /// like copies into a local alloca. Record any copied arguments in 10270 /// ArgCopyElisionCandidates. 10271 static void 10272 findArgumentCopyElisionCandidates(const DataLayout &DL, 10273 FunctionLoweringInfo *FuncInfo, 10274 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10275 // Record the state of every static alloca used in the entry block. Argument 10276 // allocas are all used in the entry block, so we need approximately as many 10277 // entries as we have arguments. 10278 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10279 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10280 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10281 StaticAllocas.reserve(NumArgs * 2); 10282 10283 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10284 if (!V) 10285 return nullptr; 10286 V = V->stripPointerCasts(); 10287 const auto *AI = dyn_cast<AllocaInst>(V); 10288 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10289 return nullptr; 10290 auto Iter = StaticAllocas.insert({AI, Unknown}); 10291 return &Iter.first->second; 10292 }; 10293 10294 // Look for stores of arguments to static allocas. Look through bitcasts and 10295 // GEPs to handle type coercions, as long as the alloca is fully initialized 10296 // by the store. Any non-store use of an alloca escapes it and any subsequent 10297 // unanalyzed store might write it. 10298 // FIXME: Handle structs initialized with multiple stores. 10299 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10300 // Look for stores, and handle non-store uses conservatively. 10301 const auto *SI = dyn_cast<StoreInst>(&I); 10302 if (!SI) { 10303 // We will look through cast uses, so ignore them completely. 10304 if (I.isCast()) 10305 continue; 10306 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10307 // to allocas. 10308 if (I.isDebugOrPseudoInst()) 10309 continue; 10310 // This is an unknown instruction. Assume it escapes or writes to all 10311 // static alloca operands. 10312 for (const Use &U : I.operands()) { 10313 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10314 *Info = StaticAllocaInfo::Clobbered; 10315 } 10316 continue; 10317 } 10318 10319 // If the stored value is a static alloca, mark it as escaped. 10320 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10321 *Info = StaticAllocaInfo::Clobbered; 10322 10323 // Check if the destination is a static alloca. 10324 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10325 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10326 if (!Info) 10327 continue; 10328 const AllocaInst *AI = cast<AllocaInst>(Dst); 10329 10330 // Skip allocas that have been initialized or clobbered. 10331 if (*Info != StaticAllocaInfo::Unknown) 10332 continue; 10333 10334 // Check if the stored value is an argument, and that this store fully 10335 // initializes the alloca. 10336 // If the argument type has padding bits we can't directly forward a pointer 10337 // as the upper bits may contain garbage. 10338 // Don't elide copies from the same argument twice. 10339 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10340 const auto *Arg = dyn_cast<Argument>(Val); 10341 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10342 Arg->getType()->isEmptyTy() || 10343 DL.getTypeStoreSize(Arg->getType()) != 10344 DL.getTypeAllocSize(AI->getAllocatedType()) || 10345 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10346 ArgCopyElisionCandidates.count(Arg)) { 10347 *Info = StaticAllocaInfo::Clobbered; 10348 continue; 10349 } 10350 10351 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10352 << '\n'); 10353 10354 // Mark this alloca and store for argument copy elision. 10355 *Info = StaticAllocaInfo::Elidable; 10356 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10357 10358 // Stop scanning if we've seen all arguments. This will happen early in -O0 10359 // builds, which is useful, because -O0 builds have large entry blocks and 10360 // many allocas. 10361 if (ArgCopyElisionCandidates.size() == NumArgs) 10362 break; 10363 } 10364 } 10365 10366 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10367 /// ArgVal is a load from a suitable fixed stack object. 10368 static void tryToElideArgumentCopy( 10369 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10370 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10371 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10372 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10373 SDValue ArgVal, bool &ArgHasUses) { 10374 // Check if this is a load from a fixed stack object. 10375 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10376 if (!LNode) 10377 return; 10378 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10379 if (!FINode) 10380 return; 10381 10382 // Check that the fixed stack object is the right size and alignment. 10383 // Look at the alignment that the user wrote on the alloca instead of looking 10384 // at the stack object. 10385 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10386 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10387 const AllocaInst *AI = ArgCopyIter->second.first; 10388 int FixedIndex = FINode->getIndex(); 10389 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10390 int OldIndex = AllocaIndex; 10391 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10392 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10393 LLVM_DEBUG( 10394 dbgs() << " argument copy elision failed due to bad fixed stack " 10395 "object size\n"); 10396 return; 10397 } 10398 Align RequiredAlignment = AI->getAlign(); 10399 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10400 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10401 "greater than stack argument alignment (" 10402 << DebugStr(RequiredAlignment) << " vs " 10403 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10404 return; 10405 } 10406 10407 // Perform the elision. Delete the old stack object and replace its only use 10408 // in the variable info map. Mark the stack object as mutable. 10409 LLVM_DEBUG({ 10410 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10411 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10412 << '\n'; 10413 }); 10414 MFI.RemoveStackObject(OldIndex); 10415 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10416 AllocaIndex = FixedIndex; 10417 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10418 Chains.push_back(ArgVal.getValue(1)); 10419 10420 // Avoid emitting code for the store implementing the copy. 10421 const StoreInst *SI = ArgCopyIter->second.second; 10422 ElidedArgCopyInstrs.insert(SI); 10423 10424 // Check for uses of the argument again so that we can avoid exporting ArgVal 10425 // if it is't used by anything other than the store. 10426 for (const Value *U : Arg.users()) { 10427 if (U != SI) { 10428 ArgHasUses = true; 10429 break; 10430 } 10431 } 10432 } 10433 10434 void SelectionDAGISel::LowerArguments(const Function &F) { 10435 SelectionDAG &DAG = SDB->DAG; 10436 SDLoc dl = SDB->getCurSDLoc(); 10437 const DataLayout &DL = DAG.getDataLayout(); 10438 SmallVector<ISD::InputArg, 16> Ins; 10439 10440 // In Naked functions we aren't going to save any registers. 10441 if (F.hasFnAttribute(Attribute::Naked)) 10442 return; 10443 10444 if (!FuncInfo->CanLowerReturn) { 10445 // Put in an sret pointer parameter before all the other parameters. 10446 SmallVector<EVT, 1> ValueVTs; 10447 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10448 F.getReturnType()->getPointerTo( 10449 DAG.getDataLayout().getAllocaAddrSpace()), 10450 ValueVTs); 10451 10452 // NOTE: Assuming that a pointer will never break down to more than one VT 10453 // or one register. 10454 ISD::ArgFlagsTy Flags; 10455 Flags.setSRet(); 10456 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10457 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10458 ISD::InputArg::NoArgIndex, 0); 10459 Ins.push_back(RetArg); 10460 } 10461 10462 // Look for stores of arguments to static allocas. Mark such arguments with a 10463 // flag to ask the target to give us the memory location of that argument if 10464 // available. 10465 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10466 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10467 ArgCopyElisionCandidates); 10468 10469 // Set up the incoming argument description vector. 10470 for (const Argument &Arg : F.args()) { 10471 unsigned ArgNo = Arg.getArgNo(); 10472 SmallVector<EVT, 4> ValueVTs; 10473 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10474 bool isArgValueUsed = !Arg.use_empty(); 10475 unsigned PartBase = 0; 10476 Type *FinalType = Arg.getType(); 10477 if (Arg.hasAttribute(Attribute::ByVal)) 10478 FinalType = Arg.getParamByValType(); 10479 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10480 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10481 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10482 Value != NumValues; ++Value) { 10483 EVT VT = ValueVTs[Value]; 10484 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10485 ISD::ArgFlagsTy Flags; 10486 10487 10488 if (Arg.getType()->isPointerTy()) { 10489 Flags.setPointer(); 10490 Flags.setPointerAddrSpace( 10491 cast<PointerType>(Arg.getType())->getAddressSpace()); 10492 } 10493 if (Arg.hasAttribute(Attribute::ZExt)) 10494 Flags.setZExt(); 10495 if (Arg.hasAttribute(Attribute::SExt)) 10496 Flags.setSExt(); 10497 if (Arg.hasAttribute(Attribute::InReg)) { 10498 // If we are using vectorcall calling convention, a structure that is 10499 // passed InReg - is surely an HVA 10500 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10501 isa<StructType>(Arg.getType())) { 10502 // The first value of a structure is marked 10503 if (0 == Value) 10504 Flags.setHvaStart(); 10505 Flags.setHva(); 10506 } 10507 // Set InReg Flag 10508 Flags.setInReg(); 10509 } 10510 if (Arg.hasAttribute(Attribute::StructRet)) 10511 Flags.setSRet(); 10512 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10513 Flags.setSwiftSelf(); 10514 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10515 Flags.setSwiftAsync(); 10516 if (Arg.hasAttribute(Attribute::SwiftError)) 10517 Flags.setSwiftError(); 10518 if (Arg.hasAttribute(Attribute::ByVal)) 10519 Flags.setByVal(); 10520 if (Arg.hasAttribute(Attribute::ByRef)) 10521 Flags.setByRef(); 10522 if (Arg.hasAttribute(Attribute::InAlloca)) { 10523 Flags.setInAlloca(); 10524 // Set the byval flag for CCAssignFn callbacks that don't know about 10525 // inalloca. This way we can know how many bytes we should've allocated 10526 // and how many bytes a callee cleanup function will pop. If we port 10527 // inalloca to more targets, we'll have to add custom inalloca handling 10528 // in the various CC lowering callbacks. 10529 Flags.setByVal(); 10530 } 10531 if (Arg.hasAttribute(Attribute::Preallocated)) { 10532 Flags.setPreallocated(); 10533 // Set the byval flag for CCAssignFn callbacks that don't know about 10534 // preallocated. This way we can know how many bytes we should've 10535 // allocated and how many bytes a callee cleanup function will pop. If 10536 // we port preallocated to more targets, we'll have to add custom 10537 // preallocated handling in the various CC lowering callbacks. 10538 Flags.setByVal(); 10539 } 10540 10541 // Certain targets (such as MIPS), may have a different ABI alignment 10542 // for a type depending on the context. Give the target a chance to 10543 // specify the alignment it wants. 10544 const Align OriginalAlignment( 10545 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10546 Flags.setOrigAlign(OriginalAlignment); 10547 10548 Align MemAlign; 10549 Type *ArgMemTy = nullptr; 10550 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10551 Flags.isByRef()) { 10552 if (!ArgMemTy) 10553 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10554 10555 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10556 10557 // For in-memory arguments, size and alignment should be passed from FE. 10558 // BE will guess if this info is not there but there are cases it cannot 10559 // get right. 10560 if (auto ParamAlign = Arg.getParamStackAlign()) 10561 MemAlign = *ParamAlign; 10562 else if ((ParamAlign = Arg.getParamAlign())) 10563 MemAlign = *ParamAlign; 10564 else 10565 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10566 if (Flags.isByRef()) 10567 Flags.setByRefSize(MemSize); 10568 else 10569 Flags.setByValSize(MemSize); 10570 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10571 MemAlign = *ParamAlign; 10572 } else { 10573 MemAlign = OriginalAlignment; 10574 } 10575 Flags.setMemAlign(MemAlign); 10576 10577 if (Arg.hasAttribute(Attribute::Nest)) 10578 Flags.setNest(); 10579 if (NeedsRegBlock) 10580 Flags.setInConsecutiveRegs(); 10581 if (ArgCopyElisionCandidates.count(&Arg)) 10582 Flags.setCopyElisionCandidate(); 10583 if (Arg.hasAttribute(Attribute::Returned)) 10584 Flags.setReturned(); 10585 10586 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10587 *CurDAG->getContext(), F.getCallingConv(), VT); 10588 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10589 *CurDAG->getContext(), F.getCallingConv(), VT); 10590 for (unsigned i = 0; i != NumRegs; ++i) { 10591 // For scalable vectors, use the minimum size; individual targets 10592 // are responsible for handling scalable vector arguments and 10593 // return values. 10594 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10595 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10596 if (NumRegs > 1 && i == 0) 10597 MyFlags.Flags.setSplit(); 10598 // if it isn't first piece, alignment must be 1 10599 else if (i > 0) { 10600 MyFlags.Flags.setOrigAlign(Align(1)); 10601 if (i == NumRegs - 1) 10602 MyFlags.Flags.setSplitEnd(); 10603 } 10604 Ins.push_back(MyFlags); 10605 } 10606 if (NeedsRegBlock && Value == NumValues - 1) 10607 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10608 PartBase += VT.getStoreSize().getKnownMinSize(); 10609 } 10610 } 10611 10612 // Call the target to set up the argument values. 10613 SmallVector<SDValue, 8> InVals; 10614 SDValue NewRoot = TLI->LowerFormalArguments( 10615 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10616 10617 // Verify that the target's LowerFormalArguments behaved as expected. 10618 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10619 "LowerFormalArguments didn't return a valid chain!"); 10620 assert(InVals.size() == Ins.size() && 10621 "LowerFormalArguments didn't emit the correct number of values!"); 10622 LLVM_DEBUG({ 10623 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10624 assert(InVals[i].getNode() && 10625 "LowerFormalArguments emitted a null value!"); 10626 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10627 "LowerFormalArguments emitted a value with the wrong type!"); 10628 } 10629 }); 10630 10631 // Update the DAG with the new chain value resulting from argument lowering. 10632 DAG.setRoot(NewRoot); 10633 10634 // Set up the argument values. 10635 unsigned i = 0; 10636 if (!FuncInfo->CanLowerReturn) { 10637 // Create a virtual register for the sret pointer, and put in a copy 10638 // from the sret argument into it. 10639 SmallVector<EVT, 1> ValueVTs; 10640 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10641 F.getReturnType()->getPointerTo( 10642 DAG.getDataLayout().getAllocaAddrSpace()), 10643 ValueVTs); 10644 MVT VT = ValueVTs[0].getSimpleVT(); 10645 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10646 Optional<ISD::NodeType> AssertOp; 10647 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10648 nullptr, F.getCallingConv(), AssertOp); 10649 10650 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10651 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10652 Register SRetReg = 10653 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10654 FuncInfo->DemoteRegister = SRetReg; 10655 NewRoot = 10656 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10657 DAG.setRoot(NewRoot); 10658 10659 // i indexes lowered arguments. Bump it past the hidden sret argument. 10660 ++i; 10661 } 10662 10663 SmallVector<SDValue, 4> Chains; 10664 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10665 for (const Argument &Arg : F.args()) { 10666 SmallVector<SDValue, 4> ArgValues; 10667 SmallVector<EVT, 4> ValueVTs; 10668 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10669 unsigned NumValues = ValueVTs.size(); 10670 if (NumValues == 0) 10671 continue; 10672 10673 bool ArgHasUses = !Arg.use_empty(); 10674 10675 // Elide the copying store if the target loaded this argument from a 10676 // suitable fixed stack object. 10677 if (Ins[i].Flags.isCopyElisionCandidate()) { 10678 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10679 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10680 InVals[i], ArgHasUses); 10681 } 10682 10683 // If this argument is unused then remember its value. It is used to generate 10684 // debugging information. 10685 bool isSwiftErrorArg = 10686 TLI->supportSwiftError() && 10687 Arg.hasAttribute(Attribute::SwiftError); 10688 if (!ArgHasUses && !isSwiftErrorArg) { 10689 SDB->setUnusedArgValue(&Arg, InVals[i]); 10690 10691 // Also remember any frame index for use in FastISel. 10692 if (FrameIndexSDNode *FI = 10693 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10694 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10695 } 10696 10697 for (unsigned Val = 0; Val != NumValues; ++Val) { 10698 EVT VT = ValueVTs[Val]; 10699 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10700 F.getCallingConv(), VT); 10701 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10702 *CurDAG->getContext(), F.getCallingConv(), VT); 10703 10704 // Even an apparent 'unused' swifterror argument needs to be returned. So 10705 // we do generate a copy for it that can be used on return from the 10706 // function. 10707 if (ArgHasUses || isSwiftErrorArg) { 10708 Optional<ISD::NodeType> AssertOp; 10709 if (Arg.hasAttribute(Attribute::SExt)) 10710 AssertOp = ISD::AssertSext; 10711 else if (Arg.hasAttribute(Attribute::ZExt)) 10712 AssertOp = ISD::AssertZext; 10713 10714 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10715 PartVT, VT, nullptr, 10716 F.getCallingConv(), AssertOp)); 10717 } 10718 10719 i += NumParts; 10720 } 10721 10722 // We don't need to do anything else for unused arguments. 10723 if (ArgValues.empty()) 10724 continue; 10725 10726 // Note down frame index. 10727 if (FrameIndexSDNode *FI = 10728 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10729 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10730 10731 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10732 SDB->getCurSDLoc()); 10733 10734 SDB->setValue(&Arg, Res); 10735 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10736 // We want to associate the argument with the frame index, among 10737 // involved operands, that correspond to the lowest address. The 10738 // getCopyFromParts function, called earlier, is swapping the order of 10739 // the operands to BUILD_PAIR depending on endianness. The result of 10740 // that swapping is that the least significant bits of the argument will 10741 // be in the first operand of the BUILD_PAIR node, and the most 10742 // significant bits will be in the second operand. 10743 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10744 if (LoadSDNode *LNode = 10745 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10746 if (FrameIndexSDNode *FI = 10747 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10748 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10749 } 10750 10751 // Analyses past this point are naive and don't expect an assertion. 10752 if (Res.getOpcode() == ISD::AssertZext) 10753 Res = Res.getOperand(0); 10754 10755 // Update the SwiftErrorVRegDefMap. 10756 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10757 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10758 if (Register::isVirtualRegister(Reg)) 10759 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10760 Reg); 10761 } 10762 10763 // If this argument is live outside of the entry block, insert a copy from 10764 // wherever we got it to the vreg that other BB's will reference it as. 10765 if (Res.getOpcode() == ISD::CopyFromReg) { 10766 // If we can, though, try to skip creating an unnecessary vreg. 10767 // FIXME: This isn't very clean... it would be nice to make this more 10768 // general. 10769 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10770 if (Register::isVirtualRegister(Reg)) { 10771 FuncInfo->ValueMap[&Arg] = Reg; 10772 continue; 10773 } 10774 } 10775 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10776 FuncInfo->InitializeRegForValue(&Arg); 10777 SDB->CopyToExportRegsIfNeeded(&Arg); 10778 } 10779 } 10780 10781 if (!Chains.empty()) { 10782 Chains.push_back(NewRoot); 10783 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10784 } 10785 10786 DAG.setRoot(NewRoot); 10787 10788 assert(i == InVals.size() && "Argument register count mismatch!"); 10789 10790 // If any argument copy elisions occurred and we have debug info, update the 10791 // stale frame indices used in the dbg.declare variable info table. 10792 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10793 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10794 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10795 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10796 if (I != ArgCopyElisionFrameIndexMap.end()) 10797 VI.Slot = I->second; 10798 } 10799 } 10800 10801 // Finally, if the target has anything special to do, allow it to do so. 10802 emitFunctionEntryCode(); 10803 } 10804 10805 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10806 /// ensure constants are generated when needed. Remember the virtual registers 10807 /// that need to be added to the Machine PHI nodes as input. We cannot just 10808 /// directly add them, because expansion might result in multiple MBB's for one 10809 /// BB. As such, the start of the BB might correspond to a different MBB than 10810 /// the end. 10811 void 10812 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10813 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10814 const Instruction *TI = LLVMBB->getTerminator(); 10815 10816 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10817 10818 // Check PHI nodes in successors that expect a value to be available from this 10819 // block. 10820 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10821 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10822 if (!isa<PHINode>(SuccBB->begin())) continue; 10823 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10824 10825 // If this terminator has multiple identical successors (common for 10826 // switches), only handle each succ once. 10827 if (!SuccsHandled.insert(SuccMBB).second) 10828 continue; 10829 10830 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10831 10832 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10833 // nodes and Machine PHI nodes, but the incoming operands have not been 10834 // emitted yet. 10835 for (const PHINode &PN : SuccBB->phis()) { 10836 // Ignore dead phi's. 10837 if (PN.use_empty()) 10838 continue; 10839 10840 // Skip empty types 10841 if (PN.getType()->isEmptyTy()) 10842 continue; 10843 10844 unsigned Reg; 10845 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10846 10847 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10848 unsigned &RegOut = ConstantsOut[C]; 10849 if (RegOut == 0) { 10850 RegOut = FuncInfo.CreateRegs(C); 10851 // We need to zero/sign extend ConstantInt phi operands to match 10852 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 10853 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 10854 if (auto *CI = dyn_cast<ConstantInt>(C)) 10855 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 10856 : ISD::ZERO_EXTEND; 10857 CopyValueToVirtualRegister(C, RegOut, ExtendType); 10858 } 10859 Reg = RegOut; 10860 } else { 10861 DenseMap<const Value *, Register>::iterator I = 10862 FuncInfo.ValueMap.find(PHIOp); 10863 if (I != FuncInfo.ValueMap.end()) 10864 Reg = I->second; 10865 else { 10866 assert(isa<AllocaInst>(PHIOp) && 10867 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10868 "Didn't codegen value into a register!??"); 10869 Reg = FuncInfo.CreateRegs(PHIOp); 10870 CopyValueToVirtualRegister(PHIOp, Reg); 10871 } 10872 } 10873 10874 // Remember that this register needs to added to the machine PHI node as 10875 // the input for this MBB. 10876 SmallVector<EVT, 4> ValueVTs; 10877 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10878 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10879 EVT VT = ValueVTs[vti]; 10880 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10881 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10882 FuncInfo.PHINodesToUpdate.push_back( 10883 std::make_pair(&*MBBI++, Reg + i)); 10884 Reg += NumRegisters; 10885 } 10886 } 10887 } 10888 10889 ConstantsOut.clear(); 10890 } 10891 10892 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10893 MachineFunction::iterator I(MBB); 10894 if (++I == FuncInfo.MF->end()) 10895 return nullptr; 10896 return &*I; 10897 } 10898 10899 /// During lowering new call nodes can be created (such as memset, etc.). 10900 /// Those will become new roots of the current DAG, but complications arise 10901 /// when they are tail calls. In such cases, the call lowering will update 10902 /// the root, but the builder still needs to know that a tail call has been 10903 /// lowered in order to avoid generating an additional return. 10904 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10905 // If the node is null, we do have a tail call. 10906 if (MaybeTC.getNode() != nullptr) 10907 DAG.setRoot(MaybeTC); 10908 else 10909 HasTailCall = true; 10910 } 10911 10912 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10913 MachineBasicBlock *SwitchMBB, 10914 MachineBasicBlock *DefaultMBB) { 10915 MachineFunction *CurMF = FuncInfo.MF; 10916 MachineBasicBlock *NextMBB = nullptr; 10917 MachineFunction::iterator BBI(W.MBB); 10918 if (++BBI != FuncInfo.MF->end()) 10919 NextMBB = &*BBI; 10920 10921 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10922 10923 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10924 10925 if (Size == 2 && W.MBB == SwitchMBB) { 10926 // If any two of the cases has the same destination, and if one value 10927 // is the same as the other, but has one bit unset that the other has set, 10928 // use bit manipulation to do two compares at once. For example: 10929 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10930 // TODO: This could be extended to merge any 2 cases in switches with 3 10931 // cases. 10932 // TODO: Handle cases where W.CaseBB != SwitchBB. 10933 CaseCluster &Small = *W.FirstCluster; 10934 CaseCluster &Big = *W.LastCluster; 10935 10936 if (Small.Low == Small.High && Big.Low == Big.High && 10937 Small.MBB == Big.MBB) { 10938 const APInt &SmallValue = Small.Low->getValue(); 10939 const APInt &BigValue = Big.Low->getValue(); 10940 10941 // Check that there is only one bit different. 10942 APInt CommonBit = BigValue ^ SmallValue; 10943 if (CommonBit.isPowerOf2()) { 10944 SDValue CondLHS = getValue(Cond); 10945 EVT VT = CondLHS.getValueType(); 10946 SDLoc DL = getCurSDLoc(); 10947 10948 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10949 DAG.getConstant(CommonBit, DL, VT)); 10950 SDValue Cond = DAG.getSetCC( 10951 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10952 ISD::SETEQ); 10953 10954 // Update successor info. 10955 // Both Small and Big will jump to Small.BB, so we sum up the 10956 // probabilities. 10957 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10958 if (BPI) 10959 addSuccessorWithProb( 10960 SwitchMBB, DefaultMBB, 10961 // The default destination is the first successor in IR. 10962 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10963 else 10964 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10965 10966 // Insert the true branch. 10967 SDValue BrCond = 10968 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10969 DAG.getBasicBlock(Small.MBB)); 10970 // Insert the false branch. 10971 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10972 DAG.getBasicBlock(DefaultMBB)); 10973 10974 DAG.setRoot(BrCond); 10975 return; 10976 } 10977 } 10978 } 10979 10980 if (TM.getOptLevel() != CodeGenOpt::None) { 10981 // Here, we order cases by probability so the most likely case will be 10982 // checked first. However, two clusters can have the same probability in 10983 // which case their relative ordering is non-deterministic. So we use Low 10984 // as a tie-breaker as clusters are guaranteed to never overlap. 10985 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10986 [](const CaseCluster &a, const CaseCluster &b) { 10987 return a.Prob != b.Prob ? 10988 a.Prob > b.Prob : 10989 a.Low->getValue().slt(b.Low->getValue()); 10990 }); 10991 10992 // Rearrange the case blocks so that the last one falls through if possible 10993 // without changing the order of probabilities. 10994 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10995 --I; 10996 if (I->Prob > W.LastCluster->Prob) 10997 break; 10998 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10999 std::swap(*I, *W.LastCluster); 11000 break; 11001 } 11002 } 11003 } 11004 11005 // Compute total probability. 11006 BranchProbability DefaultProb = W.DefaultProb; 11007 BranchProbability UnhandledProbs = DefaultProb; 11008 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11009 UnhandledProbs += I->Prob; 11010 11011 MachineBasicBlock *CurMBB = W.MBB; 11012 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11013 bool FallthroughUnreachable = false; 11014 MachineBasicBlock *Fallthrough; 11015 if (I == W.LastCluster) { 11016 // For the last cluster, fall through to the default destination. 11017 Fallthrough = DefaultMBB; 11018 FallthroughUnreachable = isa<UnreachableInst>( 11019 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11020 } else { 11021 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11022 CurMF->insert(BBI, Fallthrough); 11023 // Put Cond in a virtual register to make it available from the new blocks. 11024 ExportFromCurrentBlock(Cond); 11025 } 11026 UnhandledProbs -= I->Prob; 11027 11028 switch (I->Kind) { 11029 case CC_JumpTable: { 11030 // FIXME: Optimize away range check based on pivot comparisons. 11031 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11032 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11033 11034 // The jump block hasn't been inserted yet; insert it here. 11035 MachineBasicBlock *JumpMBB = JT->MBB; 11036 CurMF->insert(BBI, JumpMBB); 11037 11038 auto JumpProb = I->Prob; 11039 auto FallthroughProb = UnhandledProbs; 11040 11041 // If the default statement is a target of the jump table, we evenly 11042 // distribute the default probability to successors of CurMBB. Also 11043 // update the probability on the edge from JumpMBB to Fallthrough. 11044 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11045 SE = JumpMBB->succ_end(); 11046 SI != SE; ++SI) { 11047 if (*SI == DefaultMBB) { 11048 JumpProb += DefaultProb / 2; 11049 FallthroughProb -= DefaultProb / 2; 11050 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11051 JumpMBB->normalizeSuccProbs(); 11052 break; 11053 } 11054 } 11055 11056 if (FallthroughUnreachable) 11057 JTH->FallthroughUnreachable = true; 11058 11059 if (!JTH->FallthroughUnreachable) 11060 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11061 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11062 CurMBB->normalizeSuccProbs(); 11063 11064 // The jump table header will be inserted in our current block, do the 11065 // range check, and fall through to our fallthrough block. 11066 JTH->HeaderBB = CurMBB; 11067 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11068 11069 // If we're in the right place, emit the jump table header right now. 11070 if (CurMBB == SwitchMBB) { 11071 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11072 JTH->Emitted = true; 11073 } 11074 break; 11075 } 11076 case CC_BitTests: { 11077 // FIXME: Optimize away range check based on pivot comparisons. 11078 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11079 11080 // The bit test blocks haven't been inserted yet; insert them here. 11081 for (BitTestCase &BTC : BTB->Cases) 11082 CurMF->insert(BBI, BTC.ThisBB); 11083 11084 // Fill in fields of the BitTestBlock. 11085 BTB->Parent = CurMBB; 11086 BTB->Default = Fallthrough; 11087 11088 BTB->DefaultProb = UnhandledProbs; 11089 // If the cases in bit test don't form a contiguous range, we evenly 11090 // distribute the probability on the edge to Fallthrough to two 11091 // successors of CurMBB. 11092 if (!BTB->ContiguousRange) { 11093 BTB->Prob += DefaultProb / 2; 11094 BTB->DefaultProb -= DefaultProb / 2; 11095 } 11096 11097 if (FallthroughUnreachable) 11098 BTB->FallthroughUnreachable = true; 11099 11100 // If we're in the right place, emit the bit test header right now. 11101 if (CurMBB == SwitchMBB) { 11102 visitBitTestHeader(*BTB, SwitchMBB); 11103 BTB->Emitted = true; 11104 } 11105 break; 11106 } 11107 case CC_Range: { 11108 const Value *RHS, *LHS, *MHS; 11109 ISD::CondCode CC; 11110 if (I->Low == I->High) { 11111 // Check Cond == I->Low. 11112 CC = ISD::SETEQ; 11113 LHS = Cond; 11114 RHS=I->Low; 11115 MHS = nullptr; 11116 } else { 11117 // Check I->Low <= Cond <= I->High. 11118 CC = ISD::SETLE; 11119 LHS = I->Low; 11120 MHS = Cond; 11121 RHS = I->High; 11122 } 11123 11124 // If Fallthrough is unreachable, fold away the comparison. 11125 if (FallthroughUnreachable) 11126 CC = ISD::SETTRUE; 11127 11128 // The false probability is the sum of all unhandled cases. 11129 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11130 getCurSDLoc(), I->Prob, UnhandledProbs); 11131 11132 if (CurMBB == SwitchMBB) 11133 visitSwitchCase(CB, SwitchMBB); 11134 else 11135 SL->SwitchCases.push_back(CB); 11136 11137 break; 11138 } 11139 } 11140 CurMBB = Fallthrough; 11141 } 11142 } 11143 11144 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11145 CaseClusterIt First, 11146 CaseClusterIt Last) { 11147 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11148 if (X.Prob != CC.Prob) 11149 return X.Prob > CC.Prob; 11150 11151 // Ties are broken by comparing the case value. 11152 return X.Low->getValue().slt(CC.Low->getValue()); 11153 }); 11154 } 11155 11156 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11157 const SwitchWorkListItem &W, 11158 Value *Cond, 11159 MachineBasicBlock *SwitchMBB) { 11160 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11161 "Clusters not sorted?"); 11162 11163 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11164 11165 // Balance the tree based on branch probabilities to create a near-optimal (in 11166 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11167 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11168 CaseClusterIt LastLeft = W.FirstCluster; 11169 CaseClusterIt FirstRight = W.LastCluster; 11170 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11171 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11172 11173 // Move LastLeft and FirstRight towards each other from opposite directions to 11174 // find a partitioning of the clusters which balances the probability on both 11175 // sides. If LeftProb and RightProb are equal, alternate which side is 11176 // taken to ensure 0-probability nodes are distributed evenly. 11177 unsigned I = 0; 11178 while (LastLeft + 1 < FirstRight) { 11179 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11180 LeftProb += (++LastLeft)->Prob; 11181 else 11182 RightProb += (--FirstRight)->Prob; 11183 I++; 11184 } 11185 11186 while (true) { 11187 // Our binary search tree differs from a typical BST in that ours can have up 11188 // to three values in each leaf. The pivot selection above doesn't take that 11189 // into account, which means the tree might require more nodes and be less 11190 // efficient. We compensate for this here. 11191 11192 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11193 unsigned NumRight = W.LastCluster - FirstRight + 1; 11194 11195 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11196 // If one side has less than 3 clusters, and the other has more than 3, 11197 // consider taking a cluster from the other side. 11198 11199 if (NumLeft < NumRight) { 11200 // Consider moving the first cluster on the right to the left side. 11201 CaseCluster &CC = *FirstRight; 11202 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11203 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11204 if (LeftSideRank <= RightSideRank) { 11205 // Moving the cluster to the left does not demote it. 11206 ++LastLeft; 11207 ++FirstRight; 11208 continue; 11209 } 11210 } else { 11211 assert(NumRight < NumLeft); 11212 // Consider moving the last element on the left to the right side. 11213 CaseCluster &CC = *LastLeft; 11214 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11215 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11216 if (RightSideRank <= LeftSideRank) { 11217 // Moving the cluster to the right does not demot it. 11218 --LastLeft; 11219 --FirstRight; 11220 continue; 11221 } 11222 } 11223 } 11224 break; 11225 } 11226 11227 assert(LastLeft + 1 == FirstRight); 11228 assert(LastLeft >= W.FirstCluster); 11229 assert(FirstRight <= W.LastCluster); 11230 11231 // Use the first element on the right as pivot since we will make less-than 11232 // comparisons against it. 11233 CaseClusterIt PivotCluster = FirstRight; 11234 assert(PivotCluster > W.FirstCluster); 11235 assert(PivotCluster <= W.LastCluster); 11236 11237 CaseClusterIt FirstLeft = W.FirstCluster; 11238 CaseClusterIt LastRight = W.LastCluster; 11239 11240 const ConstantInt *Pivot = PivotCluster->Low; 11241 11242 // New blocks will be inserted immediately after the current one. 11243 MachineFunction::iterator BBI(W.MBB); 11244 ++BBI; 11245 11246 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11247 // we can branch to its destination directly if it's squeezed exactly in 11248 // between the known lower bound and Pivot - 1. 11249 MachineBasicBlock *LeftMBB; 11250 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11251 FirstLeft->Low == W.GE && 11252 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11253 LeftMBB = FirstLeft->MBB; 11254 } else { 11255 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11256 FuncInfo.MF->insert(BBI, LeftMBB); 11257 WorkList.push_back( 11258 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11259 // Put Cond in a virtual register to make it available from the new blocks. 11260 ExportFromCurrentBlock(Cond); 11261 } 11262 11263 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11264 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11265 // directly if RHS.High equals the current upper bound. 11266 MachineBasicBlock *RightMBB; 11267 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11268 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11269 RightMBB = FirstRight->MBB; 11270 } else { 11271 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11272 FuncInfo.MF->insert(BBI, RightMBB); 11273 WorkList.push_back( 11274 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11275 // Put Cond in a virtual register to make it available from the new blocks. 11276 ExportFromCurrentBlock(Cond); 11277 } 11278 11279 // Create the CaseBlock record that will be used to lower the branch. 11280 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11281 getCurSDLoc(), LeftProb, RightProb); 11282 11283 if (W.MBB == SwitchMBB) 11284 visitSwitchCase(CB, SwitchMBB); 11285 else 11286 SL->SwitchCases.push_back(CB); 11287 } 11288 11289 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11290 // from the swith statement. 11291 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11292 BranchProbability PeeledCaseProb) { 11293 if (PeeledCaseProb == BranchProbability::getOne()) 11294 return BranchProbability::getZero(); 11295 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11296 11297 uint32_t Numerator = CaseProb.getNumerator(); 11298 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11299 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11300 } 11301 11302 // Try to peel the top probability case if it exceeds the threshold. 11303 // Return current MachineBasicBlock for the switch statement if the peeling 11304 // does not occur. 11305 // If the peeling is performed, return the newly created MachineBasicBlock 11306 // for the peeled switch statement. Also update Clusters to remove the peeled 11307 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11308 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11309 const SwitchInst &SI, CaseClusterVector &Clusters, 11310 BranchProbability &PeeledCaseProb) { 11311 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11312 // Don't perform if there is only one cluster or optimizing for size. 11313 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11314 TM.getOptLevel() == CodeGenOpt::None || 11315 SwitchMBB->getParent()->getFunction().hasMinSize()) 11316 return SwitchMBB; 11317 11318 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11319 unsigned PeeledCaseIndex = 0; 11320 bool SwitchPeeled = false; 11321 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11322 CaseCluster &CC = Clusters[Index]; 11323 if (CC.Prob < TopCaseProb) 11324 continue; 11325 TopCaseProb = CC.Prob; 11326 PeeledCaseIndex = Index; 11327 SwitchPeeled = true; 11328 } 11329 if (!SwitchPeeled) 11330 return SwitchMBB; 11331 11332 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11333 << TopCaseProb << "\n"); 11334 11335 // Record the MBB for the peeled switch statement. 11336 MachineFunction::iterator BBI(SwitchMBB); 11337 ++BBI; 11338 MachineBasicBlock *PeeledSwitchMBB = 11339 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11340 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11341 11342 ExportFromCurrentBlock(SI.getCondition()); 11343 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11344 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11345 nullptr, nullptr, TopCaseProb.getCompl()}; 11346 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11347 11348 Clusters.erase(PeeledCaseIt); 11349 for (CaseCluster &CC : Clusters) { 11350 LLVM_DEBUG( 11351 dbgs() << "Scale the probablity for one cluster, before scaling: " 11352 << CC.Prob << "\n"); 11353 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11354 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11355 } 11356 PeeledCaseProb = TopCaseProb; 11357 return PeeledSwitchMBB; 11358 } 11359 11360 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11361 // Extract cases from the switch. 11362 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11363 CaseClusterVector Clusters; 11364 Clusters.reserve(SI.getNumCases()); 11365 for (auto I : SI.cases()) { 11366 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11367 const ConstantInt *CaseVal = I.getCaseValue(); 11368 BranchProbability Prob = 11369 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11370 : BranchProbability(1, SI.getNumCases() + 1); 11371 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11372 } 11373 11374 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11375 11376 // Cluster adjacent cases with the same destination. We do this at all 11377 // optimization levels because it's cheap to do and will make codegen faster 11378 // if there are many clusters. 11379 sortAndRangeify(Clusters); 11380 11381 // The branch probablity of the peeled case. 11382 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11383 MachineBasicBlock *PeeledSwitchMBB = 11384 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11385 11386 // If there is only the default destination, jump there directly. 11387 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11388 if (Clusters.empty()) { 11389 assert(PeeledSwitchMBB == SwitchMBB); 11390 SwitchMBB->addSuccessor(DefaultMBB); 11391 if (DefaultMBB != NextBlock(SwitchMBB)) { 11392 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11393 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11394 } 11395 return; 11396 } 11397 11398 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11399 SL->findBitTestClusters(Clusters, &SI); 11400 11401 LLVM_DEBUG({ 11402 dbgs() << "Case clusters: "; 11403 for (const CaseCluster &C : Clusters) { 11404 if (C.Kind == CC_JumpTable) 11405 dbgs() << "JT:"; 11406 if (C.Kind == CC_BitTests) 11407 dbgs() << "BT:"; 11408 11409 C.Low->getValue().print(dbgs(), true); 11410 if (C.Low != C.High) { 11411 dbgs() << '-'; 11412 C.High->getValue().print(dbgs(), true); 11413 } 11414 dbgs() << ' '; 11415 } 11416 dbgs() << '\n'; 11417 }); 11418 11419 assert(!Clusters.empty()); 11420 SwitchWorkList WorkList; 11421 CaseClusterIt First = Clusters.begin(); 11422 CaseClusterIt Last = Clusters.end() - 1; 11423 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11424 // Scale the branchprobability for DefaultMBB if the peel occurs and 11425 // DefaultMBB is not replaced. 11426 if (PeeledCaseProb != BranchProbability::getZero() && 11427 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11428 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11429 WorkList.push_back( 11430 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11431 11432 while (!WorkList.empty()) { 11433 SwitchWorkListItem W = WorkList.pop_back_val(); 11434 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11435 11436 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11437 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11438 // For optimized builds, lower large range as a balanced binary tree. 11439 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11440 continue; 11441 } 11442 11443 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11444 } 11445 } 11446 11447 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11448 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11449 auto DL = getCurSDLoc(); 11450 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11451 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11452 } 11453 11454 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11455 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11456 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11457 11458 SDLoc DL = getCurSDLoc(); 11459 SDValue V = getValue(I.getOperand(0)); 11460 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11461 11462 if (VT.isScalableVector()) { 11463 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11464 return; 11465 } 11466 11467 // Use VECTOR_SHUFFLE for the fixed-length vector 11468 // to maintain existing behavior. 11469 SmallVector<int, 8> Mask; 11470 unsigned NumElts = VT.getVectorMinNumElements(); 11471 for (unsigned i = 0; i != NumElts; ++i) 11472 Mask.push_back(NumElts - 1 - i); 11473 11474 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11475 } 11476 11477 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11478 SmallVector<EVT, 4> ValueVTs; 11479 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11480 ValueVTs); 11481 unsigned NumValues = ValueVTs.size(); 11482 if (NumValues == 0) return; 11483 11484 SmallVector<SDValue, 4> Values(NumValues); 11485 SDValue Op = getValue(I.getOperand(0)); 11486 11487 for (unsigned i = 0; i != NumValues; ++i) 11488 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11489 SDValue(Op.getNode(), Op.getResNo() + i)); 11490 11491 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11492 DAG.getVTList(ValueVTs), Values)); 11493 } 11494 11495 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11496 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11497 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11498 11499 SDLoc DL = getCurSDLoc(); 11500 SDValue V1 = getValue(I.getOperand(0)); 11501 SDValue V2 = getValue(I.getOperand(1)); 11502 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11503 11504 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11505 if (VT.isScalableVector()) { 11506 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11507 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11508 DAG.getConstant(Imm, DL, IdxVT))); 11509 return; 11510 } 11511 11512 unsigned NumElts = VT.getVectorNumElements(); 11513 11514 uint64_t Idx = (NumElts + Imm) % NumElts; 11515 11516 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11517 SmallVector<int, 8> Mask; 11518 for (unsigned i = 0; i < NumElts; ++i) 11519 Mask.push_back(Idx + i); 11520 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11521 } 11522