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/BlockFrequencyInfo.h" 28 #include "llvm/Analysis/BranchProbabilityInfo.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/Analysis/EHPersonalities.h" 31 #include "llvm/Analysis/Loads.h" 32 #include "llvm/Analysis/MemoryLocation.h" 33 #include "llvm/Analysis/ProfileSummaryInfo.h" 34 #include "llvm/Analysis/TargetLibraryInfo.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/Analysis/VectorUtils.h" 37 #include "llvm/CodeGen/Analysis.h" 38 #include "llvm/CodeGen/FunctionLoweringInfo.h" 39 #include "llvm/CodeGen/GCMetadata.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 53 #include "llvm/CodeGen/StackMaps.h" 54 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 55 #include "llvm/CodeGen/TargetFrameLowering.h" 56 #include "llvm/CodeGen/TargetInstrInfo.h" 57 #include "llvm/CodeGen/TargetOpcodes.h" 58 #include "llvm/CodeGen/TargetRegisterInfo.h" 59 #include "llvm/CodeGen/TargetSubtargetInfo.h" 60 #include "llvm/CodeGen/WinEHFuncInfo.h" 61 #include "llvm/IR/Argument.h" 62 #include "llvm/IR/Attributes.h" 63 #include "llvm/IR/BasicBlock.h" 64 #include "llvm/IR/CFG.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/ConstantRange.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugInfoMetadata.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GetElementPtrTypeIterator.h" 74 #include "llvm/IR/InlineAsm.h" 75 #include "llvm/IR/InstrTypes.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/IntrinsicsAArch64.h" 80 #include "llvm/IR/IntrinsicsWebAssembly.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Operator.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Statepoint.h" 87 #include "llvm/IR/Type.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/MC/MCContext.h" 91 #include "llvm/MC/MCSymbol.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/MathExtras.h" 98 #include "llvm/Support/raw_ostream.h" 99 #include "llvm/Target/TargetIntrinsicInfo.h" 100 #include "llvm/Target/TargetMachine.h" 101 #include "llvm/Target/TargetOptions.h" 102 #include "llvm/Transforms/Utils/Local.h" 103 #include <cstddef> 104 #include <cstring> 105 #include <iterator> 106 #include <limits> 107 #include <numeric> 108 #include <tuple> 109 110 using namespace llvm; 111 using namespace PatternMatch; 112 using namespace SwitchCG; 113 114 #define DEBUG_TYPE "isel" 115 116 /// LimitFloatPrecision - Generate low-precision inline sequences for 117 /// some float libcalls (6, 8 or 12 bits). 118 static unsigned LimitFloatPrecision; 119 120 static cl::opt<bool> 121 InsertAssertAlign("insert-assert-align", cl::init(true), 122 cl::desc("Insert the experimental `assertalign` node."), 123 cl::ReallyHidden); 124 125 static cl::opt<unsigned, true> 126 LimitFPPrecision("limit-float-precision", 127 cl::desc("Generate low-precision inline sequences " 128 "for some float libcalls"), 129 cl::location(LimitFloatPrecision), cl::Hidden, 130 cl::init(0)); 131 132 static cl::opt<unsigned> SwitchPeelThreshold( 133 "switch-peel-threshold", cl::Hidden, cl::init(66), 134 cl::desc("Set the case probability threshold for peeling the case from a " 135 "switch statement. A value greater than 100 will void this " 136 "optimization")); 137 138 // Limit the width of DAG chains. This is important in general to prevent 139 // DAG-based analysis from blowing up. For example, alias analysis and 140 // load clustering may not complete in reasonable time. It is difficult to 141 // recognize and avoid this situation within each individual analysis, and 142 // future analyses are likely to have the same behavior. Limiting DAG width is 143 // the safe approach and will be especially important with global DAGs. 144 // 145 // MaxParallelChains default is arbitrarily high to avoid affecting 146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 147 // sequence over this should have been converted to llvm.memcpy by the 148 // frontend. It is easy to induce this behavior with .ll code such as: 149 // %buffer = alloca [4096 x i8] 150 // %data = load [4096 x i8]* %argPtr 151 // store [4096 x i8] %data, [4096 x i8]* %buffer 152 static const unsigned MaxParallelChains = 64; 153 154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 155 const SDValue *Parts, unsigned NumParts, 156 MVT PartVT, EVT ValueVT, const Value *V, 157 Optional<CallingConv::ID> CC); 158 159 /// getCopyFromParts - Create a value that contains the specified legal parts 160 /// combined into the value they represent. If the parts combine to a type 161 /// larger than ValueVT then AssertOp can be used to specify whether the extra 162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 163 /// (ISD::AssertSext). 164 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 165 const SDValue *Parts, unsigned NumParts, 166 MVT PartVT, EVT ValueVT, const Value *V, 167 Optional<CallingConv::ID> CC = None, 168 Optional<ISD::NodeType> AssertOp = None) { 169 // Let the target assemble the parts if it wants to 170 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 171 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 172 PartVT, ValueVT, CC)) 173 return Val; 174 175 if (ValueVT.isVector()) 176 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 177 CC); 178 179 assert(NumParts > 0 && "No parts to assemble!"); 180 SDValue Val = Parts[0]; 181 182 if (NumParts > 1) { 183 // Assemble the value from multiple parts. 184 if (ValueVT.isInteger()) { 185 unsigned PartBits = PartVT.getSizeInBits(); 186 unsigned ValueBits = ValueVT.getSizeInBits(); 187 188 // Assemble the power of 2 part. 189 unsigned RoundParts = 190 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 191 unsigned RoundBits = PartBits * RoundParts; 192 EVT RoundVT = RoundBits == ValueBits ? 193 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 194 SDValue Lo, Hi; 195 196 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 197 198 if (RoundParts > 2) { 199 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 200 PartVT, HalfVT, V); 201 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 202 RoundParts / 2, PartVT, HalfVT, V); 203 } else { 204 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 205 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 206 } 207 208 if (DAG.getDataLayout().isBigEndian()) 209 std::swap(Lo, Hi); 210 211 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 212 213 if (RoundParts < NumParts) { 214 // Assemble the trailing non-power-of-2 part. 215 unsigned OddParts = NumParts - RoundParts; 216 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 217 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 218 OddVT, V, CC); 219 220 // Combine the round and odd parts. 221 Lo = Val; 222 if (DAG.getDataLayout().isBigEndian()) 223 std::swap(Lo, Hi); 224 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 225 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 226 Hi = 227 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 228 DAG.getConstant(Lo.getValueSizeInBits(), DL, 229 TLI.getPointerTy(DAG.getDataLayout()))); 230 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 231 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 232 } 233 } else if (PartVT.isFloatingPoint()) { 234 // FP split into multiple FP parts (for ppcf128) 235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 236 "Unexpected split"); 237 SDValue Lo, Hi; 238 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 239 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 240 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 241 std::swap(Lo, Hi); 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 243 } else { 244 // FP split into integer parts (soft fp) 245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 246 !PartVT.isVector() && "Unexpected split"); 247 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 249 } 250 } 251 252 // There is now one part, held in Val. Correct it to match ValueVT. 253 // PartEVT is the type of the register class that holds the value. 254 // ValueVT is the type of the inline asm operation. 255 EVT PartEVT = Val.getValueType(); 256 257 if (PartEVT == ValueVT) 258 return Val; 259 260 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 261 ValueVT.bitsLT(PartEVT)) { 262 // For an FP value in an integer part, we need to truncate to the right 263 // width first. 264 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 265 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 266 } 267 268 // Handle types that have the same size. 269 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 270 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 271 272 // Handle types with different sizes. 273 if (PartEVT.isInteger() && ValueVT.isInteger()) { 274 if (ValueVT.bitsLT(PartEVT)) { 275 // For a truncate, see if we have any information to 276 // indicate whether the truncated bits will always be 277 // zero or sign-extension. 278 if (AssertOp.hasValue()) 279 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 280 DAG.getValueType(ValueVT)); 281 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 282 } 283 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 284 } 285 286 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 287 // FP_ROUND's are always exact here. 288 if (ValueVT.bitsLT(Val.getValueType())) 289 return DAG.getNode( 290 ISD::FP_ROUND, DL, ValueVT, Val, 291 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 292 293 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 294 } 295 296 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 297 // then truncating. 298 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 299 ValueVT.bitsLT(PartEVT)) { 300 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 301 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 302 } 303 304 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 305 } 306 307 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 308 const Twine &ErrMsg) { 309 const Instruction *I = dyn_cast_or_null<Instruction>(V); 310 if (!V) 311 return Ctx.emitError(ErrMsg); 312 313 const char *AsmError = ", possible invalid constraint for vector type"; 314 if (const CallInst *CI = dyn_cast<CallInst>(I)) 315 if (CI->isInlineAsm()) 316 return Ctx.emitError(I, ErrMsg + AsmError); 317 318 return Ctx.emitError(I, ErrMsg); 319 } 320 321 /// getCopyFromPartsVector - Create a value that contains the specified legal 322 /// parts combined into the value they represent. If the parts combine to a 323 /// type larger than ValueVT then AssertOp can be used to specify whether the 324 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 325 /// ValueVT (ISD::AssertSext). 326 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 327 const SDValue *Parts, unsigned NumParts, 328 MVT PartVT, EVT ValueVT, const Value *V, 329 Optional<CallingConv::ID> CallConv) { 330 assert(ValueVT.isVector() && "Not a vector value"); 331 assert(NumParts > 0 && "No parts to assemble!"); 332 const bool IsABIRegCopy = CallConv.hasValue(); 333 334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 335 SDValue Val = Parts[0]; 336 337 // Handle a multi-element vector. 338 if (NumParts > 1) { 339 EVT IntermediateVT; 340 MVT RegisterVT; 341 unsigned NumIntermediates; 342 unsigned NumRegs; 343 344 if (IsABIRegCopy) { 345 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 346 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } else { 349 NumRegs = 350 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 351 NumIntermediates, RegisterVT); 352 } 353 354 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 355 NumParts = NumRegs; // Silence a compiler warning. 356 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 357 assert(RegisterVT.getSizeInBits() == 358 Parts[0].getSimpleValueType().getSizeInBits() && 359 "Part type sizes don't match!"); 360 361 // Assemble the parts into intermediate operands. 362 SmallVector<SDValue, 8> Ops(NumIntermediates); 363 if (NumIntermediates == NumParts) { 364 // If the register was not expanded, truncate or copy the value, 365 // as appropriate. 366 for (unsigned i = 0; i != NumParts; ++i) 367 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 368 PartVT, IntermediateVT, V, CallConv); 369 } else if (NumParts > 0) { 370 // If the intermediate type was expanded, build the intermediate 371 // operands from the parts. 372 assert(NumParts % NumIntermediates == 0 && 373 "Must expand into a divisible number of parts!"); 374 unsigned Factor = NumParts / NumIntermediates; 375 for (unsigned i = 0; i != NumIntermediates; ++i) 376 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 377 PartVT, IntermediateVT, V, CallConv); 378 } 379 380 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 381 // intermediate operands. 382 EVT BuiltVectorTy = 383 IntermediateVT.isVector() 384 ? EVT::getVectorVT( 385 *DAG.getContext(), IntermediateVT.getScalarType(), 386 IntermediateVT.getVectorElementCount() * NumParts) 387 : EVT::getVectorVT(*DAG.getContext(), 388 IntermediateVT.getScalarType(), 389 NumIntermediates); 390 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 391 : ISD::BUILD_VECTOR, 392 DL, BuiltVectorTy, Ops); 393 } 394 395 // There is now one part, held in Val. Correct it to match ValueVT. 396 EVT PartEVT = Val.getValueType(); 397 398 if (PartEVT == ValueVT) 399 return Val; 400 401 if (PartEVT.isVector()) { 402 // Vector/Vector bitcast. 403 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 404 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 405 406 // If the element type of the source/dest vectors are the same, but the 407 // parts vector has more elements than the value vector, then we have a 408 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 409 // elements we want. 410 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 411 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 412 ValueVT.getVectorElementCount().getKnownMinValue()) && 413 (PartEVT.getVectorElementCount().isScalable() == 414 ValueVT.getVectorElementCount().isScalable()) && 415 "Cannot narrow, it would be a lossy transformation"); 416 PartEVT = 417 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 418 ValueVT.getVectorElementCount()); 419 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 420 DAG.getVectorIdxConstant(0, DL)); 421 if (PartEVT == ValueVT) 422 return Val; 423 } 424 425 // Promoted vector extract 426 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 427 } 428 429 // Trivial bitcast if the types are the same size and the destination 430 // vector type is legal. 431 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 432 TLI.isTypeLegal(ValueVT)) 433 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 434 435 if (ValueVT.getVectorNumElements() != 1) { 436 // Certain ABIs require that vectors are passed as integers. For vectors 437 // are the same size, this is an obvious bitcast. 438 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 439 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 440 } else if (ValueVT.bitsLT(PartEVT)) { 441 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 442 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 443 // Drop the extra bits. 444 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 445 return DAG.getBitcast(ValueVT, Val); 446 } 447 448 diagnosePossiblyInvalidConstraint( 449 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 450 return DAG.getUNDEF(ValueVT); 451 } 452 453 // Handle cases such as i8 -> <1 x i1> 454 EVT ValueSVT = ValueVT.getVectorElementType(); 455 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 456 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 457 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 458 else 459 Val = ValueVT.isFloatingPoint() 460 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 461 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 462 } 463 464 return DAG.getBuildVector(ValueVT, DL, Val); 465 } 466 467 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 468 SDValue Val, SDValue *Parts, unsigned NumParts, 469 MVT PartVT, const Value *V, 470 Optional<CallingConv::ID> CallConv); 471 472 /// getCopyToParts - Create a series of nodes that contain the specified value 473 /// split into legal parts. If the parts contain more bits than Val, then, for 474 /// integers, ExtendKind can be used to specify how to generate the extra bits. 475 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 476 SDValue *Parts, unsigned NumParts, MVT PartVT, 477 const Value *V, 478 Optional<CallingConv::ID> CallConv = None, 479 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 480 // Let the target split the parts if it wants to 481 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 482 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 483 CallConv)) 484 return; 485 EVT ValueVT = Val.getValueType(); 486 487 // Handle the vector case separately. 488 if (ValueVT.isVector()) 489 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 490 CallConv); 491 492 unsigned PartBits = PartVT.getSizeInBits(); 493 unsigned OrigNumParts = NumParts; 494 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 495 "Copying to an illegal type!"); 496 497 if (NumParts == 0) 498 return; 499 500 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 501 EVT PartEVT = PartVT; 502 if (PartEVT == ValueVT) { 503 assert(NumParts == 1 && "No-op copy with multiple parts!"); 504 Parts[0] = Val; 505 return; 506 } 507 508 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 509 // If the parts cover more bits than the value has, promote the value. 510 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 511 assert(NumParts == 1 && "Do not know what to promote to!"); 512 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 513 } else { 514 if (ValueVT.isFloatingPoint()) { 515 // FP values need to be bitcast, then extended if they are being put 516 // into a larger container. 517 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 518 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 519 } 520 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 521 ValueVT.isInteger() && 522 "Unknown mismatch!"); 523 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 524 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 525 if (PartVT == MVT::x86mmx) 526 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 527 } 528 } else if (PartBits == ValueVT.getSizeInBits()) { 529 // Different types of the same size. 530 assert(NumParts == 1 && PartEVT != ValueVT); 531 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 532 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 533 // If the parts cover less bits than value has, truncate the value. 534 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 535 ValueVT.isInteger() && 536 "Unknown mismatch!"); 537 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 538 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 539 if (PartVT == MVT::x86mmx) 540 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 541 } 542 543 // The value may have changed - recompute ValueVT. 544 ValueVT = Val.getValueType(); 545 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 546 "Failed to tile the value with PartVT!"); 547 548 if (NumParts == 1) { 549 if (PartEVT != ValueVT) { 550 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 551 "scalar-to-vector conversion failed"); 552 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 553 } 554 555 Parts[0] = Val; 556 return; 557 } 558 559 // Expand the value into multiple parts. 560 if (NumParts & (NumParts - 1)) { 561 // The number of parts is not a power of 2. Split off and copy the tail. 562 assert(PartVT.isInteger() && ValueVT.isInteger() && 563 "Do not know what to expand to!"); 564 unsigned RoundParts = 1 << Log2_32(NumParts); 565 unsigned RoundBits = RoundParts * PartBits; 566 unsigned OddParts = NumParts - RoundParts; 567 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 568 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 569 570 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 571 CallConv); 572 573 if (DAG.getDataLayout().isBigEndian()) 574 // The odd parts were reversed by getCopyToParts - unreverse them. 575 std::reverse(Parts + RoundParts, Parts + NumParts); 576 577 NumParts = RoundParts; 578 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 579 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 580 } 581 582 // The number of parts is a power of 2. Repeatedly bisect the value using 583 // EXTRACT_ELEMENT. 584 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 585 EVT::getIntegerVT(*DAG.getContext(), 586 ValueVT.getSizeInBits()), 587 Val); 588 589 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 590 for (unsigned i = 0; i < NumParts; i += StepSize) { 591 unsigned ThisBits = StepSize * PartBits / 2; 592 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 593 SDValue &Part0 = Parts[i]; 594 SDValue &Part1 = Parts[i+StepSize/2]; 595 596 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 597 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 598 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 599 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 600 601 if (ThisBits == PartBits && ThisVT != PartVT) { 602 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 603 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 604 } 605 } 606 } 607 608 if (DAG.getDataLayout().isBigEndian()) 609 std::reverse(Parts, Parts + OrigNumParts); 610 } 611 612 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 613 const SDLoc &DL, EVT PartVT) { 614 if (!PartVT.isVector()) 615 return SDValue(); 616 617 EVT ValueVT = Val.getValueType(); 618 ElementCount PartNumElts = PartVT.getVectorElementCount(); 619 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 620 621 // We only support widening vectors with equivalent element types and 622 // fixed/scalable properties. If a target needs to widen a fixed-length type 623 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 624 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 625 PartNumElts.isScalable() != ValueNumElts.isScalable() || 626 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 627 return SDValue(); 628 629 // Widening a scalable vector to another scalable vector is done by inserting 630 // the vector into a larger undef one. 631 if (PartNumElts.isScalable()) 632 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 633 Val, DAG.getVectorIdxConstant(0, DL)); 634 635 EVT ElementVT = PartVT.getVectorElementType(); 636 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 637 // undef elements. 638 SmallVector<SDValue, 16> Ops; 639 DAG.ExtractVectorElements(Val, Ops); 640 SDValue EltUndef = DAG.getUNDEF(ElementVT); 641 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 642 643 // FIXME: Use CONCAT for 2x -> 4x. 644 return DAG.getBuildVector(PartVT, DL, Ops); 645 } 646 647 /// getCopyToPartsVector - Create a series of nodes that contain the specified 648 /// value split into legal parts. 649 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 650 SDValue Val, SDValue *Parts, unsigned NumParts, 651 MVT PartVT, const Value *V, 652 Optional<CallingConv::ID> CallConv) { 653 EVT ValueVT = Val.getValueType(); 654 assert(ValueVT.isVector() && "Not a vector"); 655 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 656 const bool IsABIRegCopy = CallConv.hasValue(); 657 658 if (NumParts == 1) { 659 EVT PartEVT = PartVT; 660 if (PartEVT == ValueVT) { 661 // Nothing to do. 662 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 663 // Bitconvert vector->vector case. 664 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 665 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 666 Val = Widened; 667 } else if (PartVT.isVector() && 668 PartEVT.getVectorElementType().bitsGE( 669 ValueVT.getVectorElementType()) && 670 PartEVT.getVectorElementCount() == 671 ValueVT.getVectorElementCount()) { 672 673 // Promoted vector extract 674 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 675 } else { 676 if (ValueVT.getVectorElementCount().isScalar()) { 677 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 678 DAG.getVectorIdxConstant(0, DL)); 679 } else { 680 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 681 assert(PartVT.getFixedSizeInBits() > ValueSize && 682 "lossy conversion of vector to scalar type"); 683 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 684 Val = DAG.getBitcast(IntermediateType, Val); 685 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 686 } 687 } 688 689 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 690 Parts[0] = Val; 691 return; 692 } 693 694 // Handle a multi-element vector. 695 EVT IntermediateVT; 696 MVT RegisterVT; 697 unsigned NumIntermediates; 698 unsigned NumRegs; 699 if (IsABIRegCopy) { 700 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 701 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 702 NumIntermediates, RegisterVT); 703 } else { 704 NumRegs = 705 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 706 NumIntermediates, RegisterVT); 707 } 708 709 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 710 NumParts = NumRegs; // Silence a compiler warning. 711 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 712 713 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 714 "Mixing scalable and fixed vectors when copying in parts"); 715 716 Optional<ElementCount> DestEltCnt; 717 718 if (IntermediateVT.isVector()) 719 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 720 else 721 DestEltCnt = ElementCount::getFixed(NumIntermediates); 722 723 EVT BuiltVectorTy = EVT::getVectorVT( 724 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 725 726 if (ValueVT == BuiltVectorTy) { 727 // Nothing to do. 728 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 729 // Bitconvert vector->vector case. 730 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 731 } else { 732 if (BuiltVectorTy.getVectorElementType().bitsGT( 733 ValueVT.getVectorElementType())) { 734 // Integer promotion. 735 ValueVT = EVT::getVectorVT(*DAG.getContext(), 736 BuiltVectorTy.getVectorElementType(), 737 ValueVT.getVectorElementCount()); 738 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 739 } 740 741 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 742 Val = Widened; 743 } 744 } 745 746 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 747 748 // Split the vector into intermediate operands. 749 SmallVector<SDValue, 8> Ops(NumIntermediates); 750 for (unsigned i = 0; i != NumIntermediates; ++i) { 751 if (IntermediateVT.isVector()) { 752 // This does something sensible for scalable vectors - see the 753 // definition of EXTRACT_SUBVECTOR for further details. 754 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 755 Ops[i] = 756 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 757 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 758 } else { 759 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 760 DAG.getVectorIdxConstant(i, DL)); 761 } 762 } 763 764 // Split the intermediate operands into legal parts. 765 if (NumParts == NumIntermediates) { 766 // If the register was not expanded, promote or copy the value, 767 // as appropriate. 768 for (unsigned i = 0; i != NumParts; ++i) 769 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 770 } else if (NumParts > 0) { 771 // If the intermediate type was expanded, split each the value into 772 // legal parts. 773 assert(NumIntermediates != 0 && "division by zero"); 774 assert(NumParts % NumIntermediates == 0 && 775 "Must expand into a divisible number of parts!"); 776 unsigned Factor = NumParts / NumIntermediates; 777 for (unsigned i = 0; i != NumIntermediates; ++i) 778 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 779 CallConv); 780 } 781 } 782 783 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 784 EVT valuevt, Optional<CallingConv::ID> CC) 785 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 786 RegCount(1, regs.size()), CallConv(CC) {} 787 788 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 789 const DataLayout &DL, unsigned Reg, Type *Ty, 790 Optional<CallingConv::ID> CC) { 791 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 792 793 CallConv = CC; 794 795 for (EVT ValueVT : ValueVTs) { 796 unsigned NumRegs = 797 isABIMangled() 798 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 799 : TLI.getNumRegisters(Context, ValueVT); 800 MVT RegisterVT = 801 isABIMangled() 802 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 803 : TLI.getRegisterType(Context, ValueVT); 804 for (unsigned i = 0; i != NumRegs; ++i) 805 Regs.push_back(Reg + i); 806 RegVTs.push_back(RegisterVT); 807 RegCount.push_back(NumRegs); 808 Reg += NumRegs; 809 } 810 } 811 812 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 813 FunctionLoweringInfo &FuncInfo, 814 const SDLoc &dl, SDValue &Chain, 815 SDValue *Flag, const Value *V) const { 816 // A Value with type {} or [0 x %t] needs no registers. 817 if (ValueVTs.empty()) 818 return SDValue(); 819 820 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 821 822 // Assemble the legal parts into the final values. 823 SmallVector<SDValue, 4> Values(ValueVTs.size()); 824 SmallVector<SDValue, 8> Parts; 825 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 826 // Copy the legal parts from the registers. 827 EVT ValueVT = ValueVTs[Value]; 828 unsigned NumRegs = RegCount[Value]; 829 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 830 *DAG.getContext(), 831 CallConv.getValue(), RegVTs[Value]) 832 : RegVTs[Value]; 833 834 Parts.resize(NumRegs); 835 for (unsigned i = 0; i != NumRegs; ++i) { 836 SDValue P; 837 if (!Flag) { 838 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 839 } else { 840 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 841 *Flag = P.getValue(2); 842 } 843 844 Chain = P.getValue(1); 845 Parts[i] = P; 846 847 // If the source register was virtual and if we know something about it, 848 // add an assert node. 849 if (!Register::isVirtualRegister(Regs[Part + i]) || 850 !RegisterVT.isInteger()) 851 continue; 852 853 const FunctionLoweringInfo::LiveOutInfo *LOI = 854 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 855 if (!LOI) 856 continue; 857 858 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 859 unsigned NumSignBits = LOI->NumSignBits; 860 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 861 862 if (NumZeroBits == RegSize) { 863 // The current value is a zero. 864 // Explicitly express that as it would be easier for 865 // optimizations to kick in. 866 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 867 continue; 868 } 869 870 // FIXME: We capture more information than the dag can represent. For 871 // now, just use the tightest assertzext/assertsext possible. 872 bool isSExt; 873 EVT FromVT(MVT::Other); 874 if (NumZeroBits) { 875 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 876 isSExt = false; 877 } else if (NumSignBits > 1) { 878 FromVT = 879 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 880 isSExt = true; 881 } else { 882 continue; 883 } 884 // Add an assertion node. 885 assert(FromVT != MVT::Other); 886 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 887 RegisterVT, P, DAG.getValueType(FromVT)); 888 } 889 890 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 891 RegisterVT, ValueVT, V, CallConv); 892 Part += NumRegs; 893 Parts.clear(); 894 } 895 896 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 897 } 898 899 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 900 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 901 const Value *V, 902 ISD::NodeType PreferredExtendType) const { 903 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 904 ISD::NodeType ExtendKind = PreferredExtendType; 905 906 // Get the list of the values's legal parts. 907 unsigned NumRegs = Regs.size(); 908 SmallVector<SDValue, 8> Parts(NumRegs); 909 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 910 unsigned NumParts = RegCount[Value]; 911 912 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 913 *DAG.getContext(), 914 CallConv.getValue(), RegVTs[Value]) 915 : RegVTs[Value]; 916 917 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 918 ExtendKind = ISD::ZERO_EXTEND; 919 920 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 921 NumParts, RegisterVT, V, CallConv, ExtendKind); 922 Part += NumParts; 923 } 924 925 // Copy the parts into the registers. 926 SmallVector<SDValue, 8> Chains(NumRegs); 927 for (unsigned i = 0; i != NumRegs; ++i) { 928 SDValue Part; 929 if (!Flag) { 930 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 931 } else { 932 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 933 *Flag = Part.getValue(1); 934 } 935 936 Chains[i] = Part.getValue(0); 937 } 938 939 if (NumRegs == 1 || Flag) 940 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 941 // flagged to it. That is the CopyToReg nodes and the user are considered 942 // a single scheduling unit. If we create a TokenFactor and return it as 943 // chain, then the TokenFactor is both a predecessor (operand) of the 944 // user as well as a successor (the TF operands are flagged to the user). 945 // c1, f1 = CopyToReg 946 // c2, f2 = CopyToReg 947 // c3 = TokenFactor c1, c2 948 // ... 949 // = op c3, ..., f2 950 Chain = Chains[NumRegs-1]; 951 else 952 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 953 } 954 955 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 956 unsigned MatchingIdx, const SDLoc &dl, 957 SelectionDAG &DAG, 958 std::vector<SDValue> &Ops) const { 959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 960 961 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 962 if (HasMatching) 963 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 964 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 965 // Put the register class of the virtual registers in the flag word. That 966 // way, later passes can recompute register class constraints for inline 967 // assembly as well as normal instructions. 968 // Don't do this for tied operands that can use the regclass information 969 // from the def. 970 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 971 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 972 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 973 } 974 975 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 976 Ops.push_back(Res); 977 978 if (Code == InlineAsm::Kind_Clobber) { 979 // Clobbers should always have a 1:1 mapping with registers, and may 980 // reference registers that have illegal (e.g. vector) types. Hence, we 981 // shouldn't try to apply any sort of splitting logic to them. 982 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 983 "No 1:1 mapping from clobbers to regs?"); 984 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 985 (void)SP; 986 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 987 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 988 assert( 989 (Regs[I] != SP || 990 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 991 "If we clobbered the stack pointer, MFI should know about it."); 992 } 993 return; 994 } 995 996 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 997 MVT RegisterVT = RegVTs[Value]; 998 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 999 RegisterVT); 1000 for (unsigned i = 0; i != NumRegs; ++i) { 1001 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1002 unsigned TheReg = Regs[Reg++]; 1003 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1004 } 1005 } 1006 } 1007 1008 SmallVector<std::pair<unsigned, TypeSize>, 4> 1009 RegsForValue::getRegsAndSizes() const { 1010 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1011 unsigned I = 0; 1012 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1013 unsigned RegCount = std::get<0>(CountAndVT); 1014 MVT RegisterVT = std::get<1>(CountAndVT); 1015 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1016 for (unsigned E = I + RegCount; I != E; ++I) 1017 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1018 } 1019 return OutVec; 1020 } 1021 1022 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1023 const TargetLibraryInfo *li) { 1024 AA = aa; 1025 GFI = gfi; 1026 LibInfo = li; 1027 DL = &DAG.getDataLayout(); 1028 Context = DAG.getContext(); 1029 LPadToCallSiteMap.clear(); 1030 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1031 } 1032 1033 void SelectionDAGBuilder::clear() { 1034 NodeMap.clear(); 1035 UnusedArgNodeMap.clear(); 1036 PendingLoads.clear(); 1037 PendingExports.clear(); 1038 PendingConstrainedFP.clear(); 1039 PendingConstrainedFPStrict.clear(); 1040 CurInst = nullptr; 1041 HasTailCall = false; 1042 SDNodeOrder = LowestSDNodeOrder; 1043 StatepointLowering.clear(); 1044 } 1045 1046 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1047 DanglingDebugInfoMap.clear(); 1048 } 1049 1050 // Update DAG root to include dependencies on Pending chains. 1051 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1052 SDValue Root = DAG.getRoot(); 1053 1054 if (Pending.empty()) 1055 return Root; 1056 1057 // Add current root to PendingChains, unless we already indirectly 1058 // depend on it. 1059 if (Root.getOpcode() != ISD::EntryToken) { 1060 unsigned i = 0, e = Pending.size(); 1061 for (; i != e; ++i) { 1062 assert(Pending[i].getNode()->getNumOperands() > 1); 1063 if (Pending[i].getNode()->getOperand(0) == Root) 1064 break; // Don't add the root if we already indirectly depend on it. 1065 } 1066 1067 if (i == e) 1068 Pending.push_back(Root); 1069 } 1070 1071 if (Pending.size() == 1) 1072 Root = Pending[0]; 1073 else 1074 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1075 1076 DAG.setRoot(Root); 1077 Pending.clear(); 1078 return Root; 1079 } 1080 1081 SDValue SelectionDAGBuilder::getMemoryRoot() { 1082 return updateRoot(PendingLoads); 1083 } 1084 1085 SDValue SelectionDAGBuilder::getRoot() { 1086 // Chain up all pending constrained intrinsics together with all 1087 // pending loads, by simply appending them to PendingLoads and 1088 // then calling getMemoryRoot(). 1089 PendingLoads.reserve(PendingLoads.size() + 1090 PendingConstrainedFP.size() + 1091 PendingConstrainedFPStrict.size()); 1092 PendingLoads.append(PendingConstrainedFP.begin(), 1093 PendingConstrainedFP.end()); 1094 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1095 PendingConstrainedFPStrict.end()); 1096 PendingConstrainedFP.clear(); 1097 PendingConstrainedFPStrict.clear(); 1098 return getMemoryRoot(); 1099 } 1100 1101 SDValue SelectionDAGBuilder::getControlRoot() { 1102 // We need to emit pending fpexcept.strict constrained intrinsics, 1103 // so append them to the PendingExports list. 1104 PendingExports.append(PendingConstrainedFPStrict.begin(), 1105 PendingConstrainedFPStrict.end()); 1106 PendingConstrainedFPStrict.clear(); 1107 return updateRoot(PendingExports); 1108 } 1109 1110 void SelectionDAGBuilder::visit(const Instruction &I) { 1111 // Set up outgoing PHI node register values before emitting the terminator. 1112 if (I.isTerminator()) { 1113 HandlePHINodesInSuccessorBlocks(I.getParent()); 1114 } 1115 1116 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1117 if (!isa<DbgInfoIntrinsic>(I)) 1118 ++SDNodeOrder; 1119 1120 CurInst = &I; 1121 1122 visit(I.getOpcode(), I); 1123 1124 if (!I.isTerminator() && !HasTailCall && 1125 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1126 CopyToExportRegsIfNeeded(&I); 1127 1128 CurInst = nullptr; 1129 } 1130 1131 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1132 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1133 } 1134 1135 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1136 // Note: this doesn't use InstVisitor, because it has to work with 1137 // ConstantExpr's in addition to instructions. 1138 switch (Opcode) { 1139 default: llvm_unreachable("Unknown instruction type encountered!"); 1140 // Build the switch statement using the Instruction.def file. 1141 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1142 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1143 #include "llvm/IR/Instruction.def" 1144 } 1145 } 1146 1147 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1148 DebugLoc DL, unsigned Order) { 1149 // We treat variadic dbg_values differently at this stage. 1150 if (DI->hasArgList()) { 1151 // For variadic dbg_values we will now insert an undef. 1152 // FIXME: We can potentially recover these! 1153 SmallVector<SDDbgOperand, 2> Locs; 1154 for (const Value *V : DI->getValues()) { 1155 auto Undef = UndefValue::get(V->getType()); 1156 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1157 } 1158 SDDbgValue *SDV = DAG.getDbgValueList( 1159 DI->getVariable(), DI->getExpression(), Locs, {}, 1160 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1161 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1162 } else { 1163 // TODO: Dangling debug info will eventually either be resolved or produce 1164 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1165 // between the original dbg.value location and its resolved DBG_VALUE, 1166 // which we should ideally fill with an extra Undef DBG_VALUE. 1167 assert(DI->getNumVariableLocationOps() == 1 && 1168 "DbgValueInst without an ArgList should have a single location " 1169 "operand."); 1170 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1171 } 1172 } 1173 1174 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1175 const DIExpression *Expr) { 1176 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1177 const DbgValueInst *DI = DDI.getDI(); 1178 DIVariable *DanglingVariable = DI->getVariable(); 1179 DIExpression *DanglingExpr = DI->getExpression(); 1180 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1181 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1182 return true; 1183 } 1184 return false; 1185 }; 1186 1187 for (auto &DDIMI : DanglingDebugInfoMap) { 1188 DanglingDebugInfoVector &DDIV = DDIMI.second; 1189 1190 // If debug info is to be dropped, run it through final checks to see 1191 // whether it can be salvaged. 1192 for (auto &DDI : DDIV) 1193 if (isMatchingDbgValue(DDI)) 1194 salvageUnresolvedDbgValue(DDI); 1195 1196 erase_if(DDIV, isMatchingDbgValue); 1197 } 1198 } 1199 1200 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1201 // generate the debug data structures now that we've seen its definition. 1202 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1203 SDValue Val) { 1204 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1205 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1206 return; 1207 1208 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1209 for (auto &DDI : DDIV) { 1210 const DbgValueInst *DI = DDI.getDI(); 1211 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1212 assert(DI && "Ill-formed DanglingDebugInfo"); 1213 DebugLoc dl = DDI.getdl(); 1214 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1215 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1216 DILocalVariable *Variable = DI->getVariable(); 1217 DIExpression *Expr = DI->getExpression(); 1218 assert(Variable->isValidLocationForIntrinsic(dl) && 1219 "Expected inlined-at fields to agree"); 1220 SDDbgValue *SDV; 1221 if (Val.getNode()) { 1222 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1223 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1224 // we couldn't resolve it directly when examining the DbgValue intrinsic 1225 // in the first place we should not be more successful here). Unless we 1226 // have some test case that prove this to be correct we should avoid 1227 // calling EmitFuncArgumentDbgValue here. 1228 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1229 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1230 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1231 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1232 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1233 // inserted after the definition of Val when emitting the instructions 1234 // after ISel. An alternative could be to teach 1235 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1236 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1237 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1238 << ValSDNodeOrder << "\n"); 1239 SDV = getDbgValue(Val, Variable, Expr, dl, 1240 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1241 DAG.AddDbgValue(SDV, false); 1242 } else 1243 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1244 << "in EmitFuncArgumentDbgValue\n"); 1245 } else { 1246 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1247 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1248 auto SDV = 1249 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1250 DAG.AddDbgValue(SDV, false); 1251 } 1252 } 1253 DDIV.clear(); 1254 } 1255 1256 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1257 // TODO: For the variadic implementation, instead of only checking the fail 1258 // state of `handleDebugValue`, we need know specifically which values were 1259 // invalid, so that we attempt to salvage only those values when processing 1260 // a DIArgList. 1261 assert(!DDI.getDI()->hasArgList() && 1262 "Not implemented for variadic dbg_values"); 1263 Value *V = DDI.getDI()->getValue(0); 1264 DILocalVariable *Var = DDI.getDI()->getVariable(); 1265 DIExpression *Expr = DDI.getDI()->getExpression(); 1266 DebugLoc DL = DDI.getdl(); 1267 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1268 unsigned SDOrder = DDI.getSDNodeOrder(); 1269 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1270 // that DW_OP_stack_value is desired. 1271 assert(isa<DbgValueInst>(DDI.getDI())); 1272 bool StackValue = true; 1273 1274 // Can this Value can be encoded without any further work? 1275 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1276 return; 1277 1278 // Attempt to salvage back through as many instructions as possible. Bail if 1279 // a non-instruction is seen, such as a constant expression or global 1280 // variable. FIXME: Further work could recover those too. 1281 while (isa<Instruction>(V)) { 1282 Instruction &VAsInst = *cast<Instruction>(V); 1283 // Temporary "0", awaiting real implementation. 1284 SmallVector<uint64_t, 16> Ops; 1285 SmallVector<Value *, 4> AdditionalValues; 1286 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1287 AdditionalValues); 1288 // If we cannot salvage any further, and haven't yet found a suitable debug 1289 // expression, bail out. 1290 if (!V) 1291 break; 1292 1293 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1294 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1295 // here for variadic dbg_values, remove that condition. 1296 if (!AdditionalValues.empty()) 1297 break; 1298 1299 // New value and expr now represent this debuginfo. 1300 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1301 1302 // Some kind of simplification occurred: check whether the operand of the 1303 // salvaged debug expression can be encoded in this DAG. 1304 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1305 /*IsVariadic=*/false)) { 1306 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1307 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1308 return; 1309 } 1310 } 1311 1312 // This was the final opportunity to salvage this debug information, and it 1313 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1314 // any earlier variable location. 1315 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1316 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1317 DAG.AddDbgValue(SDV, false); 1318 1319 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1320 << "\n"); 1321 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1322 << "\n"); 1323 } 1324 1325 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1326 DILocalVariable *Var, 1327 DIExpression *Expr, DebugLoc dl, 1328 DebugLoc InstDL, unsigned Order, 1329 bool IsVariadic) { 1330 if (Values.empty()) 1331 return true; 1332 SmallVector<SDDbgOperand> LocationOps; 1333 SmallVector<SDNode *> Dependencies; 1334 for (const Value *V : Values) { 1335 // Constant value. 1336 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1337 isa<ConstantPointerNull>(V)) { 1338 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1339 continue; 1340 } 1341 1342 // If the Value is a frame index, we can create a FrameIndex debug value 1343 // without relying on the DAG at all. 1344 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1345 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1346 if (SI != FuncInfo.StaticAllocaMap.end()) { 1347 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1348 continue; 1349 } 1350 } 1351 1352 // Do not use getValue() in here; we don't want to generate code at 1353 // this point if it hasn't been done yet. 1354 SDValue N = NodeMap[V]; 1355 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1356 N = UnusedArgNodeMap[V]; 1357 if (N.getNode()) { 1358 // Only emit func arg dbg value for non-variadic dbg.values for now. 1359 if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1360 return true; 1361 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1362 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1363 // describe stack slot locations. 1364 // 1365 // Consider "int x = 0; int *px = &x;". There are two kinds of 1366 // interesting debug values here after optimization: 1367 // 1368 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1369 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1370 // 1371 // Both describe the direct values of their associated variables. 1372 Dependencies.push_back(N.getNode()); 1373 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1374 continue; 1375 } 1376 LocationOps.emplace_back( 1377 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1378 continue; 1379 } 1380 1381 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1382 // Special rules apply for the first dbg.values of parameter variables in a 1383 // function. Identify them by the fact they reference Argument Values, that 1384 // they're parameters, and they are parameters of the current function. We 1385 // need to let them dangle until they get an SDNode. 1386 bool IsParamOfFunc = 1387 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1388 if (IsParamOfFunc) 1389 return false; 1390 1391 // The value is not used in this block yet (or it would have an SDNode). 1392 // We still want the value to appear for the user if possible -- if it has 1393 // an associated VReg, we can refer to that instead. 1394 auto VMI = FuncInfo.ValueMap.find(V); 1395 if (VMI != FuncInfo.ValueMap.end()) { 1396 unsigned Reg = VMI->second; 1397 // If this is a PHI node, it may be split up into several MI PHI nodes 1398 // (in FunctionLoweringInfo::set). 1399 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1400 V->getType(), None); 1401 if (RFV.occupiesMultipleRegs()) { 1402 // FIXME: We could potentially support variadic dbg_values here. 1403 if (IsVariadic) 1404 return false; 1405 unsigned Offset = 0; 1406 unsigned BitsToDescribe = 0; 1407 if (auto VarSize = Var->getSizeInBits()) 1408 BitsToDescribe = *VarSize; 1409 if (auto Fragment = Expr->getFragmentInfo()) 1410 BitsToDescribe = Fragment->SizeInBits; 1411 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1412 // Bail out if all bits are described already. 1413 if (Offset >= BitsToDescribe) 1414 break; 1415 // TODO: handle scalable vectors. 1416 unsigned RegisterSize = RegAndSize.second; 1417 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1418 ? BitsToDescribe - Offset 1419 : RegisterSize; 1420 auto FragmentExpr = DIExpression::createFragmentExpression( 1421 Expr, Offset, FragmentSize); 1422 if (!FragmentExpr) 1423 continue; 1424 SDDbgValue *SDV = DAG.getVRegDbgValue( 1425 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1426 DAG.AddDbgValue(SDV, false); 1427 Offset += RegisterSize; 1428 } 1429 return true; 1430 } 1431 // We can use simple vreg locations for variadic dbg_values as well. 1432 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1433 continue; 1434 } 1435 // We failed to create a SDDbgOperand for V. 1436 return false; 1437 } 1438 1439 // We have created a SDDbgOperand for each Value in Values. 1440 // Should use Order instead of SDNodeOrder? 1441 assert(!LocationOps.empty()); 1442 SDDbgValue *SDV = 1443 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1444 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1445 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1446 return true; 1447 } 1448 1449 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1450 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1451 for (auto &Pair : DanglingDebugInfoMap) 1452 for (auto &DDI : Pair.second) 1453 salvageUnresolvedDbgValue(DDI); 1454 clearDanglingDebugInfo(); 1455 } 1456 1457 /// getCopyFromRegs - If there was virtual register allocated for the value V 1458 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1459 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1460 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1461 SDValue Result; 1462 1463 if (It != FuncInfo.ValueMap.end()) { 1464 Register InReg = It->second; 1465 1466 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1467 DAG.getDataLayout(), InReg, Ty, 1468 None); // This is not an ABI copy. 1469 SDValue Chain = DAG.getEntryNode(); 1470 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1471 V); 1472 resolveDanglingDebugInfo(V, Result); 1473 } 1474 1475 return Result; 1476 } 1477 1478 /// getValue - Return an SDValue for the given Value. 1479 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1480 // If we already have an SDValue for this value, use it. It's important 1481 // to do this first, so that we don't create a CopyFromReg if we already 1482 // have a regular SDValue. 1483 SDValue &N = NodeMap[V]; 1484 if (N.getNode()) return N; 1485 1486 // If there's a virtual register allocated and initialized for this 1487 // value, use it. 1488 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1489 return copyFromReg; 1490 1491 // Otherwise create a new SDValue and remember it. 1492 SDValue Val = getValueImpl(V); 1493 NodeMap[V] = Val; 1494 resolveDanglingDebugInfo(V, Val); 1495 return Val; 1496 } 1497 1498 /// getNonRegisterValue - Return an SDValue for the given Value, but 1499 /// don't look in FuncInfo.ValueMap for a virtual register. 1500 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1501 // If we already have an SDValue for this value, use it. 1502 SDValue &N = NodeMap[V]; 1503 if (N.getNode()) { 1504 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1505 // Remove the debug location from the node as the node is about to be used 1506 // in a location which may differ from the original debug location. This 1507 // is relevant to Constant and ConstantFP nodes because they can appear 1508 // as constant expressions inside PHI nodes. 1509 N->setDebugLoc(DebugLoc()); 1510 } 1511 return N; 1512 } 1513 1514 // Otherwise create a new SDValue and remember it. 1515 SDValue Val = getValueImpl(V); 1516 NodeMap[V] = Val; 1517 resolveDanglingDebugInfo(V, Val); 1518 return Val; 1519 } 1520 1521 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1522 /// Create an SDValue for the given value. 1523 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1524 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1525 1526 if (const Constant *C = dyn_cast<Constant>(V)) { 1527 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1528 1529 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1530 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1531 1532 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1533 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1534 1535 if (isa<ConstantPointerNull>(C)) { 1536 unsigned AS = V->getType()->getPointerAddressSpace(); 1537 return DAG.getConstant(0, getCurSDLoc(), 1538 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1539 } 1540 1541 if (match(C, m_VScale(DAG.getDataLayout()))) 1542 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1543 1544 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1545 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1546 1547 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1548 return DAG.getUNDEF(VT); 1549 1550 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1551 visit(CE->getOpcode(), *CE); 1552 SDValue N1 = NodeMap[V]; 1553 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1554 return N1; 1555 } 1556 1557 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1558 SmallVector<SDValue, 4> Constants; 1559 for (const Use &U : C->operands()) { 1560 SDNode *Val = getValue(U).getNode(); 1561 // If the operand is an empty aggregate, there are no values. 1562 if (!Val) continue; 1563 // Add each leaf value from the operand to the Constants list 1564 // to form a flattened list of all the values. 1565 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1566 Constants.push_back(SDValue(Val, i)); 1567 } 1568 1569 return DAG.getMergeValues(Constants, getCurSDLoc()); 1570 } 1571 1572 if (const ConstantDataSequential *CDS = 1573 dyn_cast<ConstantDataSequential>(C)) { 1574 SmallVector<SDValue, 4> Ops; 1575 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1576 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1577 // Add each leaf value from the operand to the Constants list 1578 // to form a flattened list of all the values. 1579 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1580 Ops.push_back(SDValue(Val, i)); 1581 } 1582 1583 if (isa<ArrayType>(CDS->getType())) 1584 return DAG.getMergeValues(Ops, getCurSDLoc()); 1585 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1586 } 1587 1588 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1589 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1590 "Unknown struct or array constant!"); 1591 1592 SmallVector<EVT, 4> ValueVTs; 1593 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1594 unsigned NumElts = ValueVTs.size(); 1595 if (NumElts == 0) 1596 return SDValue(); // empty struct 1597 SmallVector<SDValue, 4> Constants(NumElts); 1598 for (unsigned i = 0; i != NumElts; ++i) { 1599 EVT EltVT = ValueVTs[i]; 1600 if (isa<UndefValue>(C)) 1601 Constants[i] = DAG.getUNDEF(EltVT); 1602 else if (EltVT.isFloatingPoint()) 1603 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1604 else 1605 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1606 } 1607 1608 return DAG.getMergeValues(Constants, getCurSDLoc()); 1609 } 1610 1611 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1612 return DAG.getBlockAddress(BA, VT); 1613 1614 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1615 return getValue(Equiv->getGlobalValue()); 1616 1617 VectorType *VecTy = cast<VectorType>(V->getType()); 1618 1619 // Now that we know the number and type of the elements, get that number of 1620 // elements into the Ops array based on what kind of constant it is. 1621 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1622 SmallVector<SDValue, 16> Ops; 1623 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1624 for (unsigned i = 0; i != NumElements; ++i) 1625 Ops.push_back(getValue(CV->getOperand(i))); 1626 1627 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1628 } else if (isa<ConstantAggregateZero>(C)) { 1629 EVT EltVT = 1630 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1631 1632 SDValue Op; 1633 if (EltVT.isFloatingPoint()) 1634 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1635 else 1636 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1637 1638 if (isa<ScalableVectorType>(VecTy)) 1639 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1640 else { 1641 SmallVector<SDValue, 16> Ops; 1642 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1643 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1644 } 1645 } 1646 llvm_unreachable("Unknown vector constant"); 1647 } 1648 1649 // If this is a static alloca, generate it as the frameindex instead of 1650 // computation. 1651 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1652 DenseMap<const AllocaInst*, int>::iterator SI = 1653 FuncInfo.StaticAllocaMap.find(AI); 1654 if (SI != FuncInfo.StaticAllocaMap.end()) 1655 return DAG.getFrameIndex(SI->second, 1656 TLI.getFrameIndexTy(DAG.getDataLayout())); 1657 } 1658 1659 // If this is an instruction which fast-isel has deferred, select it now. 1660 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1661 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1662 1663 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1664 Inst->getType(), None); 1665 SDValue Chain = DAG.getEntryNode(); 1666 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1667 } 1668 1669 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1670 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1671 } 1672 llvm_unreachable("Can't get register for value!"); 1673 } 1674 1675 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1676 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1677 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1678 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1679 bool IsSEH = isAsynchronousEHPersonality(Pers); 1680 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1681 if (!IsSEH) 1682 CatchPadMBB->setIsEHScopeEntry(); 1683 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1684 if (IsMSVCCXX || IsCoreCLR) 1685 CatchPadMBB->setIsEHFuncletEntry(); 1686 } 1687 1688 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1689 // Update machine-CFG edge. 1690 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1691 FuncInfo.MBB->addSuccessor(TargetMBB); 1692 TargetMBB->setIsEHCatchretTarget(true); 1693 DAG.getMachineFunction().setHasEHCatchret(true); 1694 1695 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1696 bool IsSEH = isAsynchronousEHPersonality(Pers); 1697 if (IsSEH) { 1698 // If this is not a fall-through branch or optimizations are switched off, 1699 // emit the branch. 1700 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1701 TM.getOptLevel() == CodeGenOpt::None) 1702 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1703 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1704 return; 1705 } 1706 1707 // Figure out the funclet membership for the catchret's successor. 1708 // This will be used by the FuncletLayout pass to determine how to order the 1709 // BB's. 1710 // A 'catchret' returns to the outer scope's color. 1711 Value *ParentPad = I.getCatchSwitchParentPad(); 1712 const BasicBlock *SuccessorColor; 1713 if (isa<ConstantTokenNone>(ParentPad)) 1714 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1715 else 1716 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1717 assert(SuccessorColor && "No parent funclet for catchret!"); 1718 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1719 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1720 1721 // Create the terminator node. 1722 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1723 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1724 DAG.getBasicBlock(SuccessorColorMBB)); 1725 DAG.setRoot(Ret); 1726 } 1727 1728 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1729 // Don't emit any special code for the cleanuppad instruction. It just marks 1730 // the start of an EH scope/funclet. 1731 FuncInfo.MBB->setIsEHScopeEntry(); 1732 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1733 if (Pers != EHPersonality::Wasm_CXX) { 1734 FuncInfo.MBB->setIsEHFuncletEntry(); 1735 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1736 } 1737 } 1738 1739 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1740 // not match, it is OK to add only the first unwind destination catchpad to the 1741 // successors, because there will be at least one invoke instruction within the 1742 // catch scope that points to the next unwind destination, if one exists, so 1743 // CFGSort cannot mess up with BB sorting order. 1744 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1745 // call within them, and catchpads only consisting of 'catch (...)' have a 1746 // '__cxa_end_catch' call within them, both of which generate invokes in case 1747 // the next unwind destination exists, i.e., the next unwind destination is not 1748 // the caller.) 1749 // 1750 // Having at most one EH pad successor is also simpler and helps later 1751 // transformations. 1752 // 1753 // For example, 1754 // current: 1755 // invoke void @foo to ... unwind label %catch.dispatch 1756 // catch.dispatch: 1757 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1758 // catch.start: 1759 // ... 1760 // ... in this BB or some other child BB dominated by this BB there will be an 1761 // invoke that points to 'next' BB as an unwind destination 1762 // 1763 // next: ; We don't need to add this to 'current' BB's successor 1764 // ... 1765 static void findWasmUnwindDestinations( 1766 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1767 BranchProbability Prob, 1768 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1769 &UnwindDests) { 1770 while (EHPadBB) { 1771 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1772 if (isa<CleanupPadInst>(Pad)) { 1773 // Stop on cleanup pads. 1774 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1775 UnwindDests.back().first->setIsEHScopeEntry(); 1776 break; 1777 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1778 // Add the catchpad handlers to the possible destinations. We don't 1779 // continue to the unwind destination of the catchswitch for wasm. 1780 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1781 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1782 UnwindDests.back().first->setIsEHScopeEntry(); 1783 } 1784 break; 1785 } else { 1786 continue; 1787 } 1788 } 1789 } 1790 1791 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1792 /// many places it could ultimately go. In the IR, we have a single unwind 1793 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1794 /// This function skips over imaginary basic blocks that hold catchswitch 1795 /// instructions, and finds all the "real" machine 1796 /// basic block destinations. As those destinations may not be successors of 1797 /// EHPadBB, here we also calculate the edge probability to those destinations. 1798 /// The passed-in Prob is the edge probability to EHPadBB. 1799 static void findUnwindDestinations( 1800 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1801 BranchProbability Prob, 1802 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1803 &UnwindDests) { 1804 EHPersonality Personality = 1805 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1806 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1807 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1808 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1809 bool IsSEH = isAsynchronousEHPersonality(Personality); 1810 1811 if (IsWasmCXX) { 1812 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1813 assert(UnwindDests.size() <= 1 && 1814 "There should be at most one unwind destination for wasm"); 1815 return; 1816 } 1817 1818 while (EHPadBB) { 1819 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1820 BasicBlock *NewEHPadBB = nullptr; 1821 if (isa<LandingPadInst>(Pad)) { 1822 // Stop on landingpads. They are not funclets. 1823 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1824 break; 1825 } else if (isa<CleanupPadInst>(Pad)) { 1826 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1827 // personalities. 1828 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1829 UnwindDests.back().first->setIsEHScopeEntry(); 1830 UnwindDests.back().first->setIsEHFuncletEntry(); 1831 break; 1832 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1833 // Add the catchpad handlers to the possible destinations. 1834 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1835 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1836 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1837 if (IsMSVCCXX || IsCoreCLR) 1838 UnwindDests.back().first->setIsEHFuncletEntry(); 1839 if (!IsSEH) 1840 UnwindDests.back().first->setIsEHScopeEntry(); 1841 } 1842 NewEHPadBB = CatchSwitch->getUnwindDest(); 1843 } else { 1844 continue; 1845 } 1846 1847 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1848 if (BPI && NewEHPadBB) 1849 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1850 EHPadBB = NewEHPadBB; 1851 } 1852 } 1853 1854 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1855 // Update successor info. 1856 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1857 auto UnwindDest = I.getUnwindDest(); 1858 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1859 BranchProbability UnwindDestProb = 1860 (BPI && UnwindDest) 1861 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1862 : BranchProbability::getZero(); 1863 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1864 for (auto &UnwindDest : UnwindDests) { 1865 UnwindDest.first->setIsEHPad(); 1866 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1867 } 1868 FuncInfo.MBB->normalizeSuccProbs(); 1869 1870 // Create the terminator node. 1871 SDValue Ret = 1872 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1873 DAG.setRoot(Ret); 1874 } 1875 1876 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1877 report_fatal_error("visitCatchSwitch not yet implemented!"); 1878 } 1879 1880 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1881 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1882 auto &DL = DAG.getDataLayout(); 1883 SDValue Chain = getControlRoot(); 1884 SmallVector<ISD::OutputArg, 8> Outs; 1885 SmallVector<SDValue, 8> OutVals; 1886 1887 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1888 // lower 1889 // 1890 // %val = call <ty> @llvm.experimental.deoptimize() 1891 // ret <ty> %val 1892 // 1893 // differently. 1894 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1895 LowerDeoptimizingReturn(); 1896 return; 1897 } 1898 1899 if (!FuncInfo.CanLowerReturn) { 1900 unsigned DemoteReg = FuncInfo.DemoteRegister; 1901 const Function *F = I.getParent()->getParent(); 1902 1903 // Emit a store of the return value through the virtual register. 1904 // Leave Outs empty so that LowerReturn won't try to load return 1905 // registers the usual way. 1906 SmallVector<EVT, 1> PtrValueVTs; 1907 ComputeValueVTs(TLI, DL, 1908 F->getReturnType()->getPointerTo( 1909 DAG.getDataLayout().getAllocaAddrSpace()), 1910 PtrValueVTs); 1911 1912 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1913 DemoteReg, PtrValueVTs[0]); 1914 SDValue RetOp = getValue(I.getOperand(0)); 1915 1916 SmallVector<EVT, 4> ValueVTs, MemVTs; 1917 SmallVector<uint64_t, 4> Offsets; 1918 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1919 &Offsets); 1920 unsigned NumValues = ValueVTs.size(); 1921 1922 SmallVector<SDValue, 4> Chains(NumValues); 1923 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1924 for (unsigned i = 0; i != NumValues; ++i) { 1925 // An aggregate return value cannot wrap around the address space, so 1926 // offsets to its parts don't wrap either. 1927 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1928 TypeSize::Fixed(Offsets[i])); 1929 1930 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1931 if (MemVTs[i] != ValueVTs[i]) 1932 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1933 Chains[i] = DAG.getStore( 1934 Chain, getCurSDLoc(), Val, 1935 // FIXME: better loc info would be nice. 1936 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1937 commonAlignment(BaseAlign, Offsets[i])); 1938 } 1939 1940 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1941 MVT::Other, Chains); 1942 } else if (I.getNumOperands() != 0) { 1943 SmallVector<EVT, 4> ValueVTs; 1944 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1945 unsigned NumValues = ValueVTs.size(); 1946 if (NumValues) { 1947 SDValue RetOp = getValue(I.getOperand(0)); 1948 1949 const Function *F = I.getParent()->getParent(); 1950 1951 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1952 I.getOperand(0)->getType(), F->getCallingConv(), 1953 /*IsVarArg*/ false, DL); 1954 1955 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1956 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1957 Attribute::SExt)) 1958 ExtendKind = ISD::SIGN_EXTEND; 1959 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1960 Attribute::ZExt)) 1961 ExtendKind = ISD::ZERO_EXTEND; 1962 1963 LLVMContext &Context = F->getContext(); 1964 bool RetInReg = F->getAttributes().hasAttribute( 1965 AttributeList::ReturnIndex, Attribute::InReg); 1966 1967 for (unsigned j = 0; j != NumValues; ++j) { 1968 EVT VT = ValueVTs[j]; 1969 1970 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1971 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1972 1973 CallingConv::ID CC = F->getCallingConv(); 1974 1975 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1976 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1977 SmallVector<SDValue, 4> Parts(NumParts); 1978 getCopyToParts(DAG, getCurSDLoc(), 1979 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1980 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1981 1982 // 'inreg' on function refers to return value 1983 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1984 if (RetInReg) 1985 Flags.setInReg(); 1986 1987 if (I.getOperand(0)->getType()->isPointerTy()) { 1988 Flags.setPointer(); 1989 Flags.setPointerAddrSpace( 1990 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1991 } 1992 1993 if (NeedsRegBlock) { 1994 Flags.setInConsecutiveRegs(); 1995 if (j == NumValues - 1) 1996 Flags.setInConsecutiveRegsLast(); 1997 } 1998 1999 // Propagate extension type if any 2000 if (ExtendKind == ISD::SIGN_EXTEND) 2001 Flags.setSExt(); 2002 else if (ExtendKind == ISD::ZERO_EXTEND) 2003 Flags.setZExt(); 2004 2005 for (unsigned i = 0; i < NumParts; ++i) { 2006 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 2007 VT, /*isfixed=*/true, 0, 0)); 2008 OutVals.push_back(Parts[i]); 2009 } 2010 } 2011 } 2012 } 2013 2014 // Push in swifterror virtual register as the last element of Outs. This makes 2015 // sure swifterror virtual register will be returned in the swifterror 2016 // physical register. 2017 const Function *F = I.getParent()->getParent(); 2018 if (TLI.supportSwiftError() && 2019 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2020 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2021 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2022 Flags.setSwiftError(); 2023 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 2024 EVT(TLI.getPointerTy(DL)) /*argvt*/, 2025 true /*isfixed*/, 1 /*origidx*/, 2026 0 /*partOffs*/)); 2027 // Create SDNode for the swifterror virtual register. 2028 OutVals.push_back( 2029 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2030 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2031 EVT(TLI.getPointerTy(DL)))); 2032 } 2033 2034 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2035 CallingConv::ID CallConv = 2036 DAG.getMachineFunction().getFunction().getCallingConv(); 2037 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2038 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2039 2040 // Verify that the target's LowerReturn behaved as expected. 2041 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2042 "LowerReturn didn't return a valid chain!"); 2043 2044 // Update the DAG with the new chain value resulting from return lowering. 2045 DAG.setRoot(Chain); 2046 } 2047 2048 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2049 /// created for it, emit nodes to copy the value into the virtual 2050 /// registers. 2051 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2052 // Skip empty types 2053 if (V->getType()->isEmptyTy()) 2054 return; 2055 2056 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2057 if (VMI != FuncInfo.ValueMap.end()) { 2058 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2059 CopyValueToVirtualRegister(V, VMI->second); 2060 } 2061 } 2062 2063 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2064 /// the current basic block, add it to ValueMap now so that we'll get a 2065 /// CopyTo/FromReg. 2066 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2067 // No need to export constants. 2068 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2069 2070 // Already exported? 2071 if (FuncInfo.isExportedInst(V)) return; 2072 2073 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2074 CopyValueToVirtualRegister(V, Reg); 2075 } 2076 2077 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2078 const BasicBlock *FromBB) { 2079 // The operands of the setcc have to be in this block. We don't know 2080 // how to export them from some other block. 2081 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2082 // Can export from current BB. 2083 if (VI->getParent() == FromBB) 2084 return true; 2085 2086 // Is already exported, noop. 2087 return FuncInfo.isExportedInst(V); 2088 } 2089 2090 // If this is an argument, we can export it if the BB is the entry block or 2091 // if it is already exported. 2092 if (isa<Argument>(V)) { 2093 if (FromBB->isEntryBlock()) 2094 return true; 2095 2096 // Otherwise, can only export this if it is already exported. 2097 return FuncInfo.isExportedInst(V); 2098 } 2099 2100 // Otherwise, constants can always be exported. 2101 return true; 2102 } 2103 2104 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2105 BranchProbability 2106 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2107 const MachineBasicBlock *Dst) const { 2108 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2109 const BasicBlock *SrcBB = Src->getBasicBlock(); 2110 const BasicBlock *DstBB = Dst->getBasicBlock(); 2111 if (!BPI) { 2112 // If BPI is not available, set the default probability as 1 / N, where N is 2113 // the number of successors. 2114 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2115 return BranchProbability(1, SuccSize); 2116 } 2117 return BPI->getEdgeProbability(SrcBB, DstBB); 2118 } 2119 2120 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2121 MachineBasicBlock *Dst, 2122 BranchProbability Prob) { 2123 if (!FuncInfo.BPI) 2124 Src->addSuccessorWithoutProb(Dst); 2125 else { 2126 if (Prob.isUnknown()) 2127 Prob = getEdgeProbability(Src, Dst); 2128 Src->addSuccessor(Dst, Prob); 2129 } 2130 } 2131 2132 static bool InBlock(const Value *V, const BasicBlock *BB) { 2133 if (const Instruction *I = dyn_cast<Instruction>(V)) 2134 return I->getParent() == BB; 2135 return true; 2136 } 2137 2138 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2139 /// This function emits a branch and is used at the leaves of an OR or an 2140 /// AND operator tree. 2141 void 2142 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2143 MachineBasicBlock *TBB, 2144 MachineBasicBlock *FBB, 2145 MachineBasicBlock *CurBB, 2146 MachineBasicBlock *SwitchBB, 2147 BranchProbability TProb, 2148 BranchProbability FProb, 2149 bool InvertCond) { 2150 const BasicBlock *BB = CurBB->getBasicBlock(); 2151 2152 // If the leaf of the tree is a comparison, merge the condition into 2153 // the caseblock. 2154 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2155 // The operands of the cmp have to be in this block. We don't know 2156 // how to export them from some other block. If this is the first block 2157 // of the sequence, no exporting is needed. 2158 if (CurBB == SwitchBB || 2159 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2160 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2161 ISD::CondCode Condition; 2162 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2163 ICmpInst::Predicate Pred = 2164 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2165 Condition = getICmpCondCode(Pred); 2166 } else { 2167 const FCmpInst *FC = cast<FCmpInst>(Cond); 2168 FCmpInst::Predicate Pred = 2169 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2170 Condition = getFCmpCondCode(Pred); 2171 if (TM.Options.NoNaNsFPMath) 2172 Condition = getFCmpCodeWithoutNaN(Condition); 2173 } 2174 2175 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2176 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2177 SL->SwitchCases.push_back(CB); 2178 return; 2179 } 2180 } 2181 2182 // Create a CaseBlock record representing this branch. 2183 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2184 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2185 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2186 SL->SwitchCases.push_back(CB); 2187 } 2188 2189 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2190 MachineBasicBlock *TBB, 2191 MachineBasicBlock *FBB, 2192 MachineBasicBlock *CurBB, 2193 MachineBasicBlock *SwitchBB, 2194 Instruction::BinaryOps Opc, 2195 BranchProbability TProb, 2196 BranchProbability FProb, 2197 bool InvertCond) { 2198 // Skip over not part of the tree and remember to invert op and operands at 2199 // next level. 2200 Value *NotCond; 2201 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2202 InBlock(NotCond, CurBB->getBasicBlock())) { 2203 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2204 !InvertCond); 2205 return; 2206 } 2207 2208 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2209 const Value *BOpOp0, *BOpOp1; 2210 // Compute the effective opcode for Cond, taking into account whether it needs 2211 // to be inverted, e.g. 2212 // and (not (or A, B)), C 2213 // gets lowered as 2214 // and (and (not A, not B), C) 2215 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2216 if (BOp) { 2217 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2218 ? Instruction::And 2219 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2220 ? Instruction::Or 2221 : (Instruction::BinaryOps)0); 2222 if (InvertCond) { 2223 if (BOpc == Instruction::And) 2224 BOpc = Instruction::Or; 2225 else if (BOpc == Instruction::Or) 2226 BOpc = Instruction::And; 2227 } 2228 } 2229 2230 // If this node is not part of the or/and tree, emit it as a branch. 2231 // Note that all nodes in the tree should have same opcode. 2232 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2233 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2234 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2235 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2236 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2237 TProb, FProb, InvertCond); 2238 return; 2239 } 2240 2241 // Create TmpBB after CurBB. 2242 MachineFunction::iterator BBI(CurBB); 2243 MachineFunction &MF = DAG.getMachineFunction(); 2244 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2245 CurBB->getParent()->insert(++BBI, TmpBB); 2246 2247 if (Opc == Instruction::Or) { 2248 // Codegen X | Y as: 2249 // BB1: 2250 // jmp_if_X TBB 2251 // jmp TmpBB 2252 // TmpBB: 2253 // jmp_if_Y TBB 2254 // jmp FBB 2255 // 2256 2257 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2258 // The requirement is that 2259 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2260 // = TrueProb for original BB. 2261 // Assuming the original probabilities are A and B, one choice is to set 2262 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2263 // A/(1+B) and 2B/(1+B). This choice assumes that 2264 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2265 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2266 // TmpBB, but the math is more complicated. 2267 2268 auto NewTrueProb = TProb / 2; 2269 auto NewFalseProb = TProb / 2 + FProb; 2270 // Emit the LHS condition. 2271 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2272 NewFalseProb, InvertCond); 2273 2274 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2275 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2276 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2277 // Emit the RHS condition into TmpBB. 2278 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2279 Probs[1], InvertCond); 2280 } else { 2281 assert(Opc == Instruction::And && "Unknown merge op!"); 2282 // Codegen X & Y as: 2283 // BB1: 2284 // jmp_if_X TmpBB 2285 // jmp FBB 2286 // TmpBB: 2287 // jmp_if_Y TBB 2288 // jmp FBB 2289 // 2290 // This requires creation of TmpBB after CurBB. 2291 2292 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2293 // The requirement is that 2294 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2295 // = FalseProb for original BB. 2296 // Assuming the original probabilities are A and B, one choice is to set 2297 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2298 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2299 // TrueProb for BB1 * FalseProb for TmpBB. 2300 2301 auto NewTrueProb = TProb + FProb / 2; 2302 auto NewFalseProb = FProb / 2; 2303 // Emit the LHS condition. 2304 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2305 NewFalseProb, InvertCond); 2306 2307 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2308 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2309 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2310 // Emit the RHS condition into TmpBB. 2311 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2312 Probs[1], InvertCond); 2313 } 2314 } 2315 2316 /// If the set of cases should be emitted as a series of branches, return true. 2317 /// If we should emit this as a bunch of and/or'd together conditions, return 2318 /// false. 2319 bool 2320 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2321 if (Cases.size() != 2) return true; 2322 2323 // If this is two comparisons of the same values or'd or and'd together, they 2324 // will get folded into a single comparison, so don't emit two blocks. 2325 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2326 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2327 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2328 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2329 return false; 2330 } 2331 2332 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2333 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2334 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2335 Cases[0].CC == Cases[1].CC && 2336 isa<Constant>(Cases[0].CmpRHS) && 2337 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2338 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2339 return false; 2340 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2341 return false; 2342 } 2343 2344 return true; 2345 } 2346 2347 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2348 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2349 2350 // Update machine-CFG edges. 2351 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2352 2353 if (I.isUnconditional()) { 2354 // Update machine-CFG edges. 2355 BrMBB->addSuccessor(Succ0MBB); 2356 2357 // If this is not a fall-through branch or optimizations are switched off, 2358 // emit the branch. 2359 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2360 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2361 MVT::Other, getControlRoot(), 2362 DAG.getBasicBlock(Succ0MBB))); 2363 2364 return; 2365 } 2366 2367 // If this condition is one of the special cases we handle, do special stuff 2368 // now. 2369 const Value *CondVal = I.getCondition(); 2370 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2371 2372 // If this is a series of conditions that are or'd or and'd together, emit 2373 // this as a sequence of branches instead of setcc's with and/or operations. 2374 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2375 // unpredictable branches, and vector extracts because those jumps are likely 2376 // expensive for any target), this should improve performance. 2377 // For example, instead of something like: 2378 // cmp A, B 2379 // C = seteq 2380 // cmp D, E 2381 // F = setle 2382 // or C, F 2383 // jnz foo 2384 // Emit: 2385 // cmp A, B 2386 // je foo 2387 // cmp D, E 2388 // jle foo 2389 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2390 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2391 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2392 Value *Vec; 2393 const Value *BOp0, *BOp1; 2394 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2395 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2396 Opcode = Instruction::And; 2397 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2398 Opcode = Instruction::Or; 2399 2400 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2401 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2402 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2403 getEdgeProbability(BrMBB, Succ0MBB), 2404 getEdgeProbability(BrMBB, Succ1MBB), 2405 /*InvertCond=*/false); 2406 // If the compares in later blocks need to use values not currently 2407 // exported from this block, export them now. This block should always 2408 // be the first entry. 2409 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2410 2411 // Allow some cases to be rejected. 2412 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2413 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2414 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2415 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2416 } 2417 2418 // Emit the branch for this block. 2419 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2420 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2421 return; 2422 } 2423 2424 // Okay, we decided not to do this, remove any inserted MBB's and clear 2425 // SwitchCases. 2426 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2427 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2428 2429 SL->SwitchCases.clear(); 2430 } 2431 } 2432 2433 // Create a CaseBlock record representing this branch. 2434 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2435 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2436 2437 // Use visitSwitchCase to actually insert the fast branch sequence for this 2438 // cond branch. 2439 visitSwitchCase(CB, BrMBB); 2440 } 2441 2442 /// visitSwitchCase - Emits the necessary code to represent a single node in 2443 /// the binary search tree resulting from lowering a switch instruction. 2444 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2445 MachineBasicBlock *SwitchBB) { 2446 SDValue Cond; 2447 SDValue CondLHS = getValue(CB.CmpLHS); 2448 SDLoc dl = CB.DL; 2449 2450 if (CB.CC == ISD::SETTRUE) { 2451 // Branch or fall through to TrueBB. 2452 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2453 SwitchBB->normalizeSuccProbs(); 2454 if (CB.TrueBB != NextBlock(SwitchBB)) { 2455 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2456 DAG.getBasicBlock(CB.TrueBB))); 2457 } 2458 return; 2459 } 2460 2461 auto &TLI = DAG.getTargetLoweringInfo(); 2462 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2463 2464 // Build the setcc now. 2465 if (!CB.CmpMHS) { 2466 // Fold "(X == true)" to X and "(X == false)" to !X to 2467 // handle common cases produced by branch lowering. 2468 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2469 CB.CC == ISD::SETEQ) 2470 Cond = CondLHS; 2471 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2472 CB.CC == ISD::SETEQ) { 2473 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2474 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2475 } else { 2476 SDValue CondRHS = getValue(CB.CmpRHS); 2477 2478 // If a pointer's DAG type is larger than its memory type then the DAG 2479 // values are zero-extended. This breaks signed comparisons so truncate 2480 // back to the underlying type before doing the compare. 2481 if (CondLHS.getValueType() != MemVT) { 2482 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2483 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2484 } 2485 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2486 } 2487 } else { 2488 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2489 2490 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2491 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2492 2493 SDValue CmpOp = getValue(CB.CmpMHS); 2494 EVT VT = CmpOp.getValueType(); 2495 2496 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2497 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2498 ISD::SETLE); 2499 } else { 2500 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2501 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2502 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2503 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2504 } 2505 } 2506 2507 // Update successor info 2508 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2509 // TrueBB and FalseBB are always different unless the incoming IR is 2510 // degenerate. This only happens when running llc on weird IR. 2511 if (CB.TrueBB != CB.FalseBB) 2512 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2513 SwitchBB->normalizeSuccProbs(); 2514 2515 // If the lhs block is the next block, invert the condition so that we can 2516 // fall through to the lhs instead of the rhs block. 2517 if (CB.TrueBB == NextBlock(SwitchBB)) { 2518 std::swap(CB.TrueBB, CB.FalseBB); 2519 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2520 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2521 } 2522 2523 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2524 MVT::Other, getControlRoot(), Cond, 2525 DAG.getBasicBlock(CB.TrueBB)); 2526 2527 // Insert the false branch. Do this even if it's a fall through branch, 2528 // this makes it easier to do DAG optimizations which require inverting 2529 // the branch condition. 2530 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2531 DAG.getBasicBlock(CB.FalseBB)); 2532 2533 DAG.setRoot(BrCond); 2534 } 2535 2536 /// visitJumpTable - Emit JumpTable node in the current MBB 2537 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2538 // Emit the code for the jump table 2539 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2540 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2541 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2542 JT.Reg, PTy); 2543 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2544 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2545 MVT::Other, Index.getValue(1), 2546 Table, Index); 2547 DAG.setRoot(BrJumpTable); 2548 } 2549 2550 /// visitJumpTableHeader - This function emits necessary code to produce index 2551 /// in the JumpTable from switch case. 2552 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2553 JumpTableHeader &JTH, 2554 MachineBasicBlock *SwitchBB) { 2555 SDLoc dl = getCurSDLoc(); 2556 2557 // Subtract the lowest switch case value from the value being switched on. 2558 SDValue SwitchOp = getValue(JTH.SValue); 2559 EVT VT = SwitchOp.getValueType(); 2560 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2561 DAG.getConstant(JTH.First, dl, VT)); 2562 2563 // The SDNode we just created, which holds the value being switched on minus 2564 // the smallest case value, needs to be copied to a virtual register so it 2565 // can be used as an index into the jump table in a subsequent basic block. 2566 // This value may be smaller or larger than the target's pointer type, and 2567 // therefore require extension or truncating. 2568 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2569 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2570 2571 unsigned JumpTableReg = 2572 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2573 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2574 JumpTableReg, SwitchOp); 2575 JT.Reg = JumpTableReg; 2576 2577 if (!JTH.OmitRangeCheck) { 2578 // Emit the range check for the jump table, and branch to the default block 2579 // for the switch statement if the value being switched on exceeds the 2580 // largest case in the switch. 2581 SDValue CMP = DAG.getSetCC( 2582 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2583 Sub.getValueType()), 2584 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2585 2586 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2587 MVT::Other, CopyTo, CMP, 2588 DAG.getBasicBlock(JT.Default)); 2589 2590 // Avoid emitting unnecessary branches to the next block. 2591 if (JT.MBB != NextBlock(SwitchBB)) 2592 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2593 DAG.getBasicBlock(JT.MBB)); 2594 2595 DAG.setRoot(BrCond); 2596 } else { 2597 // Avoid emitting unnecessary branches to the next block. 2598 if (JT.MBB != NextBlock(SwitchBB)) 2599 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2600 DAG.getBasicBlock(JT.MBB))); 2601 else 2602 DAG.setRoot(CopyTo); 2603 } 2604 } 2605 2606 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2607 /// variable if there exists one. 2608 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2609 SDValue &Chain) { 2610 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2611 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2612 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2613 MachineFunction &MF = DAG.getMachineFunction(); 2614 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2615 MachineSDNode *Node = 2616 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2617 if (Global) { 2618 MachinePointerInfo MPInfo(Global); 2619 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2620 MachineMemOperand::MODereferenceable; 2621 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2622 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2623 DAG.setNodeMemRefs(Node, {MemRef}); 2624 } 2625 if (PtrTy != PtrMemTy) 2626 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2627 return SDValue(Node, 0); 2628 } 2629 2630 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2631 /// tail spliced into a stack protector check success bb. 2632 /// 2633 /// For a high level explanation of how this fits into the stack protector 2634 /// generation see the comment on the declaration of class 2635 /// StackProtectorDescriptor. 2636 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2637 MachineBasicBlock *ParentBB) { 2638 2639 // First create the loads to the guard/stack slot for the comparison. 2640 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2641 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2642 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2643 2644 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2645 int FI = MFI.getStackProtectorIndex(); 2646 2647 SDValue Guard; 2648 SDLoc dl = getCurSDLoc(); 2649 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2650 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2651 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2652 2653 // Generate code to load the content of the guard slot. 2654 SDValue GuardVal = DAG.getLoad( 2655 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2656 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2657 MachineMemOperand::MOVolatile); 2658 2659 if (TLI.useStackGuardXorFP()) 2660 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2661 2662 // Retrieve guard check function, nullptr if instrumentation is inlined. 2663 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2664 // The target provides a guard check function to validate the guard value. 2665 // Generate a call to that function with the content of the guard slot as 2666 // argument. 2667 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2668 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2669 2670 TargetLowering::ArgListTy Args; 2671 TargetLowering::ArgListEntry Entry; 2672 Entry.Node = GuardVal; 2673 Entry.Ty = FnTy->getParamType(0); 2674 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2675 Entry.IsInReg = true; 2676 Args.push_back(Entry); 2677 2678 TargetLowering::CallLoweringInfo CLI(DAG); 2679 CLI.setDebugLoc(getCurSDLoc()) 2680 .setChain(DAG.getEntryNode()) 2681 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2682 getValue(GuardCheckFn), std::move(Args)); 2683 2684 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2685 DAG.setRoot(Result.second); 2686 return; 2687 } 2688 2689 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2690 // Otherwise, emit a volatile load to retrieve the stack guard value. 2691 SDValue Chain = DAG.getEntryNode(); 2692 if (TLI.useLoadStackGuardNode()) { 2693 Guard = getLoadStackGuard(DAG, dl, Chain); 2694 } else { 2695 const Value *IRGuard = TLI.getSDagStackGuard(M); 2696 SDValue GuardPtr = getValue(IRGuard); 2697 2698 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2699 MachinePointerInfo(IRGuard, 0), Align, 2700 MachineMemOperand::MOVolatile); 2701 } 2702 2703 // Perform the comparison via a getsetcc. 2704 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2705 *DAG.getContext(), 2706 Guard.getValueType()), 2707 Guard, GuardVal, ISD::SETNE); 2708 2709 // If the guard/stackslot do not equal, branch to failure MBB. 2710 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2711 MVT::Other, GuardVal.getOperand(0), 2712 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2713 // Otherwise branch to success MBB. 2714 SDValue Br = DAG.getNode(ISD::BR, dl, 2715 MVT::Other, BrCond, 2716 DAG.getBasicBlock(SPD.getSuccessMBB())); 2717 2718 DAG.setRoot(Br); 2719 } 2720 2721 /// Codegen the failure basic block for a stack protector check. 2722 /// 2723 /// A failure stack protector machine basic block consists simply of a call to 2724 /// __stack_chk_fail(). 2725 /// 2726 /// For a high level explanation of how this fits into the stack protector 2727 /// generation see the comment on the declaration of class 2728 /// StackProtectorDescriptor. 2729 void 2730 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2731 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2732 TargetLowering::MakeLibCallOptions CallOptions; 2733 CallOptions.setDiscardResult(true); 2734 SDValue Chain = 2735 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2736 None, CallOptions, getCurSDLoc()).second; 2737 // On PS4, the "return address" must still be within the calling function, 2738 // even if it's at the very end, so emit an explicit TRAP here. 2739 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2740 if (TM.getTargetTriple().isPS4CPU()) 2741 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2742 // WebAssembly needs an unreachable instruction after a non-returning call, 2743 // because the function return type can be different from __stack_chk_fail's 2744 // return type (void). 2745 if (TM.getTargetTriple().isWasm()) 2746 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2747 2748 DAG.setRoot(Chain); 2749 } 2750 2751 /// visitBitTestHeader - This function emits necessary code to produce value 2752 /// suitable for "bit tests" 2753 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2754 MachineBasicBlock *SwitchBB) { 2755 SDLoc dl = getCurSDLoc(); 2756 2757 // Subtract the minimum value. 2758 SDValue SwitchOp = getValue(B.SValue); 2759 EVT VT = SwitchOp.getValueType(); 2760 SDValue RangeSub = 2761 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2762 2763 // Determine the type of the test operands. 2764 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2765 bool UsePtrType = false; 2766 if (!TLI.isTypeLegal(VT)) { 2767 UsePtrType = true; 2768 } else { 2769 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2770 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2771 // Switch table case range are encoded into series of masks. 2772 // Just use pointer type, it's guaranteed to fit. 2773 UsePtrType = true; 2774 break; 2775 } 2776 } 2777 SDValue Sub = RangeSub; 2778 if (UsePtrType) { 2779 VT = TLI.getPointerTy(DAG.getDataLayout()); 2780 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2781 } 2782 2783 B.RegVT = VT.getSimpleVT(); 2784 B.Reg = FuncInfo.CreateReg(B.RegVT); 2785 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2786 2787 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2788 2789 if (!B.OmitRangeCheck) 2790 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2791 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2792 SwitchBB->normalizeSuccProbs(); 2793 2794 SDValue Root = CopyTo; 2795 if (!B.OmitRangeCheck) { 2796 // Conditional branch to the default block. 2797 SDValue RangeCmp = DAG.getSetCC(dl, 2798 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2799 RangeSub.getValueType()), 2800 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2801 ISD::SETUGT); 2802 2803 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2804 DAG.getBasicBlock(B.Default)); 2805 } 2806 2807 // Avoid emitting unnecessary branches to the next block. 2808 if (MBB != NextBlock(SwitchBB)) 2809 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2810 2811 DAG.setRoot(Root); 2812 } 2813 2814 /// visitBitTestCase - this function produces one "bit test" 2815 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2816 MachineBasicBlock* NextMBB, 2817 BranchProbability BranchProbToNext, 2818 unsigned Reg, 2819 BitTestCase &B, 2820 MachineBasicBlock *SwitchBB) { 2821 SDLoc dl = getCurSDLoc(); 2822 MVT VT = BB.RegVT; 2823 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2824 SDValue Cmp; 2825 unsigned PopCount = countPopulation(B.Mask); 2826 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2827 if (PopCount == 1) { 2828 // Testing for a single bit; just compare the shift count with what it 2829 // would need to be to shift a 1 bit in that position. 2830 Cmp = DAG.getSetCC( 2831 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2832 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2833 ISD::SETEQ); 2834 } else if (PopCount == BB.Range) { 2835 // There is only one zero bit in the range, test for it directly. 2836 Cmp = DAG.getSetCC( 2837 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2838 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2839 ISD::SETNE); 2840 } else { 2841 // Make desired shift 2842 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2843 DAG.getConstant(1, dl, VT), ShiftOp); 2844 2845 // Emit bit tests and jumps 2846 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2847 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2848 Cmp = DAG.getSetCC( 2849 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2850 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2851 } 2852 2853 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2854 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2855 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2856 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2857 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2858 // one as they are relative probabilities (and thus work more like weights), 2859 // and hence we need to normalize them to let the sum of them become one. 2860 SwitchBB->normalizeSuccProbs(); 2861 2862 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2863 MVT::Other, getControlRoot(), 2864 Cmp, DAG.getBasicBlock(B.TargetBB)); 2865 2866 // Avoid emitting unnecessary branches to the next block. 2867 if (NextMBB != NextBlock(SwitchBB)) 2868 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2869 DAG.getBasicBlock(NextMBB)); 2870 2871 DAG.setRoot(BrAnd); 2872 } 2873 2874 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2875 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2876 2877 // Retrieve successors. Look through artificial IR level blocks like 2878 // catchswitch for successors. 2879 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2880 const BasicBlock *EHPadBB = I.getSuccessor(1); 2881 2882 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2883 // have to do anything here to lower funclet bundles. 2884 assert(!I.hasOperandBundlesOtherThan( 2885 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2886 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2887 LLVMContext::OB_cfguardtarget, 2888 LLVMContext::OB_clang_arc_attachedcall}) && 2889 "Cannot lower invokes with arbitrary operand bundles yet!"); 2890 2891 const Value *Callee(I.getCalledOperand()); 2892 const Function *Fn = dyn_cast<Function>(Callee); 2893 if (isa<InlineAsm>(Callee)) 2894 visitInlineAsm(I, EHPadBB); 2895 else if (Fn && Fn->isIntrinsic()) { 2896 switch (Fn->getIntrinsicID()) { 2897 default: 2898 llvm_unreachable("Cannot invoke this intrinsic"); 2899 case Intrinsic::donothing: 2900 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2901 case Intrinsic::seh_try_begin: 2902 case Intrinsic::seh_scope_begin: 2903 case Intrinsic::seh_try_end: 2904 case Intrinsic::seh_scope_end: 2905 break; 2906 case Intrinsic::experimental_patchpoint_void: 2907 case Intrinsic::experimental_patchpoint_i64: 2908 visitPatchpoint(I, EHPadBB); 2909 break; 2910 case Intrinsic::experimental_gc_statepoint: 2911 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2912 break; 2913 case Intrinsic::wasm_rethrow: { 2914 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2915 // special because it can be invoked, so we manually lower it to a DAG 2916 // node here. 2917 SmallVector<SDValue, 8> Ops; 2918 Ops.push_back(getRoot()); // inchain 2919 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2920 Ops.push_back( 2921 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2922 TLI.getPointerTy(DAG.getDataLayout()))); 2923 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2924 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2925 break; 2926 } 2927 } 2928 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2929 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2930 // Eventually we will support lowering the @llvm.experimental.deoptimize 2931 // intrinsic, and right now there are no plans to support other intrinsics 2932 // with deopt state. 2933 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2934 } else { 2935 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 2936 } 2937 2938 // If the value of the invoke is used outside of its defining block, make it 2939 // available as a virtual register. 2940 // We already took care of the exported value for the statepoint instruction 2941 // during call to the LowerStatepoint. 2942 if (!isa<GCStatepointInst>(I)) { 2943 CopyToExportRegsIfNeeded(&I); 2944 } 2945 2946 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2947 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2948 BranchProbability EHPadBBProb = 2949 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2950 : BranchProbability::getZero(); 2951 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2952 2953 // Update successor info. 2954 addSuccessorWithProb(InvokeMBB, Return); 2955 for (auto &UnwindDest : UnwindDests) { 2956 UnwindDest.first->setIsEHPad(); 2957 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2958 } 2959 InvokeMBB->normalizeSuccProbs(); 2960 2961 // Drop into normal successor. 2962 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2963 DAG.getBasicBlock(Return))); 2964 } 2965 2966 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2967 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2968 2969 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2970 // have to do anything here to lower funclet bundles. 2971 assert(!I.hasOperandBundlesOtherThan( 2972 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2973 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2974 2975 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2976 visitInlineAsm(I); 2977 CopyToExportRegsIfNeeded(&I); 2978 2979 // Retrieve successors. 2980 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2981 2982 // Update successor info. 2983 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2984 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2985 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2986 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2987 Target->setIsInlineAsmBrIndirectTarget(); 2988 } 2989 CallBrMBB->normalizeSuccProbs(); 2990 2991 // Drop into default successor. 2992 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2993 MVT::Other, getControlRoot(), 2994 DAG.getBasicBlock(Return))); 2995 } 2996 2997 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2998 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2999 } 3000 3001 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3002 assert(FuncInfo.MBB->isEHPad() && 3003 "Call to landingpad not in landing pad!"); 3004 3005 // If there aren't registers to copy the values into (e.g., during SjLj 3006 // exceptions), then don't bother to create these DAG nodes. 3007 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3008 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3009 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3010 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3011 return; 3012 3013 // If landingpad's return type is token type, we don't create DAG nodes 3014 // for its exception pointer and selector value. The extraction of exception 3015 // pointer or selector value from token type landingpads is not currently 3016 // supported. 3017 if (LP.getType()->isTokenTy()) 3018 return; 3019 3020 SmallVector<EVT, 2> ValueVTs; 3021 SDLoc dl = getCurSDLoc(); 3022 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3023 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3024 3025 // Get the two live-in registers as SDValues. The physregs have already been 3026 // copied into virtual registers. 3027 SDValue Ops[2]; 3028 if (FuncInfo.ExceptionPointerVirtReg) { 3029 Ops[0] = DAG.getZExtOrTrunc( 3030 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3031 FuncInfo.ExceptionPointerVirtReg, 3032 TLI.getPointerTy(DAG.getDataLayout())), 3033 dl, ValueVTs[0]); 3034 } else { 3035 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3036 } 3037 Ops[1] = DAG.getZExtOrTrunc( 3038 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3039 FuncInfo.ExceptionSelectorVirtReg, 3040 TLI.getPointerTy(DAG.getDataLayout())), 3041 dl, ValueVTs[1]); 3042 3043 // Merge into one. 3044 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3045 DAG.getVTList(ValueVTs), Ops); 3046 setValue(&LP, Res); 3047 } 3048 3049 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3050 MachineBasicBlock *Last) { 3051 // Update JTCases. 3052 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 3053 if (SL->JTCases[i].first.HeaderBB == First) 3054 SL->JTCases[i].first.HeaderBB = Last; 3055 3056 // Update BitTestCases. 3057 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 3058 if (SL->BitTestCases[i].Parent == First) 3059 SL->BitTestCases[i].Parent = Last; 3060 } 3061 3062 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3063 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3064 3065 // Update machine-CFG edges with unique successors. 3066 SmallSet<BasicBlock*, 32> Done; 3067 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3068 BasicBlock *BB = I.getSuccessor(i); 3069 bool Inserted = Done.insert(BB).second; 3070 if (!Inserted) 3071 continue; 3072 3073 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3074 addSuccessorWithProb(IndirectBrMBB, Succ); 3075 } 3076 IndirectBrMBB->normalizeSuccProbs(); 3077 3078 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3079 MVT::Other, getControlRoot(), 3080 getValue(I.getAddress()))); 3081 } 3082 3083 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3084 if (!DAG.getTarget().Options.TrapUnreachable) 3085 return; 3086 3087 // We may be able to ignore unreachable behind a noreturn call. 3088 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3089 const BasicBlock &BB = *I.getParent(); 3090 if (&I != &BB.front()) { 3091 BasicBlock::const_iterator PredI = 3092 std::prev(BasicBlock::const_iterator(&I)); 3093 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3094 if (Call->doesNotReturn()) 3095 return; 3096 } 3097 } 3098 } 3099 3100 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3101 } 3102 3103 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3104 SDNodeFlags Flags; 3105 3106 SDValue Op = getValue(I.getOperand(0)); 3107 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3108 Op, Flags); 3109 setValue(&I, UnNodeValue); 3110 } 3111 3112 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3113 SDNodeFlags Flags; 3114 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3115 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3116 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3117 } 3118 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3119 Flags.setExact(ExactOp->isExact()); 3120 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3121 Flags.copyFMF(*FPOp); 3122 3123 SDValue Op1 = getValue(I.getOperand(0)); 3124 SDValue Op2 = getValue(I.getOperand(1)); 3125 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3126 Op1, Op2, Flags); 3127 setValue(&I, BinNodeValue); 3128 } 3129 3130 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3131 SDValue Op1 = getValue(I.getOperand(0)); 3132 SDValue Op2 = getValue(I.getOperand(1)); 3133 3134 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3135 Op1.getValueType(), DAG.getDataLayout()); 3136 3137 // Coerce the shift amount to the right type if we can. 3138 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3139 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3140 unsigned Op2Size = Op2.getValueSizeInBits(); 3141 SDLoc DL = getCurSDLoc(); 3142 3143 // If the operand is smaller than the shift count type, promote it. 3144 if (ShiftSize > Op2Size) 3145 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3146 3147 // If the operand is larger than the shift count type but the shift 3148 // count type has enough bits to represent any shift value, truncate 3149 // it now. This is a common case and it exposes the truncate to 3150 // optimization early. 3151 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3152 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3153 // Otherwise we'll need to temporarily settle for some other convenient 3154 // type. Type legalization will make adjustments once the shiftee is split. 3155 else 3156 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3157 } 3158 3159 bool nuw = false; 3160 bool nsw = false; 3161 bool exact = false; 3162 3163 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3164 3165 if (const OverflowingBinaryOperator *OFBinOp = 3166 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3167 nuw = OFBinOp->hasNoUnsignedWrap(); 3168 nsw = OFBinOp->hasNoSignedWrap(); 3169 } 3170 if (const PossiblyExactOperator *ExactOp = 3171 dyn_cast<const PossiblyExactOperator>(&I)) 3172 exact = ExactOp->isExact(); 3173 } 3174 SDNodeFlags Flags; 3175 Flags.setExact(exact); 3176 Flags.setNoSignedWrap(nsw); 3177 Flags.setNoUnsignedWrap(nuw); 3178 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3179 Flags); 3180 setValue(&I, Res); 3181 } 3182 3183 void SelectionDAGBuilder::visitSDiv(const User &I) { 3184 SDValue Op1 = getValue(I.getOperand(0)); 3185 SDValue Op2 = getValue(I.getOperand(1)); 3186 3187 SDNodeFlags Flags; 3188 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3189 cast<PossiblyExactOperator>(&I)->isExact()); 3190 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3191 Op2, Flags)); 3192 } 3193 3194 void SelectionDAGBuilder::visitICmp(const User &I) { 3195 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3196 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3197 predicate = IC->getPredicate(); 3198 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3199 predicate = ICmpInst::Predicate(IC->getPredicate()); 3200 SDValue Op1 = getValue(I.getOperand(0)); 3201 SDValue Op2 = getValue(I.getOperand(1)); 3202 ISD::CondCode Opcode = getICmpCondCode(predicate); 3203 3204 auto &TLI = DAG.getTargetLoweringInfo(); 3205 EVT MemVT = 3206 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3207 3208 // If a pointer's DAG type is larger than its memory type then the DAG values 3209 // are zero-extended. This breaks signed comparisons so truncate back to the 3210 // underlying type before doing the compare. 3211 if (Op1.getValueType() != MemVT) { 3212 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3213 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3214 } 3215 3216 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3217 I.getType()); 3218 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3219 } 3220 3221 void SelectionDAGBuilder::visitFCmp(const User &I) { 3222 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3223 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3224 predicate = FC->getPredicate(); 3225 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3226 predicate = FCmpInst::Predicate(FC->getPredicate()); 3227 SDValue Op1 = getValue(I.getOperand(0)); 3228 SDValue Op2 = getValue(I.getOperand(1)); 3229 3230 ISD::CondCode Condition = getFCmpCondCode(predicate); 3231 auto *FPMO = cast<FPMathOperator>(&I); 3232 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3233 Condition = getFCmpCodeWithoutNaN(Condition); 3234 3235 SDNodeFlags Flags; 3236 Flags.copyFMF(*FPMO); 3237 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3238 3239 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3240 I.getType()); 3241 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3242 } 3243 3244 // Check if the condition of the select has one use or two users that are both 3245 // selects with the same condition. 3246 static bool hasOnlySelectUsers(const Value *Cond) { 3247 return llvm::all_of(Cond->users(), [](const Value *V) { 3248 return isa<SelectInst>(V); 3249 }); 3250 } 3251 3252 void SelectionDAGBuilder::visitSelect(const User &I) { 3253 SmallVector<EVT, 4> ValueVTs; 3254 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3255 ValueVTs); 3256 unsigned NumValues = ValueVTs.size(); 3257 if (NumValues == 0) return; 3258 3259 SmallVector<SDValue, 4> Values(NumValues); 3260 SDValue Cond = getValue(I.getOperand(0)); 3261 SDValue LHSVal = getValue(I.getOperand(1)); 3262 SDValue RHSVal = getValue(I.getOperand(2)); 3263 SmallVector<SDValue, 1> BaseOps(1, Cond); 3264 ISD::NodeType OpCode = 3265 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3266 3267 bool IsUnaryAbs = false; 3268 bool Negate = false; 3269 3270 SDNodeFlags Flags; 3271 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3272 Flags.copyFMF(*FPOp); 3273 3274 // Min/max matching is only viable if all output VTs are the same. 3275 if (is_splat(ValueVTs)) { 3276 EVT VT = ValueVTs[0]; 3277 LLVMContext &Ctx = *DAG.getContext(); 3278 auto &TLI = DAG.getTargetLoweringInfo(); 3279 3280 // We care about the legality of the operation after it has been type 3281 // legalized. 3282 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3283 VT = TLI.getTypeToTransformTo(Ctx, VT); 3284 3285 // If the vselect is legal, assume we want to leave this as a vector setcc + 3286 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3287 // min/max is legal on the scalar type. 3288 bool UseScalarMinMax = VT.isVector() && 3289 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3290 3291 Value *LHS, *RHS; 3292 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3293 ISD::NodeType Opc = ISD::DELETED_NODE; 3294 switch (SPR.Flavor) { 3295 case SPF_UMAX: Opc = ISD::UMAX; break; 3296 case SPF_UMIN: Opc = ISD::UMIN; break; 3297 case SPF_SMAX: Opc = ISD::SMAX; break; 3298 case SPF_SMIN: Opc = ISD::SMIN; break; 3299 case SPF_FMINNUM: 3300 switch (SPR.NaNBehavior) { 3301 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3302 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3303 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3304 case SPNB_RETURNS_ANY: { 3305 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3306 Opc = ISD::FMINNUM; 3307 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3308 Opc = ISD::FMINIMUM; 3309 else if (UseScalarMinMax) 3310 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3311 ISD::FMINNUM : ISD::FMINIMUM; 3312 break; 3313 } 3314 } 3315 break; 3316 case SPF_FMAXNUM: 3317 switch (SPR.NaNBehavior) { 3318 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3319 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3320 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3321 case SPNB_RETURNS_ANY: 3322 3323 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3324 Opc = ISD::FMAXNUM; 3325 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3326 Opc = ISD::FMAXIMUM; 3327 else if (UseScalarMinMax) 3328 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3329 ISD::FMAXNUM : ISD::FMAXIMUM; 3330 break; 3331 } 3332 break; 3333 case SPF_NABS: 3334 Negate = true; 3335 LLVM_FALLTHROUGH; 3336 case SPF_ABS: 3337 IsUnaryAbs = true; 3338 Opc = ISD::ABS; 3339 break; 3340 default: break; 3341 } 3342 3343 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3344 (TLI.isOperationLegalOrCustom(Opc, VT) || 3345 (UseScalarMinMax && 3346 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3347 // If the underlying comparison instruction is used by any other 3348 // instruction, the consumed instructions won't be destroyed, so it is 3349 // not profitable to convert to a min/max. 3350 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3351 OpCode = Opc; 3352 LHSVal = getValue(LHS); 3353 RHSVal = getValue(RHS); 3354 BaseOps.clear(); 3355 } 3356 3357 if (IsUnaryAbs) { 3358 OpCode = Opc; 3359 LHSVal = getValue(LHS); 3360 BaseOps.clear(); 3361 } 3362 } 3363 3364 if (IsUnaryAbs) { 3365 for (unsigned i = 0; i != NumValues; ++i) { 3366 SDLoc dl = getCurSDLoc(); 3367 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3368 Values[i] = 3369 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3370 if (Negate) 3371 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3372 Values[i]); 3373 } 3374 } else { 3375 for (unsigned i = 0; i != NumValues; ++i) { 3376 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3377 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3378 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3379 Values[i] = DAG.getNode( 3380 OpCode, getCurSDLoc(), 3381 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3382 } 3383 } 3384 3385 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3386 DAG.getVTList(ValueVTs), Values)); 3387 } 3388 3389 void SelectionDAGBuilder::visitTrunc(const User &I) { 3390 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3391 SDValue N = getValue(I.getOperand(0)); 3392 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3393 I.getType()); 3394 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3395 } 3396 3397 void SelectionDAGBuilder::visitZExt(const User &I) { 3398 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3399 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3400 SDValue N = getValue(I.getOperand(0)); 3401 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3402 I.getType()); 3403 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3404 } 3405 3406 void SelectionDAGBuilder::visitSExt(const User &I) { 3407 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3408 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3409 SDValue N = getValue(I.getOperand(0)); 3410 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3411 I.getType()); 3412 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3413 } 3414 3415 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3416 // FPTrunc is never a no-op cast, no need to check 3417 SDValue N = getValue(I.getOperand(0)); 3418 SDLoc dl = getCurSDLoc(); 3419 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3420 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3421 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3422 DAG.getTargetConstant( 3423 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3424 } 3425 3426 void SelectionDAGBuilder::visitFPExt(const User &I) { 3427 // FPExt is never a no-op cast, no need to check 3428 SDValue N = getValue(I.getOperand(0)); 3429 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3430 I.getType()); 3431 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3432 } 3433 3434 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3435 // FPToUI is never a no-op cast, no need to check 3436 SDValue N = getValue(I.getOperand(0)); 3437 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3438 I.getType()); 3439 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3440 } 3441 3442 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3443 // FPToSI is never a no-op cast, no need to check 3444 SDValue N = getValue(I.getOperand(0)); 3445 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3446 I.getType()); 3447 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3448 } 3449 3450 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3451 // UIToFP is never a no-op cast, no need to check 3452 SDValue N = getValue(I.getOperand(0)); 3453 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3454 I.getType()); 3455 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3456 } 3457 3458 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3459 // SIToFP is never a no-op cast, no need to check 3460 SDValue N = getValue(I.getOperand(0)); 3461 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3462 I.getType()); 3463 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3464 } 3465 3466 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3467 // What to do depends on the size of the integer and the size of the pointer. 3468 // We can either truncate, zero extend, or no-op, accordingly. 3469 SDValue N = getValue(I.getOperand(0)); 3470 auto &TLI = DAG.getTargetLoweringInfo(); 3471 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3472 I.getType()); 3473 EVT PtrMemVT = 3474 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3475 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3476 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3477 setValue(&I, N); 3478 } 3479 3480 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3481 // What to do depends on the size of the integer and the size of the pointer. 3482 // We can either truncate, zero extend, or no-op, accordingly. 3483 SDValue N = getValue(I.getOperand(0)); 3484 auto &TLI = DAG.getTargetLoweringInfo(); 3485 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3486 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3487 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3488 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3489 setValue(&I, N); 3490 } 3491 3492 void SelectionDAGBuilder::visitBitCast(const User &I) { 3493 SDValue N = getValue(I.getOperand(0)); 3494 SDLoc dl = getCurSDLoc(); 3495 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3496 I.getType()); 3497 3498 // BitCast assures us that source and destination are the same size so this is 3499 // either a BITCAST or a no-op. 3500 if (DestVT != N.getValueType()) 3501 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3502 DestVT, N)); // convert types. 3503 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3504 // might fold any kind of constant expression to an integer constant and that 3505 // is not what we are looking for. Only recognize a bitcast of a genuine 3506 // constant integer as an opaque constant. 3507 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3508 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3509 /*isOpaque*/true)); 3510 else 3511 setValue(&I, N); // noop cast. 3512 } 3513 3514 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3515 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3516 const Value *SV = I.getOperand(0); 3517 SDValue N = getValue(SV); 3518 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3519 3520 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3521 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3522 3523 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3524 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3525 3526 setValue(&I, N); 3527 } 3528 3529 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3530 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3531 SDValue InVec = getValue(I.getOperand(0)); 3532 SDValue InVal = getValue(I.getOperand(1)); 3533 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3534 TLI.getVectorIdxTy(DAG.getDataLayout())); 3535 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3536 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3537 InVec, InVal, InIdx)); 3538 } 3539 3540 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3541 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3542 SDValue InVec = getValue(I.getOperand(0)); 3543 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3544 TLI.getVectorIdxTy(DAG.getDataLayout())); 3545 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3546 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3547 InVec, InIdx)); 3548 } 3549 3550 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3551 SDValue Src1 = getValue(I.getOperand(0)); 3552 SDValue Src2 = getValue(I.getOperand(1)); 3553 ArrayRef<int> Mask; 3554 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3555 Mask = SVI->getShuffleMask(); 3556 else 3557 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3558 SDLoc DL = getCurSDLoc(); 3559 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3560 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3561 EVT SrcVT = Src1.getValueType(); 3562 3563 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3564 VT.isScalableVector()) { 3565 // Canonical splat form of first element of first input vector. 3566 SDValue FirstElt = 3567 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3568 DAG.getVectorIdxConstant(0, DL)); 3569 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3570 return; 3571 } 3572 3573 // For now, we only handle splats for scalable vectors. 3574 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3575 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3576 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3577 3578 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3579 unsigned MaskNumElts = Mask.size(); 3580 3581 if (SrcNumElts == MaskNumElts) { 3582 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3583 return; 3584 } 3585 3586 // Normalize the shuffle vector since mask and vector length don't match. 3587 if (SrcNumElts < MaskNumElts) { 3588 // Mask is longer than the source vectors. We can use concatenate vector to 3589 // make the mask and vectors lengths match. 3590 3591 if (MaskNumElts % SrcNumElts == 0) { 3592 // Mask length is a multiple of the source vector length. 3593 // Check if the shuffle is some kind of concatenation of the input 3594 // vectors. 3595 unsigned NumConcat = MaskNumElts / SrcNumElts; 3596 bool IsConcat = true; 3597 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3598 for (unsigned i = 0; i != MaskNumElts; ++i) { 3599 int Idx = Mask[i]; 3600 if (Idx < 0) 3601 continue; 3602 // Ensure the indices in each SrcVT sized piece are sequential and that 3603 // the same source is used for the whole piece. 3604 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3605 (ConcatSrcs[i / SrcNumElts] >= 0 && 3606 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3607 IsConcat = false; 3608 break; 3609 } 3610 // Remember which source this index came from. 3611 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3612 } 3613 3614 // The shuffle is concatenating multiple vectors together. Just emit 3615 // a CONCAT_VECTORS operation. 3616 if (IsConcat) { 3617 SmallVector<SDValue, 8> ConcatOps; 3618 for (auto Src : ConcatSrcs) { 3619 if (Src < 0) 3620 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3621 else if (Src == 0) 3622 ConcatOps.push_back(Src1); 3623 else 3624 ConcatOps.push_back(Src2); 3625 } 3626 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3627 return; 3628 } 3629 } 3630 3631 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3632 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3633 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3634 PaddedMaskNumElts); 3635 3636 // Pad both vectors with undefs to make them the same length as the mask. 3637 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3638 3639 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3640 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3641 MOps1[0] = Src1; 3642 MOps2[0] = Src2; 3643 3644 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3645 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3646 3647 // Readjust mask for new input vector length. 3648 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3649 for (unsigned i = 0; i != MaskNumElts; ++i) { 3650 int Idx = Mask[i]; 3651 if (Idx >= (int)SrcNumElts) 3652 Idx -= SrcNumElts - PaddedMaskNumElts; 3653 MappedOps[i] = Idx; 3654 } 3655 3656 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3657 3658 // If the concatenated vector was padded, extract a subvector with the 3659 // correct number of elements. 3660 if (MaskNumElts != PaddedMaskNumElts) 3661 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3662 DAG.getVectorIdxConstant(0, DL)); 3663 3664 setValue(&I, Result); 3665 return; 3666 } 3667 3668 if (SrcNumElts > MaskNumElts) { 3669 // Analyze the access pattern of the vector to see if we can extract 3670 // two subvectors and do the shuffle. 3671 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3672 bool CanExtract = true; 3673 for (int Idx : Mask) { 3674 unsigned Input = 0; 3675 if (Idx < 0) 3676 continue; 3677 3678 if (Idx >= (int)SrcNumElts) { 3679 Input = 1; 3680 Idx -= SrcNumElts; 3681 } 3682 3683 // If all the indices come from the same MaskNumElts sized portion of 3684 // the sources we can use extract. Also make sure the extract wouldn't 3685 // extract past the end of the source. 3686 int NewStartIdx = alignDown(Idx, MaskNumElts); 3687 if (NewStartIdx + MaskNumElts > SrcNumElts || 3688 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3689 CanExtract = false; 3690 // Make sure we always update StartIdx as we use it to track if all 3691 // elements are undef. 3692 StartIdx[Input] = NewStartIdx; 3693 } 3694 3695 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3696 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3697 return; 3698 } 3699 if (CanExtract) { 3700 // Extract appropriate subvector and generate a vector shuffle 3701 for (unsigned Input = 0; Input < 2; ++Input) { 3702 SDValue &Src = Input == 0 ? Src1 : Src2; 3703 if (StartIdx[Input] < 0) 3704 Src = DAG.getUNDEF(VT); 3705 else { 3706 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3707 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3708 } 3709 } 3710 3711 // Calculate new mask. 3712 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3713 for (int &Idx : MappedOps) { 3714 if (Idx >= (int)SrcNumElts) 3715 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3716 else if (Idx >= 0) 3717 Idx -= StartIdx[0]; 3718 } 3719 3720 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3721 return; 3722 } 3723 } 3724 3725 // We can't use either concat vectors or extract subvectors so fall back to 3726 // replacing the shuffle with extract and build vector. 3727 // to insert and build vector. 3728 EVT EltVT = VT.getVectorElementType(); 3729 SmallVector<SDValue,8> Ops; 3730 for (int Idx : Mask) { 3731 SDValue Res; 3732 3733 if (Idx < 0) { 3734 Res = DAG.getUNDEF(EltVT); 3735 } else { 3736 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3737 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3738 3739 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3740 DAG.getVectorIdxConstant(Idx, DL)); 3741 } 3742 3743 Ops.push_back(Res); 3744 } 3745 3746 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3747 } 3748 3749 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3750 ArrayRef<unsigned> Indices; 3751 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3752 Indices = IV->getIndices(); 3753 else 3754 Indices = cast<ConstantExpr>(&I)->getIndices(); 3755 3756 const Value *Op0 = I.getOperand(0); 3757 const Value *Op1 = I.getOperand(1); 3758 Type *AggTy = I.getType(); 3759 Type *ValTy = Op1->getType(); 3760 bool IntoUndef = isa<UndefValue>(Op0); 3761 bool FromUndef = isa<UndefValue>(Op1); 3762 3763 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3764 3765 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3766 SmallVector<EVT, 4> AggValueVTs; 3767 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3768 SmallVector<EVT, 4> ValValueVTs; 3769 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3770 3771 unsigned NumAggValues = AggValueVTs.size(); 3772 unsigned NumValValues = ValValueVTs.size(); 3773 SmallVector<SDValue, 4> Values(NumAggValues); 3774 3775 // Ignore an insertvalue that produces an empty object 3776 if (!NumAggValues) { 3777 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3778 return; 3779 } 3780 3781 SDValue Agg = getValue(Op0); 3782 unsigned i = 0; 3783 // Copy the beginning value(s) from the original aggregate. 3784 for (; i != LinearIndex; ++i) 3785 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3786 SDValue(Agg.getNode(), Agg.getResNo() + i); 3787 // Copy values from the inserted value(s). 3788 if (NumValValues) { 3789 SDValue Val = getValue(Op1); 3790 for (; i != LinearIndex + NumValValues; ++i) 3791 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3792 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3793 } 3794 // Copy remaining value(s) from the original aggregate. 3795 for (; i != NumAggValues; ++i) 3796 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3797 SDValue(Agg.getNode(), Agg.getResNo() + i); 3798 3799 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3800 DAG.getVTList(AggValueVTs), Values)); 3801 } 3802 3803 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3804 ArrayRef<unsigned> Indices; 3805 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3806 Indices = EV->getIndices(); 3807 else 3808 Indices = cast<ConstantExpr>(&I)->getIndices(); 3809 3810 const Value *Op0 = I.getOperand(0); 3811 Type *AggTy = Op0->getType(); 3812 Type *ValTy = I.getType(); 3813 bool OutOfUndef = isa<UndefValue>(Op0); 3814 3815 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3816 3817 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3818 SmallVector<EVT, 4> ValValueVTs; 3819 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3820 3821 unsigned NumValValues = ValValueVTs.size(); 3822 3823 // Ignore a extractvalue that produces an empty object 3824 if (!NumValValues) { 3825 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3826 return; 3827 } 3828 3829 SmallVector<SDValue, 4> Values(NumValValues); 3830 3831 SDValue Agg = getValue(Op0); 3832 // Copy out the selected value(s). 3833 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3834 Values[i - LinearIndex] = 3835 OutOfUndef ? 3836 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3837 SDValue(Agg.getNode(), Agg.getResNo() + i); 3838 3839 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3840 DAG.getVTList(ValValueVTs), Values)); 3841 } 3842 3843 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3844 Value *Op0 = I.getOperand(0); 3845 // Note that the pointer operand may be a vector of pointers. Take the scalar 3846 // element which holds a pointer. 3847 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3848 SDValue N = getValue(Op0); 3849 SDLoc dl = getCurSDLoc(); 3850 auto &TLI = DAG.getTargetLoweringInfo(); 3851 3852 // Normalize Vector GEP - all scalar operands should be converted to the 3853 // splat vector. 3854 bool IsVectorGEP = I.getType()->isVectorTy(); 3855 ElementCount VectorElementCount = 3856 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3857 : ElementCount::getFixed(0); 3858 3859 if (IsVectorGEP && !N.getValueType().isVector()) { 3860 LLVMContext &Context = *DAG.getContext(); 3861 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3862 if (VectorElementCount.isScalable()) 3863 N = DAG.getSplatVector(VT, dl, N); 3864 else 3865 N = DAG.getSplatBuildVector(VT, dl, N); 3866 } 3867 3868 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3869 GTI != E; ++GTI) { 3870 const Value *Idx = GTI.getOperand(); 3871 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3872 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3873 if (Field) { 3874 // N = N + Offset 3875 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3876 3877 // In an inbounds GEP with an offset that is nonnegative even when 3878 // interpreted as signed, assume there is no unsigned overflow. 3879 SDNodeFlags Flags; 3880 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3881 Flags.setNoUnsignedWrap(true); 3882 3883 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3884 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3885 } 3886 } else { 3887 // IdxSize is the width of the arithmetic according to IR semantics. 3888 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3889 // (and fix up the result later). 3890 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3891 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3892 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3893 // We intentionally mask away the high bits here; ElementSize may not 3894 // fit in IdxTy. 3895 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3896 bool ElementScalable = ElementSize.isScalable(); 3897 3898 // If this is a scalar constant or a splat vector of constants, 3899 // handle it quickly. 3900 const auto *C = dyn_cast<Constant>(Idx); 3901 if (C && isa<VectorType>(C->getType())) 3902 C = C->getSplatValue(); 3903 3904 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3905 if (CI && CI->isZero()) 3906 continue; 3907 if (CI && !ElementScalable) { 3908 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3909 LLVMContext &Context = *DAG.getContext(); 3910 SDValue OffsVal; 3911 if (IsVectorGEP) 3912 OffsVal = DAG.getConstant( 3913 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3914 else 3915 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3916 3917 // In an inbounds GEP with an offset that is nonnegative even when 3918 // interpreted as signed, assume there is no unsigned overflow. 3919 SDNodeFlags Flags; 3920 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3921 Flags.setNoUnsignedWrap(true); 3922 3923 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3924 3925 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3926 continue; 3927 } 3928 3929 // N = N + Idx * ElementMul; 3930 SDValue IdxN = getValue(Idx); 3931 3932 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3933 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3934 VectorElementCount); 3935 if (VectorElementCount.isScalable()) 3936 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3937 else 3938 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3939 } 3940 3941 // If the index is smaller or larger than intptr_t, truncate or extend 3942 // it. 3943 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3944 3945 if (ElementScalable) { 3946 EVT VScaleTy = N.getValueType().getScalarType(); 3947 SDValue VScale = DAG.getNode( 3948 ISD::VSCALE, dl, VScaleTy, 3949 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3950 if (IsVectorGEP) 3951 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3952 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3953 } else { 3954 // If this is a multiply by a power of two, turn it into a shl 3955 // immediately. This is a very common case. 3956 if (ElementMul != 1) { 3957 if (ElementMul.isPowerOf2()) { 3958 unsigned Amt = ElementMul.logBase2(); 3959 IdxN = DAG.getNode(ISD::SHL, dl, 3960 N.getValueType(), IdxN, 3961 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3962 } else { 3963 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3964 IdxN.getValueType()); 3965 IdxN = DAG.getNode(ISD::MUL, dl, 3966 N.getValueType(), IdxN, Scale); 3967 } 3968 } 3969 } 3970 3971 N = DAG.getNode(ISD::ADD, dl, 3972 N.getValueType(), N, IdxN); 3973 } 3974 } 3975 3976 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3977 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3978 if (IsVectorGEP) { 3979 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3980 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3981 } 3982 3983 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3984 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3985 3986 setValue(&I, N); 3987 } 3988 3989 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3990 // If this is a fixed sized alloca in the entry block of the function, 3991 // allocate it statically on the stack. 3992 if (FuncInfo.StaticAllocaMap.count(&I)) 3993 return; // getValue will auto-populate this. 3994 3995 SDLoc dl = getCurSDLoc(); 3996 Type *Ty = I.getAllocatedType(); 3997 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3998 auto &DL = DAG.getDataLayout(); 3999 uint64_t TySize = DL.getTypeAllocSize(Ty); 4000 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4001 4002 SDValue AllocSize = getValue(I.getArraySize()); 4003 4004 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 4005 if (AllocSize.getValueType() != IntPtr) 4006 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4007 4008 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 4009 AllocSize, 4010 DAG.getConstant(TySize, dl, IntPtr)); 4011 4012 // Handle alignment. If the requested alignment is less than or equal to 4013 // the stack alignment, ignore it. If the size is greater than or equal to 4014 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4015 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4016 if (*Alignment <= StackAlign) 4017 Alignment = None; 4018 4019 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4020 // Round the size of the allocation up to the stack alignment size 4021 // by add SA-1 to the size. This doesn't overflow because we're computing 4022 // an address inside an alloca. 4023 SDNodeFlags Flags; 4024 Flags.setNoUnsignedWrap(true); 4025 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4026 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4027 4028 // Mask out the low bits for alignment purposes. 4029 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4030 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4031 4032 SDValue Ops[] = { 4033 getRoot(), AllocSize, 4034 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4035 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4036 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4037 setValue(&I, DSA); 4038 DAG.setRoot(DSA.getValue(1)); 4039 4040 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4041 } 4042 4043 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4044 if (I.isAtomic()) 4045 return visitAtomicLoad(I); 4046 4047 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4048 const Value *SV = I.getOperand(0); 4049 if (TLI.supportSwiftError()) { 4050 // Swifterror values can come from either a function parameter with 4051 // swifterror attribute or an alloca with swifterror attribute. 4052 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4053 if (Arg->hasSwiftErrorAttr()) 4054 return visitLoadFromSwiftError(I); 4055 } 4056 4057 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4058 if (Alloca->isSwiftError()) 4059 return visitLoadFromSwiftError(I); 4060 } 4061 } 4062 4063 SDValue Ptr = getValue(SV); 4064 4065 Type *Ty = I.getType(); 4066 Align Alignment = I.getAlign(); 4067 4068 AAMDNodes AAInfo; 4069 I.getAAMetadata(AAInfo); 4070 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4071 4072 SmallVector<EVT, 4> ValueVTs, MemVTs; 4073 SmallVector<uint64_t, 4> Offsets; 4074 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4075 unsigned NumValues = ValueVTs.size(); 4076 if (NumValues == 0) 4077 return; 4078 4079 bool isVolatile = I.isVolatile(); 4080 4081 SDValue Root; 4082 bool ConstantMemory = false; 4083 if (isVolatile) 4084 // Serialize volatile loads with other side effects. 4085 Root = getRoot(); 4086 else if (NumValues > MaxParallelChains) 4087 Root = getMemoryRoot(); 4088 else if (AA && 4089 AA->pointsToConstantMemory(MemoryLocation( 4090 SV, 4091 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4092 AAInfo))) { 4093 // Do not serialize (non-volatile) loads of constant memory with anything. 4094 Root = DAG.getEntryNode(); 4095 ConstantMemory = true; 4096 } else { 4097 // Do not serialize non-volatile loads against each other. 4098 Root = DAG.getRoot(); 4099 } 4100 4101 SDLoc dl = getCurSDLoc(); 4102 4103 if (isVolatile) 4104 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4105 4106 // An aggregate load cannot wrap around the address space, so offsets to its 4107 // parts don't wrap either. 4108 SDNodeFlags Flags; 4109 Flags.setNoUnsignedWrap(true); 4110 4111 SmallVector<SDValue, 4> Values(NumValues); 4112 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4113 EVT PtrVT = Ptr.getValueType(); 4114 4115 MachineMemOperand::Flags MMOFlags 4116 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4117 4118 unsigned ChainI = 0; 4119 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4120 // Serializing loads here may result in excessive register pressure, and 4121 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4122 // could recover a bit by hoisting nodes upward in the chain by recognizing 4123 // they are side-effect free or do not alias. The optimizer should really 4124 // avoid this case by converting large object/array copies to llvm.memcpy 4125 // (MaxParallelChains should always remain as failsafe). 4126 if (ChainI == MaxParallelChains) { 4127 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4128 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4129 makeArrayRef(Chains.data(), ChainI)); 4130 Root = Chain; 4131 ChainI = 0; 4132 } 4133 SDValue A = DAG.getNode(ISD::ADD, dl, 4134 PtrVT, Ptr, 4135 DAG.getConstant(Offsets[i], dl, PtrVT), 4136 Flags); 4137 4138 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4139 MachinePointerInfo(SV, Offsets[i]), Alignment, 4140 MMOFlags, AAInfo, Ranges); 4141 Chains[ChainI] = L.getValue(1); 4142 4143 if (MemVTs[i] != ValueVTs[i]) 4144 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4145 4146 Values[i] = L; 4147 } 4148 4149 if (!ConstantMemory) { 4150 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4151 makeArrayRef(Chains.data(), ChainI)); 4152 if (isVolatile) 4153 DAG.setRoot(Chain); 4154 else 4155 PendingLoads.push_back(Chain); 4156 } 4157 4158 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4159 DAG.getVTList(ValueVTs), Values)); 4160 } 4161 4162 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4163 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4164 "call visitStoreToSwiftError when backend supports swifterror"); 4165 4166 SmallVector<EVT, 4> ValueVTs; 4167 SmallVector<uint64_t, 4> Offsets; 4168 const Value *SrcV = I.getOperand(0); 4169 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4170 SrcV->getType(), ValueVTs, &Offsets); 4171 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4172 "expect a single EVT for swifterror"); 4173 4174 SDValue Src = getValue(SrcV); 4175 // Create a virtual register, then update the virtual register. 4176 Register VReg = 4177 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4178 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4179 // Chain can be getRoot or getControlRoot. 4180 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4181 SDValue(Src.getNode(), Src.getResNo())); 4182 DAG.setRoot(CopyNode); 4183 } 4184 4185 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4186 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4187 "call visitLoadFromSwiftError when backend supports swifterror"); 4188 4189 assert(!I.isVolatile() && 4190 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4191 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4192 "Support volatile, non temporal, invariant for load_from_swift_error"); 4193 4194 const Value *SV = I.getOperand(0); 4195 Type *Ty = I.getType(); 4196 AAMDNodes AAInfo; 4197 I.getAAMetadata(AAInfo); 4198 assert( 4199 (!AA || 4200 !AA->pointsToConstantMemory(MemoryLocation( 4201 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4202 AAInfo))) && 4203 "load_from_swift_error should not be constant memory"); 4204 4205 SmallVector<EVT, 4> ValueVTs; 4206 SmallVector<uint64_t, 4> Offsets; 4207 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4208 ValueVTs, &Offsets); 4209 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4210 "expect a single EVT for swifterror"); 4211 4212 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4213 SDValue L = DAG.getCopyFromReg( 4214 getRoot(), getCurSDLoc(), 4215 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4216 4217 setValue(&I, L); 4218 } 4219 4220 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4221 if (I.isAtomic()) 4222 return visitAtomicStore(I); 4223 4224 const Value *SrcV = I.getOperand(0); 4225 const Value *PtrV = I.getOperand(1); 4226 4227 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4228 if (TLI.supportSwiftError()) { 4229 // Swifterror values can come from either a function parameter with 4230 // swifterror attribute or an alloca with swifterror attribute. 4231 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4232 if (Arg->hasSwiftErrorAttr()) 4233 return visitStoreToSwiftError(I); 4234 } 4235 4236 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4237 if (Alloca->isSwiftError()) 4238 return visitStoreToSwiftError(I); 4239 } 4240 } 4241 4242 SmallVector<EVT, 4> ValueVTs, MemVTs; 4243 SmallVector<uint64_t, 4> Offsets; 4244 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4245 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4246 unsigned NumValues = ValueVTs.size(); 4247 if (NumValues == 0) 4248 return; 4249 4250 // Get the lowered operands. Note that we do this after 4251 // checking if NumResults is zero, because with zero results 4252 // the operands won't have values in the map. 4253 SDValue Src = getValue(SrcV); 4254 SDValue Ptr = getValue(PtrV); 4255 4256 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4257 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4258 SDLoc dl = getCurSDLoc(); 4259 Align Alignment = I.getAlign(); 4260 AAMDNodes AAInfo; 4261 I.getAAMetadata(AAInfo); 4262 4263 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4264 4265 // An aggregate load cannot wrap around the address space, so offsets to its 4266 // parts don't wrap either. 4267 SDNodeFlags Flags; 4268 Flags.setNoUnsignedWrap(true); 4269 4270 unsigned ChainI = 0; 4271 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4272 // See visitLoad comments. 4273 if (ChainI == MaxParallelChains) { 4274 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4275 makeArrayRef(Chains.data(), ChainI)); 4276 Root = Chain; 4277 ChainI = 0; 4278 } 4279 SDValue Add = 4280 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4281 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4282 if (MemVTs[i] != ValueVTs[i]) 4283 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4284 SDValue St = 4285 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4286 Alignment, MMOFlags, AAInfo); 4287 Chains[ChainI] = St; 4288 } 4289 4290 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4291 makeArrayRef(Chains.data(), ChainI)); 4292 DAG.setRoot(StoreNode); 4293 } 4294 4295 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4296 bool IsCompressing) { 4297 SDLoc sdl = getCurSDLoc(); 4298 4299 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4300 MaybeAlign &Alignment) { 4301 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4302 Src0 = I.getArgOperand(0); 4303 Ptr = I.getArgOperand(1); 4304 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4305 Mask = I.getArgOperand(3); 4306 }; 4307 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4308 MaybeAlign &Alignment) { 4309 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4310 Src0 = I.getArgOperand(0); 4311 Ptr = I.getArgOperand(1); 4312 Mask = I.getArgOperand(2); 4313 Alignment = None; 4314 }; 4315 4316 Value *PtrOperand, *MaskOperand, *Src0Operand; 4317 MaybeAlign Alignment; 4318 if (IsCompressing) 4319 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4320 else 4321 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4322 4323 SDValue Ptr = getValue(PtrOperand); 4324 SDValue Src0 = getValue(Src0Operand); 4325 SDValue Mask = getValue(MaskOperand); 4326 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4327 4328 EVT VT = Src0.getValueType(); 4329 if (!Alignment) 4330 Alignment = DAG.getEVTAlign(VT); 4331 4332 AAMDNodes AAInfo; 4333 I.getAAMetadata(AAInfo); 4334 4335 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4336 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4337 // TODO: Make MachineMemOperands aware of scalable 4338 // vectors. 4339 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4340 SDValue StoreNode = 4341 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4342 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4343 DAG.setRoot(StoreNode); 4344 setValue(&I, StoreNode); 4345 } 4346 4347 // Get a uniform base for the Gather/Scatter intrinsic. 4348 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4349 // We try to represent it as a base pointer + vector of indices. 4350 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4351 // The first operand of the GEP may be a single pointer or a vector of pointers 4352 // Example: 4353 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4354 // or 4355 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4356 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4357 // 4358 // When the first GEP operand is a single pointer - it is the uniform base we 4359 // are looking for. If first operand of the GEP is a splat vector - we 4360 // extract the splat value and use it as a uniform base. 4361 // In all other cases the function returns 'false'. 4362 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4363 ISD::MemIndexType &IndexType, SDValue &Scale, 4364 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4365 SelectionDAG& DAG = SDB->DAG; 4366 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4367 const DataLayout &DL = DAG.getDataLayout(); 4368 4369 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4370 4371 // Handle splat constant pointer. 4372 if (auto *C = dyn_cast<Constant>(Ptr)) { 4373 C = C->getSplatValue(); 4374 if (!C) 4375 return false; 4376 4377 Base = SDB->getValue(C); 4378 4379 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4380 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4381 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4382 IndexType = ISD::SIGNED_SCALED; 4383 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4384 return true; 4385 } 4386 4387 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4388 if (!GEP || GEP->getParent() != CurBB) 4389 return false; 4390 4391 if (GEP->getNumOperands() != 2) 4392 return false; 4393 4394 const Value *BasePtr = GEP->getPointerOperand(); 4395 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4396 4397 // Make sure the base is scalar and the index is a vector. 4398 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4399 return false; 4400 4401 Base = SDB->getValue(BasePtr); 4402 Index = SDB->getValue(IndexVal); 4403 IndexType = ISD::SIGNED_SCALED; 4404 Scale = DAG.getTargetConstant( 4405 DL.getTypeAllocSize(GEP->getResultElementType()), 4406 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4407 return true; 4408 } 4409 4410 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4411 SDLoc sdl = getCurSDLoc(); 4412 4413 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4414 const Value *Ptr = I.getArgOperand(1); 4415 SDValue Src0 = getValue(I.getArgOperand(0)); 4416 SDValue Mask = getValue(I.getArgOperand(3)); 4417 EVT VT = Src0.getValueType(); 4418 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4419 ->getMaybeAlignValue() 4420 .getValueOr(DAG.getEVTAlign(VT.getScalarType())); 4421 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4422 4423 AAMDNodes AAInfo; 4424 I.getAAMetadata(AAInfo); 4425 4426 SDValue Base; 4427 SDValue Index; 4428 ISD::MemIndexType IndexType; 4429 SDValue Scale; 4430 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4431 I.getParent()); 4432 4433 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4434 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4435 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4436 // TODO: Make MachineMemOperands aware of scalable 4437 // vectors. 4438 MemoryLocation::UnknownSize, Alignment, AAInfo); 4439 if (!UniformBase) { 4440 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4441 Index = getValue(Ptr); 4442 IndexType = ISD::SIGNED_UNSCALED; 4443 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4444 } 4445 4446 EVT IdxVT = Index.getValueType(); 4447 EVT EltTy = IdxVT.getVectorElementType(); 4448 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4449 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4450 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4451 } 4452 4453 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4454 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4455 Ops, MMO, IndexType, false); 4456 DAG.setRoot(Scatter); 4457 setValue(&I, Scatter); 4458 } 4459 4460 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4461 SDLoc sdl = getCurSDLoc(); 4462 4463 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4464 MaybeAlign &Alignment) { 4465 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4466 Ptr = I.getArgOperand(0); 4467 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4468 Mask = I.getArgOperand(2); 4469 Src0 = I.getArgOperand(3); 4470 }; 4471 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4472 MaybeAlign &Alignment) { 4473 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4474 Ptr = I.getArgOperand(0); 4475 Alignment = None; 4476 Mask = I.getArgOperand(1); 4477 Src0 = I.getArgOperand(2); 4478 }; 4479 4480 Value *PtrOperand, *MaskOperand, *Src0Operand; 4481 MaybeAlign Alignment; 4482 if (IsExpanding) 4483 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4484 else 4485 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4486 4487 SDValue Ptr = getValue(PtrOperand); 4488 SDValue Src0 = getValue(Src0Operand); 4489 SDValue Mask = getValue(MaskOperand); 4490 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4491 4492 EVT VT = Src0.getValueType(); 4493 if (!Alignment) 4494 Alignment = DAG.getEVTAlign(VT); 4495 4496 AAMDNodes AAInfo; 4497 I.getAAMetadata(AAInfo); 4498 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4499 4500 // Do not serialize masked loads of constant memory with anything. 4501 MemoryLocation ML; 4502 if (VT.isScalableVector()) 4503 ML = MemoryLocation::getAfter(PtrOperand); 4504 else 4505 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4506 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4507 AAInfo); 4508 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4509 4510 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4511 4512 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4513 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4514 // TODO: Make MachineMemOperands aware of scalable 4515 // vectors. 4516 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4517 4518 SDValue Load = 4519 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4520 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4521 if (AddToChain) 4522 PendingLoads.push_back(Load.getValue(1)); 4523 setValue(&I, Load); 4524 } 4525 4526 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4527 SDLoc sdl = getCurSDLoc(); 4528 4529 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4530 const Value *Ptr = I.getArgOperand(0); 4531 SDValue Src0 = getValue(I.getArgOperand(3)); 4532 SDValue Mask = getValue(I.getArgOperand(2)); 4533 4534 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4535 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4536 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4537 ->getMaybeAlignValue() 4538 .getValueOr(DAG.getEVTAlign(VT.getScalarType())); 4539 4540 AAMDNodes AAInfo; 4541 I.getAAMetadata(AAInfo); 4542 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4543 4544 SDValue Root = DAG.getRoot(); 4545 SDValue Base; 4546 SDValue Index; 4547 ISD::MemIndexType IndexType; 4548 SDValue Scale; 4549 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4550 I.getParent()); 4551 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4552 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4553 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4554 // TODO: Make MachineMemOperands aware of scalable 4555 // vectors. 4556 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4557 4558 if (!UniformBase) { 4559 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4560 Index = getValue(Ptr); 4561 IndexType = ISD::SIGNED_UNSCALED; 4562 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4563 } 4564 4565 EVT IdxVT = Index.getValueType(); 4566 EVT EltTy = IdxVT.getVectorElementType(); 4567 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4568 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4569 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4570 } 4571 4572 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4573 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4574 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4575 4576 PendingLoads.push_back(Gather.getValue(1)); 4577 setValue(&I, Gather); 4578 } 4579 4580 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4581 SDLoc dl = getCurSDLoc(); 4582 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4583 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4584 SyncScope::ID SSID = I.getSyncScopeID(); 4585 4586 SDValue InChain = getRoot(); 4587 4588 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4589 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4590 4591 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4592 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4593 4594 MachineFunction &MF = DAG.getMachineFunction(); 4595 MachineMemOperand *MMO = MF.getMachineMemOperand( 4596 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4597 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4598 FailureOrdering); 4599 4600 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4601 dl, MemVT, VTs, InChain, 4602 getValue(I.getPointerOperand()), 4603 getValue(I.getCompareOperand()), 4604 getValue(I.getNewValOperand()), MMO); 4605 4606 SDValue OutChain = L.getValue(2); 4607 4608 setValue(&I, L); 4609 DAG.setRoot(OutChain); 4610 } 4611 4612 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4613 SDLoc dl = getCurSDLoc(); 4614 ISD::NodeType NT; 4615 switch (I.getOperation()) { 4616 default: llvm_unreachable("Unknown atomicrmw operation"); 4617 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4618 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4619 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4620 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4621 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4622 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4623 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4624 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4625 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4626 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4627 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4628 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4629 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4630 } 4631 AtomicOrdering Ordering = I.getOrdering(); 4632 SyncScope::ID SSID = I.getSyncScopeID(); 4633 4634 SDValue InChain = getRoot(); 4635 4636 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4637 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4638 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4639 4640 MachineFunction &MF = DAG.getMachineFunction(); 4641 MachineMemOperand *MMO = MF.getMachineMemOperand( 4642 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4643 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4644 4645 SDValue L = 4646 DAG.getAtomic(NT, dl, MemVT, InChain, 4647 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4648 MMO); 4649 4650 SDValue OutChain = L.getValue(1); 4651 4652 setValue(&I, L); 4653 DAG.setRoot(OutChain); 4654 } 4655 4656 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4657 SDLoc dl = getCurSDLoc(); 4658 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4659 SDValue Ops[3]; 4660 Ops[0] = getRoot(); 4661 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4662 TLI.getFenceOperandTy(DAG.getDataLayout())); 4663 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4664 TLI.getFenceOperandTy(DAG.getDataLayout())); 4665 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4666 } 4667 4668 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4669 SDLoc dl = getCurSDLoc(); 4670 AtomicOrdering Order = I.getOrdering(); 4671 SyncScope::ID SSID = I.getSyncScopeID(); 4672 4673 SDValue InChain = getRoot(); 4674 4675 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4676 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4677 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4678 4679 if (!TLI.supportsUnalignedAtomics() && 4680 I.getAlignment() < MemVT.getSizeInBits() / 8) 4681 report_fatal_error("Cannot generate unaligned atomic load"); 4682 4683 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4684 4685 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4686 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4687 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4688 4689 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4690 4691 SDValue Ptr = getValue(I.getPointerOperand()); 4692 4693 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4694 // TODO: Once this is better exercised by tests, it should be merged with 4695 // the normal path for loads to prevent future divergence. 4696 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4697 if (MemVT != VT) 4698 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4699 4700 setValue(&I, L); 4701 SDValue OutChain = L.getValue(1); 4702 if (!I.isUnordered()) 4703 DAG.setRoot(OutChain); 4704 else 4705 PendingLoads.push_back(OutChain); 4706 return; 4707 } 4708 4709 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4710 Ptr, MMO); 4711 4712 SDValue OutChain = L.getValue(1); 4713 if (MemVT != VT) 4714 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4715 4716 setValue(&I, L); 4717 DAG.setRoot(OutChain); 4718 } 4719 4720 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4721 SDLoc dl = getCurSDLoc(); 4722 4723 AtomicOrdering Ordering = I.getOrdering(); 4724 SyncScope::ID SSID = I.getSyncScopeID(); 4725 4726 SDValue InChain = getRoot(); 4727 4728 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4729 EVT MemVT = 4730 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4731 4732 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4733 report_fatal_error("Cannot generate unaligned atomic store"); 4734 4735 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4736 4737 MachineFunction &MF = DAG.getMachineFunction(); 4738 MachineMemOperand *MMO = MF.getMachineMemOperand( 4739 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4740 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4741 4742 SDValue Val = getValue(I.getValueOperand()); 4743 if (Val.getValueType() != MemVT) 4744 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4745 SDValue Ptr = getValue(I.getPointerOperand()); 4746 4747 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4748 // TODO: Once this is better exercised by tests, it should be merged with 4749 // the normal path for stores to prevent future divergence. 4750 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4751 DAG.setRoot(S); 4752 return; 4753 } 4754 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4755 Ptr, Val, MMO); 4756 4757 4758 DAG.setRoot(OutChain); 4759 } 4760 4761 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4762 /// node. 4763 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4764 unsigned Intrinsic) { 4765 // Ignore the callsite's attributes. A specific call site may be marked with 4766 // readnone, but the lowering code will expect the chain based on the 4767 // definition. 4768 const Function *F = I.getCalledFunction(); 4769 bool HasChain = !F->doesNotAccessMemory(); 4770 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4771 4772 // Build the operand list. 4773 SmallVector<SDValue, 8> Ops; 4774 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4775 if (OnlyLoad) { 4776 // We don't need to serialize loads against other loads. 4777 Ops.push_back(DAG.getRoot()); 4778 } else { 4779 Ops.push_back(getRoot()); 4780 } 4781 } 4782 4783 // Info is set by getTgtMemInstrinsic 4784 TargetLowering::IntrinsicInfo Info; 4785 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4786 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4787 DAG.getMachineFunction(), 4788 Intrinsic); 4789 4790 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4791 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4792 Info.opc == ISD::INTRINSIC_W_CHAIN) 4793 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4794 TLI.getPointerTy(DAG.getDataLayout()))); 4795 4796 // Add all operands of the call to the operand list. 4797 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4798 const Value *Arg = I.getArgOperand(i); 4799 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4800 Ops.push_back(getValue(Arg)); 4801 continue; 4802 } 4803 4804 // Use TargetConstant instead of a regular constant for immarg. 4805 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4806 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4807 assert(CI->getBitWidth() <= 64 && 4808 "large intrinsic immediates not handled"); 4809 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4810 } else { 4811 Ops.push_back( 4812 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4813 } 4814 } 4815 4816 SmallVector<EVT, 4> ValueVTs; 4817 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4818 4819 if (HasChain) 4820 ValueVTs.push_back(MVT::Other); 4821 4822 SDVTList VTs = DAG.getVTList(ValueVTs); 4823 4824 // Propagate fast-math-flags from IR to node(s). 4825 SDNodeFlags Flags; 4826 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4827 Flags.copyFMF(*FPMO); 4828 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4829 4830 // Create the node. 4831 SDValue Result; 4832 if (IsTgtIntrinsic) { 4833 // This is target intrinsic that touches memory 4834 AAMDNodes AAInfo; 4835 I.getAAMetadata(AAInfo); 4836 Result = 4837 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4838 MachinePointerInfo(Info.ptrVal, Info.offset), 4839 Info.align, Info.flags, Info.size, AAInfo); 4840 } else if (!HasChain) { 4841 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4842 } else if (!I.getType()->isVoidTy()) { 4843 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4844 } else { 4845 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4846 } 4847 4848 if (HasChain) { 4849 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4850 if (OnlyLoad) 4851 PendingLoads.push_back(Chain); 4852 else 4853 DAG.setRoot(Chain); 4854 } 4855 4856 if (!I.getType()->isVoidTy()) { 4857 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4858 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4859 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4860 } else 4861 Result = lowerRangeToAssertZExt(DAG, I, Result); 4862 4863 MaybeAlign Alignment = I.getRetAlign(); 4864 if (!Alignment) 4865 Alignment = F->getAttributes().getRetAlignment(); 4866 // Insert `assertalign` node if there's an alignment. 4867 if (InsertAssertAlign && Alignment) { 4868 Result = 4869 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4870 } 4871 4872 setValue(&I, Result); 4873 } 4874 } 4875 4876 /// GetSignificand - Get the significand and build it into a floating-point 4877 /// number with exponent of 1: 4878 /// 4879 /// Op = (Op & 0x007fffff) | 0x3f800000; 4880 /// 4881 /// where Op is the hexadecimal representation of floating point value. 4882 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4883 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4884 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4885 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4886 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4887 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4888 } 4889 4890 /// GetExponent - Get the exponent: 4891 /// 4892 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4893 /// 4894 /// where Op is the hexadecimal representation of floating point value. 4895 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4896 const TargetLowering &TLI, const SDLoc &dl) { 4897 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4898 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4899 SDValue t1 = DAG.getNode( 4900 ISD::SRL, dl, MVT::i32, t0, 4901 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4902 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4903 DAG.getConstant(127, dl, MVT::i32)); 4904 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4905 } 4906 4907 /// getF32Constant - Get 32-bit floating point constant. 4908 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4909 const SDLoc &dl) { 4910 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4911 MVT::f32); 4912 } 4913 4914 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4915 SelectionDAG &DAG) { 4916 // TODO: What fast-math-flags should be set on the floating-point nodes? 4917 4918 // IntegerPartOfX = ((int32_t)(t0); 4919 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4920 4921 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4922 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4923 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4924 4925 // IntegerPartOfX <<= 23; 4926 IntegerPartOfX = DAG.getNode( 4927 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4928 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4929 DAG.getDataLayout()))); 4930 4931 SDValue TwoToFractionalPartOfX; 4932 if (LimitFloatPrecision <= 6) { 4933 // For floating-point precision of 6: 4934 // 4935 // TwoToFractionalPartOfX = 4936 // 0.997535578f + 4937 // (0.735607626f + 0.252464424f * x) * x; 4938 // 4939 // error 0.0144103317, which is 6 bits 4940 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4941 getF32Constant(DAG, 0x3e814304, dl)); 4942 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4943 getF32Constant(DAG, 0x3f3c50c8, dl)); 4944 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4945 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4946 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4947 } else if (LimitFloatPrecision <= 12) { 4948 // For floating-point precision of 12: 4949 // 4950 // TwoToFractionalPartOfX = 4951 // 0.999892986f + 4952 // (0.696457318f + 4953 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4954 // 4955 // error 0.000107046256, which is 13 to 14 bits 4956 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4957 getF32Constant(DAG, 0x3da235e3, dl)); 4958 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4959 getF32Constant(DAG, 0x3e65b8f3, dl)); 4960 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4961 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4962 getF32Constant(DAG, 0x3f324b07, dl)); 4963 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4964 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4965 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4966 } else { // LimitFloatPrecision <= 18 4967 // For floating-point precision of 18: 4968 // 4969 // TwoToFractionalPartOfX = 4970 // 0.999999982f + 4971 // (0.693148872f + 4972 // (0.240227044f + 4973 // (0.554906021e-1f + 4974 // (0.961591928e-2f + 4975 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4976 // error 2.47208000*10^(-7), which is better than 18 bits 4977 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4978 getF32Constant(DAG, 0x3924b03e, dl)); 4979 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4980 getF32Constant(DAG, 0x3ab24b87, dl)); 4981 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4982 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4983 getF32Constant(DAG, 0x3c1d8c17, dl)); 4984 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4985 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4986 getF32Constant(DAG, 0x3d634a1d, dl)); 4987 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4988 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4989 getF32Constant(DAG, 0x3e75fe14, dl)); 4990 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4991 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4992 getF32Constant(DAG, 0x3f317234, dl)); 4993 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4994 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4995 getF32Constant(DAG, 0x3f800000, dl)); 4996 } 4997 4998 // Add the exponent into the result in integer domain. 4999 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5000 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5001 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5002 } 5003 5004 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5005 /// limited-precision mode. 5006 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5007 const TargetLowering &TLI, SDNodeFlags Flags) { 5008 if (Op.getValueType() == MVT::f32 && 5009 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5010 5011 // Put the exponent in the right bit position for later addition to the 5012 // final result: 5013 // 5014 // t0 = Op * log2(e) 5015 5016 // TODO: What fast-math-flags should be set here? 5017 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5018 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5019 return getLimitedPrecisionExp2(t0, dl, DAG); 5020 } 5021 5022 // No special expansion. 5023 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5024 } 5025 5026 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5027 /// limited-precision mode. 5028 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5029 const TargetLowering &TLI, SDNodeFlags Flags) { 5030 // TODO: What fast-math-flags should be set on the floating-point nodes? 5031 5032 if (Op.getValueType() == MVT::f32 && 5033 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5034 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5035 5036 // Scale the exponent by log(2). 5037 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5038 SDValue LogOfExponent = 5039 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5040 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5041 5042 // Get the significand and build it into a floating-point number with 5043 // exponent of 1. 5044 SDValue X = GetSignificand(DAG, Op1, dl); 5045 5046 SDValue LogOfMantissa; 5047 if (LimitFloatPrecision <= 6) { 5048 // For floating-point precision of 6: 5049 // 5050 // LogofMantissa = 5051 // -1.1609546f + 5052 // (1.4034025f - 0.23903021f * x) * x; 5053 // 5054 // error 0.0034276066, which is better than 8 bits 5055 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5056 getF32Constant(DAG, 0xbe74c456, dl)); 5057 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5058 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5059 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5060 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5061 getF32Constant(DAG, 0x3f949a29, dl)); 5062 } else if (LimitFloatPrecision <= 12) { 5063 // For floating-point precision of 12: 5064 // 5065 // LogOfMantissa = 5066 // -1.7417939f + 5067 // (2.8212026f + 5068 // (-1.4699568f + 5069 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5070 // 5071 // error 0.000061011436, which is 14 bits 5072 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5073 getF32Constant(DAG, 0xbd67b6d6, dl)); 5074 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5075 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5076 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5077 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5078 getF32Constant(DAG, 0x3fbc278b, dl)); 5079 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5080 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5081 getF32Constant(DAG, 0x40348e95, dl)); 5082 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5083 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5084 getF32Constant(DAG, 0x3fdef31a, dl)); 5085 } else { // LimitFloatPrecision <= 18 5086 // For floating-point precision of 18: 5087 // 5088 // LogOfMantissa = 5089 // -2.1072184f + 5090 // (4.2372794f + 5091 // (-3.7029485f + 5092 // (2.2781945f + 5093 // (-0.87823314f + 5094 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5095 // 5096 // error 0.0000023660568, which is better than 18 bits 5097 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5098 getF32Constant(DAG, 0xbc91e5ac, dl)); 5099 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5100 getF32Constant(DAG, 0x3e4350aa, dl)); 5101 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5102 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5103 getF32Constant(DAG, 0x3f60d3e3, dl)); 5104 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5105 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5106 getF32Constant(DAG, 0x4011cdf0, dl)); 5107 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5108 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5109 getF32Constant(DAG, 0x406cfd1c, dl)); 5110 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5111 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5112 getF32Constant(DAG, 0x408797cb, dl)); 5113 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5114 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5115 getF32Constant(DAG, 0x4006dcab, dl)); 5116 } 5117 5118 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5119 } 5120 5121 // No special expansion. 5122 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5123 } 5124 5125 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5126 /// limited-precision mode. 5127 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5128 const TargetLowering &TLI, SDNodeFlags Flags) { 5129 // TODO: What fast-math-flags should be set on the floating-point nodes? 5130 5131 if (Op.getValueType() == MVT::f32 && 5132 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5133 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5134 5135 // Get the exponent. 5136 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5137 5138 // Get the significand and build it into a floating-point number with 5139 // exponent of 1. 5140 SDValue X = GetSignificand(DAG, Op1, dl); 5141 5142 // Different possible minimax approximations of significand in 5143 // floating-point for various degrees of accuracy over [1,2]. 5144 SDValue Log2ofMantissa; 5145 if (LimitFloatPrecision <= 6) { 5146 // For floating-point precision of 6: 5147 // 5148 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5149 // 5150 // error 0.0049451742, which is more than 7 bits 5151 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5152 getF32Constant(DAG, 0xbeb08fe0, dl)); 5153 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5154 getF32Constant(DAG, 0x40019463, dl)); 5155 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5156 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5157 getF32Constant(DAG, 0x3fd6633d, dl)); 5158 } else if (LimitFloatPrecision <= 12) { 5159 // For floating-point precision of 12: 5160 // 5161 // Log2ofMantissa = 5162 // -2.51285454f + 5163 // (4.07009056f + 5164 // (-2.12067489f + 5165 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5166 // 5167 // error 0.0000876136000, which is better than 13 bits 5168 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5169 getF32Constant(DAG, 0xbda7262e, dl)); 5170 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5171 getF32Constant(DAG, 0x3f25280b, dl)); 5172 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5173 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5174 getF32Constant(DAG, 0x4007b923, dl)); 5175 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5176 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5177 getF32Constant(DAG, 0x40823e2f, dl)); 5178 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5179 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5180 getF32Constant(DAG, 0x4020d29c, dl)); 5181 } else { // LimitFloatPrecision <= 18 5182 // For floating-point precision of 18: 5183 // 5184 // Log2ofMantissa = 5185 // -3.0400495f + 5186 // (6.1129976f + 5187 // (-5.3420409f + 5188 // (3.2865683f + 5189 // (-1.2669343f + 5190 // (0.27515199f - 5191 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5192 // 5193 // error 0.0000018516, which is better than 18 bits 5194 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5195 getF32Constant(DAG, 0xbcd2769e, dl)); 5196 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5197 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5198 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5199 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5200 getF32Constant(DAG, 0x3fa22ae7, dl)); 5201 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5202 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5203 getF32Constant(DAG, 0x40525723, dl)); 5204 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5205 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5206 getF32Constant(DAG, 0x40aaf200, dl)); 5207 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5208 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5209 getF32Constant(DAG, 0x40c39dad, dl)); 5210 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5211 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5212 getF32Constant(DAG, 0x4042902c, dl)); 5213 } 5214 5215 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5216 } 5217 5218 // No special expansion. 5219 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5220 } 5221 5222 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5223 /// limited-precision mode. 5224 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5225 const TargetLowering &TLI, SDNodeFlags Flags) { 5226 // TODO: What fast-math-flags should be set on the floating-point nodes? 5227 5228 if (Op.getValueType() == MVT::f32 && 5229 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5230 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5231 5232 // Scale the exponent by log10(2) [0.30102999f]. 5233 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5234 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5235 getF32Constant(DAG, 0x3e9a209a, dl)); 5236 5237 // Get the significand and build it into a floating-point number with 5238 // exponent of 1. 5239 SDValue X = GetSignificand(DAG, Op1, dl); 5240 5241 SDValue Log10ofMantissa; 5242 if (LimitFloatPrecision <= 6) { 5243 // For floating-point precision of 6: 5244 // 5245 // Log10ofMantissa = 5246 // -0.50419619f + 5247 // (0.60948995f - 0.10380950f * x) * x; 5248 // 5249 // error 0.0014886165, which is 6 bits 5250 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5251 getF32Constant(DAG, 0xbdd49a13, dl)); 5252 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5253 getF32Constant(DAG, 0x3f1c0789, dl)); 5254 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5255 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5256 getF32Constant(DAG, 0x3f011300, dl)); 5257 } else if (LimitFloatPrecision <= 12) { 5258 // For floating-point precision of 12: 5259 // 5260 // Log10ofMantissa = 5261 // -0.64831180f + 5262 // (0.91751397f + 5263 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5264 // 5265 // error 0.00019228036, which is better than 12 bits 5266 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5267 getF32Constant(DAG, 0x3d431f31, dl)); 5268 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5269 getF32Constant(DAG, 0x3ea21fb2, dl)); 5270 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5271 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5272 getF32Constant(DAG, 0x3f6ae232, dl)); 5273 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5274 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5275 getF32Constant(DAG, 0x3f25f7c3, dl)); 5276 } else { // LimitFloatPrecision <= 18 5277 // For floating-point precision of 18: 5278 // 5279 // Log10ofMantissa = 5280 // -0.84299375f + 5281 // (1.5327582f + 5282 // (-1.0688956f + 5283 // (0.49102474f + 5284 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5285 // 5286 // error 0.0000037995730, which is better than 18 bits 5287 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5288 getF32Constant(DAG, 0x3c5d51ce, dl)); 5289 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5290 getF32Constant(DAG, 0x3e00685a, dl)); 5291 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5292 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5293 getF32Constant(DAG, 0x3efb6798, dl)); 5294 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5295 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5296 getF32Constant(DAG, 0x3f88d192, dl)); 5297 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5298 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5299 getF32Constant(DAG, 0x3fc4316c, dl)); 5300 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5301 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5302 getF32Constant(DAG, 0x3f57ce70, dl)); 5303 } 5304 5305 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5306 } 5307 5308 // No special expansion. 5309 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5310 } 5311 5312 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5313 /// limited-precision mode. 5314 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5315 const TargetLowering &TLI, SDNodeFlags Flags) { 5316 if (Op.getValueType() == MVT::f32 && 5317 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5318 return getLimitedPrecisionExp2(Op, dl, DAG); 5319 5320 // No special expansion. 5321 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5322 } 5323 5324 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5325 /// limited-precision mode with x == 10.0f. 5326 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5327 SelectionDAG &DAG, const TargetLowering &TLI, 5328 SDNodeFlags Flags) { 5329 bool IsExp10 = false; 5330 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5331 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5332 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5333 APFloat Ten(10.0f); 5334 IsExp10 = LHSC->isExactlyValue(Ten); 5335 } 5336 } 5337 5338 // TODO: What fast-math-flags should be set on the FMUL node? 5339 if (IsExp10) { 5340 // Put the exponent in the right bit position for later addition to the 5341 // final result: 5342 // 5343 // #define LOG2OF10 3.3219281f 5344 // t0 = Op * LOG2OF10; 5345 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5346 getF32Constant(DAG, 0x40549a78, dl)); 5347 return getLimitedPrecisionExp2(t0, dl, DAG); 5348 } 5349 5350 // No special expansion. 5351 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5352 } 5353 5354 /// ExpandPowI - Expand a llvm.powi intrinsic. 5355 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5356 SelectionDAG &DAG) { 5357 // If RHS is a constant, we can expand this out to a multiplication tree, 5358 // otherwise we end up lowering to a call to __powidf2 (for example). When 5359 // optimizing for size, we only want to do this if the expansion would produce 5360 // a small number of multiplies, otherwise we do the full expansion. 5361 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5362 // Get the exponent as a positive value. 5363 unsigned Val = RHSC->getSExtValue(); 5364 if ((int)Val < 0) Val = -Val; 5365 5366 // powi(x, 0) -> 1.0 5367 if (Val == 0) 5368 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5369 5370 bool OptForSize = DAG.shouldOptForSize(); 5371 if (!OptForSize || 5372 // If optimizing for size, don't insert too many multiplies. 5373 // This inserts up to 5 multiplies. 5374 countPopulation(Val) + Log2_32(Val) < 7) { 5375 // We use the simple binary decomposition method to generate the multiply 5376 // sequence. There are more optimal ways to do this (for example, 5377 // powi(x,15) generates one more multiply than it should), but this has 5378 // the benefit of being both really simple and much better than a libcall. 5379 SDValue Res; // Logically starts equal to 1.0 5380 SDValue CurSquare = LHS; 5381 // TODO: Intrinsics should have fast-math-flags that propagate to these 5382 // nodes. 5383 while (Val) { 5384 if (Val & 1) { 5385 if (Res.getNode()) 5386 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5387 else 5388 Res = CurSquare; // 1.0*CurSquare. 5389 } 5390 5391 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5392 CurSquare, CurSquare); 5393 Val >>= 1; 5394 } 5395 5396 // If the original was negative, invert the result, producing 1/(x*x*x). 5397 if (RHSC->getSExtValue() < 0) 5398 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5399 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5400 return Res; 5401 } 5402 } 5403 5404 // Otherwise, expand to a libcall. 5405 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5406 } 5407 5408 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5409 SDValue LHS, SDValue RHS, SDValue Scale, 5410 SelectionDAG &DAG, const TargetLowering &TLI) { 5411 EVT VT = LHS.getValueType(); 5412 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5413 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5414 LLVMContext &Ctx = *DAG.getContext(); 5415 5416 // If the type is legal but the operation isn't, this node might survive all 5417 // the way to operation legalization. If we end up there and we do not have 5418 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5419 // node. 5420 5421 // Coax the legalizer into expanding the node during type legalization instead 5422 // by bumping the size by one bit. This will force it to Promote, enabling the 5423 // early expansion and avoiding the need to expand later. 5424 5425 // We don't have to do this if Scale is 0; that can always be expanded, unless 5426 // it's a saturating signed operation. Those can experience true integer 5427 // division overflow, a case which we must avoid. 5428 5429 // FIXME: We wouldn't have to do this (or any of the early 5430 // expansion/promotion) if it was possible to expand a libcall of an 5431 // illegal type during operation legalization. But it's not, so things 5432 // get a bit hacky. 5433 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5434 if ((ScaleInt > 0 || (Saturating && Signed)) && 5435 (TLI.isTypeLegal(VT) || 5436 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5437 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5438 Opcode, VT, ScaleInt); 5439 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5440 EVT PromVT; 5441 if (VT.isScalarInteger()) 5442 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5443 else if (VT.isVector()) { 5444 PromVT = VT.getVectorElementType(); 5445 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5446 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5447 } else 5448 llvm_unreachable("Wrong VT for DIVFIX?"); 5449 if (Signed) { 5450 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5451 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5452 } else { 5453 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5454 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5455 } 5456 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5457 // For saturating operations, we need to shift up the LHS to get the 5458 // proper saturation width, and then shift down again afterwards. 5459 if (Saturating) 5460 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5461 DAG.getConstant(1, DL, ShiftTy)); 5462 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5463 if (Saturating) 5464 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5465 DAG.getConstant(1, DL, ShiftTy)); 5466 return DAG.getZExtOrTrunc(Res, DL, VT); 5467 } 5468 } 5469 5470 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5471 } 5472 5473 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5474 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5475 static void 5476 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5477 const SDValue &N) { 5478 switch (N.getOpcode()) { 5479 case ISD::CopyFromReg: { 5480 SDValue Op = N.getOperand(1); 5481 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5482 Op.getValueType().getSizeInBits()); 5483 return; 5484 } 5485 case ISD::BITCAST: 5486 case ISD::AssertZext: 5487 case ISD::AssertSext: 5488 case ISD::TRUNCATE: 5489 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5490 return; 5491 case ISD::BUILD_PAIR: 5492 case ISD::BUILD_VECTOR: 5493 case ISD::CONCAT_VECTORS: 5494 for (SDValue Op : N->op_values()) 5495 getUnderlyingArgRegs(Regs, Op); 5496 return; 5497 default: 5498 return; 5499 } 5500 } 5501 5502 /// If the DbgValueInst is a dbg_value of a function argument, create the 5503 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5504 /// instruction selection, they will be inserted to the entry BB. 5505 /// We don't currently support this for variadic dbg_values, as they shouldn't 5506 /// appear for function arguments or in the prologue. 5507 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5508 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5509 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5510 const Argument *Arg = dyn_cast<Argument>(V); 5511 if (!Arg) 5512 return false; 5513 5514 MachineFunction &MF = DAG.getMachineFunction(); 5515 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5516 5517 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5518 // we've been asked to pursue. 5519 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5520 bool Indirect) { 5521 if (Reg.isVirtual() && TM.Options.ValueTrackingVariableLocations) { 5522 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5523 // pointing at the VReg, which will be patched up later. 5524 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5525 auto MIB = BuildMI(MF, DL, Inst); 5526 MIB.addReg(Reg, RegState::Debug); 5527 MIB.addImm(0); 5528 MIB.addMetadata(Variable); 5529 auto *NewDIExpr = FragExpr; 5530 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5531 // the DIExpression. 5532 if (Indirect) 5533 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5534 MIB.addMetadata(NewDIExpr); 5535 return MIB; 5536 } else { 5537 // Create a completely standard DBG_VALUE. 5538 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5539 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5540 } 5541 }; 5542 5543 if (!IsDbgDeclare) { 5544 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5545 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5546 // the entry block. 5547 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5548 if (!IsInEntryBlock) 5549 return false; 5550 5551 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5552 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5553 // variable that also is a param. 5554 // 5555 // Although, if we are at the top of the entry block already, we can still 5556 // emit using ArgDbgValue. This might catch some situations when the 5557 // dbg.value refers to an argument that isn't used in the entry block, so 5558 // any CopyToReg node would be optimized out and the only way to express 5559 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5560 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5561 // we should only emit as ArgDbgValue if the Variable is an argument to the 5562 // current function, and the dbg.value intrinsic is found in the entry 5563 // block. 5564 bool VariableIsFunctionInputArg = Variable->isParameter() && 5565 !DL->getInlinedAt(); 5566 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5567 if (!IsInPrologue && !VariableIsFunctionInputArg) 5568 return false; 5569 5570 // Here we assume that a function argument on IR level only can be used to 5571 // describe one input parameter on source level. If we for example have 5572 // source code like this 5573 // 5574 // struct A { long x, y; }; 5575 // void foo(struct A a, long b) { 5576 // ... 5577 // b = a.x; 5578 // ... 5579 // } 5580 // 5581 // and IR like this 5582 // 5583 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5584 // entry: 5585 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5586 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5587 // call void @llvm.dbg.value(metadata i32 %b, "b", 5588 // ... 5589 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5590 // ... 5591 // 5592 // then the last dbg.value is describing a parameter "b" using a value that 5593 // is an argument. But since we already has used %a1 to describe a parameter 5594 // we should not handle that last dbg.value here (that would result in an 5595 // incorrect hoisting of the DBG_VALUE to the function entry). 5596 // Notice that we allow one dbg.value per IR level argument, to accommodate 5597 // for the situation with fragments above. 5598 if (VariableIsFunctionInputArg) { 5599 unsigned ArgNo = Arg->getArgNo(); 5600 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5601 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5602 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5603 return false; 5604 FuncInfo.DescribedArgs.set(ArgNo); 5605 } 5606 } 5607 5608 bool IsIndirect = false; 5609 Optional<MachineOperand> Op; 5610 // Some arguments' frame index is recorded during argument lowering. 5611 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5612 if (FI != std::numeric_limits<int>::max()) 5613 Op = MachineOperand::CreateFI(FI); 5614 5615 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5616 if (!Op && N.getNode()) { 5617 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5618 Register Reg; 5619 if (ArgRegsAndSizes.size() == 1) 5620 Reg = ArgRegsAndSizes.front().first; 5621 5622 if (Reg && Reg.isVirtual()) { 5623 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5624 Register PR = RegInfo.getLiveInPhysReg(Reg); 5625 if (PR) 5626 Reg = PR; 5627 } 5628 if (Reg) { 5629 Op = MachineOperand::CreateReg(Reg, false); 5630 IsIndirect = IsDbgDeclare; 5631 } 5632 } 5633 5634 if (!Op && N.getNode()) { 5635 // Check if frame index is available. 5636 SDValue LCandidate = peekThroughBitcasts(N); 5637 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5638 if (FrameIndexSDNode *FINode = 5639 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5640 Op = MachineOperand::CreateFI(FINode->getIndex()); 5641 } 5642 5643 if (!Op) { 5644 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5645 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5646 SplitRegs) { 5647 unsigned Offset = 0; 5648 for (auto RegAndSize : SplitRegs) { 5649 // If the expression is already a fragment, the current register 5650 // offset+size might extend beyond the fragment. In this case, only 5651 // the register bits that are inside the fragment are relevant. 5652 int RegFragmentSizeInBits = RegAndSize.second; 5653 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5654 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5655 // The register is entirely outside the expression fragment, 5656 // so is irrelevant for debug info. 5657 if (Offset >= ExprFragmentSizeInBits) 5658 break; 5659 // The register is partially outside the expression fragment, only 5660 // the low bits within the fragment are relevant for debug info. 5661 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5662 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5663 } 5664 } 5665 5666 auto FragmentExpr = DIExpression::createFragmentExpression( 5667 Expr, Offset, RegFragmentSizeInBits); 5668 Offset += RegAndSize.second; 5669 // If a valid fragment expression cannot be created, the variable's 5670 // correct value cannot be determined and so it is set as Undef. 5671 if (!FragmentExpr) { 5672 SDDbgValue *SDV = DAG.getConstantDbgValue( 5673 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5674 DAG.AddDbgValue(SDV, false); 5675 continue; 5676 } 5677 MachineInstr *NewMI = 5678 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare); 5679 FuncInfo.ArgDbgValues.push_back(NewMI); 5680 } 5681 }; 5682 5683 // Check if ValueMap has reg number. 5684 DenseMap<const Value *, Register>::const_iterator 5685 VMI = FuncInfo.ValueMap.find(V); 5686 if (VMI != FuncInfo.ValueMap.end()) { 5687 const auto &TLI = DAG.getTargetLoweringInfo(); 5688 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5689 V->getType(), None); 5690 if (RFV.occupiesMultipleRegs()) { 5691 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5692 return true; 5693 } 5694 5695 Op = MachineOperand::CreateReg(VMI->second, false); 5696 IsIndirect = IsDbgDeclare; 5697 } else if (ArgRegsAndSizes.size() > 1) { 5698 // This was split due to the calling convention, and no virtual register 5699 // mapping exists for the value. 5700 splitMultiRegDbgValue(ArgRegsAndSizes); 5701 return true; 5702 } 5703 } 5704 5705 if (!Op) 5706 return false; 5707 5708 assert(Variable->isValidLocationForIntrinsic(DL) && 5709 "Expected inlined-at fields to agree"); 5710 MachineInstr *NewMI = nullptr; 5711 5712 if (Op->isReg()) 5713 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5714 else 5715 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5716 Variable, Expr); 5717 5718 FuncInfo.ArgDbgValues.push_back(NewMI); 5719 return true; 5720 } 5721 5722 /// Return the appropriate SDDbgValue based on N. 5723 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5724 DILocalVariable *Variable, 5725 DIExpression *Expr, 5726 const DebugLoc &dl, 5727 unsigned DbgSDNodeOrder) { 5728 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5729 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5730 // stack slot locations. 5731 // 5732 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5733 // debug values here after optimization: 5734 // 5735 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5736 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5737 // 5738 // Both describe the direct values of their associated variables. 5739 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5740 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5741 } 5742 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5743 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5744 } 5745 5746 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5747 switch (Intrinsic) { 5748 case Intrinsic::smul_fix: 5749 return ISD::SMULFIX; 5750 case Intrinsic::umul_fix: 5751 return ISD::UMULFIX; 5752 case Intrinsic::smul_fix_sat: 5753 return ISD::SMULFIXSAT; 5754 case Intrinsic::umul_fix_sat: 5755 return ISD::UMULFIXSAT; 5756 case Intrinsic::sdiv_fix: 5757 return ISD::SDIVFIX; 5758 case Intrinsic::udiv_fix: 5759 return ISD::UDIVFIX; 5760 case Intrinsic::sdiv_fix_sat: 5761 return ISD::SDIVFIXSAT; 5762 case Intrinsic::udiv_fix_sat: 5763 return ISD::UDIVFIXSAT; 5764 default: 5765 llvm_unreachable("Unhandled fixed point intrinsic"); 5766 } 5767 } 5768 5769 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5770 const char *FunctionName) { 5771 assert(FunctionName && "FunctionName must not be nullptr"); 5772 SDValue Callee = DAG.getExternalSymbol( 5773 FunctionName, 5774 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5775 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5776 } 5777 5778 /// Given a @llvm.call.preallocated.setup, return the corresponding 5779 /// preallocated call. 5780 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5781 assert(cast<CallBase>(PreallocatedSetup) 5782 ->getCalledFunction() 5783 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5784 "expected call_preallocated_setup Value"); 5785 for (auto *U : PreallocatedSetup->users()) { 5786 auto *UseCall = cast<CallBase>(U); 5787 const Function *Fn = UseCall->getCalledFunction(); 5788 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5789 return UseCall; 5790 } 5791 } 5792 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5793 } 5794 5795 /// Lower the call to the specified intrinsic function. 5796 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5797 unsigned Intrinsic) { 5798 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5799 SDLoc sdl = getCurSDLoc(); 5800 DebugLoc dl = getCurDebugLoc(); 5801 SDValue Res; 5802 5803 SDNodeFlags Flags; 5804 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5805 Flags.copyFMF(*FPOp); 5806 5807 switch (Intrinsic) { 5808 default: 5809 // By default, turn this into a target intrinsic node. 5810 visitTargetIntrinsic(I, Intrinsic); 5811 return; 5812 case Intrinsic::vscale: { 5813 match(&I, m_VScale(DAG.getDataLayout())); 5814 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5815 setValue(&I, 5816 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5817 return; 5818 } 5819 case Intrinsic::vastart: visitVAStart(I); return; 5820 case Intrinsic::vaend: visitVAEnd(I); return; 5821 case Intrinsic::vacopy: visitVACopy(I); return; 5822 case Intrinsic::returnaddress: 5823 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5824 TLI.getPointerTy(DAG.getDataLayout()), 5825 getValue(I.getArgOperand(0)))); 5826 return; 5827 case Intrinsic::addressofreturnaddress: 5828 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5829 TLI.getPointerTy(DAG.getDataLayout()))); 5830 return; 5831 case Intrinsic::sponentry: 5832 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5833 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5834 return; 5835 case Intrinsic::frameaddress: 5836 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5837 TLI.getFrameIndexTy(DAG.getDataLayout()), 5838 getValue(I.getArgOperand(0)))); 5839 return; 5840 case Intrinsic::read_volatile_register: 5841 case Intrinsic::read_register: { 5842 Value *Reg = I.getArgOperand(0); 5843 SDValue Chain = getRoot(); 5844 SDValue RegName = 5845 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5846 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5847 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5848 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5849 setValue(&I, Res); 5850 DAG.setRoot(Res.getValue(1)); 5851 return; 5852 } 5853 case Intrinsic::write_register: { 5854 Value *Reg = I.getArgOperand(0); 5855 Value *RegValue = I.getArgOperand(1); 5856 SDValue Chain = getRoot(); 5857 SDValue RegName = 5858 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5859 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5860 RegName, getValue(RegValue))); 5861 return; 5862 } 5863 case Intrinsic::memcpy: { 5864 const auto &MCI = cast<MemCpyInst>(I); 5865 SDValue Op1 = getValue(I.getArgOperand(0)); 5866 SDValue Op2 = getValue(I.getArgOperand(1)); 5867 SDValue Op3 = getValue(I.getArgOperand(2)); 5868 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5869 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5870 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5871 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5872 bool isVol = MCI.isVolatile(); 5873 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5874 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5875 // node. 5876 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5877 AAMDNodes AAInfo; 5878 I.getAAMetadata(AAInfo); 5879 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5880 /* AlwaysInline */ false, isTC, 5881 MachinePointerInfo(I.getArgOperand(0)), 5882 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 5883 updateDAGForMaybeTailCall(MC); 5884 return; 5885 } 5886 case Intrinsic::memcpy_inline: { 5887 const auto &MCI = cast<MemCpyInlineInst>(I); 5888 SDValue Dst = getValue(I.getArgOperand(0)); 5889 SDValue Src = getValue(I.getArgOperand(1)); 5890 SDValue Size = getValue(I.getArgOperand(2)); 5891 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5892 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5893 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5894 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5895 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5896 bool isVol = MCI.isVolatile(); 5897 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5898 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5899 // node. 5900 AAMDNodes AAInfo; 5901 I.getAAMetadata(AAInfo); 5902 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5903 /* AlwaysInline */ true, isTC, 5904 MachinePointerInfo(I.getArgOperand(0)), 5905 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 5906 updateDAGForMaybeTailCall(MC); 5907 return; 5908 } 5909 case Intrinsic::memset: { 5910 const auto &MSI = cast<MemSetInst>(I); 5911 SDValue Op1 = getValue(I.getArgOperand(0)); 5912 SDValue Op2 = getValue(I.getArgOperand(1)); 5913 SDValue Op3 = getValue(I.getArgOperand(2)); 5914 // @llvm.memset defines 0 and 1 to both mean no alignment. 5915 Align Alignment = MSI.getDestAlign().valueOrOne(); 5916 bool isVol = MSI.isVolatile(); 5917 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5918 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5919 AAMDNodes AAInfo; 5920 I.getAAMetadata(AAInfo); 5921 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5922 MachinePointerInfo(I.getArgOperand(0)), AAInfo); 5923 updateDAGForMaybeTailCall(MS); 5924 return; 5925 } 5926 case Intrinsic::memmove: { 5927 const auto &MMI = cast<MemMoveInst>(I); 5928 SDValue Op1 = getValue(I.getArgOperand(0)); 5929 SDValue Op2 = getValue(I.getArgOperand(1)); 5930 SDValue Op3 = getValue(I.getArgOperand(2)); 5931 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5932 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5933 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5934 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5935 bool isVol = MMI.isVolatile(); 5936 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5937 // FIXME: Support passing different dest/src alignments to the memmove DAG 5938 // node. 5939 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5940 AAMDNodes AAInfo; 5941 I.getAAMetadata(AAInfo); 5942 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5943 isTC, MachinePointerInfo(I.getArgOperand(0)), 5944 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 5945 updateDAGForMaybeTailCall(MM); 5946 return; 5947 } 5948 case Intrinsic::memcpy_element_unordered_atomic: { 5949 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5950 SDValue Dst = getValue(MI.getRawDest()); 5951 SDValue Src = getValue(MI.getRawSource()); 5952 SDValue Length = getValue(MI.getLength()); 5953 5954 unsigned DstAlign = MI.getDestAlignment(); 5955 unsigned SrcAlign = MI.getSourceAlignment(); 5956 Type *LengthTy = MI.getLength()->getType(); 5957 unsigned ElemSz = MI.getElementSizeInBytes(); 5958 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5959 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5960 SrcAlign, Length, LengthTy, ElemSz, isTC, 5961 MachinePointerInfo(MI.getRawDest()), 5962 MachinePointerInfo(MI.getRawSource())); 5963 updateDAGForMaybeTailCall(MC); 5964 return; 5965 } 5966 case Intrinsic::memmove_element_unordered_atomic: { 5967 auto &MI = cast<AtomicMemMoveInst>(I); 5968 SDValue Dst = getValue(MI.getRawDest()); 5969 SDValue Src = getValue(MI.getRawSource()); 5970 SDValue Length = getValue(MI.getLength()); 5971 5972 unsigned DstAlign = MI.getDestAlignment(); 5973 unsigned SrcAlign = MI.getSourceAlignment(); 5974 Type *LengthTy = MI.getLength()->getType(); 5975 unsigned ElemSz = MI.getElementSizeInBytes(); 5976 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5977 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5978 SrcAlign, Length, LengthTy, ElemSz, isTC, 5979 MachinePointerInfo(MI.getRawDest()), 5980 MachinePointerInfo(MI.getRawSource())); 5981 updateDAGForMaybeTailCall(MC); 5982 return; 5983 } 5984 case Intrinsic::memset_element_unordered_atomic: { 5985 auto &MI = cast<AtomicMemSetInst>(I); 5986 SDValue Dst = getValue(MI.getRawDest()); 5987 SDValue Val = getValue(MI.getValue()); 5988 SDValue Length = getValue(MI.getLength()); 5989 5990 unsigned DstAlign = MI.getDestAlignment(); 5991 Type *LengthTy = MI.getLength()->getType(); 5992 unsigned ElemSz = MI.getElementSizeInBytes(); 5993 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5994 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5995 LengthTy, ElemSz, isTC, 5996 MachinePointerInfo(MI.getRawDest())); 5997 updateDAGForMaybeTailCall(MC); 5998 return; 5999 } 6000 case Intrinsic::call_preallocated_setup: { 6001 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6002 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6003 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6004 getRoot(), SrcValue); 6005 setValue(&I, Res); 6006 DAG.setRoot(Res); 6007 return; 6008 } 6009 case Intrinsic::call_preallocated_arg: { 6010 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6011 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6012 SDValue Ops[3]; 6013 Ops[0] = getRoot(); 6014 Ops[1] = SrcValue; 6015 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6016 MVT::i32); // arg index 6017 SDValue Res = DAG.getNode( 6018 ISD::PREALLOCATED_ARG, sdl, 6019 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6020 setValue(&I, Res); 6021 DAG.setRoot(Res.getValue(1)); 6022 return; 6023 } 6024 case Intrinsic::dbg_addr: 6025 case Intrinsic::dbg_declare: { 6026 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6027 // they are non-variadic. 6028 const auto &DI = cast<DbgVariableIntrinsic>(I); 6029 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6030 DILocalVariable *Variable = DI.getVariable(); 6031 DIExpression *Expression = DI.getExpression(); 6032 dropDanglingDebugInfo(Variable, Expression); 6033 assert(Variable && "Missing variable"); 6034 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6035 << "\n"); 6036 // Check if address has undef value. 6037 const Value *Address = DI.getVariableLocationOp(0); 6038 if (!Address || isa<UndefValue>(Address) || 6039 (Address->use_empty() && !isa<Argument>(Address))) { 6040 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6041 << " (bad/undef/unused-arg address)\n"); 6042 return; 6043 } 6044 6045 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6046 6047 // Check if this variable can be described by a frame index, typically 6048 // either as a static alloca or a byval parameter. 6049 int FI = std::numeric_limits<int>::max(); 6050 if (const auto *AI = 6051 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6052 if (AI->isStaticAlloca()) { 6053 auto I = FuncInfo.StaticAllocaMap.find(AI); 6054 if (I != FuncInfo.StaticAllocaMap.end()) 6055 FI = I->second; 6056 } 6057 } else if (const auto *Arg = dyn_cast<Argument>( 6058 Address->stripInBoundsConstantOffsets())) { 6059 FI = FuncInfo.getArgumentFrameIndex(Arg); 6060 } 6061 6062 // llvm.dbg.addr is control dependent and always generates indirect 6063 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6064 // the MachineFunction variable table. 6065 if (FI != std::numeric_limits<int>::max()) { 6066 if (Intrinsic == Intrinsic::dbg_addr) { 6067 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6068 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6069 dl, SDNodeOrder); 6070 DAG.AddDbgValue(SDV, isParameter); 6071 } else { 6072 LLVM_DEBUG(dbgs() << "Skipping " << DI 6073 << " (variable info stashed in MF side table)\n"); 6074 } 6075 return; 6076 } 6077 6078 SDValue &N = NodeMap[Address]; 6079 if (!N.getNode() && isa<Argument>(Address)) 6080 // Check unused arguments map. 6081 N = UnusedArgNodeMap[Address]; 6082 SDDbgValue *SDV; 6083 if (N.getNode()) { 6084 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6085 Address = BCI->getOperand(0); 6086 // Parameters are handled specially. 6087 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6088 if (isParameter && FINode) { 6089 // Byval parameter. We have a frame index at this point. 6090 SDV = 6091 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6092 /*IsIndirect*/ true, dl, SDNodeOrder); 6093 } else if (isa<Argument>(Address)) { 6094 // Address is an argument, so try to emit its dbg value using 6095 // virtual register info from the FuncInfo.ValueMap. 6096 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6097 return; 6098 } else { 6099 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6100 true, dl, SDNodeOrder); 6101 } 6102 DAG.AddDbgValue(SDV, isParameter); 6103 } else { 6104 // If Address is an argument then try to emit its dbg value using 6105 // virtual register info from the FuncInfo.ValueMap. 6106 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6107 N)) { 6108 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6109 << " (could not emit func-arg dbg_value)\n"); 6110 } 6111 } 6112 return; 6113 } 6114 case Intrinsic::dbg_label: { 6115 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6116 DILabel *Label = DI.getLabel(); 6117 assert(Label && "Missing label"); 6118 6119 SDDbgLabel *SDV; 6120 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6121 DAG.AddDbgLabel(SDV); 6122 return; 6123 } 6124 case Intrinsic::dbg_value: { 6125 const DbgValueInst &DI = cast<DbgValueInst>(I); 6126 assert(DI.getVariable() && "Missing variable"); 6127 6128 DILocalVariable *Variable = DI.getVariable(); 6129 DIExpression *Expression = DI.getExpression(); 6130 dropDanglingDebugInfo(Variable, Expression); 6131 SmallVector<Value *, 4> Values(DI.getValues()); 6132 if (Values.empty()) 6133 return; 6134 6135 if (std::count(Values.begin(), Values.end(), nullptr)) 6136 return; 6137 6138 bool IsVariadic = DI.hasArgList(); 6139 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6140 SDNodeOrder, IsVariadic)) 6141 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6142 return; 6143 } 6144 6145 case Intrinsic::eh_typeid_for: { 6146 // Find the type id for the given typeinfo. 6147 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6148 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6149 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6150 setValue(&I, Res); 6151 return; 6152 } 6153 6154 case Intrinsic::eh_return_i32: 6155 case Intrinsic::eh_return_i64: 6156 DAG.getMachineFunction().setCallsEHReturn(true); 6157 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6158 MVT::Other, 6159 getControlRoot(), 6160 getValue(I.getArgOperand(0)), 6161 getValue(I.getArgOperand(1)))); 6162 return; 6163 case Intrinsic::eh_unwind_init: 6164 DAG.getMachineFunction().setCallsUnwindInit(true); 6165 return; 6166 case Intrinsic::eh_dwarf_cfa: 6167 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6168 TLI.getPointerTy(DAG.getDataLayout()), 6169 getValue(I.getArgOperand(0)))); 6170 return; 6171 case Intrinsic::eh_sjlj_callsite: { 6172 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6173 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6174 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6175 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6176 6177 MMI.setCurrentCallSite(CI->getZExtValue()); 6178 return; 6179 } 6180 case Intrinsic::eh_sjlj_functioncontext: { 6181 // Get and store the index of the function context. 6182 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6183 AllocaInst *FnCtx = 6184 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6185 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6186 MFI.setFunctionContextIndex(FI); 6187 return; 6188 } 6189 case Intrinsic::eh_sjlj_setjmp: { 6190 SDValue Ops[2]; 6191 Ops[0] = getRoot(); 6192 Ops[1] = getValue(I.getArgOperand(0)); 6193 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6194 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6195 setValue(&I, Op.getValue(0)); 6196 DAG.setRoot(Op.getValue(1)); 6197 return; 6198 } 6199 case Intrinsic::eh_sjlj_longjmp: 6200 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6201 getRoot(), getValue(I.getArgOperand(0)))); 6202 return; 6203 case Intrinsic::eh_sjlj_setup_dispatch: 6204 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6205 getRoot())); 6206 return; 6207 case Intrinsic::masked_gather: 6208 visitMaskedGather(I); 6209 return; 6210 case Intrinsic::masked_load: 6211 visitMaskedLoad(I); 6212 return; 6213 case Intrinsic::masked_scatter: 6214 visitMaskedScatter(I); 6215 return; 6216 case Intrinsic::masked_store: 6217 visitMaskedStore(I); 6218 return; 6219 case Intrinsic::masked_expandload: 6220 visitMaskedLoad(I, true /* IsExpanding */); 6221 return; 6222 case Intrinsic::masked_compressstore: 6223 visitMaskedStore(I, true /* IsCompressing */); 6224 return; 6225 case Intrinsic::powi: 6226 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6227 getValue(I.getArgOperand(1)), DAG)); 6228 return; 6229 case Intrinsic::log: 6230 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6231 return; 6232 case Intrinsic::log2: 6233 setValue(&I, 6234 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6235 return; 6236 case Intrinsic::log10: 6237 setValue(&I, 6238 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6239 return; 6240 case Intrinsic::exp: 6241 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6242 return; 6243 case Intrinsic::exp2: 6244 setValue(&I, 6245 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6246 return; 6247 case Intrinsic::pow: 6248 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6249 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6250 return; 6251 case Intrinsic::sqrt: 6252 case Intrinsic::fabs: 6253 case Intrinsic::sin: 6254 case Intrinsic::cos: 6255 case Intrinsic::floor: 6256 case Intrinsic::ceil: 6257 case Intrinsic::trunc: 6258 case Intrinsic::rint: 6259 case Intrinsic::nearbyint: 6260 case Intrinsic::round: 6261 case Intrinsic::roundeven: 6262 case Intrinsic::canonicalize: { 6263 unsigned Opcode; 6264 switch (Intrinsic) { 6265 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6266 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6267 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6268 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6269 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6270 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6271 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6272 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6273 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6274 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6275 case Intrinsic::round: Opcode = ISD::FROUND; break; 6276 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6277 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6278 } 6279 6280 setValue(&I, DAG.getNode(Opcode, sdl, 6281 getValue(I.getArgOperand(0)).getValueType(), 6282 getValue(I.getArgOperand(0)), Flags)); 6283 return; 6284 } 6285 case Intrinsic::lround: 6286 case Intrinsic::llround: 6287 case Intrinsic::lrint: 6288 case Intrinsic::llrint: { 6289 unsigned Opcode; 6290 switch (Intrinsic) { 6291 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6292 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6293 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6294 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6295 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6296 } 6297 6298 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6299 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6300 getValue(I.getArgOperand(0)))); 6301 return; 6302 } 6303 case Intrinsic::minnum: 6304 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6305 getValue(I.getArgOperand(0)).getValueType(), 6306 getValue(I.getArgOperand(0)), 6307 getValue(I.getArgOperand(1)), Flags)); 6308 return; 6309 case Intrinsic::maxnum: 6310 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6311 getValue(I.getArgOperand(0)).getValueType(), 6312 getValue(I.getArgOperand(0)), 6313 getValue(I.getArgOperand(1)), Flags)); 6314 return; 6315 case Intrinsic::minimum: 6316 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6317 getValue(I.getArgOperand(0)).getValueType(), 6318 getValue(I.getArgOperand(0)), 6319 getValue(I.getArgOperand(1)), Flags)); 6320 return; 6321 case Intrinsic::maximum: 6322 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6323 getValue(I.getArgOperand(0)).getValueType(), 6324 getValue(I.getArgOperand(0)), 6325 getValue(I.getArgOperand(1)), Flags)); 6326 return; 6327 case Intrinsic::copysign: 6328 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6329 getValue(I.getArgOperand(0)).getValueType(), 6330 getValue(I.getArgOperand(0)), 6331 getValue(I.getArgOperand(1)), Flags)); 6332 return; 6333 case Intrinsic::arithmetic_fence: { 6334 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6335 getValue(I.getArgOperand(0)).getValueType(), 6336 getValue(I.getArgOperand(0)), Flags)); 6337 return; 6338 } 6339 case Intrinsic::fma: 6340 setValue(&I, DAG.getNode( 6341 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6342 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6343 getValue(I.getArgOperand(2)), Flags)); 6344 return; 6345 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6346 case Intrinsic::INTRINSIC: 6347 #include "llvm/IR/ConstrainedOps.def" 6348 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6349 return; 6350 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6351 #include "llvm/IR/VPIntrinsics.def" 6352 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6353 return; 6354 case Intrinsic::fmuladd: { 6355 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6356 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6357 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6358 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6359 getValue(I.getArgOperand(0)).getValueType(), 6360 getValue(I.getArgOperand(0)), 6361 getValue(I.getArgOperand(1)), 6362 getValue(I.getArgOperand(2)), Flags)); 6363 } else { 6364 // TODO: Intrinsic calls should have fast-math-flags. 6365 SDValue Mul = DAG.getNode( 6366 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6367 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6368 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6369 getValue(I.getArgOperand(0)).getValueType(), 6370 Mul, getValue(I.getArgOperand(2)), Flags); 6371 setValue(&I, Add); 6372 } 6373 return; 6374 } 6375 case Intrinsic::convert_to_fp16: 6376 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6377 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6378 getValue(I.getArgOperand(0)), 6379 DAG.getTargetConstant(0, sdl, 6380 MVT::i32)))); 6381 return; 6382 case Intrinsic::convert_from_fp16: 6383 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6384 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6385 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6386 getValue(I.getArgOperand(0))))); 6387 return; 6388 case Intrinsic::fptosi_sat: { 6389 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6390 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6391 getValue(I.getArgOperand(0)), 6392 DAG.getValueType(VT.getScalarType()))); 6393 return; 6394 } 6395 case Intrinsic::fptoui_sat: { 6396 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6397 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6398 getValue(I.getArgOperand(0)), 6399 DAG.getValueType(VT.getScalarType()))); 6400 return; 6401 } 6402 case Intrinsic::set_rounding: 6403 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6404 {getRoot(), getValue(I.getArgOperand(0))}); 6405 setValue(&I, Res); 6406 DAG.setRoot(Res.getValue(0)); 6407 return; 6408 case Intrinsic::pcmarker: { 6409 SDValue Tmp = getValue(I.getArgOperand(0)); 6410 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6411 return; 6412 } 6413 case Intrinsic::isnan: { 6414 const DataLayout DLayout = DAG.getDataLayout(); 6415 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6416 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6417 MachineFunction &MF = DAG.getMachineFunction(); 6418 const Function &F = MF.getFunction(); 6419 SDValue Op = getValue(I.getArgOperand(0)); 6420 SDNodeFlags Flags; 6421 Flags.setNoFPExcept( 6422 !F.getAttributes().hasFnAttribute(llvm::Attribute::StrictFP)); 6423 6424 // If ISD::ISNAN should be expanded, do it right now, because the expansion 6425 // can use illegal types. Making expansion early allows to legalize these 6426 // types prior to selection. 6427 if (!TLI.isOperationLegalOrCustom(ISD::ISNAN, ArgVT)) { 6428 SDValue Result = TLI.expandISNAN(DestVT, Op, Flags, sdl, DAG); 6429 setValue(&I, Result); 6430 return; 6431 } 6432 6433 SDValue V = DAG.getNode(ISD::ISNAN, sdl, DestVT, Op, Flags); 6434 setValue(&I, V); 6435 return; 6436 } 6437 case Intrinsic::readcyclecounter: { 6438 SDValue Op = getRoot(); 6439 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6440 DAG.getVTList(MVT::i64, MVT::Other), Op); 6441 setValue(&I, Res); 6442 DAG.setRoot(Res.getValue(1)); 6443 return; 6444 } 6445 case Intrinsic::bitreverse: 6446 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6447 getValue(I.getArgOperand(0)).getValueType(), 6448 getValue(I.getArgOperand(0)))); 6449 return; 6450 case Intrinsic::bswap: 6451 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6452 getValue(I.getArgOperand(0)).getValueType(), 6453 getValue(I.getArgOperand(0)))); 6454 return; 6455 case Intrinsic::cttz: { 6456 SDValue Arg = getValue(I.getArgOperand(0)); 6457 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6458 EVT Ty = Arg.getValueType(); 6459 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6460 sdl, Ty, Arg)); 6461 return; 6462 } 6463 case Intrinsic::ctlz: { 6464 SDValue Arg = getValue(I.getArgOperand(0)); 6465 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6466 EVT Ty = Arg.getValueType(); 6467 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6468 sdl, Ty, Arg)); 6469 return; 6470 } 6471 case Intrinsic::ctpop: { 6472 SDValue Arg = getValue(I.getArgOperand(0)); 6473 EVT Ty = Arg.getValueType(); 6474 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6475 return; 6476 } 6477 case Intrinsic::fshl: 6478 case Intrinsic::fshr: { 6479 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6480 SDValue X = getValue(I.getArgOperand(0)); 6481 SDValue Y = getValue(I.getArgOperand(1)); 6482 SDValue Z = getValue(I.getArgOperand(2)); 6483 EVT VT = X.getValueType(); 6484 6485 if (X == Y) { 6486 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6487 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6488 } else { 6489 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6490 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6491 } 6492 return; 6493 } 6494 case Intrinsic::sadd_sat: { 6495 SDValue Op1 = getValue(I.getArgOperand(0)); 6496 SDValue Op2 = getValue(I.getArgOperand(1)); 6497 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6498 return; 6499 } 6500 case Intrinsic::uadd_sat: { 6501 SDValue Op1 = getValue(I.getArgOperand(0)); 6502 SDValue Op2 = getValue(I.getArgOperand(1)); 6503 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6504 return; 6505 } 6506 case Intrinsic::ssub_sat: { 6507 SDValue Op1 = getValue(I.getArgOperand(0)); 6508 SDValue Op2 = getValue(I.getArgOperand(1)); 6509 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6510 return; 6511 } 6512 case Intrinsic::usub_sat: { 6513 SDValue Op1 = getValue(I.getArgOperand(0)); 6514 SDValue Op2 = getValue(I.getArgOperand(1)); 6515 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6516 return; 6517 } 6518 case Intrinsic::sshl_sat: { 6519 SDValue Op1 = getValue(I.getArgOperand(0)); 6520 SDValue Op2 = getValue(I.getArgOperand(1)); 6521 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6522 return; 6523 } 6524 case Intrinsic::ushl_sat: { 6525 SDValue Op1 = getValue(I.getArgOperand(0)); 6526 SDValue Op2 = getValue(I.getArgOperand(1)); 6527 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6528 return; 6529 } 6530 case Intrinsic::smul_fix: 6531 case Intrinsic::umul_fix: 6532 case Intrinsic::smul_fix_sat: 6533 case Intrinsic::umul_fix_sat: { 6534 SDValue Op1 = getValue(I.getArgOperand(0)); 6535 SDValue Op2 = getValue(I.getArgOperand(1)); 6536 SDValue Op3 = getValue(I.getArgOperand(2)); 6537 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6538 Op1.getValueType(), Op1, Op2, Op3)); 6539 return; 6540 } 6541 case Intrinsic::sdiv_fix: 6542 case Intrinsic::udiv_fix: 6543 case Intrinsic::sdiv_fix_sat: 6544 case Intrinsic::udiv_fix_sat: { 6545 SDValue Op1 = getValue(I.getArgOperand(0)); 6546 SDValue Op2 = getValue(I.getArgOperand(1)); 6547 SDValue Op3 = getValue(I.getArgOperand(2)); 6548 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6549 Op1, Op2, Op3, DAG, TLI)); 6550 return; 6551 } 6552 case Intrinsic::smax: { 6553 SDValue Op1 = getValue(I.getArgOperand(0)); 6554 SDValue Op2 = getValue(I.getArgOperand(1)); 6555 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6556 return; 6557 } 6558 case Intrinsic::smin: { 6559 SDValue Op1 = getValue(I.getArgOperand(0)); 6560 SDValue Op2 = getValue(I.getArgOperand(1)); 6561 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6562 return; 6563 } 6564 case Intrinsic::umax: { 6565 SDValue Op1 = getValue(I.getArgOperand(0)); 6566 SDValue Op2 = getValue(I.getArgOperand(1)); 6567 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6568 return; 6569 } 6570 case Intrinsic::umin: { 6571 SDValue Op1 = getValue(I.getArgOperand(0)); 6572 SDValue Op2 = getValue(I.getArgOperand(1)); 6573 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6574 return; 6575 } 6576 case Intrinsic::abs: { 6577 // TODO: Preserve "int min is poison" arg in SDAG? 6578 SDValue Op1 = getValue(I.getArgOperand(0)); 6579 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6580 return; 6581 } 6582 case Intrinsic::stacksave: { 6583 SDValue Op = getRoot(); 6584 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6585 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6586 setValue(&I, Res); 6587 DAG.setRoot(Res.getValue(1)); 6588 return; 6589 } 6590 case Intrinsic::stackrestore: 6591 Res = getValue(I.getArgOperand(0)); 6592 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6593 return; 6594 case Intrinsic::get_dynamic_area_offset: { 6595 SDValue Op = getRoot(); 6596 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6597 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6598 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6599 // target. 6600 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6601 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6602 " intrinsic!"); 6603 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6604 Op); 6605 DAG.setRoot(Op); 6606 setValue(&I, Res); 6607 return; 6608 } 6609 case Intrinsic::stackguard: { 6610 MachineFunction &MF = DAG.getMachineFunction(); 6611 const Module &M = *MF.getFunction().getParent(); 6612 SDValue Chain = getRoot(); 6613 if (TLI.useLoadStackGuardNode()) { 6614 Res = getLoadStackGuard(DAG, sdl, Chain); 6615 } else { 6616 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6617 const Value *Global = TLI.getSDagStackGuard(M); 6618 Align Align = DL->getPrefTypeAlign(Global->getType()); 6619 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6620 MachinePointerInfo(Global, 0), Align, 6621 MachineMemOperand::MOVolatile); 6622 } 6623 if (TLI.useStackGuardXorFP()) 6624 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6625 DAG.setRoot(Chain); 6626 setValue(&I, Res); 6627 return; 6628 } 6629 case Intrinsic::stackprotector: { 6630 // Emit code into the DAG to store the stack guard onto the stack. 6631 MachineFunction &MF = DAG.getMachineFunction(); 6632 MachineFrameInfo &MFI = MF.getFrameInfo(); 6633 SDValue Src, Chain = getRoot(); 6634 6635 if (TLI.useLoadStackGuardNode()) 6636 Src = getLoadStackGuard(DAG, sdl, Chain); 6637 else 6638 Src = getValue(I.getArgOperand(0)); // The guard's value. 6639 6640 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6641 6642 int FI = FuncInfo.StaticAllocaMap[Slot]; 6643 MFI.setStackProtectorIndex(FI); 6644 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6645 6646 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6647 6648 // Store the stack protector onto the stack. 6649 Res = DAG.getStore( 6650 Chain, sdl, Src, FIN, 6651 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6652 MaybeAlign(), MachineMemOperand::MOVolatile); 6653 setValue(&I, Res); 6654 DAG.setRoot(Res); 6655 return; 6656 } 6657 case Intrinsic::objectsize: 6658 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6659 6660 case Intrinsic::is_constant: 6661 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6662 6663 case Intrinsic::annotation: 6664 case Intrinsic::ptr_annotation: 6665 case Intrinsic::launder_invariant_group: 6666 case Intrinsic::strip_invariant_group: 6667 // Drop the intrinsic, but forward the value 6668 setValue(&I, getValue(I.getOperand(0))); 6669 return; 6670 6671 case Intrinsic::assume: 6672 case Intrinsic::experimental_noalias_scope_decl: 6673 case Intrinsic::var_annotation: 6674 case Intrinsic::sideeffect: 6675 // Discard annotate attributes, noalias scope declarations, assumptions, and 6676 // artificial side-effects. 6677 return; 6678 6679 case Intrinsic::codeview_annotation: { 6680 // Emit a label associated with this metadata. 6681 MachineFunction &MF = DAG.getMachineFunction(); 6682 MCSymbol *Label = 6683 MF.getMMI().getContext().createTempSymbol("annotation", true); 6684 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6685 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6686 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6687 DAG.setRoot(Res); 6688 return; 6689 } 6690 6691 case Intrinsic::init_trampoline: { 6692 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6693 6694 SDValue Ops[6]; 6695 Ops[0] = getRoot(); 6696 Ops[1] = getValue(I.getArgOperand(0)); 6697 Ops[2] = getValue(I.getArgOperand(1)); 6698 Ops[3] = getValue(I.getArgOperand(2)); 6699 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6700 Ops[5] = DAG.getSrcValue(F); 6701 6702 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6703 6704 DAG.setRoot(Res); 6705 return; 6706 } 6707 case Intrinsic::adjust_trampoline: 6708 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6709 TLI.getPointerTy(DAG.getDataLayout()), 6710 getValue(I.getArgOperand(0)))); 6711 return; 6712 case Intrinsic::gcroot: { 6713 assert(DAG.getMachineFunction().getFunction().hasGC() && 6714 "only valid in functions with gc specified, enforced by Verifier"); 6715 assert(GFI && "implied by previous"); 6716 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6717 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6718 6719 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6720 GFI->addStackRoot(FI->getIndex(), TypeMap); 6721 return; 6722 } 6723 case Intrinsic::gcread: 6724 case Intrinsic::gcwrite: 6725 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6726 case Intrinsic::flt_rounds: 6727 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6728 setValue(&I, Res); 6729 DAG.setRoot(Res.getValue(1)); 6730 return; 6731 6732 case Intrinsic::expect: 6733 // Just replace __builtin_expect(exp, c) with EXP. 6734 setValue(&I, getValue(I.getArgOperand(0))); 6735 return; 6736 6737 case Intrinsic::ubsantrap: 6738 case Intrinsic::debugtrap: 6739 case Intrinsic::trap: { 6740 StringRef TrapFuncName = 6741 I.getAttributes() 6742 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6743 .getValueAsString(); 6744 if (TrapFuncName.empty()) { 6745 switch (Intrinsic) { 6746 case Intrinsic::trap: 6747 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6748 break; 6749 case Intrinsic::debugtrap: 6750 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6751 break; 6752 case Intrinsic::ubsantrap: 6753 DAG.setRoot(DAG.getNode( 6754 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6755 DAG.getTargetConstant( 6756 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6757 MVT::i32))); 6758 break; 6759 default: llvm_unreachable("unknown trap intrinsic"); 6760 } 6761 return; 6762 } 6763 TargetLowering::ArgListTy Args; 6764 if (Intrinsic == Intrinsic::ubsantrap) { 6765 Args.push_back(TargetLoweringBase::ArgListEntry()); 6766 Args[0].Val = I.getArgOperand(0); 6767 Args[0].Node = getValue(Args[0].Val); 6768 Args[0].Ty = Args[0].Val->getType(); 6769 } 6770 6771 TargetLowering::CallLoweringInfo CLI(DAG); 6772 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6773 CallingConv::C, I.getType(), 6774 DAG.getExternalSymbol(TrapFuncName.data(), 6775 TLI.getPointerTy(DAG.getDataLayout())), 6776 std::move(Args)); 6777 6778 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6779 DAG.setRoot(Result.second); 6780 return; 6781 } 6782 6783 case Intrinsic::uadd_with_overflow: 6784 case Intrinsic::sadd_with_overflow: 6785 case Intrinsic::usub_with_overflow: 6786 case Intrinsic::ssub_with_overflow: 6787 case Intrinsic::umul_with_overflow: 6788 case Intrinsic::smul_with_overflow: { 6789 ISD::NodeType Op; 6790 switch (Intrinsic) { 6791 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6792 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6793 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6794 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6795 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6796 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6797 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6798 } 6799 SDValue Op1 = getValue(I.getArgOperand(0)); 6800 SDValue Op2 = getValue(I.getArgOperand(1)); 6801 6802 EVT ResultVT = Op1.getValueType(); 6803 EVT OverflowVT = MVT::i1; 6804 if (ResultVT.isVector()) 6805 OverflowVT = EVT::getVectorVT( 6806 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6807 6808 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6809 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6810 return; 6811 } 6812 case Intrinsic::prefetch: { 6813 SDValue Ops[5]; 6814 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6815 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6816 Ops[0] = DAG.getRoot(); 6817 Ops[1] = getValue(I.getArgOperand(0)); 6818 Ops[2] = getValue(I.getArgOperand(1)); 6819 Ops[3] = getValue(I.getArgOperand(2)); 6820 Ops[4] = getValue(I.getArgOperand(3)); 6821 SDValue Result = DAG.getMemIntrinsicNode( 6822 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6823 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6824 /* align */ None, Flags); 6825 6826 // Chain the prefetch in parallell with any pending loads, to stay out of 6827 // the way of later optimizations. 6828 PendingLoads.push_back(Result); 6829 Result = getRoot(); 6830 DAG.setRoot(Result); 6831 return; 6832 } 6833 case Intrinsic::lifetime_start: 6834 case Intrinsic::lifetime_end: { 6835 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6836 // Stack coloring is not enabled in O0, discard region information. 6837 if (TM.getOptLevel() == CodeGenOpt::None) 6838 return; 6839 6840 const int64_t ObjectSize = 6841 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6842 Value *const ObjectPtr = I.getArgOperand(1); 6843 SmallVector<const Value *, 4> Allocas; 6844 getUnderlyingObjects(ObjectPtr, Allocas); 6845 6846 for (const Value *Alloca : Allocas) { 6847 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6848 6849 // Could not find an Alloca. 6850 if (!LifetimeObject) 6851 continue; 6852 6853 // First check that the Alloca is static, otherwise it won't have a 6854 // valid frame index. 6855 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6856 if (SI == FuncInfo.StaticAllocaMap.end()) 6857 return; 6858 6859 const int FrameIndex = SI->second; 6860 int64_t Offset; 6861 if (GetPointerBaseWithConstantOffset( 6862 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6863 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6864 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6865 Offset); 6866 DAG.setRoot(Res); 6867 } 6868 return; 6869 } 6870 case Intrinsic::pseudoprobe: { 6871 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6872 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6873 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6874 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6875 DAG.setRoot(Res); 6876 return; 6877 } 6878 case Intrinsic::invariant_start: 6879 // Discard region information. 6880 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6881 return; 6882 case Intrinsic::invariant_end: 6883 // Discard region information. 6884 return; 6885 case Intrinsic::clear_cache: 6886 /// FunctionName may be null. 6887 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6888 lowerCallToExternalSymbol(I, FunctionName); 6889 return; 6890 case Intrinsic::donothing: 6891 case Intrinsic::seh_try_begin: 6892 case Intrinsic::seh_scope_begin: 6893 case Intrinsic::seh_try_end: 6894 case Intrinsic::seh_scope_end: 6895 // ignore 6896 return; 6897 case Intrinsic::experimental_stackmap: 6898 visitStackmap(I); 6899 return; 6900 case Intrinsic::experimental_patchpoint_void: 6901 case Intrinsic::experimental_patchpoint_i64: 6902 visitPatchpoint(I); 6903 return; 6904 case Intrinsic::experimental_gc_statepoint: 6905 LowerStatepoint(cast<GCStatepointInst>(I)); 6906 return; 6907 case Intrinsic::experimental_gc_result: 6908 visitGCResult(cast<GCResultInst>(I)); 6909 return; 6910 case Intrinsic::experimental_gc_relocate: 6911 visitGCRelocate(cast<GCRelocateInst>(I)); 6912 return; 6913 case Intrinsic::instrprof_increment: 6914 llvm_unreachable("instrprof failed to lower an increment"); 6915 case Intrinsic::instrprof_value_profile: 6916 llvm_unreachable("instrprof failed to lower a value profiling call"); 6917 case Intrinsic::localescape: { 6918 MachineFunction &MF = DAG.getMachineFunction(); 6919 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6920 6921 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6922 // is the same on all targets. 6923 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6924 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6925 if (isa<ConstantPointerNull>(Arg)) 6926 continue; // Skip null pointers. They represent a hole in index space. 6927 AllocaInst *Slot = cast<AllocaInst>(Arg); 6928 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6929 "can only escape static allocas"); 6930 int FI = FuncInfo.StaticAllocaMap[Slot]; 6931 MCSymbol *FrameAllocSym = 6932 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6933 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6934 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6935 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6936 .addSym(FrameAllocSym) 6937 .addFrameIndex(FI); 6938 } 6939 6940 return; 6941 } 6942 6943 case Intrinsic::localrecover: { 6944 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6945 MachineFunction &MF = DAG.getMachineFunction(); 6946 6947 // Get the symbol that defines the frame offset. 6948 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6949 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6950 unsigned IdxVal = 6951 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6952 MCSymbol *FrameAllocSym = 6953 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6954 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6955 6956 Value *FP = I.getArgOperand(1); 6957 SDValue FPVal = getValue(FP); 6958 EVT PtrVT = FPVal.getValueType(); 6959 6960 // Create a MCSymbol for the label to avoid any target lowering 6961 // that would make this PC relative. 6962 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6963 SDValue OffsetVal = 6964 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6965 6966 // Add the offset to the FP. 6967 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6968 setValue(&I, Add); 6969 6970 return; 6971 } 6972 6973 case Intrinsic::eh_exceptionpointer: 6974 case Intrinsic::eh_exceptioncode: { 6975 // Get the exception pointer vreg, copy from it, and resize it to fit. 6976 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6977 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6978 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6979 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6980 SDValue N = 6981 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6982 if (Intrinsic == Intrinsic::eh_exceptioncode) 6983 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6984 setValue(&I, N); 6985 return; 6986 } 6987 case Intrinsic::xray_customevent: { 6988 // Here we want to make sure that the intrinsic behaves as if it has a 6989 // specific calling convention, and only for x86_64. 6990 // FIXME: Support other platforms later. 6991 const auto &Triple = DAG.getTarget().getTargetTriple(); 6992 if (Triple.getArch() != Triple::x86_64) 6993 return; 6994 6995 SDLoc DL = getCurSDLoc(); 6996 SmallVector<SDValue, 8> Ops; 6997 6998 // We want to say that we always want the arguments in registers. 6999 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7000 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7001 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7002 SDValue Chain = getRoot(); 7003 Ops.push_back(LogEntryVal); 7004 Ops.push_back(StrSizeVal); 7005 Ops.push_back(Chain); 7006 7007 // We need to enforce the calling convention for the callsite, so that 7008 // argument ordering is enforced correctly, and that register allocation can 7009 // see that some registers may be assumed clobbered and have to preserve 7010 // them across calls to the intrinsic. 7011 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7012 DL, NodeTys, Ops); 7013 SDValue patchableNode = SDValue(MN, 0); 7014 DAG.setRoot(patchableNode); 7015 setValue(&I, patchableNode); 7016 return; 7017 } 7018 case Intrinsic::xray_typedevent: { 7019 // Here we want to make sure that the intrinsic behaves as if it has a 7020 // specific calling convention, and only for x86_64. 7021 // FIXME: Support other platforms later. 7022 const auto &Triple = DAG.getTarget().getTargetTriple(); 7023 if (Triple.getArch() != Triple::x86_64) 7024 return; 7025 7026 SDLoc DL = getCurSDLoc(); 7027 SmallVector<SDValue, 8> Ops; 7028 7029 // We want to say that we always want the arguments in registers. 7030 // It's unclear to me how manipulating the selection DAG here forces callers 7031 // to provide arguments in registers instead of on the stack. 7032 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7033 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7034 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7035 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7036 SDValue Chain = getRoot(); 7037 Ops.push_back(LogTypeId); 7038 Ops.push_back(LogEntryVal); 7039 Ops.push_back(StrSizeVal); 7040 Ops.push_back(Chain); 7041 7042 // We need to enforce the calling convention for the callsite, so that 7043 // argument ordering is enforced correctly, and that register allocation can 7044 // see that some registers may be assumed clobbered and have to preserve 7045 // them across calls to the intrinsic. 7046 MachineSDNode *MN = DAG.getMachineNode( 7047 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 7048 SDValue patchableNode = SDValue(MN, 0); 7049 DAG.setRoot(patchableNode); 7050 setValue(&I, patchableNode); 7051 return; 7052 } 7053 case Intrinsic::experimental_deoptimize: 7054 LowerDeoptimizeCall(&I); 7055 return; 7056 case Intrinsic::experimental_stepvector: 7057 visitStepVector(I); 7058 return; 7059 case Intrinsic::vector_reduce_fadd: 7060 case Intrinsic::vector_reduce_fmul: 7061 case Intrinsic::vector_reduce_add: 7062 case Intrinsic::vector_reduce_mul: 7063 case Intrinsic::vector_reduce_and: 7064 case Intrinsic::vector_reduce_or: 7065 case Intrinsic::vector_reduce_xor: 7066 case Intrinsic::vector_reduce_smax: 7067 case Intrinsic::vector_reduce_smin: 7068 case Intrinsic::vector_reduce_umax: 7069 case Intrinsic::vector_reduce_umin: 7070 case Intrinsic::vector_reduce_fmax: 7071 case Intrinsic::vector_reduce_fmin: 7072 visitVectorReduce(I, Intrinsic); 7073 return; 7074 7075 case Intrinsic::icall_branch_funnel: { 7076 SmallVector<SDValue, 16> Ops; 7077 Ops.push_back(getValue(I.getArgOperand(0))); 7078 7079 int64_t Offset; 7080 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7081 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7082 if (!Base) 7083 report_fatal_error( 7084 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7085 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 7086 7087 struct BranchFunnelTarget { 7088 int64_t Offset; 7089 SDValue Target; 7090 }; 7091 SmallVector<BranchFunnelTarget, 8> Targets; 7092 7093 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 7094 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7095 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7096 if (ElemBase != Base) 7097 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7098 "to the same GlobalValue"); 7099 7100 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7101 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7102 if (!GA) 7103 report_fatal_error( 7104 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7105 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7106 GA->getGlobal(), getCurSDLoc(), 7107 Val.getValueType(), GA->getOffset())}); 7108 } 7109 llvm::sort(Targets, 7110 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7111 return T1.Offset < T2.Offset; 7112 }); 7113 7114 for (auto &T : Targets) { 7115 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 7116 Ops.push_back(T.Target); 7117 } 7118 7119 Ops.push_back(DAG.getRoot()); // Chain 7120 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 7121 getCurSDLoc(), MVT::Other, Ops), 7122 0); 7123 DAG.setRoot(N); 7124 setValue(&I, N); 7125 HasTailCall = true; 7126 return; 7127 } 7128 7129 case Intrinsic::wasm_landingpad_index: 7130 // Information this intrinsic contained has been transferred to 7131 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7132 // delete it now. 7133 return; 7134 7135 case Intrinsic::aarch64_settag: 7136 case Intrinsic::aarch64_settag_zero: { 7137 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7138 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7139 SDValue Val = TSI.EmitTargetCodeForSetTag( 7140 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 7141 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7142 ZeroMemory); 7143 DAG.setRoot(Val); 7144 setValue(&I, Val); 7145 return; 7146 } 7147 case Intrinsic::ptrmask: { 7148 SDValue Ptr = getValue(I.getOperand(0)); 7149 SDValue Const = getValue(I.getOperand(1)); 7150 7151 EVT PtrVT = Ptr.getValueType(); 7152 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 7153 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 7154 return; 7155 } 7156 case Intrinsic::get_active_lane_mask: { 7157 auto DL = getCurSDLoc(); 7158 SDValue Index = getValue(I.getOperand(0)); 7159 SDValue TripCount = getValue(I.getOperand(1)); 7160 Type *ElementTy = I.getOperand(0)->getType(); 7161 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7162 unsigned VecWidth = VT.getVectorNumElements(); 7163 7164 SmallVector<SDValue, 16> OpsTripCount; 7165 SmallVector<SDValue, 16> OpsIndex; 7166 SmallVector<SDValue, 16> OpsStepConstants; 7167 for (unsigned i = 0; i < VecWidth; i++) { 7168 OpsTripCount.push_back(TripCount); 7169 OpsIndex.push_back(Index); 7170 OpsStepConstants.push_back( 7171 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 7172 } 7173 7174 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 7175 7176 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 7177 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 7178 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 7179 SDValue VectorInduction = DAG.getNode( 7180 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 7181 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 7182 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 7183 VectorTripCount, ISD::CondCode::SETULT); 7184 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 7185 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 7186 SetCC)); 7187 return; 7188 } 7189 case Intrinsic::experimental_vector_insert: { 7190 auto DL = getCurSDLoc(); 7191 7192 SDValue Vec = getValue(I.getOperand(0)); 7193 SDValue SubVec = getValue(I.getOperand(1)); 7194 SDValue Index = getValue(I.getOperand(2)); 7195 7196 // The intrinsic's index type is i64, but the SDNode requires an index type 7197 // suitable for the target. Convert the index as required. 7198 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7199 if (Index.getValueType() != VectorIdxTy) 7200 Index = DAG.getVectorIdxConstant( 7201 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7202 7203 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7204 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec, 7205 Index)); 7206 return; 7207 } 7208 case Intrinsic::experimental_vector_extract: { 7209 auto DL = getCurSDLoc(); 7210 7211 SDValue Vec = getValue(I.getOperand(0)); 7212 SDValue Index = getValue(I.getOperand(1)); 7213 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7214 7215 // The intrinsic's index type is i64, but the SDNode requires an index type 7216 // suitable for the target. Convert the index as required. 7217 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7218 if (Index.getValueType() != VectorIdxTy) 7219 Index = DAG.getVectorIdxConstant( 7220 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7221 7222 setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index)); 7223 return; 7224 } 7225 case Intrinsic::experimental_vector_reverse: 7226 visitVectorReverse(I); 7227 return; 7228 case Intrinsic::experimental_vector_splice: 7229 visitVectorSplice(I); 7230 return; 7231 } 7232 } 7233 7234 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7235 const ConstrainedFPIntrinsic &FPI) { 7236 SDLoc sdl = getCurSDLoc(); 7237 7238 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7239 SmallVector<EVT, 4> ValueVTs; 7240 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7241 ValueVTs.push_back(MVT::Other); // Out chain 7242 7243 // We do not need to serialize constrained FP intrinsics against 7244 // each other or against (nonvolatile) loads, so they can be 7245 // chained like loads. 7246 SDValue Chain = DAG.getRoot(); 7247 SmallVector<SDValue, 4> Opers; 7248 Opers.push_back(Chain); 7249 if (FPI.isUnaryOp()) { 7250 Opers.push_back(getValue(FPI.getArgOperand(0))); 7251 } else if (FPI.isTernaryOp()) { 7252 Opers.push_back(getValue(FPI.getArgOperand(0))); 7253 Opers.push_back(getValue(FPI.getArgOperand(1))); 7254 Opers.push_back(getValue(FPI.getArgOperand(2))); 7255 } else { 7256 Opers.push_back(getValue(FPI.getArgOperand(0))); 7257 Opers.push_back(getValue(FPI.getArgOperand(1))); 7258 } 7259 7260 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7261 assert(Result.getNode()->getNumValues() == 2); 7262 7263 // Push node to the appropriate list so that future instructions can be 7264 // chained up correctly. 7265 SDValue OutChain = Result.getValue(1); 7266 switch (EB) { 7267 case fp::ExceptionBehavior::ebIgnore: 7268 // The only reason why ebIgnore nodes still need to be chained is that 7269 // they might depend on the current rounding mode, and therefore must 7270 // not be moved across instruction that may change that mode. 7271 LLVM_FALLTHROUGH; 7272 case fp::ExceptionBehavior::ebMayTrap: 7273 // These must not be moved across calls or instructions that may change 7274 // floating-point exception masks. 7275 PendingConstrainedFP.push_back(OutChain); 7276 break; 7277 case fp::ExceptionBehavior::ebStrict: 7278 // These must not be moved across calls or instructions that may change 7279 // floating-point exception masks or read floating-point exception flags. 7280 // In addition, they cannot be optimized out even if unused. 7281 PendingConstrainedFPStrict.push_back(OutChain); 7282 break; 7283 } 7284 }; 7285 7286 SDVTList VTs = DAG.getVTList(ValueVTs); 7287 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7288 7289 SDNodeFlags Flags; 7290 if (EB == fp::ExceptionBehavior::ebIgnore) 7291 Flags.setNoFPExcept(true); 7292 7293 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7294 Flags.copyFMF(*FPOp); 7295 7296 unsigned Opcode; 7297 switch (FPI.getIntrinsicID()) { 7298 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7299 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7300 case Intrinsic::INTRINSIC: \ 7301 Opcode = ISD::STRICT_##DAGN; \ 7302 break; 7303 #include "llvm/IR/ConstrainedOps.def" 7304 case Intrinsic::experimental_constrained_fmuladd: { 7305 Opcode = ISD::STRICT_FMA; 7306 // Break fmuladd into fmul and fadd. 7307 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7308 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7309 ValueVTs[0])) { 7310 Opers.pop_back(); 7311 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7312 pushOutChain(Mul, EB); 7313 Opcode = ISD::STRICT_FADD; 7314 Opers.clear(); 7315 Opers.push_back(Mul.getValue(1)); 7316 Opers.push_back(Mul.getValue(0)); 7317 Opers.push_back(getValue(FPI.getArgOperand(2))); 7318 } 7319 break; 7320 } 7321 } 7322 7323 // A few strict DAG nodes carry additional operands that are not 7324 // set up by the default code above. 7325 switch (Opcode) { 7326 default: break; 7327 case ISD::STRICT_FP_ROUND: 7328 Opers.push_back( 7329 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7330 break; 7331 case ISD::STRICT_FSETCC: 7332 case ISD::STRICT_FSETCCS: { 7333 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7334 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7335 if (TM.Options.NoNaNsFPMath) 7336 Condition = getFCmpCodeWithoutNaN(Condition); 7337 Opers.push_back(DAG.getCondCode(Condition)); 7338 break; 7339 } 7340 } 7341 7342 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7343 pushOutChain(Result, EB); 7344 7345 SDValue FPResult = Result.getValue(0); 7346 setValue(&FPI, FPResult); 7347 } 7348 7349 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7350 Optional<unsigned> ResOPC; 7351 switch (VPIntrin.getIntrinsicID()) { 7352 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN: 7353 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID; 7354 #define END_REGISTER_VP_INTRINSIC(...) break; 7355 #include "llvm/IR/VPIntrinsics.def" 7356 } 7357 7358 if (!ResOPC.hasValue()) 7359 llvm_unreachable( 7360 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7361 7362 return ResOPC.getValue(); 7363 } 7364 7365 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7366 const VPIntrinsic &VPIntrin) { 7367 SDLoc DL = getCurSDLoc(); 7368 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7369 7370 SmallVector<EVT, 4> ValueVTs; 7371 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7372 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7373 SDVTList VTs = DAG.getVTList(ValueVTs); 7374 7375 auto EVLParamPos = 7376 VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID()); 7377 7378 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7379 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7380 "Unexpected target EVL type"); 7381 7382 // Request operands. 7383 SmallVector<SDValue, 7> OpValues; 7384 for (unsigned I = 0; I < VPIntrin.getNumArgOperands(); ++I) { 7385 auto Op = getValue(VPIntrin.getArgOperand(I)); 7386 if (I == EVLParamPos) 7387 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7388 OpValues.push_back(Op); 7389 } 7390 7391 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7392 setValue(&VPIntrin, Result); 7393 } 7394 7395 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7396 const BasicBlock *EHPadBB, 7397 MCSymbol *&BeginLabel) { 7398 MachineFunction &MF = DAG.getMachineFunction(); 7399 MachineModuleInfo &MMI = MF.getMMI(); 7400 7401 // Insert a label before the invoke call to mark the try range. This can be 7402 // used to detect deletion of the invoke via the MachineModuleInfo. 7403 BeginLabel = MMI.getContext().createTempSymbol(); 7404 7405 // For SjLj, keep track of which landing pads go with which invokes 7406 // so as to maintain the ordering of pads in the LSDA. 7407 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7408 if (CallSiteIndex) { 7409 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7410 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7411 7412 // Now that the call site is handled, stop tracking it. 7413 MMI.setCurrentCallSite(0); 7414 } 7415 7416 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7417 } 7418 7419 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7420 const BasicBlock *EHPadBB, 7421 MCSymbol *BeginLabel) { 7422 assert(BeginLabel && "BeginLabel should've been set"); 7423 7424 MachineFunction &MF = DAG.getMachineFunction(); 7425 MachineModuleInfo &MMI = MF.getMMI(); 7426 7427 // Insert a label at the end of the invoke call to mark the try range. This 7428 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7429 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7430 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7431 7432 // Inform MachineModuleInfo of range. 7433 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7434 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7435 // actually use outlined funclets and their LSDA info style. 7436 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7437 assert(II && "II should've been set"); 7438 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7439 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7440 } else if (!isScopedEHPersonality(Pers)) { 7441 assert(EHPadBB); 7442 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7443 } 7444 7445 return Chain; 7446 } 7447 7448 std::pair<SDValue, SDValue> 7449 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7450 const BasicBlock *EHPadBB) { 7451 MCSymbol *BeginLabel = nullptr; 7452 7453 if (EHPadBB) { 7454 // Both PendingLoads and PendingExports must be flushed here; 7455 // this call might not return. 7456 (void)getRoot(); 7457 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7458 CLI.setChain(getRoot()); 7459 } 7460 7461 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7462 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7463 7464 assert((CLI.IsTailCall || Result.second.getNode()) && 7465 "Non-null chain expected with non-tail call!"); 7466 assert((Result.second.getNode() || !Result.first.getNode()) && 7467 "Null value expected with tail call!"); 7468 7469 if (!Result.second.getNode()) { 7470 // As a special case, a null chain means that a tail call has been emitted 7471 // and the DAG root is already updated. 7472 HasTailCall = true; 7473 7474 // Since there's no actual continuation from this block, nothing can be 7475 // relying on us setting vregs for them. 7476 PendingExports.clear(); 7477 } else { 7478 DAG.setRoot(Result.second); 7479 } 7480 7481 if (EHPadBB) { 7482 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7483 BeginLabel)); 7484 } 7485 7486 return Result; 7487 } 7488 7489 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7490 bool isTailCall, 7491 bool isMustTailCall, 7492 const BasicBlock *EHPadBB) { 7493 auto &DL = DAG.getDataLayout(); 7494 FunctionType *FTy = CB.getFunctionType(); 7495 Type *RetTy = CB.getType(); 7496 7497 TargetLowering::ArgListTy Args; 7498 Args.reserve(CB.arg_size()); 7499 7500 const Value *SwiftErrorVal = nullptr; 7501 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7502 7503 if (isTailCall) { 7504 // Avoid emitting tail calls in functions with the disable-tail-calls 7505 // attribute. 7506 auto *Caller = CB.getParent()->getParent(); 7507 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7508 "true" && !isMustTailCall) 7509 isTailCall = false; 7510 7511 // We can't tail call inside a function with a swifterror argument. Lowering 7512 // does not support this yet. It would have to move into the swifterror 7513 // register before the call. 7514 if (TLI.supportSwiftError() && 7515 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7516 isTailCall = false; 7517 } 7518 7519 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7520 TargetLowering::ArgListEntry Entry; 7521 const Value *V = *I; 7522 7523 // Skip empty types 7524 if (V->getType()->isEmptyTy()) 7525 continue; 7526 7527 SDValue ArgNode = getValue(V); 7528 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7529 7530 Entry.setAttributes(&CB, I - CB.arg_begin()); 7531 7532 // Use swifterror virtual register as input to the call. 7533 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7534 SwiftErrorVal = V; 7535 // We find the virtual register for the actual swifterror argument. 7536 // Instead of using the Value, we use the virtual register instead. 7537 Entry.Node = 7538 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7539 EVT(TLI.getPointerTy(DL))); 7540 } 7541 7542 Args.push_back(Entry); 7543 7544 // If we have an explicit sret argument that is an Instruction, (i.e., it 7545 // might point to function-local memory), we can't meaningfully tail-call. 7546 if (Entry.IsSRet && isa<Instruction>(V)) 7547 isTailCall = false; 7548 } 7549 7550 // If call site has a cfguardtarget operand bundle, create and add an 7551 // additional ArgListEntry. 7552 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7553 TargetLowering::ArgListEntry Entry; 7554 Value *V = Bundle->Inputs[0]; 7555 SDValue ArgNode = getValue(V); 7556 Entry.Node = ArgNode; 7557 Entry.Ty = V->getType(); 7558 Entry.IsCFGuardTarget = true; 7559 Args.push_back(Entry); 7560 } 7561 7562 // Check if target-independent constraints permit a tail call here. 7563 // Target-dependent constraints are checked within TLI->LowerCallTo. 7564 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7565 isTailCall = false; 7566 7567 // Disable tail calls if there is an swifterror argument. Targets have not 7568 // been updated to support tail calls. 7569 if (TLI.supportSwiftError() && SwiftErrorVal) 7570 isTailCall = false; 7571 7572 TargetLowering::CallLoweringInfo CLI(DAG); 7573 CLI.setDebugLoc(getCurSDLoc()) 7574 .setChain(getRoot()) 7575 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7576 .setTailCall(isTailCall) 7577 .setConvergent(CB.isConvergent()) 7578 .setIsPreallocated( 7579 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7580 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7581 7582 if (Result.first.getNode()) { 7583 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7584 setValue(&CB, Result.first); 7585 } 7586 7587 // The last element of CLI.InVals has the SDValue for swifterror return. 7588 // Here we copy it to a virtual register and update SwiftErrorMap for 7589 // book-keeping. 7590 if (SwiftErrorVal && TLI.supportSwiftError()) { 7591 // Get the last element of InVals. 7592 SDValue Src = CLI.InVals.back(); 7593 Register VReg = 7594 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7595 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7596 DAG.setRoot(CopyNode); 7597 } 7598 } 7599 7600 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7601 SelectionDAGBuilder &Builder) { 7602 // Check to see if this load can be trivially constant folded, e.g. if the 7603 // input is from a string literal. 7604 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7605 // Cast pointer to the type we really want to load. 7606 Type *LoadTy = 7607 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7608 if (LoadVT.isVector()) 7609 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7610 7611 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7612 PointerType::getUnqual(LoadTy)); 7613 7614 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7615 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7616 return Builder.getValue(LoadCst); 7617 } 7618 7619 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7620 // still constant memory, the input chain can be the entry node. 7621 SDValue Root; 7622 bool ConstantMemory = false; 7623 7624 // Do not serialize (non-volatile) loads of constant memory with anything. 7625 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7626 Root = Builder.DAG.getEntryNode(); 7627 ConstantMemory = true; 7628 } else { 7629 // Do not serialize non-volatile loads against each other. 7630 Root = Builder.DAG.getRoot(); 7631 } 7632 7633 SDValue Ptr = Builder.getValue(PtrVal); 7634 SDValue LoadVal = 7635 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7636 MachinePointerInfo(PtrVal), Align(1)); 7637 7638 if (!ConstantMemory) 7639 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7640 return LoadVal; 7641 } 7642 7643 /// Record the value for an instruction that produces an integer result, 7644 /// converting the type where necessary. 7645 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7646 SDValue Value, 7647 bool IsSigned) { 7648 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7649 I.getType(), true); 7650 if (IsSigned) 7651 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7652 else 7653 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7654 setValue(&I, Value); 7655 } 7656 7657 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7658 /// true and lower it. Otherwise return false, and it will be lowered like a 7659 /// normal call. 7660 /// The caller already checked that \p I calls the appropriate LibFunc with a 7661 /// correct prototype. 7662 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7663 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7664 const Value *Size = I.getArgOperand(2); 7665 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7666 if (CSize && CSize->getZExtValue() == 0) { 7667 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7668 I.getType(), true); 7669 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7670 return true; 7671 } 7672 7673 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7674 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7675 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7676 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7677 if (Res.first.getNode()) { 7678 processIntegerCallValue(I, Res.first, true); 7679 PendingLoads.push_back(Res.second); 7680 return true; 7681 } 7682 7683 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7684 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7685 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7686 return false; 7687 7688 // If the target has a fast compare for the given size, it will return a 7689 // preferred load type for that size. Require that the load VT is legal and 7690 // that the target supports unaligned loads of that type. Otherwise, return 7691 // INVALID. 7692 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7693 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7694 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7695 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7696 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7697 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7698 // TODO: Check alignment of src and dest ptrs. 7699 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7700 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7701 if (!TLI.isTypeLegal(LVT) || 7702 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7703 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7704 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7705 } 7706 7707 return LVT; 7708 }; 7709 7710 // This turns into unaligned loads. We only do this if the target natively 7711 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7712 // we'll only produce a small number of byte loads. 7713 MVT LoadVT; 7714 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7715 switch (NumBitsToCompare) { 7716 default: 7717 return false; 7718 case 16: 7719 LoadVT = MVT::i16; 7720 break; 7721 case 32: 7722 LoadVT = MVT::i32; 7723 break; 7724 case 64: 7725 case 128: 7726 case 256: 7727 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7728 break; 7729 } 7730 7731 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7732 return false; 7733 7734 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7735 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7736 7737 // Bitcast to a wide integer type if the loads are vectors. 7738 if (LoadVT.isVector()) { 7739 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7740 LoadL = DAG.getBitcast(CmpVT, LoadL); 7741 LoadR = DAG.getBitcast(CmpVT, LoadR); 7742 } 7743 7744 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7745 processIntegerCallValue(I, Cmp, false); 7746 return true; 7747 } 7748 7749 /// See if we can lower a memchr call into an optimized form. If so, return 7750 /// true and lower it. Otherwise return false, and it will be lowered like a 7751 /// normal call. 7752 /// The caller already checked that \p I calls the appropriate LibFunc with a 7753 /// correct prototype. 7754 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7755 const Value *Src = I.getArgOperand(0); 7756 const Value *Char = I.getArgOperand(1); 7757 const Value *Length = I.getArgOperand(2); 7758 7759 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7760 std::pair<SDValue, SDValue> Res = 7761 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7762 getValue(Src), getValue(Char), getValue(Length), 7763 MachinePointerInfo(Src)); 7764 if (Res.first.getNode()) { 7765 setValue(&I, Res.first); 7766 PendingLoads.push_back(Res.second); 7767 return true; 7768 } 7769 7770 return false; 7771 } 7772 7773 /// See if we can lower a mempcpy call into an optimized form. If so, return 7774 /// true and lower it. Otherwise return false, and it will be lowered like a 7775 /// normal call. 7776 /// The caller already checked that \p I calls the appropriate LibFunc with a 7777 /// correct prototype. 7778 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7779 SDValue Dst = getValue(I.getArgOperand(0)); 7780 SDValue Src = getValue(I.getArgOperand(1)); 7781 SDValue Size = getValue(I.getArgOperand(2)); 7782 7783 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7784 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7785 // DAG::getMemcpy needs Alignment to be defined. 7786 Align Alignment = std::min(DstAlign, SrcAlign); 7787 7788 bool isVol = false; 7789 SDLoc sdl = getCurSDLoc(); 7790 7791 // In the mempcpy context we need to pass in a false value for isTailCall 7792 // because the return pointer needs to be adjusted by the size of 7793 // the copied memory. 7794 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7795 AAMDNodes AAInfo; 7796 I.getAAMetadata(AAInfo); 7797 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7798 /*isTailCall=*/false, 7799 MachinePointerInfo(I.getArgOperand(0)), 7800 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 7801 assert(MC.getNode() != nullptr && 7802 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7803 DAG.setRoot(MC); 7804 7805 // Check if Size needs to be truncated or extended. 7806 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7807 7808 // Adjust return pointer to point just past the last dst byte. 7809 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7810 Dst, Size); 7811 setValue(&I, DstPlusSize); 7812 return true; 7813 } 7814 7815 /// See if we can lower a strcpy call into an optimized form. If so, return 7816 /// true and lower it, otherwise return false and it will be lowered like a 7817 /// normal call. 7818 /// The caller already checked that \p I calls the appropriate LibFunc with a 7819 /// correct prototype. 7820 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7821 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7822 7823 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7824 std::pair<SDValue, SDValue> Res = 7825 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7826 getValue(Arg0), getValue(Arg1), 7827 MachinePointerInfo(Arg0), 7828 MachinePointerInfo(Arg1), isStpcpy); 7829 if (Res.first.getNode()) { 7830 setValue(&I, Res.first); 7831 DAG.setRoot(Res.second); 7832 return true; 7833 } 7834 7835 return false; 7836 } 7837 7838 /// See if we can lower a strcmp call into an optimized form. If so, return 7839 /// true and lower it, otherwise return false and it will be lowered like a 7840 /// normal call. 7841 /// The caller already checked that \p I calls the appropriate LibFunc with a 7842 /// correct prototype. 7843 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7844 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7845 7846 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7847 std::pair<SDValue, SDValue> Res = 7848 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7849 getValue(Arg0), getValue(Arg1), 7850 MachinePointerInfo(Arg0), 7851 MachinePointerInfo(Arg1)); 7852 if (Res.first.getNode()) { 7853 processIntegerCallValue(I, Res.first, true); 7854 PendingLoads.push_back(Res.second); 7855 return true; 7856 } 7857 7858 return false; 7859 } 7860 7861 /// See if we can lower a strlen call into an optimized form. If so, return 7862 /// true and lower it, otherwise return false and it will be lowered like a 7863 /// normal call. 7864 /// The caller already checked that \p I calls the appropriate LibFunc with a 7865 /// correct prototype. 7866 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7867 const Value *Arg0 = I.getArgOperand(0); 7868 7869 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7870 std::pair<SDValue, SDValue> Res = 7871 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7872 getValue(Arg0), MachinePointerInfo(Arg0)); 7873 if (Res.first.getNode()) { 7874 processIntegerCallValue(I, Res.first, false); 7875 PendingLoads.push_back(Res.second); 7876 return true; 7877 } 7878 7879 return false; 7880 } 7881 7882 /// See if we can lower a strnlen call into an optimized form. If so, return 7883 /// true and lower it, otherwise return false and it will be lowered like a 7884 /// normal call. 7885 /// The caller already checked that \p I calls the appropriate LibFunc with a 7886 /// correct prototype. 7887 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7888 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7889 7890 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7891 std::pair<SDValue, SDValue> Res = 7892 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7893 getValue(Arg0), getValue(Arg1), 7894 MachinePointerInfo(Arg0)); 7895 if (Res.first.getNode()) { 7896 processIntegerCallValue(I, Res.first, false); 7897 PendingLoads.push_back(Res.second); 7898 return true; 7899 } 7900 7901 return false; 7902 } 7903 7904 /// See if we can lower a unary floating-point operation into an SDNode with 7905 /// the specified Opcode. If so, return true and lower it, otherwise return 7906 /// false and it will be lowered like a normal call. 7907 /// The caller already checked that \p I calls the appropriate LibFunc with a 7908 /// correct prototype. 7909 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7910 unsigned Opcode) { 7911 // We already checked this call's prototype; verify it doesn't modify errno. 7912 if (!I.onlyReadsMemory()) 7913 return false; 7914 7915 SDNodeFlags Flags; 7916 Flags.copyFMF(cast<FPMathOperator>(I)); 7917 7918 SDValue Tmp = getValue(I.getArgOperand(0)); 7919 setValue(&I, 7920 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7921 return true; 7922 } 7923 7924 /// See if we can lower a binary floating-point operation into an SDNode with 7925 /// the specified Opcode. If so, return true and lower it. Otherwise return 7926 /// false, and it will be lowered like a normal call. 7927 /// The caller already checked that \p I calls the appropriate LibFunc with a 7928 /// correct prototype. 7929 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7930 unsigned Opcode) { 7931 // We already checked this call's prototype; verify it doesn't modify errno. 7932 if (!I.onlyReadsMemory()) 7933 return false; 7934 7935 SDNodeFlags Flags; 7936 Flags.copyFMF(cast<FPMathOperator>(I)); 7937 7938 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7939 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7940 EVT VT = Tmp0.getValueType(); 7941 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7942 return true; 7943 } 7944 7945 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7946 // Handle inline assembly differently. 7947 if (I.isInlineAsm()) { 7948 visitInlineAsm(I); 7949 return; 7950 } 7951 7952 if (Function *F = I.getCalledFunction()) { 7953 if (F->isDeclaration()) { 7954 // Is this an LLVM intrinsic or a target-specific intrinsic? 7955 unsigned IID = F->getIntrinsicID(); 7956 if (!IID) 7957 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7958 IID = II->getIntrinsicID(F); 7959 7960 if (IID) { 7961 visitIntrinsicCall(I, IID); 7962 return; 7963 } 7964 } 7965 7966 // Check for well-known libc/libm calls. If the function is internal, it 7967 // can't be a library call. Don't do the check if marked as nobuiltin for 7968 // some reason or the call site requires strict floating point semantics. 7969 LibFunc Func; 7970 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7971 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7972 LibInfo->hasOptimizedCodeGen(Func)) { 7973 switch (Func) { 7974 default: break; 7975 case LibFunc_bcmp: 7976 if (visitMemCmpBCmpCall(I)) 7977 return; 7978 break; 7979 case LibFunc_copysign: 7980 case LibFunc_copysignf: 7981 case LibFunc_copysignl: 7982 // We already checked this call's prototype; verify it doesn't modify 7983 // errno. 7984 if (I.onlyReadsMemory()) { 7985 SDValue LHS = getValue(I.getArgOperand(0)); 7986 SDValue RHS = getValue(I.getArgOperand(1)); 7987 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7988 LHS.getValueType(), LHS, RHS)); 7989 return; 7990 } 7991 break; 7992 case LibFunc_fabs: 7993 case LibFunc_fabsf: 7994 case LibFunc_fabsl: 7995 if (visitUnaryFloatCall(I, ISD::FABS)) 7996 return; 7997 break; 7998 case LibFunc_fmin: 7999 case LibFunc_fminf: 8000 case LibFunc_fminl: 8001 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8002 return; 8003 break; 8004 case LibFunc_fmax: 8005 case LibFunc_fmaxf: 8006 case LibFunc_fmaxl: 8007 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8008 return; 8009 break; 8010 case LibFunc_sin: 8011 case LibFunc_sinf: 8012 case LibFunc_sinl: 8013 if (visitUnaryFloatCall(I, ISD::FSIN)) 8014 return; 8015 break; 8016 case LibFunc_cos: 8017 case LibFunc_cosf: 8018 case LibFunc_cosl: 8019 if (visitUnaryFloatCall(I, ISD::FCOS)) 8020 return; 8021 break; 8022 case LibFunc_sqrt: 8023 case LibFunc_sqrtf: 8024 case LibFunc_sqrtl: 8025 case LibFunc_sqrt_finite: 8026 case LibFunc_sqrtf_finite: 8027 case LibFunc_sqrtl_finite: 8028 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8029 return; 8030 break; 8031 case LibFunc_floor: 8032 case LibFunc_floorf: 8033 case LibFunc_floorl: 8034 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8035 return; 8036 break; 8037 case LibFunc_nearbyint: 8038 case LibFunc_nearbyintf: 8039 case LibFunc_nearbyintl: 8040 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8041 return; 8042 break; 8043 case LibFunc_ceil: 8044 case LibFunc_ceilf: 8045 case LibFunc_ceill: 8046 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8047 return; 8048 break; 8049 case LibFunc_rint: 8050 case LibFunc_rintf: 8051 case LibFunc_rintl: 8052 if (visitUnaryFloatCall(I, ISD::FRINT)) 8053 return; 8054 break; 8055 case LibFunc_round: 8056 case LibFunc_roundf: 8057 case LibFunc_roundl: 8058 if (visitUnaryFloatCall(I, ISD::FROUND)) 8059 return; 8060 break; 8061 case LibFunc_trunc: 8062 case LibFunc_truncf: 8063 case LibFunc_truncl: 8064 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8065 return; 8066 break; 8067 case LibFunc_log2: 8068 case LibFunc_log2f: 8069 case LibFunc_log2l: 8070 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8071 return; 8072 break; 8073 case LibFunc_exp2: 8074 case LibFunc_exp2f: 8075 case LibFunc_exp2l: 8076 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8077 return; 8078 break; 8079 case LibFunc_memcmp: 8080 if (visitMemCmpBCmpCall(I)) 8081 return; 8082 break; 8083 case LibFunc_mempcpy: 8084 if (visitMemPCpyCall(I)) 8085 return; 8086 break; 8087 case LibFunc_memchr: 8088 if (visitMemChrCall(I)) 8089 return; 8090 break; 8091 case LibFunc_strcpy: 8092 if (visitStrCpyCall(I, false)) 8093 return; 8094 break; 8095 case LibFunc_stpcpy: 8096 if (visitStrCpyCall(I, true)) 8097 return; 8098 break; 8099 case LibFunc_strcmp: 8100 if (visitStrCmpCall(I)) 8101 return; 8102 break; 8103 case LibFunc_strlen: 8104 if (visitStrLenCall(I)) 8105 return; 8106 break; 8107 case LibFunc_strnlen: 8108 if (visitStrNLenCall(I)) 8109 return; 8110 break; 8111 } 8112 } 8113 } 8114 8115 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8116 // have to do anything here to lower funclet bundles. 8117 // CFGuardTarget bundles are lowered in LowerCallTo. 8118 assert(!I.hasOperandBundlesOtherThan( 8119 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8120 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8121 LLVMContext::OB_clang_arc_attachedcall}) && 8122 "Cannot lower calls with arbitrary operand bundles!"); 8123 8124 SDValue Callee = getValue(I.getCalledOperand()); 8125 8126 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8127 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8128 else 8129 // Check if we can potentially perform a tail call. More detailed checking 8130 // is be done within LowerCallTo, after more information about the call is 8131 // known. 8132 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8133 } 8134 8135 namespace { 8136 8137 /// AsmOperandInfo - This contains information for each constraint that we are 8138 /// lowering. 8139 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8140 public: 8141 /// CallOperand - If this is the result output operand or a clobber 8142 /// this is null, otherwise it is the incoming operand to the CallInst. 8143 /// This gets modified as the asm is processed. 8144 SDValue CallOperand; 8145 8146 /// AssignedRegs - If this is a register or register class operand, this 8147 /// contains the set of register corresponding to the operand. 8148 RegsForValue AssignedRegs; 8149 8150 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8151 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8152 } 8153 8154 /// Whether or not this operand accesses memory 8155 bool hasMemory(const TargetLowering &TLI) const { 8156 // Indirect operand accesses access memory. 8157 if (isIndirect) 8158 return true; 8159 8160 for (const auto &Code : Codes) 8161 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8162 return true; 8163 8164 return false; 8165 } 8166 8167 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8168 /// corresponds to. If there is no Value* for this operand, it returns 8169 /// MVT::Other. 8170 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8171 const DataLayout &DL) const { 8172 if (!CallOperandVal) return MVT::Other; 8173 8174 if (isa<BasicBlock>(CallOperandVal)) 8175 return TLI.getProgramPointerTy(DL); 8176 8177 llvm::Type *OpTy = CallOperandVal->getType(); 8178 8179 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8180 // If this is an indirect operand, the operand is a pointer to the 8181 // accessed type. 8182 if (isIndirect) { 8183 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 8184 if (!PtrTy) 8185 report_fatal_error("Indirect operand for inline asm not a pointer!"); 8186 OpTy = PtrTy->getElementType(); 8187 } 8188 8189 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8190 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8191 if (STy->getNumElements() == 1) 8192 OpTy = STy->getElementType(0); 8193 8194 // If OpTy is not a single value, it may be a struct/union that we 8195 // can tile with integers. 8196 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8197 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8198 switch (BitSize) { 8199 default: break; 8200 case 1: 8201 case 8: 8202 case 16: 8203 case 32: 8204 case 64: 8205 case 128: 8206 OpTy = IntegerType::get(Context, BitSize); 8207 break; 8208 } 8209 } 8210 8211 return TLI.getAsmOperandValueType(DL, OpTy, true); 8212 } 8213 }; 8214 8215 8216 } // end anonymous namespace 8217 8218 /// Make sure that the output operand \p OpInfo and its corresponding input 8219 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8220 /// out). 8221 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8222 SDISelAsmOperandInfo &MatchingOpInfo, 8223 SelectionDAG &DAG) { 8224 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8225 return; 8226 8227 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8228 const auto &TLI = DAG.getTargetLoweringInfo(); 8229 8230 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8231 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8232 OpInfo.ConstraintVT); 8233 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8234 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8235 MatchingOpInfo.ConstraintVT); 8236 if ((OpInfo.ConstraintVT.isInteger() != 8237 MatchingOpInfo.ConstraintVT.isInteger()) || 8238 (MatchRC.second != InputRC.second)) { 8239 // FIXME: error out in a more elegant fashion 8240 report_fatal_error("Unsupported asm: input constraint" 8241 " with a matching output constraint of" 8242 " incompatible type!"); 8243 } 8244 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8245 } 8246 8247 /// Get a direct memory input to behave well as an indirect operand. 8248 /// This may introduce stores, hence the need for a \p Chain. 8249 /// \return The (possibly updated) chain. 8250 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8251 SDISelAsmOperandInfo &OpInfo, 8252 SelectionDAG &DAG) { 8253 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8254 8255 // If we don't have an indirect input, put it in the constpool if we can, 8256 // otherwise spill it to a stack slot. 8257 // TODO: This isn't quite right. We need to handle these according to 8258 // the addressing mode that the constraint wants. Also, this may take 8259 // an additional register for the computation and we don't want that 8260 // either. 8261 8262 // If the operand is a float, integer, or vector constant, spill to a 8263 // constant pool entry to get its address. 8264 const Value *OpVal = OpInfo.CallOperandVal; 8265 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8266 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8267 OpInfo.CallOperand = DAG.getConstantPool( 8268 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8269 return Chain; 8270 } 8271 8272 // Otherwise, create a stack slot and emit a store to it before the asm. 8273 Type *Ty = OpVal->getType(); 8274 auto &DL = DAG.getDataLayout(); 8275 uint64_t TySize = DL.getTypeAllocSize(Ty); 8276 MachineFunction &MF = DAG.getMachineFunction(); 8277 int SSFI = MF.getFrameInfo().CreateStackObject( 8278 TySize, DL.getPrefTypeAlign(Ty), false); 8279 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8280 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8281 MachinePointerInfo::getFixedStack(MF, SSFI), 8282 TLI.getMemValueType(DL, Ty)); 8283 OpInfo.CallOperand = StackSlot; 8284 8285 return Chain; 8286 } 8287 8288 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8289 /// specified operand. We prefer to assign virtual registers, to allow the 8290 /// register allocator to handle the assignment process. However, if the asm 8291 /// uses features that we can't model on machineinstrs, we have SDISel do the 8292 /// allocation. This produces generally horrible, but correct, code. 8293 /// 8294 /// OpInfo describes the operand 8295 /// RefOpInfo describes the matching operand if any, the operand otherwise 8296 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8297 SDISelAsmOperandInfo &OpInfo, 8298 SDISelAsmOperandInfo &RefOpInfo) { 8299 LLVMContext &Context = *DAG.getContext(); 8300 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8301 8302 MachineFunction &MF = DAG.getMachineFunction(); 8303 SmallVector<unsigned, 4> Regs; 8304 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8305 8306 // No work to do for memory operations. 8307 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8308 return; 8309 8310 // If this is a constraint for a single physreg, or a constraint for a 8311 // register class, find it. 8312 unsigned AssignedReg; 8313 const TargetRegisterClass *RC; 8314 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8315 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8316 // RC is unset only on failure. Return immediately. 8317 if (!RC) 8318 return; 8319 8320 // Get the actual register value type. This is important, because the user 8321 // may have asked for (e.g.) the AX register in i32 type. We need to 8322 // remember that AX is actually i16 to get the right extension. 8323 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8324 8325 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8326 // If this is an FP operand in an integer register (or visa versa), or more 8327 // generally if the operand value disagrees with the register class we plan 8328 // to stick it in, fix the operand type. 8329 // 8330 // If this is an input value, the bitcast to the new type is done now. 8331 // Bitcast for output value is done at the end of visitInlineAsm(). 8332 if ((OpInfo.Type == InlineAsm::isOutput || 8333 OpInfo.Type == InlineAsm::isInput) && 8334 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8335 // Try to convert to the first EVT that the reg class contains. If the 8336 // types are identical size, use a bitcast to convert (e.g. two differing 8337 // vector types). Note: output bitcast is done at the end of 8338 // visitInlineAsm(). 8339 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8340 // Exclude indirect inputs while they are unsupported because the code 8341 // to perform the load is missing and thus OpInfo.CallOperand still 8342 // refers to the input address rather than the pointed-to value. 8343 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8344 OpInfo.CallOperand = 8345 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8346 OpInfo.ConstraintVT = RegVT; 8347 // If the operand is an FP value and we want it in integer registers, 8348 // use the corresponding integer type. This turns an f64 value into 8349 // i64, which can be passed with two i32 values on a 32-bit machine. 8350 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8351 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8352 if (OpInfo.Type == InlineAsm::isInput) 8353 OpInfo.CallOperand = 8354 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8355 OpInfo.ConstraintVT = VT; 8356 } 8357 } 8358 } 8359 8360 // No need to allocate a matching input constraint since the constraint it's 8361 // matching to has already been allocated. 8362 if (OpInfo.isMatchingInputConstraint()) 8363 return; 8364 8365 EVT ValueVT = OpInfo.ConstraintVT; 8366 if (OpInfo.ConstraintVT == MVT::Other) 8367 ValueVT = RegVT; 8368 8369 // Initialize NumRegs. 8370 unsigned NumRegs = 1; 8371 if (OpInfo.ConstraintVT != MVT::Other) 8372 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8373 8374 // If this is a constraint for a specific physical register, like {r17}, 8375 // assign it now. 8376 8377 // If this associated to a specific register, initialize iterator to correct 8378 // place. If virtual, make sure we have enough registers 8379 8380 // Initialize iterator if necessary 8381 TargetRegisterClass::iterator I = RC->begin(); 8382 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8383 8384 // Do not check for single registers. 8385 if (AssignedReg) { 8386 for (; *I != AssignedReg; ++I) 8387 assert(I != RC->end() && "AssignedReg should be member of RC"); 8388 } 8389 8390 for (; NumRegs; --NumRegs, ++I) { 8391 assert(I != RC->end() && "Ran out of registers to allocate!"); 8392 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8393 Regs.push_back(R); 8394 } 8395 8396 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8397 } 8398 8399 static unsigned 8400 findMatchingInlineAsmOperand(unsigned OperandNo, 8401 const std::vector<SDValue> &AsmNodeOperands) { 8402 // Scan until we find the definition we already emitted of this operand. 8403 unsigned CurOp = InlineAsm::Op_FirstOperand; 8404 for (; OperandNo; --OperandNo) { 8405 // Advance to the next operand. 8406 unsigned OpFlag = 8407 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8408 assert((InlineAsm::isRegDefKind(OpFlag) || 8409 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8410 InlineAsm::isMemKind(OpFlag)) && 8411 "Skipped past definitions?"); 8412 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8413 } 8414 return CurOp; 8415 } 8416 8417 namespace { 8418 8419 class ExtraFlags { 8420 unsigned Flags = 0; 8421 8422 public: 8423 explicit ExtraFlags(const CallBase &Call) { 8424 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8425 if (IA->hasSideEffects()) 8426 Flags |= InlineAsm::Extra_HasSideEffects; 8427 if (IA->isAlignStack()) 8428 Flags |= InlineAsm::Extra_IsAlignStack; 8429 if (Call.isConvergent()) 8430 Flags |= InlineAsm::Extra_IsConvergent; 8431 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8432 } 8433 8434 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8435 // Ideally, we would only check against memory constraints. However, the 8436 // meaning of an Other constraint can be target-specific and we can't easily 8437 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8438 // for Other constraints as well. 8439 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8440 OpInfo.ConstraintType == TargetLowering::C_Other) { 8441 if (OpInfo.Type == InlineAsm::isInput) 8442 Flags |= InlineAsm::Extra_MayLoad; 8443 else if (OpInfo.Type == InlineAsm::isOutput) 8444 Flags |= InlineAsm::Extra_MayStore; 8445 else if (OpInfo.Type == InlineAsm::isClobber) 8446 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8447 } 8448 } 8449 8450 unsigned get() const { return Flags; } 8451 }; 8452 8453 } // end anonymous namespace 8454 8455 /// visitInlineAsm - Handle a call to an InlineAsm object. 8456 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8457 const BasicBlock *EHPadBB) { 8458 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8459 8460 /// ConstraintOperands - Information about all of the constraints. 8461 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8462 8463 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8464 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8465 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8466 8467 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8468 // AsmDialect, MayLoad, MayStore). 8469 bool HasSideEffect = IA->hasSideEffects(); 8470 ExtraFlags ExtraInfo(Call); 8471 8472 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8473 unsigned ResNo = 0; // ResNo - The result number of the next output. 8474 unsigned NumMatchingOps = 0; 8475 for (auto &T : TargetConstraints) { 8476 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8477 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8478 8479 // Compute the value type for each operand. 8480 if (OpInfo.Type == InlineAsm::isInput || 8481 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8482 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8483 8484 // Process the call argument. BasicBlocks are labels, currently appearing 8485 // only in asm's. 8486 if (isa<CallBrInst>(Call) && 8487 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8488 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8489 NumMatchingOps) && 8490 (NumMatchingOps == 0 || 8491 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8492 NumMatchingOps))) { 8493 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8494 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8495 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8496 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8497 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8498 } else { 8499 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8500 } 8501 8502 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8503 DAG.getDataLayout()); 8504 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8505 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8506 // The return value of the call is this value. As such, there is no 8507 // corresponding argument. 8508 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8509 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8510 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8511 DAG.getDataLayout(), STy->getElementType(ResNo)); 8512 } else { 8513 assert(ResNo == 0 && "Asm only has one result!"); 8514 OpInfo.ConstraintVT = TLI.getAsmOperandValueType( 8515 DAG.getDataLayout(), Call.getType()).getSimpleVT(); 8516 } 8517 ++ResNo; 8518 } else { 8519 OpInfo.ConstraintVT = MVT::Other; 8520 } 8521 8522 if (OpInfo.hasMatchingInput()) 8523 ++NumMatchingOps; 8524 8525 if (!HasSideEffect) 8526 HasSideEffect = OpInfo.hasMemory(TLI); 8527 8528 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8529 // FIXME: Could we compute this on OpInfo rather than T? 8530 8531 // Compute the constraint code and ConstraintType to use. 8532 TLI.ComputeConstraintToUse(T, SDValue()); 8533 8534 if (T.ConstraintType == TargetLowering::C_Immediate && 8535 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8536 // We've delayed emitting a diagnostic like the "n" constraint because 8537 // inlining could cause an integer showing up. 8538 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8539 "' expects an integer constant " 8540 "expression"); 8541 8542 ExtraInfo.update(T); 8543 } 8544 8545 // We won't need to flush pending loads if this asm doesn't touch 8546 // memory and is nonvolatile. 8547 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8548 8549 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8550 if (EmitEHLabels) { 8551 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8552 } 8553 bool IsCallBr = isa<CallBrInst>(Call); 8554 8555 if (IsCallBr || EmitEHLabels) { 8556 // If this is a callbr or invoke we need to flush pending exports since 8557 // inlineasm_br and invoke are terminators. 8558 // We need to do this before nodes are glued to the inlineasm_br node. 8559 Chain = getControlRoot(); 8560 } 8561 8562 MCSymbol *BeginLabel = nullptr; 8563 if (EmitEHLabels) { 8564 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8565 } 8566 8567 // Second pass over the constraints: compute which constraint option to use. 8568 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8569 // If this is an output operand with a matching input operand, look up the 8570 // matching input. If their types mismatch, e.g. one is an integer, the 8571 // other is floating point, or their sizes are different, flag it as an 8572 // error. 8573 if (OpInfo.hasMatchingInput()) { 8574 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8575 patchMatchingInput(OpInfo, Input, DAG); 8576 } 8577 8578 // Compute the constraint code and ConstraintType to use. 8579 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8580 8581 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8582 OpInfo.Type == InlineAsm::isClobber) 8583 continue; 8584 8585 // If this is a memory input, and if the operand is not indirect, do what we 8586 // need to provide an address for the memory input. 8587 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8588 !OpInfo.isIndirect) { 8589 assert((OpInfo.isMultipleAlternative || 8590 (OpInfo.Type == InlineAsm::isInput)) && 8591 "Can only indirectify direct input operands!"); 8592 8593 // Memory operands really want the address of the value. 8594 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8595 8596 // There is no longer a Value* corresponding to this operand. 8597 OpInfo.CallOperandVal = nullptr; 8598 8599 // It is now an indirect operand. 8600 OpInfo.isIndirect = true; 8601 } 8602 8603 } 8604 8605 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8606 std::vector<SDValue> AsmNodeOperands; 8607 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8608 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8609 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8610 8611 // If we have a !srcloc metadata node associated with it, we want to attach 8612 // this to the ultimately generated inline asm machineinstr. To do this, we 8613 // pass in the third operand as this (potentially null) inline asm MDNode. 8614 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8615 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8616 8617 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8618 // bits as operand 3. 8619 AsmNodeOperands.push_back(DAG.getTargetConstant( 8620 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8621 8622 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8623 // this, assign virtual and physical registers for inputs and otput. 8624 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8625 // Assign Registers. 8626 SDISelAsmOperandInfo &RefOpInfo = 8627 OpInfo.isMatchingInputConstraint() 8628 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8629 : OpInfo; 8630 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8631 8632 auto DetectWriteToReservedRegister = [&]() { 8633 const MachineFunction &MF = DAG.getMachineFunction(); 8634 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8635 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8636 if (Register::isPhysicalRegister(Reg) && 8637 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8638 const char *RegName = TRI.getName(Reg); 8639 emitInlineAsmError(Call, "write to reserved register '" + 8640 Twine(RegName) + "'"); 8641 return true; 8642 } 8643 } 8644 return false; 8645 }; 8646 8647 switch (OpInfo.Type) { 8648 case InlineAsm::isOutput: 8649 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8650 unsigned ConstraintID = 8651 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8652 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8653 "Failed to convert memory constraint code to constraint id."); 8654 8655 // Add information to the INLINEASM node to know about this output. 8656 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8657 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8658 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8659 MVT::i32)); 8660 AsmNodeOperands.push_back(OpInfo.CallOperand); 8661 } else { 8662 // Otherwise, this outputs to a register (directly for C_Register / 8663 // C_RegisterClass, and a target-defined fashion for 8664 // C_Immediate/C_Other). Find a register that we can use. 8665 if (OpInfo.AssignedRegs.Regs.empty()) { 8666 emitInlineAsmError( 8667 Call, "couldn't allocate output register for constraint '" + 8668 Twine(OpInfo.ConstraintCode) + "'"); 8669 return; 8670 } 8671 8672 if (DetectWriteToReservedRegister()) 8673 return; 8674 8675 // Add information to the INLINEASM node to know that this register is 8676 // set. 8677 OpInfo.AssignedRegs.AddInlineAsmOperands( 8678 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8679 : InlineAsm::Kind_RegDef, 8680 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8681 } 8682 break; 8683 8684 case InlineAsm::isInput: { 8685 SDValue InOperandVal = OpInfo.CallOperand; 8686 8687 if (OpInfo.isMatchingInputConstraint()) { 8688 // If this is required to match an output register we have already set, 8689 // just use its register. 8690 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8691 AsmNodeOperands); 8692 unsigned OpFlag = 8693 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8694 if (InlineAsm::isRegDefKind(OpFlag) || 8695 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8696 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8697 if (OpInfo.isIndirect) { 8698 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8699 emitInlineAsmError(Call, "inline asm not supported yet: " 8700 "don't know how to handle tied " 8701 "indirect register inputs"); 8702 return; 8703 } 8704 8705 SmallVector<unsigned, 4> Regs; 8706 MachineFunction &MF = DAG.getMachineFunction(); 8707 MachineRegisterInfo &MRI = MF.getRegInfo(); 8708 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8709 RegisterSDNode *R = dyn_cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 8710 Register TiedReg = R->getReg(); 8711 MVT RegVT = R->getSimpleValueType(0); 8712 const TargetRegisterClass *RC = TiedReg.isVirtual() ? 8713 MRI.getRegClass(TiedReg) : TRI.getMinimalPhysRegClass(TiedReg); 8714 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8715 for (unsigned i = 0; i != NumRegs; ++i) 8716 Regs.push_back(MRI.createVirtualRegister(RC)); 8717 8718 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8719 8720 SDLoc dl = getCurSDLoc(); 8721 // Use the produced MatchedRegs object to 8722 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8723 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8724 true, OpInfo.getMatchedOperand(), dl, 8725 DAG, AsmNodeOperands); 8726 break; 8727 } 8728 8729 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8730 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8731 "Unexpected number of operands"); 8732 // Add information to the INLINEASM node to know about this input. 8733 // See InlineAsm.h isUseOperandTiedToDef. 8734 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8735 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8736 OpInfo.getMatchedOperand()); 8737 AsmNodeOperands.push_back(DAG.getTargetConstant( 8738 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8739 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8740 break; 8741 } 8742 8743 // Treat indirect 'X' constraint as memory. 8744 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8745 OpInfo.isIndirect) 8746 OpInfo.ConstraintType = TargetLowering::C_Memory; 8747 8748 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8749 OpInfo.ConstraintType == TargetLowering::C_Other) { 8750 std::vector<SDValue> Ops; 8751 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8752 Ops, DAG); 8753 if (Ops.empty()) { 8754 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8755 if (isa<ConstantSDNode>(InOperandVal)) { 8756 emitInlineAsmError(Call, "value out of range for constraint '" + 8757 Twine(OpInfo.ConstraintCode) + "'"); 8758 return; 8759 } 8760 8761 emitInlineAsmError(Call, 8762 "invalid operand for inline asm constraint '" + 8763 Twine(OpInfo.ConstraintCode) + "'"); 8764 return; 8765 } 8766 8767 // Add information to the INLINEASM node to know about this input. 8768 unsigned ResOpType = 8769 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8770 AsmNodeOperands.push_back(DAG.getTargetConstant( 8771 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8772 llvm::append_range(AsmNodeOperands, Ops); 8773 break; 8774 } 8775 8776 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8777 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8778 assert(InOperandVal.getValueType() == 8779 TLI.getPointerTy(DAG.getDataLayout()) && 8780 "Memory operands expect pointer values"); 8781 8782 unsigned ConstraintID = 8783 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8784 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8785 "Failed to convert memory constraint code to constraint id."); 8786 8787 // Add information to the INLINEASM node to know about this input. 8788 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8789 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8790 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8791 getCurSDLoc(), 8792 MVT::i32)); 8793 AsmNodeOperands.push_back(InOperandVal); 8794 break; 8795 } 8796 8797 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8798 OpInfo.ConstraintType == TargetLowering::C_Register) && 8799 "Unknown constraint type!"); 8800 8801 // TODO: Support this. 8802 if (OpInfo.isIndirect) { 8803 emitInlineAsmError( 8804 Call, "Don't know how to handle indirect register inputs yet " 8805 "for constraint '" + 8806 Twine(OpInfo.ConstraintCode) + "'"); 8807 return; 8808 } 8809 8810 // Copy the input into the appropriate registers. 8811 if (OpInfo.AssignedRegs.Regs.empty()) { 8812 emitInlineAsmError(Call, 8813 "couldn't allocate input reg for constraint '" + 8814 Twine(OpInfo.ConstraintCode) + "'"); 8815 return; 8816 } 8817 8818 if (DetectWriteToReservedRegister()) 8819 return; 8820 8821 SDLoc dl = getCurSDLoc(); 8822 8823 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8824 &Call); 8825 8826 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8827 dl, DAG, AsmNodeOperands); 8828 break; 8829 } 8830 case InlineAsm::isClobber: 8831 // Add the clobbered value to the operand list, so that the register 8832 // allocator is aware that the physreg got clobbered. 8833 if (!OpInfo.AssignedRegs.Regs.empty()) 8834 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8835 false, 0, getCurSDLoc(), DAG, 8836 AsmNodeOperands); 8837 break; 8838 } 8839 } 8840 8841 // Finish up input operands. Set the input chain and add the flag last. 8842 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8843 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8844 8845 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8846 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8847 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8848 Flag = Chain.getValue(1); 8849 8850 // Do additional work to generate outputs. 8851 8852 SmallVector<EVT, 1> ResultVTs; 8853 SmallVector<SDValue, 1> ResultValues; 8854 SmallVector<SDValue, 8> OutChains; 8855 8856 llvm::Type *CallResultType = Call.getType(); 8857 ArrayRef<Type *> ResultTypes; 8858 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8859 ResultTypes = StructResult->elements(); 8860 else if (!CallResultType->isVoidTy()) 8861 ResultTypes = makeArrayRef(CallResultType); 8862 8863 auto CurResultType = ResultTypes.begin(); 8864 auto handleRegAssign = [&](SDValue V) { 8865 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8866 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8867 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8868 ++CurResultType; 8869 // If the type of the inline asm call site return value is different but has 8870 // same size as the type of the asm output bitcast it. One example of this 8871 // is for vectors with different width / number of elements. This can 8872 // happen for register classes that can contain multiple different value 8873 // types. The preg or vreg allocated may not have the same VT as was 8874 // expected. 8875 // 8876 // This can also happen for a return value that disagrees with the register 8877 // class it is put in, eg. a double in a general-purpose register on a 8878 // 32-bit machine. 8879 if (ResultVT != V.getValueType() && 8880 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8881 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8882 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8883 V.getValueType().isInteger()) { 8884 // If a result value was tied to an input value, the computed result 8885 // may have a wider width than the expected result. Extract the 8886 // relevant portion. 8887 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8888 } 8889 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8890 ResultVTs.push_back(ResultVT); 8891 ResultValues.push_back(V); 8892 }; 8893 8894 // Deal with output operands. 8895 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8896 if (OpInfo.Type == InlineAsm::isOutput) { 8897 SDValue Val; 8898 // Skip trivial output operands. 8899 if (OpInfo.AssignedRegs.Regs.empty()) 8900 continue; 8901 8902 switch (OpInfo.ConstraintType) { 8903 case TargetLowering::C_Register: 8904 case TargetLowering::C_RegisterClass: 8905 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8906 Chain, &Flag, &Call); 8907 break; 8908 case TargetLowering::C_Immediate: 8909 case TargetLowering::C_Other: 8910 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8911 OpInfo, DAG); 8912 break; 8913 case TargetLowering::C_Memory: 8914 break; // Already handled. 8915 case TargetLowering::C_Unknown: 8916 assert(false && "Unexpected unknown constraint"); 8917 } 8918 8919 // Indirect output manifest as stores. Record output chains. 8920 if (OpInfo.isIndirect) { 8921 const Value *Ptr = OpInfo.CallOperandVal; 8922 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8923 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8924 MachinePointerInfo(Ptr)); 8925 OutChains.push_back(Store); 8926 } else { 8927 // generate CopyFromRegs to associated registers. 8928 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8929 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8930 for (const SDValue &V : Val->op_values()) 8931 handleRegAssign(V); 8932 } else 8933 handleRegAssign(Val); 8934 } 8935 } 8936 } 8937 8938 // Set results. 8939 if (!ResultValues.empty()) { 8940 assert(CurResultType == ResultTypes.end() && 8941 "Mismatch in number of ResultTypes"); 8942 assert(ResultValues.size() == ResultTypes.size() && 8943 "Mismatch in number of output operands in asm result"); 8944 8945 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8946 DAG.getVTList(ResultVTs), ResultValues); 8947 setValue(&Call, V); 8948 } 8949 8950 // Collect store chains. 8951 if (!OutChains.empty()) 8952 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8953 8954 if (EmitEHLabels) { 8955 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 8956 } 8957 8958 // Only Update Root if inline assembly has a memory effect. 8959 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 8960 EmitEHLabels) 8961 DAG.setRoot(Chain); 8962 } 8963 8964 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8965 const Twine &Message) { 8966 LLVMContext &Ctx = *DAG.getContext(); 8967 Ctx.emitError(&Call, Message); 8968 8969 // Make sure we leave the DAG in a valid state 8970 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8971 SmallVector<EVT, 1> ValueVTs; 8972 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8973 8974 if (ValueVTs.empty()) 8975 return; 8976 8977 SmallVector<SDValue, 1> Ops; 8978 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8979 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8980 8981 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8982 } 8983 8984 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8985 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8986 MVT::Other, getRoot(), 8987 getValue(I.getArgOperand(0)), 8988 DAG.getSrcValue(I.getArgOperand(0)))); 8989 } 8990 8991 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8992 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8993 const DataLayout &DL = DAG.getDataLayout(); 8994 SDValue V = DAG.getVAArg( 8995 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8996 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8997 DL.getABITypeAlign(I.getType()).value()); 8998 DAG.setRoot(V.getValue(1)); 8999 9000 if (I.getType()->isPointerTy()) 9001 V = DAG.getPtrExtOrTrunc( 9002 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9003 setValue(&I, V); 9004 } 9005 9006 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9007 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9008 MVT::Other, getRoot(), 9009 getValue(I.getArgOperand(0)), 9010 DAG.getSrcValue(I.getArgOperand(0)))); 9011 } 9012 9013 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9014 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9015 MVT::Other, getRoot(), 9016 getValue(I.getArgOperand(0)), 9017 getValue(I.getArgOperand(1)), 9018 DAG.getSrcValue(I.getArgOperand(0)), 9019 DAG.getSrcValue(I.getArgOperand(1)))); 9020 } 9021 9022 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9023 const Instruction &I, 9024 SDValue Op) { 9025 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9026 if (!Range) 9027 return Op; 9028 9029 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9030 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9031 return Op; 9032 9033 APInt Lo = CR.getUnsignedMin(); 9034 if (!Lo.isMinValue()) 9035 return Op; 9036 9037 APInt Hi = CR.getUnsignedMax(); 9038 unsigned Bits = std::max(Hi.getActiveBits(), 9039 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9040 9041 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9042 9043 SDLoc SL = getCurSDLoc(); 9044 9045 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9046 DAG.getValueType(SmallVT)); 9047 unsigned NumVals = Op.getNode()->getNumValues(); 9048 if (NumVals == 1) 9049 return ZExt; 9050 9051 SmallVector<SDValue, 4> Ops; 9052 9053 Ops.push_back(ZExt); 9054 for (unsigned I = 1; I != NumVals; ++I) 9055 Ops.push_back(Op.getValue(I)); 9056 9057 return DAG.getMergeValues(Ops, SL); 9058 } 9059 9060 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9061 /// the call being lowered. 9062 /// 9063 /// This is a helper for lowering intrinsics that follow a target calling 9064 /// convention or require stack pointer adjustment. Only a subset of the 9065 /// intrinsic's operands need to participate in the calling convention. 9066 void SelectionDAGBuilder::populateCallLoweringInfo( 9067 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9068 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9069 bool IsPatchPoint) { 9070 TargetLowering::ArgListTy Args; 9071 Args.reserve(NumArgs); 9072 9073 // Populate the argument list. 9074 // Attributes for args start at offset 1, after the return attribute. 9075 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9076 ArgI != ArgE; ++ArgI) { 9077 const Value *V = Call->getOperand(ArgI); 9078 9079 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9080 9081 TargetLowering::ArgListEntry Entry; 9082 Entry.Node = getValue(V); 9083 Entry.Ty = V->getType(); 9084 Entry.setAttributes(Call, ArgI); 9085 Args.push_back(Entry); 9086 } 9087 9088 CLI.setDebugLoc(getCurSDLoc()) 9089 .setChain(getRoot()) 9090 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9091 .setDiscardResult(Call->use_empty()) 9092 .setIsPatchPoint(IsPatchPoint) 9093 .setIsPreallocated( 9094 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9095 } 9096 9097 /// Add a stack map intrinsic call's live variable operands to a stackmap 9098 /// or patchpoint target node's operand list. 9099 /// 9100 /// Constants are converted to TargetConstants purely as an optimization to 9101 /// avoid constant materialization and register allocation. 9102 /// 9103 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9104 /// generate addess computation nodes, and so FinalizeISel can convert the 9105 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9106 /// address materialization and register allocation, but may also be required 9107 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9108 /// alloca in the entry block, then the runtime may assume that the alloca's 9109 /// StackMap location can be read immediately after compilation and that the 9110 /// location is valid at any point during execution (this is similar to the 9111 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9112 /// only available in a register, then the runtime would need to trap when 9113 /// execution reaches the StackMap in order to read the alloca's location. 9114 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9115 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9116 SelectionDAGBuilder &Builder) { 9117 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 9118 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 9119 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 9120 Ops.push_back( 9121 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 9122 Ops.push_back( 9123 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 9124 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 9125 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 9126 Ops.push_back(Builder.DAG.getTargetFrameIndex( 9127 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 9128 } else 9129 Ops.push_back(OpVal); 9130 } 9131 } 9132 9133 /// Lower llvm.experimental.stackmap directly to its target opcode. 9134 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9135 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 9136 // [live variables...]) 9137 9138 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9139 9140 SDValue Chain, InFlag, Callee, NullPtr; 9141 SmallVector<SDValue, 32> Ops; 9142 9143 SDLoc DL = getCurSDLoc(); 9144 Callee = getValue(CI.getCalledOperand()); 9145 NullPtr = DAG.getIntPtrConstant(0, DL, true); 9146 9147 // The stackmap intrinsic only records the live variables (the arguments 9148 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9149 // intrinsic, this won't be lowered to a function call. This means we don't 9150 // have to worry about calling conventions and target specific lowering code. 9151 // Instead we perform the call lowering right here. 9152 // 9153 // chain, flag = CALLSEQ_START(chain, 0, 0) 9154 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9155 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9156 // 9157 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9158 InFlag = Chain.getValue(1); 9159 9160 // Add the <id> and <numBytes> constants. 9161 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 9162 Ops.push_back(DAG.getTargetConstant( 9163 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 9164 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 9165 Ops.push_back(DAG.getTargetConstant( 9166 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 9167 MVT::i32)); 9168 9169 // Push live variables for the stack map. 9170 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9171 9172 // We are not pushing any register mask info here on the operands list, 9173 // because the stackmap doesn't clobber anything. 9174 9175 // Push the chain and the glue flag. 9176 Ops.push_back(Chain); 9177 Ops.push_back(InFlag); 9178 9179 // Create the STACKMAP node. 9180 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9181 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9182 Chain = SDValue(SM, 0); 9183 InFlag = Chain.getValue(1); 9184 9185 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9186 9187 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9188 9189 // Set the root to the target-lowered call chain. 9190 DAG.setRoot(Chain); 9191 9192 // Inform the Frame Information that we have a stackmap in this function. 9193 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9194 } 9195 9196 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9197 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9198 const BasicBlock *EHPadBB) { 9199 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9200 // i32 <numBytes>, 9201 // i8* <target>, 9202 // i32 <numArgs>, 9203 // [Args...], 9204 // [live variables...]) 9205 9206 CallingConv::ID CC = CB.getCallingConv(); 9207 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9208 bool HasDef = !CB.getType()->isVoidTy(); 9209 SDLoc dl = getCurSDLoc(); 9210 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9211 9212 // Handle immediate and symbolic callees. 9213 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9214 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9215 /*isTarget=*/true); 9216 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9217 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9218 SDLoc(SymbolicCallee), 9219 SymbolicCallee->getValueType(0)); 9220 9221 // Get the real number of arguments participating in the call <numArgs> 9222 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9223 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9224 9225 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9226 // Intrinsics include all meta-operands up to but not including CC. 9227 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9228 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9229 "Not enough arguments provided to the patchpoint intrinsic"); 9230 9231 // For AnyRegCC the arguments are lowered later on manually. 9232 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9233 Type *ReturnTy = 9234 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9235 9236 TargetLowering::CallLoweringInfo CLI(DAG); 9237 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9238 ReturnTy, true); 9239 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9240 9241 SDNode *CallEnd = Result.second.getNode(); 9242 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9243 CallEnd = CallEnd->getOperand(0).getNode(); 9244 9245 /// Get a call instruction from the call sequence chain. 9246 /// Tail calls are not allowed. 9247 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9248 "Expected a callseq node."); 9249 SDNode *Call = CallEnd->getOperand(0).getNode(); 9250 bool HasGlue = Call->getGluedNode(); 9251 9252 // Replace the target specific call node with the patchable intrinsic. 9253 SmallVector<SDValue, 8> Ops; 9254 9255 // Add the <id> and <numBytes> constants. 9256 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9257 Ops.push_back(DAG.getTargetConstant( 9258 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9259 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9260 Ops.push_back(DAG.getTargetConstant( 9261 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9262 MVT::i32)); 9263 9264 // Add the callee. 9265 Ops.push_back(Callee); 9266 9267 // Adjust <numArgs> to account for any arguments that have been passed on the 9268 // stack instead. 9269 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9270 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9271 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9272 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9273 9274 // Add the calling convention 9275 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9276 9277 // Add the arguments we omitted previously. The register allocator should 9278 // place these in any free register. 9279 if (IsAnyRegCC) 9280 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9281 Ops.push_back(getValue(CB.getArgOperand(i))); 9282 9283 // Push the arguments from the call instruction up to the register mask. 9284 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9285 Ops.append(Call->op_begin() + 2, e); 9286 9287 // Push live variables for the stack map. 9288 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9289 9290 // Push the register mask info. 9291 if (HasGlue) 9292 Ops.push_back(*(Call->op_end()-2)); 9293 else 9294 Ops.push_back(*(Call->op_end()-1)); 9295 9296 // Push the chain (this is originally the first operand of the call, but 9297 // becomes now the last or second to last operand). 9298 Ops.push_back(*(Call->op_begin())); 9299 9300 // Push the glue flag (last operand). 9301 if (HasGlue) 9302 Ops.push_back(*(Call->op_end()-1)); 9303 9304 SDVTList NodeTys; 9305 if (IsAnyRegCC && HasDef) { 9306 // Create the return types based on the intrinsic definition 9307 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9308 SmallVector<EVT, 3> ValueVTs; 9309 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9310 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9311 9312 // There is always a chain and a glue type at the end 9313 ValueVTs.push_back(MVT::Other); 9314 ValueVTs.push_back(MVT::Glue); 9315 NodeTys = DAG.getVTList(ValueVTs); 9316 } else 9317 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9318 9319 // Replace the target specific call node with a PATCHPOINT node. 9320 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9321 dl, NodeTys, Ops); 9322 9323 // Update the NodeMap. 9324 if (HasDef) { 9325 if (IsAnyRegCC) 9326 setValue(&CB, SDValue(MN, 0)); 9327 else 9328 setValue(&CB, Result.first); 9329 } 9330 9331 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9332 // call sequence. Furthermore the location of the chain and glue can change 9333 // when the AnyReg calling convention is used and the intrinsic returns a 9334 // value. 9335 if (IsAnyRegCC && HasDef) { 9336 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9337 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9338 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9339 } else 9340 DAG.ReplaceAllUsesWith(Call, MN); 9341 DAG.DeleteNode(Call); 9342 9343 // Inform the Frame Information that we have a patchpoint in this function. 9344 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9345 } 9346 9347 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9348 unsigned Intrinsic) { 9349 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9350 SDValue Op1 = getValue(I.getArgOperand(0)); 9351 SDValue Op2; 9352 if (I.getNumArgOperands() > 1) 9353 Op2 = getValue(I.getArgOperand(1)); 9354 SDLoc dl = getCurSDLoc(); 9355 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9356 SDValue Res; 9357 SDNodeFlags SDFlags; 9358 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9359 SDFlags.copyFMF(*FPMO); 9360 9361 switch (Intrinsic) { 9362 case Intrinsic::vector_reduce_fadd: 9363 if (SDFlags.hasAllowReassociation()) 9364 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9365 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9366 SDFlags); 9367 else 9368 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9369 break; 9370 case Intrinsic::vector_reduce_fmul: 9371 if (SDFlags.hasAllowReassociation()) 9372 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9373 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9374 SDFlags); 9375 else 9376 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9377 break; 9378 case Intrinsic::vector_reduce_add: 9379 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9380 break; 9381 case Intrinsic::vector_reduce_mul: 9382 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9383 break; 9384 case Intrinsic::vector_reduce_and: 9385 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9386 break; 9387 case Intrinsic::vector_reduce_or: 9388 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9389 break; 9390 case Intrinsic::vector_reduce_xor: 9391 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9392 break; 9393 case Intrinsic::vector_reduce_smax: 9394 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9395 break; 9396 case Intrinsic::vector_reduce_smin: 9397 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9398 break; 9399 case Intrinsic::vector_reduce_umax: 9400 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9401 break; 9402 case Intrinsic::vector_reduce_umin: 9403 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9404 break; 9405 case Intrinsic::vector_reduce_fmax: 9406 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9407 break; 9408 case Intrinsic::vector_reduce_fmin: 9409 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9410 break; 9411 default: 9412 llvm_unreachable("Unhandled vector reduce intrinsic"); 9413 } 9414 setValue(&I, Res); 9415 } 9416 9417 /// Returns an AttributeList representing the attributes applied to the return 9418 /// value of the given call. 9419 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9420 SmallVector<Attribute::AttrKind, 2> Attrs; 9421 if (CLI.RetSExt) 9422 Attrs.push_back(Attribute::SExt); 9423 if (CLI.RetZExt) 9424 Attrs.push_back(Attribute::ZExt); 9425 if (CLI.IsInReg) 9426 Attrs.push_back(Attribute::InReg); 9427 9428 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9429 Attrs); 9430 } 9431 9432 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9433 /// implementation, which just calls LowerCall. 9434 /// FIXME: When all targets are 9435 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9436 std::pair<SDValue, SDValue> 9437 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9438 // Handle the incoming return values from the call. 9439 CLI.Ins.clear(); 9440 Type *OrigRetTy = CLI.RetTy; 9441 SmallVector<EVT, 4> RetTys; 9442 SmallVector<uint64_t, 4> Offsets; 9443 auto &DL = CLI.DAG.getDataLayout(); 9444 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9445 9446 if (CLI.IsPostTypeLegalization) { 9447 // If we are lowering a libcall after legalization, split the return type. 9448 SmallVector<EVT, 4> OldRetTys; 9449 SmallVector<uint64_t, 4> OldOffsets; 9450 RetTys.swap(OldRetTys); 9451 Offsets.swap(OldOffsets); 9452 9453 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9454 EVT RetVT = OldRetTys[i]; 9455 uint64_t Offset = OldOffsets[i]; 9456 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9457 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9458 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9459 RetTys.append(NumRegs, RegisterVT); 9460 for (unsigned j = 0; j != NumRegs; ++j) 9461 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9462 } 9463 } 9464 9465 SmallVector<ISD::OutputArg, 4> Outs; 9466 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9467 9468 bool CanLowerReturn = 9469 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9470 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9471 9472 SDValue DemoteStackSlot; 9473 int DemoteStackIdx = -100; 9474 if (!CanLowerReturn) { 9475 // FIXME: equivalent assert? 9476 // assert(!CS.hasInAllocaArgument() && 9477 // "sret demotion is incompatible with inalloca"); 9478 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9479 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9480 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9481 DemoteStackIdx = 9482 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9483 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9484 DL.getAllocaAddrSpace()); 9485 9486 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9487 ArgListEntry Entry; 9488 Entry.Node = DemoteStackSlot; 9489 Entry.Ty = StackSlotPtrType; 9490 Entry.IsSExt = false; 9491 Entry.IsZExt = false; 9492 Entry.IsInReg = false; 9493 Entry.IsSRet = true; 9494 Entry.IsNest = false; 9495 Entry.IsByVal = false; 9496 Entry.IsByRef = false; 9497 Entry.IsReturned = false; 9498 Entry.IsSwiftSelf = false; 9499 Entry.IsSwiftAsync = false; 9500 Entry.IsSwiftError = false; 9501 Entry.IsCFGuardTarget = false; 9502 Entry.Alignment = Alignment; 9503 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9504 CLI.NumFixedArgs += 1; 9505 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9506 9507 // sret demotion isn't compatible with tail-calls, since the sret argument 9508 // points into the callers stack frame. 9509 CLI.IsTailCall = false; 9510 } else { 9511 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9512 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9513 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9514 ISD::ArgFlagsTy Flags; 9515 if (NeedsRegBlock) { 9516 Flags.setInConsecutiveRegs(); 9517 if (I == RetTys.size() - 1) 9518 Flags.setInConsecutiveRegsLast(); 9519 } 9520 EVT VT = RetTys[I]; 9521 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9522 CLI.CallConv, VT); 9523 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9524 CLI.CallConv, VT); 9525 for (unsigned i = 0; i != NumRegs; ++i) { 9526 ISD::InputArg MyFlags; 9527 MyFlags.Flags = Flags; 9528 MyFlags.VT = RegisterVT; 9529 MyFlags.ArgVT = VT; 9530 MyFlags.Used = CLI.IsReturnValueUsed; 9531 if (CLI.RetTy->isPointerTy()) { 9532 MyFlags.Flags.setPointer(); 9533 MyFlags.Flags.setPointerAddrSpace( 9534 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9535 } 9536 if (CLI.RetSExt) 9537 MyFlags.Flags.setSExt(); 9538 if (CLI.RetZExt) 9539 MyFlags.Flags.setZExt(); 9540 if (CLI.IsInReg) 9541 MyFlags.Flags.setInReg(); 9542 CLI.Ins.push_back(MyFlags); 9543 } 9544 } 9545 } 9546 9547 // We push in swifterror return as the last element of CLI.Ins. 9548 ArgListTy &Args = CLI.getArgs(); 9549 if (supportSwiftError()) { 9550 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9551 if (Args[i].IsSwiftError) { 9552 ISD::InputArg MyFlags; 9553 MyFlags.VT = getPointerTy(DL); 9554 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9555 MyFlags.Flags.setSwiftError(); 9556 CLI.Ins.push_back(MyFlags); 9557 } 9558 } 9559 } 9560 9561 // Handle all of the outgoing arguments. 9562 CLI.Outs.clear(); 9563 CLI.OutVals.clear(); 9564 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9565 SmallVector<EVT, 4> ValueVTs; 9566 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9567 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9568 Type *FinalType = Args[i].Ty; 9569 if (Args[i].IsByVal) 9570 FinalType = Args[i].IndirectType; 9571 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9572 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 9573 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9574 ++Value) { 9575 EVT VT = ValueVTs[Value]; 9576 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9577 SDValue Op = SDValue(Args[i].Node.getNode(), 9578 Args[i].Node.getResNo() + Value); 9579 ISD::ArgFlagsTy Flags; 9580 9581 // Certain targets (such as MIPS), may have a different ABI alignment 9582 // for a type depending on the context. Give the target a chance to 9583 // specify the alignment it wants. 9584 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9585 Flags.setOrigAlign(OriginalAlignment); 9586 9587 if (Args[i].Ty->isPointerTy()) { 9588 Flags.setPointer(); 9589 Flags.setPointerAddrSpace( 9590 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9591 } 9592 if (Args[i].IsZExt) 9593 Flags.setZExt(); 9594 if (Args[i].IsSExt) 9595 Flags.setSExt(); 9596 if (Args[i].IsInReg) { 9597 // If we are using vectorcall calling convention, a structure that is 9598 // passed InReg - is surely an HVA 9599 if (CLI.CallConv == CallingConv::X86_VectorCall && 9600 isa<StructType>(FinalType)) { 9601 // The first value of a structure is marked 9602 if (0 == Value) 9603 Flags.setHvaStart(); 9604 Flags.setHva(); 9605 } 9606 // Set InReg Flag 9607 Flags.setInReg(); 9608 } 9609 if (Args[i].IsSRet) 9610 Flags.setSRet(); 9611 if (Args[i].IsSwiftSelf) 9612 Flags.setSwiftSelf(); 9613 if (Args[i].IsSwiftAsync) 9614 Flags.setSwiftAsync(); 9615 if (Args[i].IsSwiftError) 9616 Flags.setSwiftError(); 9617 if (Args[i].IsCFGuardTarget) 9618 Flags.setCFGuardTarget(); 9619 if (Args[i].IsByVal) 9620 Flags.setByVal(); 9621 if (Args[i].IsByRef) 9622 Flags.setByRef(); 9623 if (Args[i].IsPreallocated) { 9624 Flags.setPreallocated(); 9625 // Set the byval flag for CCAssignFn callbacks that don't know about 9626 // preallocated. This way we can know how many bytes we should've 9627 // allocated and how many bytes a callee cleanup function will pop. If 9628 // we port preallocated to more targets, we'll have to add custom 9629 // preallocated handling in the various CC lowering callbacks. 9630 Flags.setByVal(); 9631 } 9632 if (Args[i].IsInAlloca) { 9633 Flags.setInAlloca(); 9634 // Set the byval flag for CCAssignFn callbacks that don't know about 9635 // inalloca. This way we can know how many bytes we should've allocated 9636 // and how many bytes a callee cleanup function will pop. If we port 9637 // inalloca to more targets, we'll have to add custom inalloca handling 9638 // in the various CC lowering callbacks. 9639 Flags.setByVal(); 9640 } 9641 Align MemAlign; 9642 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9643 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 9644 Flags.setByValSize(FrameSize); 9645 9646 // info is not there but there are cases it cannot get right. 9647 if (auto MA = Args[i].Alignment) 9648 MemAlign = *MA; 9649 else 9650 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 9651 } else if (auto MA = Args[i].Alignment) { 9652 MemAlign = *MA; 9653 } else { 9654 MemAlign = OriginalAlignment; 9655 } 9656 Flags.setMemAlign(MemAlign); 9657 if (Args[i].IsNest) 9658 Flags.setNest(); 9659 if (NeedsRegBlock) 9660 Flags.setInConsecutiveRegs(); 9661 9662 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9663 CLI.CallConv, VT); 9664 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9665 CLI.CallConv, VT); 9666 SmallVector<SDValue, 4> Parts(NumParts); 9667 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9668 9669 if (Args[i].IsSExt) 9670 ExtendKind = ISD::SIGN_EXTEND; 9671 else if (Args[i].IsZExt) 9672 ExtendKind = ISD::ZERO_EXTEND; 9673 9674 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9675 // for now. 9676 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9677 CanLowerReturn) { 9678 assert((CLI.RetTy == Args[i].Ty || 9679 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9680 CLI.RetTy->getPointerAddressSpace() == 9681 Args[i].Ty->getPointerAddressSpace())) && 9682 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9683 // Before passing 'returned' to the target lowering code, ensure that 9684 // either the register MVT and the actual EVT are the same size or that 9685 // the return value and argument are extended in the same way; in these 9686 // cases it's safe to pass the argument register value unchanged as the 9687 // return register value (although it's at the target's option whether 9688 // to do so) 9689 // TODO: allow code generation to take advantage of partially preserved 9690 // registers rather than clobbering the entire register when the 9691 // parameter extension method is not compatible with the return 9692 // extension method 9693 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9694 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9695 CLI.RetZExt == Args[i].IsZExt)) 9696 Flags.setReturned(); 9697 } 9698 9699 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9700 CLI.CallConv, ExtendKind); 9701 9702 for (unsigned j = 0; j != NumParts; ++j) { 9703 // if it isn't first piece, alignment must be 1 9704 // For scalable vectors the scalable part is currently handled 9705 // by individual targets, so we just use the known minimum size here. 9706 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9707 i < CLI.NumFixedArgs, i, 9708 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9709 if (NumParts > 1 && j == 0) 9710 MyFlags.Flags.setSplit(); 9711 else if (j != 0) { 9712 MyFlags.Flags.setOrigAlign(Align(1)); 9713 if (j == NumParts - 1) 9714 MyFlags.Flags.setSplitEnd(); 9715 } 9716 9717 CLI.Outs.push_back(MyFlags); 9718 CLI.OutVals.push_back(Parts[j]); 9719 } 9720 9721 if (NeedsRegBlock && Value == NumValues - 1) 9722 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9723 } 9724 } 9725 9726 SmallVector<SDValue, 4> InVals; 9727 CLI.Chain = LowerCall(CLI, InVals); 9728 9729 // Update CLI.InVals to use outside of this function. 9730 CLI.InVals = InVals; 9731 9732 // Verify that the target's LowerCall behaved as expected. 9733 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9734 "LowerCall didn't return a valid chain!"); 9735 assert((!CLI.IsTailCall || InVals.empty()) && 9736 "LowerCall emitted a return value for a tail call!"); 9737 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9738 "LowerCall didn't emit the correct number of values!"); 9739 9740 // For a tail call, the return value is merely live-out and there aren't 9741 // any nodes in the DAG representing it. Return a special value to 9742 // indicate that a tail call has been emitted and no more Instructions 9743 // should be processed in the current block. 9744 if (CLI.IsTailCall) { 9745 CLI.DAG.setRoot(CLI.Chain); 9746 return std::make_pair(SDValue(), SDValue()); 9747 } 9748 9749 #ifndef NDEBUG 9750 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9751 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9752 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9753 "LowerCall emitted a value with the wrong type!"); 9754 } 9755 #endif 9756 9757 SmallVector<SDValue, 4> ReturnValues; 9758 if (!CanLowerReturn) { 9759 // The instruction result is the result of loading from the 9760 // hidden sret parameter. 9761 SmallVector<EVT, 1> PVTs; 9762 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9763 9764 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9765 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9766 EVT PtrVT = PVTs[0]; 9767 9768 unsigned NumValues = RetTys.size(); 9769 ReturnValues.resize(NumValues); 9770 SmallVector<SDValue, 4> Chains(NumValues); 9771 9772 // An aggregate return value cannot wrap around the address space, so 9773 // offsets to its parts don't wrap either. 9774 SDNodeFlags Flags; 9775 Flags.setNoUnsignedWrap(true); 9776 9777 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9778 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9779 for (unsigned i = 0; i < NumValues; ++i) { 9780 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9781 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9782 PtrVT), Flags); 9783 SDValue L = CLI.DAG.getLoad( 9784 RetTys[i], CLI.DL, CLI.Chain, Add, 9785 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9786 DemoteStackIdx, Offsets[i]), 9787 HiddenSRetAlign); 9788 ReturnValues[i] = L; 9789 Chains[i] = L.getValue(1); 9790 } 9791 9792 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9793 } else { 9794 // Collect the legal value parts into potentially illegal values 9795 // that correspond to the original function's return values. 9796 Optional<ISD::NodeType> AssertOp; 9797 if (CLI.RetSExt) 9798 AssertOp = ISD::AssertSext; 9799 else if (CLI.RetZExt) 9800 AssertOp = ISD::AssertZext; 9801 unsigned CurReg = 0; 9802 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9803 EVT VT = RetTys[I]; 9804 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9805 CLI.CallConv, VT); 9806 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9807 CLI.CallConv, VT); 9808 9809 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9810 NumRegs, RegisterVT, VT, nullptr, 9811 CLI.CallConv, AssertOp)); 9812 CurReg += NumRegs; 9813 } 9814 9815 // For a function returning void, there is no return value. We can't create 9816 // such a node, so we just return a null return value in that case. In 9817 // that case, nothing will actually look at the value. 9818 if (ReturnValues.empty()) 9819 return std::make_pair(SDValue(), CLI.Chain); 9820 } 9821 9822 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9823 CLI.DAG.getVTList(RetTys), ReturnValues); 9824 return std::make_pair(Res, CLI.Chain); 9825 } 9826 9827 /// Places new result values for the node in Results (their number 9828 /// and types must exactly match those of the original return values of 9829 /// the node), or leaves Results empty, which indicates that the node is not 9830 /// to be custom lowered after all. 9831 void TargetLowering::LowerOperationWrapper(SDNode *N, 9832 SmallVectorImpl<SDValue> &Results, 9833 SelectionDAG &DAG) const { 9834 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9835 9836 if (!Res.getNode()) 9837 return; 9838 9839 // If the original node has one result, take the return value from 9840 // LowerOperation as is. It might not be result number 0. 9841 if (N->getNumValues() == 1) { 9842 Results.push_back(Res); 9843 return; 9844 } 9845 9846 // If the original node has multiple results, then the return node should 9847 // have the same number of results. 9848 assert((N->getNumValues() == Res->getNumValues()) && 9849 "Lowering returned the wrong number of results!"); 9850 9851 // Places new result values base on N result number. 9852 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9853 Results.push_back(Res.getValue(I)); 9854 } 9855 9856 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9857 llvm_unreachable("LowerOperation not implemented for this target!"); 9858 } 9859 9860 void 9861 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9862 SDValue Op = getNonRegisterValue(V); 9863 assert((Op.getOpcode() != ISD::CopyFromReg || 9864 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9865 "Copy from a reg to the same reg!"); 9866 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9867 9868 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9869 // If this is an InlineAsm we have to match the registers required, not the 9870 // notional registers required by the type. 9871 9872 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9873 None); // This is not an ABI copy. 9874 SDValue Chain = DAG.getEntryNode(); 9875 9876 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9877 FuncInfo.PreferredExtendType.end()) 9878 ? ISD::ANY_EXTEND 9879 : FuncInfo.PreferredExtendType[V]; 9880 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9881 PendingExports.push_back(Chain); 9882 } 9883 9884 #include "llvm/CodeGen/SelectionDAGISel.h" 9885 9886 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9887 /// entry block, return true. This includes arguments used by switches, since 9888 /// the switch may expand into multiple basic blocks. 9889 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9890 // With FastISel active, we may be splitting blocks, so force creation 9891 // of virtual registers for all non-dead arguments. 9892 if (FastISel) 9893 return A->use_empty(); 9894 9895 const BasicBlock &Entry = A->getParent()->front(); 9896 for (const User *U : A->users()) 9897 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9898 return false; // Use not in entry block. 9899 9900 return true; 9901 } 9902 9903 using ArgCopyElisionMapTy = 9904 DenseMap<const Argument *, 9905 std::pair<const AllocaInst *, const StoreInst *>>; 9906 9907 /// Scan the entry block of the function in FuncInfo for arguments that look 9908 /// like copies into a local alloca. Record any copied arguments in 9909 /// ArgCopyElisionCandidates. 9910 static void 9911 findArgumentCopyElisionCandidates(const DataLayout &DL, 9912 FunctionLoweringInfo *FuncInfo, 9913 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9914 // Record the state of every static alloca used in the entry block. Argument 9915 // allocas are all used in the entry block, so we need approximately as many 9916 // entries as we have arguments. 9917 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9918 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9919 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9920 StaticAllocas.reserve(NumArgs * 2); 9921 9922 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9923 if (!V) 9924 return nullptr; 9925 V = V->stripPointerCasts(); 9926 const auto *AI = dyn_cast<AllocaInst>(V); 9927 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9928 return nullptr; 9929 auto Iter = StaticAllocas.insert({AI, Unknown}); 9930 return &Iter.first->second; 9931 }; 9932 9933 // Look for stores of arguments to static allocas. Look through bitcasts and 9934 // GEPs to handle type coercions, as long as the alloca is fully initialized 9935 // by the store. Any non-store use of an alloca escapes it and any subsequent 9936 // unanalyzed store might write it. 9937 // FIXME: Handle structs initialized with multiple stores. 9938 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9939 // Look for stores, and handle non-store uses conservatively. 9940 const auto *SI = dyn_cast<StoreInst>(&I); 9941 if (!SI) { 9942 // We will look through cast uses, so ignore them completely. 9943 if (I.isCast()) 9944 continue; 9945 // Ignore debug info and pseudo op intrinsics, they don't escape or store 9946 // to allocas. 9947 if (I.isDebugOrPseudoInst()) 9948 continue; 9949 // This is an unknown instruction. Assume it escapes or writes to all 9950 // static alloca operands. 9951 for (const Use &U : I.operands()) { 9952 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9953 *Info = StaticAllocaInfo::Clobbered; 9954 } 9955 continue; 9956 } 9957 9958 // If the stored value is a static alloca, mark it as escaped. 9959 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9960 *Info = StaticAllocaInfo::Clobbered; 9961 9962 // Check if the destination is a static alloca. 9963 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9964 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9965 if (!Info) 9966 continue; 9967 const AllocaInst *AI = cast<AllocaInst>(Dst); 9968 9969 // Skip allocas that have been initialized or clobbered. 9970 if (*Info != StaticAllocaInfo::Unknown) 9971 continue; 9972 9973 // Check if the stored value is an argument, and that this store fully 9974 // initializes the alloca. 9975 // If the argument type has padding bits we can't directly forward a pointer 9976 // as the upper bits may contain garbage. 9977 // Don't elide copies from the same argument twice. 9978 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9979 const auto *Arg = dyn_cast<Argument>(Val); 9980 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9981 Arg->getType()->isEmptyTy() || 9982 DL.getTypeStoreSize(Arg->getType()) != 9983 DL.getTypeAllocSize(AI->getAllocatedType()) || 9984 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 9985 ArgCopyElisionCandidates.count(Arg)) { 9986 *Info = StaticAllocaInfo::Clobbered; 9987 continue; 9988 } 9989 9990 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9991 << '\n'); 9992 9993 // Mark this alloca and store for argument copy elision. 9994 *Info = StaticAllocaInfo::Elidable; 9995 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9996 9997 // Stop scanning if we've seen all arguments. This will happen early in -O0 9998 // builds, which is useful, because -O0 builds have large entry blocks and 9999 // many allocas. 10000 if (ArgCopyElisionCandidates.size() == NumArgs) 10001 break; 10002 } 10003 } 10004 10005 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10006 /// ArgVal is a load from a suitable fixed stack object. 10007 static void tryToElideArgumentCopy( 10008 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10009 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10010 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10011 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10012 SDValue ArgVal, bool &ArgHasUses) { 10013 // Check if this is a load from a fixed stack object. 10014 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10015 if (!LNode) 10016 return; 10017 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10018 if (!FINode) 10019 return; 10020 10021 // Check that the fixed stack object is the right size and alignment. 10022 // Look at the alignment that the user wrote on the alloca instead of looking 10023 // at the stack object. 10024 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10025 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10026 const AllocaInst *AI = ArgCopyIter->second.first; 10027 int FixedIndex = FINode->getIndex(); 10028 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10029 int OldIndex = AllocaIndex; 10030 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10031 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10032 LLVM_DEBUG( 10033 dbgs() << " argument copy elision failed due to bad fixed stack " 10034 "object size\n"); 10035 return; 10036 } 10037 Align RequiredAlignment = AI->getAlign(); 10038 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10039 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10040 "greater than stack argument alignment (" 10041 << DebugStr(RequiredAlignment) << " vs " 10042 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10043 return; 10044 } 10045 10046 // Perform the elision. Delete the old stack object and replace its only use 10047 // in the variable info map. Mark the stack object as mutable. 10048 LLVM_DEBUG({ 10049 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10050 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10051 << '\n'; 10052 }); 10053 MFI.RemoveStackObject(OldIndex); 10054 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10055 AllocaIndex = FixedIndex; 10056 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10057 Chains.push_back(ArgVal.getValue(1)); 10058 10059 // Avoid emitting code for the store implementing the copy. 10060 const StoreInst *SI = ArgCopyIter->second.second; 10061 ElidedArgCopyInstrs.insert(SI); 10062 10063 // Check for uses of the argument again so that we can avoid exporting ArgVal 10064 // if it is't used by anything other than the store. 10065 for (const Value *U : Arg.users()) { 10066 if (U != SI) { 10067 ArgHasUses = true; 10068 break; 10069 } 10070 } 10071 } 10072 10073 void SelectionDAGISel::LowerArguments(const Function &F) { 10074 SelectionDAG &DAG = SDB->DAG; 10075 SDLoc dl = SDB->getCurSDLoc(); 10076 const DataLayout &DL = DAG.getDataLayout(); 10077 SmallVector<ISD::InputArg, 16> Ins; 10078 10079 // In Naked functions we aren't going to save any registers. 10080 if (F.hasFnAttribute(Attribute::Naked)) 10081 return; 10082 10083 if (!FuncInfo->CanLowerReturn) { 10084 // Put in an sret pointer parameter before all the other parameters. 10085 SmallVector<EVT, 1> ValueVTs; 10086 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10087 F.getReturnType()->getPointerTo( 10088 DAG.getDataLayout().getAllocaAddrSpace()), 10089 ValueVTs); 10090 10091 // NOTE: Assuming that a pointer will never break down to more than one VT 10092 // or one register. 10093 ISD::ArgFlagsTy Flags; 10094 Flags.setSRet(); 10095 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10096 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10097 ISD::InputArg::NoArgIndex, 0); 10098 Ins.push_back(RetArg); 10099 } 10100 10101 // Look for stores of arguments to static allocas. Mark such arguments with a 10102 // flag to ask the target to give us the memory location of that argument if 10103 // available. 10104 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10105 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10106 ArgCopyElisionCandidates); 10107 10108 // Set up the incoming argument description vector. 10109 for (const Argument &Arg : F.args()) { 10110 unsigned ArgNo = Arg.getArgNo(); 10111 SmallVector<EVT, 4> ValueVTs; 10112 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10113 bool isArgValueUsed = !Arg.use_empty(); 10114 unsigned PartBase = 0; 10115 Type *FinalType = Arg.getType(); 10116 if (Arg.hasAttribute(Attribute::ByVal)) 10117 FinalType = Arg.getParamByValType(); 10118 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10119 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10120 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10121 Value != NumValues; ++Value) { 10122 EVT VT = ValueVTs[Value]; 10123 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10124 ISD::ArgFlagsTy Flags; 10125 10126 10127 if (Arg.getType()->isPointerTy()) { 10128 Flags.setPointer(); 10129 Flags.setPointerAddrSpace( 10130 cast<PointerType>(Arg.getType())->getAddressSpace()); 10131 } 10132 if (Arg.hasAttribute(Attribute::ZExt)) 10133 Flags.setZExt(); 10134 if (Arg.hasAttribute(Attribute::SExt)) 10135 Flags.setSExt(); 10136 if (Arg.hasAttribute(Attribute::InReg)) { 10137 // If we are using vectorcall calling convention, a structure that is 10138 // passed InReg - is surely an HVA 10139 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10140 isa<StructType>(Arg.getType())) { 10141 // The first value of a structure is marked 10142 if (0 == Value) 10143 Flags.setHvaStart(); 10144 Flags.setHva(); 10145 } 10146 // Set InReg Flag 10147 Flags.setInReg(); 10148 } 10149 if (Arg.hasAttribute(Attribute::StructRet)) 10150 Flags.setSRet(); 10151 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10152 Flags.setSwiftSelf(); 10153 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10154 Flags.setSwiftAsync(); 10155 if (Arg.hasAttribute(Attribute::SwiftError)) 10156 Flags.setSwiftError(); 10157 if (Arg.hasAttribute(Attribute::ByVal)) 10158 Flags.setByVal(); 10159 if (Arg.hasAttribute(Attribute::ByRef)) 10160 Flags.setByRef(); 10161 if (Arg.hasAttribute(Attribute::InAlloca)) { 10162 Flags.setInAlloca(); 10163 // Set the byval flag for CCAssignFn callbacks that don't know about 10164 // inalloca. This way we can know how many bytes we should've allocated 10165 // and how many bytes a callee cleanup function will pop. If we port 10166 // inalloca to more targets, we'll have to add custom inalloca handling 10167 // in the various CC lowering callbacks. 10168 Flags.setByVal(); 10169 } 10170 if (Arg.hasAttribute(Attribute::Preallocated)) { 10171 Flags.setPreallocated(); 10172 // Set the byval flag for CCAssignFn callbacks that don't know about 10173 // preallocated. This way we can know how many bytes we should've 10174 // allocated and how many bytes a callee cleanup function will pop. If 10175 // we port preallocated to more targets, we'll have to add custom 10176 // preallocated handling in the various CC lowering callbacks. 10177 Flags.setByVal(); 10178 } 10179 10180 // Certain targets (such as MIPS), may have a different ABI alignment 10181 // for a type depending on the context. Give the target a chance to 10182 // specify the alignment it wants. 10183 const Align OriginalAlignment( 10184 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10185 Flags.setOrigAlign(OriginalAlignment); 10186 10187 Align MemAlign; 10188 Type *ArgMemTy = nullptr; 10189 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10190 Flags.isByRef()) { 10191 if (!ArgMemTy) 10192 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10193 10194 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10195 10196 // For in-memory arguments, size and alignment should be passed from FE. 10197 // BE will guess if this info is not there but there are cases it cannot 10198 // get right. 10199 if (auto ParamAlign = Arg.getParamStackAlign()) 10200 MemAlign = *ParamAlign; 10201 else if ((ParamAlign = Arg.getParamAlign())) 10202 MemAlign = *ParamAlign; 10203 else 10204 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10205 if (Flags.isByRef()) 10206 Flags.setByRefSize(MemSize); 10207 else 10208 Flags.setByValSize(MemSize); 10209 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10210 MemAlign = *ParamAlign; 10211 } else { 10212 MemAlign = OriginalAlignment; 10213 } 10214 Flags.setMemAlign(MemAlign); 10215 10216 if (Arg.hasAttribute(Attribute::Nest)) 10217 Flags.setNest(); 10218 if (NeedsRegBlock) 10219 Flags.setInConsecutiveRegs(); 10220 if (ArgCopyElisionCandidates.count(&Arg)) 10221 Flags.setCopyElisionCandidate(); 10222 if (Arg.hasAttribute(Attribute::Returned)) 10223 Flags.setReturned(); 10224 10225 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10226 *CurDAG->getContext(), F.getCallingConv(), VT); 10227 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10228 *CurDAG->getContext(), F.getCallingConv(), VT); 10229 for (unsigned i = 0; i != NumRegs; ++i) { 10230 // For scalable vectors, use the minimum size; individual targets 10231 // are responsible for handling scalable vector arguments and 10232 // return values. 10233 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10234 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10235 if (NumRegs > 1 && i == 0) 10236 MyFlags.Flags.setSplit(); 10237 // if it isn't first piece, alignment must be 1 10238 else if (i > 0) { 10239 MyFlags.Flags.setOrigAlign(Align(1)); 10240 if (i == NumRegs - 1) 10241 MyFlags.Flags.setSplitEnd(); 10242 } 10243 Ins.push_back(MyFlags); 10244 } 10245 if (NeedsRegBlock && Value == NumValues - 1) 10246 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10247 PartBase += VT.getStoreSize().getKnownMinSize(); 10248 } 10249 } 10250 10251 // Call the target to set up the argument values. 10252 SmallVector<SDValue, 8> InVals; 10253 SDValue NewRoot = TLI->LowerFormalArguments( 10254 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10255 10256 // Verify that the target's LowerFormalArguments behaved as expected. 10257 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10258 "LowerFormalArguments didn't return a valid chain!"); 10259 assert(InVals.size() == Ins.size() && 10260 "LowerFormalArguments didn't emit the correct number of values!"); 10261 LLVM_DEBUG({ 10262 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10263 assert(InVals[i].getNode() && 10264 "LowerFormalArguments emitted a null value!"); 10265 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10266 "LowerFormalArguments emitted a value with the wrong type!"); 10267 } 10268 }); 10269 10270 // Update the DAG with the new chain value resulting from argument lowering. 10271 DAG.setRoot(NewRoot); 10272 10273 // Set up the argument values. 10274 unsigned i = 0; 10275 if (!FuncInfo->CanLowerReturn) { 10276 // Create a virtual register for the sret pointer, and put in a copy 10277 // from the sret argument into it. 10278 SmallVector<EVT, 1> ValueVTs; 10279 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10280 F.getReturnType()->getPointerTo( 10281 DAG.getDataLayout().getAllocaAddrSpace()), 10282 ValueVTs); 10283 MVT VT = ValueVTs[0].getSimpleVT(); 10284 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10285 Optional<ISD::NodeType> AssertOp = None; 10286 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10287 nullptr, F.getCallingConv(), AssertOp); 10288 10289 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10290 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10291 Register SRetReg = 10292 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10293 FuncInfo->DemoteRegister = SRetReg; 10294 NewRoot = 10295 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10296 DAG.setRoot(NewRoot); 10297 10298 // i indexes lowered arguments. Bump it past the hidden sret argument. 10299 ++i; 10300 } 10301 10302 SmallVector<SDValue, 4> Chains; 10303 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10304 for (const Argument &Arg : F.args()) { 10305 SmallVector<SDValue, 4> ArgValues; 10306 SmallVector<EVT, 4> ValueVTs; 10307 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10308 unsigned NumValues = ValueVTs.size(); 10309 if (NumValues == 0) 10310 continue; 10311 10312 bool ArgHasUses = !Arg.use_empty(); 10313 10314 // Elide the copying store if the target loaded this argument from a 10315 // suitable fixed stack object. 10316 if (Ins[i].Flags.isCopyElisionCandidate()) { 10317 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10318 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10319 InVals[i], ArgHasUses); 10320 } 10321 10322 // If this argument is unused then remember its value. It is used to generate 10323 // debugging information. 10324 bool isSwiftErrorArg = 10325 TLI->supportSwiftError() && 10326 Arg.hasAttribute(Attribute::SwiftError); 10327 if (!ArgHasUses && !isSwiftErrorArg) { 10328 SDB->setUnusedArgValue(&Arg, InVals[i]); 10329 10330 // Also remember any frame index for use in FastISel. 10331 if (FrameIndexSDNode *FI = 10332 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10333 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10334 } 10335 10336 for (unsigned Val = 0; Val != NumValues; ++Val) { 10337 EVT VT = ValueVTs[Val]; 10338 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10339 F.getCallingConv(), VT); 10340 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10341 *CurDAG->getContext(), F.getCallingConv(), VT); 10342 10343 // Even an apparent 'unused' swifterror argument needs to be returned. So 10344 // we do generate a copy for it that can be used on return from the 10345 // function. 10346 if (ArgHasUses || isSwiftErrorArg) { 10347 Optional<ISD::NodeType> AssertOp; 10348 if (Arg.hasAttribute(Attribute::SExt)) 10349 AssertOp = ISD::AssertSext; 10350 else if (Arg.hasAttribute(Attribute::ZExt)) 10351 AssertOp = ISD::AssertZext; 10352 10353 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10354 PartVT, VT, nullptr, 10355 F.getCallingConv(), AssertOp)); 10356 } 10357 10358 i += NumParts; 10359 } 10360 10361 // We don't need to do anything else for unused arguments. 10362 if (ArgValues.empty()) 10363 continue; 10364 10365 // Note down frame index. 10366 if (FrameIndexSDNode *FI = 10367 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10368 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10369 10370 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10371 SDB->getCurSDLoc()); 10372 10373 SDB->setValue(&Arg, Res); 10374 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10375 // We want to associate the argument with the frame index, among 10376 // involved operands, that correspond to the lowest address. The 10377 // getCopyFromParts function, called earlier, is swapping the order of 10378 // the operands to BUILD_PAIR depending on endianness. The result of 10379 // that swapping is that the least significant bits of the argument will 10380 // be in the first operand of the BUILD_PAIR node, and the most 10381 // significant bits will be in the second operand. 10382 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10383 if (LoadSDNode *LNode = 10384 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10385 if (FrameIndexSDNode *FI = 10386 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10387 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10388 } 10389 10390 // Analyses past this point are naive and don't expect an assertion. 10391 if (Res.getOpcode() == ISD::AssertZext) 10392 Res = Res.getOperand(0); 10393 10394 // Update the SwiftErrorVRegDefMap. 10395 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10396 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10397 if (Register::isVirtualRegister(Reg)) 10398 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10399 Reg); 10400 } 10401 10402 // If this argument is live outside of the entry block, insert a copy from 10403 // wherever we got it to the vreg that other BB's will reference it as. 10404 if (Res.getOpcode() == ISD::CopyFromReg) { 10405 // If we can, though, try to skip creating an unnecessary vreg. 10406 // FIXME: This isn't very clean... it would be nice to make this more 10407 // general. 10408 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10409 if (Register::isVirtualRegister(Reg)) { 10410 FuncInfo->ValueMap[&Arg] = Reg; 10411 continue; 10412 } 10413 } 10414 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10415 FuncInfo->InitializeRegForValue(&Arg); 10416 SDB->CopyToExportRegsIfNeeded(&Arg); 10417 } 10418 } 10419 10420 if (!Chains.empty()) { 10421 Chains.push_back(NewRoot); 10422 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10423 } 10424 10425 DAG.setRoot(NewRoot); 10426 10427 assert(i == InVals.size() && "Argument register count mismatch!"); 10428 10429 // If any argument copy elisions occurred and we have debug info, update the 10430 // stale frame indices used in the dbg.declare variable info table. 10431 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10432 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10433 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10434 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10435 if (I != ArgCopyElisionFrameIndexMap.end()) 10436 VI.Slot = I->second; 10437 } 10438 } 10439 10440 // Finally, if the target has anything special to do, allow it to do so. 10441 emitFunctionEntryCode(); 10442 } 10443 10444 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10445 /// ensure constants are generated when needed. Remember the virtual registers 10446 /// that need to be added to the Machine PHI nodes as input. We cannot just 10447 /// directly add them, because expansion might result in multiple MBB's for one 10448 /// BB. As such, the start of the BB might correspond to a different MBB than 10449 /// the end. 10450 void 10451 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10452 const Instruction *TI = LLVMBB->getTerminator(); 10453 10454 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10455 10456 // Check PHI nodes in successors that expect a value to be available from this 10457 // block. 10458 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10459 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10460 if (!isa<PHINode>(SuccBB->begin())) continue; 10461 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10462 10463 // If this terminator has multiple identical successors (common for 10464 // switches), only handle each succ once. 10465 if (!SuccsHandled.insert(SuccMBB).second) 10466 continue; 10467 10468 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10469 10470 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10471 // nodes and Machine PHI nodes, but the incoming operands have not been 10472 // emitted yet. 10473 for (const PHINode &PN : SuccBB->phis()) { 10474 // Ignore dead phi's. 10475 if (PN.use_empty()) 10476 continue; 10477 10478 // Skip empty types 10479 if (PN.getType()->isEmptyTy()) 10480 continue; 10481 10482 unsigned Reg; 10483 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10484 10485 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10486 unsigned &RegOut = ConstantsOut[C]; 10487 if (RegOut == 0) { 10488 RegOut = FuncInfo.CreateRegs(C); 10489 CopyValueToVirtualRegister(C, RegOut); 10490 } 10491 Reg = RegOut; 10492 } else { 10493 DenseMap<const Value *, Register>::iterator I = 10494 FuncInfo.ValueMap.find(PHIOp); 10495 if (I != FuncInfo.ValueMap.end()) 10496 Reg = I->second; 10497 else { 10498 assert(isa<AllocaInst>(PHIOp) && 10499 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10500 "Didn't codegen value into a register!??"); 10501 Reg = FuncInfo.CreateRegs(PHIOp); 10502 CopyValueToVirtualRegister(PHIOp, Reg); 10503 } 10504 } 10505 10506 // Remember that this register needs to added to the machine PHI node as 10507 // the input for this MBB. 10508 SmallVector<EVT, 4> ValueVTs; 10509 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10510 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10511 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10512 EVT VT = ValueVTs[vti]; 10513 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10514 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10515 FuncInfo.PHINodesToUpdate.push_back( 10516 std::make_pair(&*MBBI++, Reg + i)); 10517 Reg += NumRegisters; 10518 } 10519 } 10520 } 10521 10522 ConstantsOut.clear(); 10523 } 10524 10525 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10526 /// is 0. 10527 MachineBasicBlock * 10528 SelectionDAGBuilder::StackProtectorDescriptor:: 10529 AddSuccessorMBB(const BasicBlock *BB, 10530 MachineBasicBlock *ParentMBB, 10531 bool IsLikely, 10532 MachineBasicBlock *SuccMBB) { 10533 // If SuccBB has not been created yet, create it. 10534 if (!SuccMBB) { 10535 MachineFunction *MF = ParentMBB->getParent(); 10536 MachineFunction::iterator BBI(ParentMBB); 10537 SuccMBB = MF->CreateMachineBasicBlock(BB); 10538 MF->insert(++BBI, SuccMBB); 10539 } 10540 // Add it as a successor of ParentMBB. 10541 ParentMBB->addSuccessor( 10542 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10543 return SuccMBB; 10544 } 10545 10546 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10547 MachineFunction::iterator I(MBB); 10548 if (++I == FuncInfo.MF->end()) 10549 return nullptr; 10550 return &*I; 10551 } 10552 10553 /// During lowering new call nodes can be created (such as memset, etc.). 10554 /// Those will become new roots of the current DAG, but complications arise 10555 /// when they are tail calls. In such cases, the call lowering will update 10556 /// the root, but the builder still needs to know that a tail call has been 10557 /// lowered in order to avoid generating an additional return. 10558 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10559 // If the node is null, we do have a tail call. 10560 if (MaybeTC.getNode() != nullptr) 10561 DAG.setRoot(MaybeTC); 10562 else 10563 HasTailCall = true; 10564 } 10565 10566 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10567 MachineBasicBlock *SwitchMBB, 10568 MachineBasicBlock *DefaultMBB) { 10569 MachineFunction *CurMF = FuncInfo.MF; 10570 MachineBasicBlock *NextMBB = nullptr; 10571 MachineFunction::iterator BBI(W.MBB); 10572 if (++BBI != FuncInfo.MF->end()) 10573 NextMBB = &*BBI; 10574 10575 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10576 10577 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10578 10579 if (Size == 2 && W.MBB == SwitchMBB) { 10580 // If any two of the cases has the same destination, and if one value 10581 // is the same as the other, but has one bit unset that the other has set, 10582 // use bit manipulation to do two compares at once. For example: 10583 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10584 // TODO: This could be extended to merge any 2 cases in switches with 3 10585 // cases. 10586 // TODO: Handle cases where W.CaseBB != SwitchBB. 10587 CaseCluster &Small = *W.FirstCluster; 10588 CaseCluster &Big = *W.LastCluster; 10589 10590 if (Small.Low == Small.High && Big.Low == Big.High && 10591 Small.MBB == Big.MBB) { 10592 const APInt &SmallValue = Small.Low->getValue(); 10593 const APInt &BigValue = Big.Low->getValue(); 10594 10595 // Check that there is only one bit different. 10596 APInt CommonBit = BigValue ^ SmallValue; 10597 if (CommonBit.isPowerOf2()) { 10598 SDValue CondLHS = getValue(Cond); 10599 EVT VT = CondLHS.getValueType(); 10600 SDLoc DL = getCurSDLoc(); 10601 10602 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10603 DAG.getConstant(CommonBit, DL, VT)); 10604 SDValue Cond = DAG.getSetCC( 10605 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10606 ISD::SETEQ); 10607 10608 // Update successor info. 10609 // Both Small and Big will jump to Small.BB, so we sum up the 10610 // probabilities. 10611 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10612 if (BPI) 10613 addSuccessorWithProb( 10614 SwitchMBB, DefaultMBB, 10615 // The default destination is the first successor in IR. 10616 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10617 else 10618 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10619 10620 // Insert the true branch. 10621 SDValue BrCond = 10622 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10623 DAG.getBasicBlock(Small.MBB)); 10624 // Insert the false branch. 10625 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10626 DAG.getBasicBlock(DefaultMBB)); 10627 10628 DAG.setRoot(BrCond); 10629 return; 10630 } 10631 } 10632 } 10633 10634 if (TM.getOptLevel() != CodeGenOpt::None) { 10635 // Here, we order cases by probability so the most likely case will be 10636 // checked first. However, two clusters can have the same probability in 10637 // which case their relative ordering is non-deterministic. So we use Low 10638 // as a tie-breaker as clusters are guaranteed to never overlap. 10639 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10640 [](const CaseCluster &a, const CaseCluster &b) { 10641 return a.Prob != b.Prob ? 10642 a.Prob > b.Prob : 10643 a.Low->getValue().slt(b.Low->getValue()); 10644 }); 10645 10646 // Rearrange the case blocks so that the last one falls through if possible 10647 // without changing the order of probabilities. 10648 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10649 --I; 10650 if (I->Prob > W.LastCluster->Prob) 10651 break; 10652 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10653 std::swap(*I, *W.LastCluster); 10654 break; 10655 } 10656 } 10657 } 10658 10659 // Compute total probability. 10660 BranchProbability DefaultProb = W.DefaultProb; 10661 BranchProbability UnhandledProbs = DefaultProb; 10662 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10663 UnhandledProbs += I->Prob; 10664 10665 MachineBasicBlock *CurMBB = W.MBB; 10666 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10667 bool FallthroughUnreachable = false; 10668 MachineBasicBlock *Fallthrough; 10669 if (I == W.LastCluster) { 10670 // For the last cluster, fall through to the default destination. 10671 Fallthrough = DefaultMBB; 10672 FallthroughUnreachable = isa<UnreachableInst>( 10673 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10674 } else { 10675 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10676 CurMF->insert(BBI, Fallthrough); 10677 // Put Cond in a virtual register to make it available from the new blocks. 10678 ExportFromCurrentBlock(Cond); 10679 } 10680 UnhandledProbs -= I->Prob; 10681 10682 switch (I->Kind) { 10683 case CC_JumpTable: { 10684 // FIXME: Optimize away range check based on pivot comparisons. 10685 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10686 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10687 10688 // The jump block hasn't been inserted yet; insert it here. 10689 MachineBasicBlock *JumpMBB = JT->MBB; 10690 CurMF->insert(BBI, JumpMBB); 10691 10692 auto JumpProb = I->Prob; 10693 auto FallthroughProb = UnhandledProbs; 10694 10695 // If the default statement is a target of the jump table, we evenly 10696 // distribute the default probability to successors of CurMBB. Also 10697 // update the probability on the edge from JumpMBB to Fallthrough. 10698 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10699 SE = JumpMBB->succ_end(); 10700 SI != SE; ++SI) { 10701 if (*SI == DefaultMBB) { 10702 JumpProb += DefaultProb / 2; 10703 FallthroughProb -= DefaultProb / 2; 10704 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10705 JumpMBB->normalizeSuccProbs(); 10706 break; 10707 } 10708 } 10709 10710 if (FallthroughUnreachable) { 10711 // Skip the range check if the fallthrough block is unreachable. 10712 JTH->OmitRangeCheck = true; 10713 } 10714 10715 if (!JTH->OmitRangeCheck) 10716 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10717 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10718 CurMBB->normalizeSuccProbs(); 10719 10720 // The jump table header will be inserted in our current block, do the 10721 // range check, and fall through to our fallthrough block. 10722 JTH->HeaderBB = CurMBB; 10723 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10724 10725 // If we're in the right place, emit the jump table header right now. 10726 if (CurMBB == SwitchMBB) { 10727 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10728 JTH->Emitted = true; 10729 } 10730 break; 10731 } 10732 case CC_BitTests: { 10733 // FIXME: Optimize away range check based on pivot comparisons. 10734 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10735 10736 // The bit test blocks haven't been inserted yet; insert them here. 10737 for (BitTestCase &BTC : BTB->Cases) 10738 CurMF->insert(BBI, BTC.ThisBB); 10739 10740 // Fill in fields of the BitTestBlock. 10741 BTB->Parent = CurMBB; 10742 BTB->Default = Fallthrough; 10743 10744 BTB->DefaultProb = UnhandledProbs; 10745 // If the cases in bit test don't form a contiguous range, we evenly 10746 // distribute the probability on the edge to Fallthrough to two 10747 // successors of CurMBB. 10748 if (!BTB->ContiguousRange) { 10749 BTB->Prob += DefaultProb / 2; 10750 BTB->DefaultProb -= DefaultProb / 2; 10751 } 10752 10753 if (FallthroughUnreachable) { 10754 // Skip the range check if the fallthrough block is unreachable. 10755 BTB->OmitRangeCheck = true; 10756 } 10757 10758 // If we're in the right place, emit the bit test header right now. 10759 if (CurMBB == SwitchMBB) { 10760 visitBitTestHeader(*BTB, SwitchMBB); 10761 BTB->Emitted = true; 10762 } 10763 break; 10764 } 10765 case CC_Range: { 10766 const Value *RHS, *LHS, *MHS; 10767 ISD::CondCode CC; 10768 if (I->Low == I->High) { 10769 // Check Cond == I->Low. 10770 CC = ISD::SETEQ; 10771 LHS = Cond; 10772 RHS=I->Low; 10773 MHS = nullptr; 10774 } else { 10775 // Check I->Low <= Cond <= I->High. 10776 CC = ISD::SETLE; 10777 LHS = I->Low; 10778 MHS = Cond; 10779 RHS = I->High; 10780 } 10781 10782 // If Fallthrough is unreachable, fold away the comparison. 10783 if (FallthroughUnreachable) 10784 CC = ISD::SETTRUE; 10785 10786 // The false probability is the sum of all unhandled cases. 10787 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10788 getCurSDLoc(), I->Prob, UnhandledProbs); 10789 10790 if (CurMBB == SwitchMBB) 10791 visitSwitchCase(CB, SwitchMBB); 10792 else 10793 SL->SwitchCases.push_back(CB); 10794 10795 break; 10796 } 10797 } 10798 CurMBB = Fallthrough; 10799 } 10800 } 10801 10802 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10803 CaseClusterIt First, 10804 CaseClusterIt Last) { 10805 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10806 if (X.Prob != CC.Prob) 10807 return X.Prob > CC.Prob; 10808 10809 // Ties are broken by comparing the case value. 10810 return X.Low->getValue().slt(CC.Low->getValue()); 10811 }); 10812 } 10813 10814 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10815 const SwitchWorkListItem &W, 10816 Value *Cond, 10817 MachineBasicBlock *SwitchMBB) { 10818 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10819 "Clusters not sorted?"); 10820 10821 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10822 10823 // Balance the tree based on branch probabilities to create a near-optimal (in 10824 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10825 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10826 CaseClusterIt LastLeft = W.FirstCluster; 10827 CaseClusterIt FirstRight = W.LastCluster; 10828 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10829 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10830 10831 // Move LastLeft and FirstRight towards each other from opposite directions to 10832 // find a partitioning of the clusters which balances the probability on both 10833 // sides. If LeftProb and RightProb are equal, alternate which side is 10834 // taken to ensure 0-probability nodes are distributed evenly. 10835 unsigned I = 0; 10836 while (LastLeft + 1 < FirstRight) { 10837 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10838 LeftProb += (++LastLeft)->Prob; 10839 else 10840 RightProb += (--FirstRight)->Prob; 10841 I++; 10842 } 10843 10844 while (true) { 10845 // Our binary search tree differs from a typical BST in that ours can have up 10846 // to three values in each leaf. The pivot selection above doesn't take that 10847 // into account, which means the tree might require more nodes and be less 10848 // efficient. We compensate for this here. 10849 10850 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10851 unsigned NumRight = W.LastCluster - FirstRight + 1; 10852 10853 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10854 // If one side has less than 3 clusters, and the other has more than 3, 10855 // consider taking a cluster from the other side. 10856 10857 if (NumLeft < NumRight) { 10858 // Consider moving the first cluster on the right to the left side. 10859 CaseCluster &CC = *FirstRight; 10860 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10861 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10862 if (LeftSideRank <= RightSideRank) { 10863 // Moving the cluster to the left does not demote it. 10864 ++LastLeft; 10865 ++FirstRight; 10866 continue; 10867 } 10868 } else { 10869 assert(NumRight < NumLeft); 10870 // Consider moving the last element on the left to the right side. 10871 CaseCluster &CC = *LastLeft; 10872 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10873 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10874 if (RightSideRank <= LeftSideRank) { 10875 // Moving the cluster to the right does not demot it. 10876 --LastLeft; 10877 --FirstRight; 10878 continue; 10879 } 10880 } 10881 } 10882 break; 10883 } 10884 10885 assert(LastLeft + 1 == FirstRight); 10886 assert(LastLeft >= W.FirstCluster); 10887 assert(FirstRight <= W.LastCluster); 10888 10889 // Use the first element on the right as pivot since we will make less-than 10890 // comparisons against it. 10891 CaseClusterIt PivotCluster = FirstRight; 10892 assert(PivotCluster > W.FirstCluster); 10893 assert(PivotCluster <= W.LastCluster); 10894 10895 CaseClusterIt FirstLeft = W.FirstCluster; 10896 CaseClusterIt LastRight = W.LastCluster; 10897 10898 const ConstantInt *Pivot = PivotCluster->Low; 10899 10900 // New blocks will be inserted immediately after the current one. 10901 MachineFunction::iterator BBI(W.MBB); 10902 ++BBI; 10903 10904 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10905 // we can branch to its destination directly if it's squeezed exactly in 10906 // between the known lower bound and Pivot - 1. 10907 MachineBasicBlock *LeftMBB; 10908 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10909 FirstLeft->Low == W.GE && 10910 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10911 LeftMBB = FirstLeft->MBB; 10912 } else { 10913 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10914 FuncInfo.MF->insert(BBI, LeftMBB); 10915 WorkList.push_back( 10916 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10917 // Put Cond in a virtual register to make it available from the new blocks. 10918 ExportFromCurrentBlock(Cond); 10919 } 10920 10921 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10922 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10923 // directly if RHS.High equals the current upper bound. 10924 MachineBasicBlock *RightMBB; 10925 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10926 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10927 RightMBB = FirstRight->MBB; 10928 } else { 10929 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10930 FuncInfo.MF->insert(BBI, RightMBB); 10931 WorkList.push_back( 10932 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10933 // Put Cond in a virtual register to make it available from the new blocks. 10934 ExportFromCurrentBlock(Cond); 10935 } 10936 10937 // Create the CaseBlock record that will be used to lower the branch. 10938 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10939 getCurSDLoc(), LeftProb, RightProb); 10940 10941 if (W.MBB == SwitchMBB) 10942 visitSwitchCase(CB, SwitchMBB); 10943 else 10944 SL->SwitchCases.push_back(CB); 10945 } 10946 10947 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10948 // from the swith statement. 10949 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10950 BranchProbability PeeledCaseProb) { 10951 if (PeeledCaseProb == BranchProbability::getOne()) 10952 return BranchProbability::getZero(); 10953 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10954 10955 uint32_t Numerator = CaseProb.getNumerator(); 10956 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10957 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10958 } 10959 10960 // Try to peel the top probability case if it exceeds the threshold. 10961 // Return current MachineBasicBlock for the switch statement if the peeling 10962 // does not occur. 10963 // If the peeling is performed, return the newly created MachineBasicBlock 10964 // for the peeled switch statement. Also update Clusters to remove the peeled 10965 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10966 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10967 const SwitchInst &SI, CaseClusterVector &Clusters, 10968 BranchProbability &PeeledCaseProb) { 10969 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10970 // Don't perform if there is only one cluster or optimizing for size. 10971 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10972 TM.getOptLevel() == CodeGenOpt::None || 10973 SwitchMBB->getParent()->getFunction().hasMinSize()) 10974 return SwitchMBB; 10975 10976 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10977 unsigned PeeledCaseIndex = 0; 10978 bool SwitchPeeled = false; 10979 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10980 CaseCluster &CC = Clusters[Index]; 10981 if (CC.Prob < TopCaseProb) 10982 continue; 10983 TopCaseProb = CC.Prob; 10984 PeeledCaseIndex = Index; 10985 SwitchPeeled = true; 10986 } 10987 if (!SwitchPeeled) 10988 return SwitchMBB; 10989 10990 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10991 << TopCaseProb << "\n"); 10992 10993 // Record the MBB for the peeled switch statement. 10994 MachineFunction::iterator BBI(SwitchMBB); 10995 ++BBI; 10996 MachineBasicBlock *PeeledSwitchMBB = 10997 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10998 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10999 11000 ExportFromCurrentBlock(SI.getCondition()); 11001 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11002 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11003 nullptr, nullptr, TopCaseProb.getCompl()}; 11004 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11005 11006 Clusters.erase(PeeledCaseIt); 11007 for (CaseCluster &CC : Clusters) { 11008 LLVM_DEBUG( 11009 dbgs() << "Scale the probablity for one cluster, before scaling: " 11010 << CC.Prob << "\n"); 11011 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11012 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11013 } 11014 PeeledCaseProb = TopCaseProb; 11015 return PeeledSwitchMBB; 11016 } 11017 11018 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11019 // Extract cases from the switch. 11020 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11021 CaseClusterVector Clusters; 11022 Clusters.reserve(SI.getNumCases()); 11023 for (auto I : SI.cases()) { 11024 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11025 const ConstantInt *CaseVal = I.getCaseValue(); 11026 BranchProbability Prob = 11027 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11028 : BranchProbability(1, SI.getNumCases() + 1); 11029 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11030 } 11031 11032 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11033 11034 // Cluster adjacent cases with the same destination. We do this at all 11035 // optimization levels because it's cheap to do and will make codegen faster 11036 // if there are many clusters. 11037 sortAndRangeify(Clusters); 11038 11039 // The branch probablity of the peeled case. 11040 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11041 MachineBasicBlock *PeeledSwitchMBB = 11042 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11043 11044 // If there is only the default destination, jump there directly. 11045 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11046 if (Clusters.empty()) { 11047 assert(PeeledSwitchMBB == SwitchMBB); 11048 SwitchMBB->addSuccessor(DefaultMBB); 11049 if (DefaultMBB != NextBlock(SwitchMBB)) { 11050 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11051 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11052 } 11053 return; 11054 } 11055 11056 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11057 SL->findBitTestClusters(Clusters, &SI); 11058 11059 LLVM_DEBUG({ 11060 dbgs() << "Case clusters: "; 11061 for (const CaseCluster &C : Clusters) { 11062 if (C.Kind == CC_JumpTable) 11063 dbgs() << "JT:"; 11064 if (C.Kind == CC_BitTests) 11065 dbgs() << "BT:"; 11066 11067 C.Low->getValue().print(dbgs(), true); 11068 if (C.Low != C.High) { 11069 dbgs() << '-'; 11070 C.High->getValue().print(dbgs(), true); 11071 } 11072 dbgs() << ' '; 11073 } 11074 dbgs() << '\n'; 11075 }); 11076 11077 assert(!Clusters.empty()); 11078 SwitchWorkList WorkList; 11079 CaseClusterIt First = Clusters.begin(); 11080 CaseClusterIt Last = Clusters.end() - 1; 11081 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11082 // Scale the branchprobability for DefaultMBB if the peel occurs and 11083 // DefaultMBB is not replaced. 11084 if (PeeledCaseProb != BranchProbability::getZero() && 11085 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11086 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11087 WorkList.push_back( 11088 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11089 11090 while (!WorkList.empty()) { 11091 SwitchWorkListItem W = WorkList.pop_back_val(); 11092 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11093 11094 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11095 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11096 // For optimized builds, lower large range as a balanced binary tree. 11097 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11098 continue; 11099 } 11100 11101 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11102 } 11103 } 11104 11105 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11106 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11107 auto DL = getCurSDLoc(); 11108 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11109 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11110 } 11111 11112 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11113 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11114 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11115 11116 SDLoc DL = getCurSDLoc(); 11117 SDValue V = getValue(I.getOperand(0)); 11118 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11119 11120 if (VT.isScalableVector()) { 11121 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11122 return; 11123 } 11124 11125 // Use VECTOR_SHUFFLE for the fixed-length vector 11126 // to maintain existing behavior. 11127 SmallVector<int, 8> Mask; 11128 unsigned NumElts = VT.getVectorMinNumElements(); 11129 for (unsigned i = 0; i != NumElts; ++i) 11130 Mask.push_back(NumElts - 1 - i); 11131 11132 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11133 } 11134 11135 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11136 SmallVector<EVT, 4> ValueVTs; 11137 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11138 ValueVTs); 11139 unsigned NumValues = ValueVTs.size(); 11140 if (NumValues == 0) return; 11141 11142 SmallVector<SDValue, 4> Values(NumValues); 11143 SDValue Op = getValue(I.getOperand(0)); 11144 11145 for (unsigned i = 0; i != NumValues; ++i) 11146 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11147 SDValue(Op.getNode(), Op.getResNo() + i)); 11148 11149 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11150 DAG.getVTList(ValueVTs), Values)); 11151 } 11152 11153 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11154 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11155 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11156 11157 SDLoc DL = getCurSDLoc(); 11158 SDValue V1 = getValue(I.getOperand(0)); 11159 SDValue V2 = getValue(I.getOperand(1)); 11160 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11161 11162 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11163 if (VT.isScalableVector()) { 11164 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11165 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11166 DAG.getConstant(Imm, DL, IdxVT))); 11167 return; 11168 } 11169 11170 unsigned NumElts = VT.getVectorNumElements(); 11171 11172 if ((-Imm > NumElts) || (Imm >= NumElts)) { 11173 // Result is undefined if immediate is out-of-bounds. 11174 setValue(&I, DAG.getUNDEF(VT)); 11175 return; 11176 } 11177 11178 uint64_t Idx = (NumElts + Imm) % NumElts; 11179 11180 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11181 SmallVector<int, 8> Mask; 11182 for (unsigned i = 0; i < NumElts; ++i) 11183 Mask.push_back(Idx + i); 11184 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11185 } 11186