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 // If the element type of the source/dest vectors are the same, but the 403 // parts vector has more elements than the value vector, then we have a 404 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 405 // elements we want. 406 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 407 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 408 ValueVT.getVectorElementCount().getKnownMinValue()) && 409 (PartEVT.getVectorElementCount().isScalable() == 410 ValueVT.getVectorElementCount().isScalable()) && 411 "Cannot narrow, it would be a lossy transformation"); 412 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 413 DAG.getVectorIdxConstant(0, DL)); 414 } 415 416 // Vector/Vector bitcast. 417 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 418 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 419 420 assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() && 421 "Cannot handle this kind of promotion"); 422 // Promoted vector extract 423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 424 425 } 426 427 // Trivial bitcast if the types are the same size and the destination 428 // vector type is legal. 429 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 430 TLI.isTypeLegal(ValueVT)) 431 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 432 433 if (ValueVT.getVectorNumElements() != 1) { 434 // Certain ABIs require that vectors are passed as integers. For vectors 435 // are the same size, this is an obvious bitcast. 436 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 437 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 438 } else if (ValueVT.bitsLT(PartEVT)) { 439 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 440 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 441 // Drop the extra bits. 442 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 443 return DAG.getBitcast(ValueVT, Val); 444 } 445 446 diagnosePossiblyInvalidConstraint( 447 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 448 return DAG.getUNDEF(ValueVT); 449 } 450 451 // Handle cases such as i8 -> <1 x i1> 452 EVT ValueSVT = ValueVT.getVectorElementType(); 453 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 454 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 455 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 456 else 457 Val = ValueVT.isFloatingPoint() 458 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 459 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 460 } 461 462 return DAG.getBuildVector(ValueVT, DL, Val); 463 } 464 465 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 466 SDValue Val, SDValue *Parts, unsigned NumParts, 467 MVT PartVT, const Value *V, 468 Optional<CallingConv::ID> CallConv); 469 470 /// getCopyToParts - Create a series of nodes that contain the specified value 471 /// split into legal parts. If the parts contain more bits than Val, then, for 472 /// integers, ExtendKind can be used to specify how to generate the extra bits. 473 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 474 SDValue *Parts, unsigned NumParts, MVT PartVT, 475 const Value *V, 476 Optional<CallingConv::ID> CallConv = None, 477 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 478 // Let the target split the parts if it wants to 479 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 480 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 481 CallConv)) 482 return; 483 EVT ValueVT = Val.getValueType(); 484 485 // Handle the vector case separately. 486 if (ValueVT.isVector()) 487 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 488 CallConv); 489 490 unsigned PartBits = PartVT.getSizeInBits(); 491 unsigned OrigNumParts = NumParts; 492 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 493 "Copying to an illegal type!"); 494 495 if (NumParts == 0) 496 return; 497 498 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 499 EVT PartEVT = PartVT; 500 if (PartEVT == ValueVT) { 501 assert(NumParts == 1 && "No-op copy with multiple parts!"); 502 Parts[0] = Val; 503 return; 504 } 505 506 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 507 // If the parts cover more bits than the value has, promote the value. 508 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 509 assert(NumParts == 1 && "Do not know what to promote to!"); 510 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 511 } else { 512 if (ValueVT.isFloatingPoint()) { 513 // FP values need to be bitcast, then extended if they are being put 514 // into a larger container. 515 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 516 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 517 } 518 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 519 ValueVT.isInteger() && 520 "Unknown mismatch!"); 521 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 522 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 523 if (PartVT == MVT::x86mmx) 524 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 525 } 526 } else if (PartBits == ValueVT.getSizeInBits()) { 527 // Different types of the same size. 528 assert(NumParts == 1 && PartEVT != ValueVT); 529 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 530 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 531 // If the parts cover less bits than value has, truncate the value. 532 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 533 ValueVT.isInteger() && 534 "Unknown mismatch!"); 535 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 536 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 537 if (PartVT == MVT::x86mmx) 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } 540 541 // The value may have changed - recompute ValueVT. 542 ValueVT = Val.getValueType(); 543 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 544 "Failed to tile the value with PartVT!"); 545 546 if (NumParts == 1) { 547 if (PartEVT != ValueVT) { 548 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 549 "scalar-to-vector conversion failed"); 550 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 551 } 552 553 Parts[0] = Val; 554 return; 555 } 556 557 // Expand the value into multiple parts. 558 if (NumParts & (NumParts - 1)) { 559 // The number of parts is not a power of 2. Split off and copy the tail. 560 assert(PartVT.isInteger() && ValueVT.isInteger() && 561 "Do not know what to expand to!"); 562 unsigned RoundParts = 1 << Log2_32(NumParts); 563 unsigned RoundBits = RoundParts * PartBits; 564 unsigned OddParts = NumParts - RoundParts; 565 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 566 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 567 568 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 569 CallConv); 570 571 if (DAG.getDataLayout().isBigEndian()) 572 // The odd parts were reversed by getCopyToParts - unreverse them. 573 std::reverse(Parts + RoundParts, Parts + NumParts); 574 575 NumParts = RoundParts; 576 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 577 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 578 } 579 580 // The number of parts is a power of 2. Repeatedly bisect the value using 581 // EXTRACT_ELEMENT. 582 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 583 EVT::getIntegerVT(*DAG.getContext(), 584 ValueVT.getSizeInBits()), 585 Val); 586 587 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 588 for (unsigned i = 0; i < NumParts; i += StepSize) { 589 unsigned ThisBits = StepSize * PartBits / 2; 590 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 591 SDValue &Part0 = Parts[i]; 592 SDValue &Part1 = Parts[i+StepSize/2]; 593 594 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 595 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 596 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 597 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 598 599 if (ThisBits == PartBits && ThisVT != PartVT) { 600 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 601 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 602 } 603 } 604 } 605 606 if (DAG.getDataLayout().isBigEndian()) 607 std::reverse(Parts, Parts + OrigNumParts); 608 } 609 610 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 611 const SDLoc &DL, EVT PartVT) { 612 if (!PartVT.isVector()) 613 return SDValue(); 614 615 EVT ValueVT = Val.getValueType(); 616 ElementCount PartNumElts = PartVT.getVectorElementCount(); 617 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 618 619 // We only support widening vectors with equivalent element types and 620 // fixed/scalable properties. If a target needs to widen a fixed-length type 621 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 622 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 623 PartNumElts.isScalable() != ValueNumElts.isScalable() || 624 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 625 return SDValue(); 626 627 // Widening a scalable vector to another scalable vector is done by inserting 628 // the vector into a larger undef one. 629 if (PartNumElts.isScalable()) 630 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 631 Val, DAG.getVectorIdxConstant(0, DL)); 632 633 EVT ElementVT = PartVT.getVectorElementType(); 634 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 635 // undef elements. 636 SmallVector<SDValue, 16> Ops; 637 DAG.ExtractVectorElements(Val, Ops); 638 SDValue EltUndef = DAG.getUNDEF(ElementVT); 639 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 640 641 // FIXME: Use CONCAT for 2x -> 4x. 642 return DAG.getBuildVector(PartVT, DL, Ops); 643 } 644 645 /// getCopyToPartsVector - Create a series of nodes that contain the specified 646 /// value split into legal parts. 647 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 648 SDValue Val, SDValue *Parts, unsigned NumParts, 649 MVT PartVT, const Value *V, 650 Optional<CallingConv::ID> CallConv) { 651 EVT ValueVT = Val.getValueType(); 652 assert(ValueVT.isVector() && "Not a vector"); 653 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 654 const bool IsABIRegCopy = CallConv.hasValue(); 655 656 if (NumParts == 1) { 657 EVT PartEVT = PartVT; 658 if (PartEVT == ValueVT) { 659 // Nothing to do. 660 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 661 // Bitconvert vector->vector case. 662 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 663 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 664 Val = Widened; 665 } else if (PartVT.isVector() && 666 PartEVT.getVectorElementType().bitsGE( 667 ValueVT.getVectorElementType()) && 668 PartEVT.getVectorElementCount() == 669 ValueVT.getVectorElementCount()) { 670 671 // Promoted vector extract 672 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 673 } else { 674 if (ValueVT.getVectorElementCount().isScalar()) { 675 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 676 DAG.getVectorIdxConstant(0, DL)); 677 } else { 678 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 679 assert(PartVT.getFixedSizeInBits() > ValueSize && 680 "lossy conversion of vector to scalar type"); 681 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 682 Val = DAG.getBitcast(IntermediateType, Val); 683 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 684 } 685 } 686 687 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 688 Parts[0] = Val; 689 return; 690 } 691 692 // Handle a multi-element vector. 693 EVT IntermediateVT; 694 MVT RegisterVT; 695 unsigned NumIntermediates; 696 unsigned NumRegs; 697 if (IsABIRegCopy) { 698 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 699 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 700 NumIntermediates, RegisterVT); 701 } else { 702 NumRegs = 703 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 704 NumIntermediates, RegisterVT); 705 } 706 707 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 708 NumParts = NumRegs; // Silence a compiler warning. 709 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 710 711 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 712 "Mixing scalable and fixed vectors when copying in parts"); 713 714 Optional<ElementCount> DestEltCnt; 715 716 if (IntermediateVT.isVector()) 717 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 718 else 719 DestEltCnt = ElementCount::getFixed(NumIntermediates); 720 721 EVT BuiltVectorTy = EVT::getVectorVT( 722 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 723 724 if (ValueVT == BuiltVectorTy) { 725 // Nothing to do. 726 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 727 // Bitconvert vector->vector case. 728 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 729 } else if (SDValue Widened = 730 widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 731 Val = Widened; 732 } else if (BuiltVectorTy.getVectorElementType().bitsGE( 733 ValueVT.getVectorElementType()) && 734 BuiltVectorTy.getVectorElementCount() == 735 ValueVT.getVectorElementCount()) { 736 // Promoted vector extract 737 Val = DAG.getAnyExtOrTrunc(Val, DL, BuiltVectorTy); 738 } 739 740 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 741 742 // Split the vector into intermediate operands. 743 SmallVector<SDValue, 8> Ops(NumIntermediates); 744 for (unsigned i = 0; i != NumIntermediates; ++i) { 745 if (IntermediateVT.isVector()) { 746 // This does something sensible for scalable vectors - see the 747 // definition of EXTRACT_SUBVECTOR for further details. 748 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 749 Ops[i] = 750 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 751 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 752 } else { 753 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 754 DAG.getVectorIdxConstant(i, DL)); 755 } 756 } 757 758 // Split the intermediate operands into legal parts. 759 if (NumParts == NumIntermediates) { 760 // If the register was not expanded, promote or copy the value, 761 // as appropriate. 762 for (unsigned i = 0; i != NumParts; ++i) 763 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 764 } else if (NumParts > 0) { 765 // If the intermediate type was expanded, split each the value into 766 // legal parts. 767 assert(NumIntermediates != 0 && "division by zero"); 768 assert(NumParts % NumIntermediates == 0 && 769 "Must expand into a divisible number of parts!"); 770 unsigned Factor = NumParts / NumIntermediates; 771 for (unsigned i = 0; i != NumIntermediates; ++i) 772 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 773 CallConv); 774 } 775 } 776 777 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 778 EVT valuevt, Optional<CallingConv::ID> CC) 779 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 780 RegCount(1, regs.size()), CallConv(CC) {} 781 782 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 783 const DataLayout &DL, unsigned Reg, Type *Ty, 784 Optional<CallingConv::ID> CC) { 785 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 786 787 CallConv = CC; 788 789 for (EVT ValueVT : ValueVTs) { 790 unsigned NumRegs = 791 isABIMangled() 792 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 793 : TLI.getNumRegisters(Context, ValueVT); 794 MVT RegisterVT = 795 isABIMangled() 796 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 797 : TLI.getRegisterType(Context, ValueVT); 798 for (unsigned i = 0; i != NumRegs; ++i) 799 Regs.push_back(Reg + i); 800 RegVTs.push_back(RegisterVT); 801 RegCount.push_back(NumRegs); 802 Reg += NumRegs; 803 } 804 } 805 806 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 807 FunctionLoweringInfo &FuncInfo, 808 const SDLoc &dl, SDValue &Chain, 809 SDValue *Flag, const Value *V) const { 810 // A Value with type {} or [0 x %t] needs no registers. 811 if (ValueVTs.empty()) 812 return SDValue(); 813 814 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 815 816 // Assemble the legal parts into the final values. 817 SmallVector<SDValue, 4> Values(ValueVTs.size()); 818 SmallVector<SDValue, 8> Parts; 819 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 820 // Copy the legal parts from the registers. 821 EVT ValueVT = ValueVTs[Value]; 822 unsigned NumRegs = RegCount[Value]; 823 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 824 *DAG.getContext(), 825 CallConv.getValue(), RegVTs[Value]) 826 : RegVTs[Value]; 827 828 Parts.resize(NumRegs); 829 for (unsigned i = 0; i != NumRegs; ++i) { 830 SDValue P; 831 if (!Flag) { 832 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 833 } else { 834 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 835 *Flag = P.getValue(2); 836 } 837 838 Chain = P.getValue(1); 839 Parts[i] = P; 840 841 // If the source register was virtual and if we know something about it, 842 // add an assert node. 843 if (!Register::isVirtualRegister(Regs[Part + i]) || 844 !RegisterVT.isInteger()) 845 continue; 846 847 const FunctionLoweringInfo::LiveOutInfo *LOI = 848 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 849 if (!LOI) 850 continue; 851 852 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 853 unsigned NumSignBits = LOI->NumSignBits; 854 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 855 856 if (NumZeroBits == RegSize) { 857 // The current value is a zero. 858 // Explicitly express that as it would be easier for 859 // optimizations to kick in. 860 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 861 continue; 862 } 863 864 // FIXME: We capture more information than the dag can represent. For 865 // now, just use the tightest assertzext/assertsext possible. 866 bool isSExt; 867 EVT FromVT(MVT::Other); 868 if (NumZeroBits) { 869 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 870 isSExt = false; 871 } else if (NumSignBits > 1) { 872 FromVT = 873 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 874 isSExt = true; 875 } else { 876 continue; 877 } 878 // Add an assertion node. 879 assert(FromVT != MVT::Other); 880 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 881 RegisterVT, P, DAG.getValueType(FromVT)); 882 } 883 884 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 885 RegisterVT, ValueVT, V, CallConv); 886 Part += NumRegs; 887 Parts.clear(); 888 } 889 890 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 891 } 892 893 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 894 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 895 const Value *V, 896 ISD::NodeType PreferredExtendType) const { 897 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 898 ISD::NodeType ExtendKind = PreferredExtendType; 899 900 // Get the list of the values's legal parts. 901 unsigned NumRegs = Regs.size(); 902 SmallVector<SDValue, 8> Parts(NumRegs); 903 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 904 unsigned NumParts = RegCount[Value]; 905 906 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 907 *DAG.getContext(), 908 CallConv.getValue(), RegVTs[Value]) 909 : RegVTs[Value]; 910 911 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 912 ExtendKind = ISD::ZERO_EXTEND; 913 914 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 915 NumParts, RegisterVT, V, CallConv, ExtendKind); 916 Part += NumParts; 917 } 918 919 // Copy the parts into the registers. 920 SmallVector<SDValue, 8> Chains(NumRegs); 921 for (unsigned i = 0; i != NumRegs; ++i) { 922 SDValue Part; 923 if (!Flag) { 924 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 925 } else { 926 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 927 *Flag = Part.getValue(1); 928 } 929 930 Chains[i] = Part.getValue(0); 931 } 932 933 if (NumRegs == 1 || Flag) 934 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 935 // flagged to it. That is the CopyToReg nodes and the user are considered 936 // a single scheduling unit. If we create a TokenFactor and return it as 937 // chain, then the TokenFactor is both a predecessor (operand) of the 938 // user as well as a successor (the TF operands are flagged to the user). 939 // c1, f1 = CopyToReg 940 // c2, f2 = CopyToReg 941 // c3 = TokenFactor c1, c2 942 // ... 943 // = op c3, ..., f2 944 Chain = Chains[NumRegs-1]; 945 else 946 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 947 } 948 949 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 950 unsigned MatchingIdx, const SDLoc &dl, 951 SelectionDAG &DAG, 952 std::vector<SDValue> &Ops) const { 953 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 954 955 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 956 if (HasMatching) 957 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 958 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 959 // Put the register class of the virtual registers in the flag word. That 960 // way, later passes can recompute register class constraints for inline 961 // assembly as well as normal instructions. 962 // Don't do this for tied operands that can use the regclass information 963 // from the def. 964 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 965 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 966 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 967 } 968 969 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 970 Ops.push_back(Res); 971 972 if (Code == InlineAsm::Kind_Clobber) { 973 // Clobbers should always have a 1:1 mapping with registers, and may 974 // reference registers that have illegal (e.g. vector) types. Hence, we 975 // shouldn't try to apply any sort of splitting logic to them. 976 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 977 "No 1:1 mapping from clobbers to regs?"); 978 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 979 (void)SP; 980 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 981 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 982 assert( 983 (Regs[I] != SP || 984 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 985 "If we clobbered the stack pointer, MFI should know about it."); 986 } 987 return; 988 } 989 990 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 991 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 992 MVT RegisterVT = RegVTs[Value]; 993 for (unsigned i = 0; i != NumRegs; ++i) { 994 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 995 unsigned TheReg = Regs[Reg++]; 996 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 997 } 998 } 999 } 1000 1001 SmallVector<std::pair<unsigned, TypeSize>, 4> 1002 RegsForValue::getRegsAndSizes() const { 1003 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1004 unsigned I = 0; 1005 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1006 unsigned RegCount = std::get<0>(CountAndVT); 1007 MVT RegisterVT = std::get<1>(CountAndVT); 1008 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1009 for (unsigned E = I + RegCount; I != E; ++I) 1010 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1011 } 1012 return OutVec; 1013 } 1014 1015 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1016 const TargetLibraryInfo *li) { 1017 AA = aa; 1018 GFI = gfi; 1019 LibInfo = li; 1020 DL = &DAG.getDataLayout(); 1021 Context = DAG.getContext(); 1022 LPadToCallSiteMap.clear(); 1023 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1024 } 1025 1026 void SelectionDAGBuilder::clear() { 1027 NodeMap.clear(); 1028 UnusedArgNodeMap.clear(); 1029 PendingLoads.clear(); 1030 PendingExports.clear(); 1031 PendingConstrainedFP.clear(); 1032 PendingConstrainedFPStrict.clear(); 1033 CurInst = nullptr; 1034 HasTailCall = false; 1035 SDNodeOrder = LowestSDNodeOrder; 1036 StatepointLowering.clear(); 1037 } 1038 1039 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1040 DanglingDebugInfoMap.clear(); 1041 } 1042 1043 // Update DAG root to include dependencies on Pending chains. 1044 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1045 SDValue Root = DAG.getRoot(); 1046 1047 if (Pending.empty()) 1048 return Root; 1049 1050 // Add current root to PendingChains, unless we already indirectly 1051 // depend on it. 1052 if (Root.getOpcode() != ISD::EntryToken) { 1053 unsigned i = 0, e = Pending.size(); 1054 for (; i != e; ++i) { 1055 assert(Pending[i].getNode()->getNumOperands() > 1); 1056 if (Pending[i].getNode()->getOperand(0) == Root) 1057 break; // Don't add the root if we already indirectly depend on it. 1058 } 1059 1060 if (i == e) 1061 Pending.push_back(Root); 1062 } 1063 1064 if (Pending.size() == 1) 1065 Root = Pending[0]; 1066 else 1067 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1068 1069 DAG.setRoot(Root); 1070 Pending.clear(); 1071 return Root; 1072 } 1073 1074 SDValue SelectionDAGBuilder::getMemoryRoot() { 1075 return updateRoot(PendingLoads); 1076 } 1077 1078 SDValue SelectionDAGBuilder::getRoot() { 1079 // Chain up all pending constrained intrinsics together with all 1080 // pending loads, by simply appending them to PendingLoads and 1081 // then calling getMemoryRoot(). 1082 PendingLoads.reserve(PendingLoads.size() + 1083 PendingConstrainedFP.size() + 1084 PendingConstrainedFPStrict.size()); 1085 PendingLoads.append(PendingConstrainedFP.begin(), 1086 PendingConstrainedFP.end()); 1087 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1088 PendingConstrainedFPStrict.end()); 1089 PendingConstrainedFP.clear(); 1090 PendingConstrainedFPStrict.clear(); 1091 return getMemoryRoot(); 1092 } 1093 1094 SDValue SelectionDAGBuilder::getControlRoot() { 1095 // We need to emit pending fpexcept.strict constrained intrinsics, 1096 // so append them to the PendingExports list. 1097 PendingExports.append(PendingConstrainedFPStrict.begin(), 1098 PendingConstrainedFPStrict.end()); 1099 PendingConstrainedFPStrict.clear(); 1100 return updateRoot(PendingExports); 1101 } 1102 1103 void SelectionDAGBuilder::visit(const Instruction &I) { 1104 // Set up outgoing PHI node register values before emitting the terminator. 1105 if (I.isTerminator()) { 1106 HandlePHINodesInSuccessorBlocks(I.getParent()); 1107 } 1108 1109 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1110 if (!isa<DbgInfoIntrinsic>(I)) 1111 ++SDNodeOrder; 1112 1113 CurInst = &I; 1114 1115 visit(I.getOpcode(), I); 1116 1117 if (!I.isTerminator() && !HasTailCall && 1118 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1119 CopyToExportRegsIfNeeded(&I); 1120 1121 CurInst = nullptr; 1122 } 1123 1124 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1125 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1126 } 1127 1128 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1129 // Note: this doesn't use InstVisitor, because it has to work with 1130 // ConstantExpr's in addition to instructions. 1131 switch (Opcode) { 1132 default: llvm_unreachable("Unknown instruction type encountered!"); 1133 // Build the switch statement using the Instruction.def file. 1134 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1135 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1136 #include "llvm/IR/Instruction.def" 1137 } 1138 } 1139 1140 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1141 DebugLoc DL, unsigned Order) { 1142 // We treat variadic dbg_values differently at this stage. 1143 if (DI->hasArgList()) { 1144 // For variadic dbg_values we will now insert an undef. 1145 // FIXME: We can potentially recover these! 1146 SmallVector<SDDbgOperand, 2> Locs; 1147 for (const Value *V : DI->getValues()) { 1148 auto Undef = UndefValue::get(V->getType()); 1149 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1150 } 1151 SDDbgValue *SDV = DAG.getDbgValueList( 1152 DI->getVariable(), DI->getExpression(), Locs, {}, 1153 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1154 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1155 } else { 1156 // TODO: Dangling debug info will eventually either be resolved or produce 1157 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1158 // between the original dbg.value location and its resolved DBG_VALUE, 1159 // which we should ideally fill with an extra Undef DBG_VALUE. 1160 assert(DI->getNumVariableLocationOps() == 1 && 1161 "DbgValueInst without an ArgList should have a single location " 1162 "operand."); 1163 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1164 } 1165 } 1166 1167 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1168 const DIExpression *Expr) { 1169 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1170 const DbgValueInst *DI = DDI.getDI(); 1171 DIVariable *DanglingVariable = DI->getVariable(); 1172 DIExpression *DanglingExpr = DI->getExpression(); 1173 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1174 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1175 return true; 1176 } 1177 return false; 1178 }; 1179 1180 for (auto &DDIMI : DanglingDebugInfoMap) { 1181 DanglingDebugInfoVector &DDIV = DDIMI.second; 1182 1183 // If debug info is to be dropped, run it through final checks to see 1184 // whether it can be salvaged. 1185 for (auto &DDI : DDIV) 1186 if (isMatchingDbgValue(DDI)) 1187 salvageUnresolvedDbgValue(DDI); 1188 1189 erase_if(DDIV, isMatchingDbgValue); 1190 } 1191 } 1192 1193 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1194 // generate the debug data structures now that we've seen its definition. 1195 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1196 SDValue Val) { 1197 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1198 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1199 return; 1200 1201 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1202 for (auto &DDI : DDIV) { 1203 const DbgValueInst *DI = DDI.getDI(); 1204 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1205 assert(DI && "Ill-formed DanglingDebugInfo"); 1206 DebugLoc dl = DDI.getdl(); 1207 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1208 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1209 DILocalVariable *Variable = DI->getVariable(); 1210 DIExpression *Expr = DI->getExpression(); 1211 assert(Variable->isValidLocationForIntrinsic(dl) && 1212 "Expected inlined-at fields to agree"); 1213 SDDbgValue *SDV; 1214 if (Val.getNode()) { 1215 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1216 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1217 // we couldn't resolve it directly when examining the DbgValue intrinsic 1218 // in the first place we should not be more successful here). Unless we 1219 // have some test case that prove this to be correct we should avoid 1220 // calling EmitFuncArgumentDbgValue here. 1221 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1222 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1223 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1224 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1225 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1226 // inserted after the definition of Val when emitting the instructions 1227 // after ISel. An alternative could be to teach 1228 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1229 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1230 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1231 << ValSDNodeOrder << "\n"); 1232 SDV = getDbgValue(Val, Variable, Expr, dl, 1233 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1234 DAG.AddDbgValue(SDV, false); 1235 } else 1236 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1237 << "in EmitFuncArgumentDbgValue\n"); 1238 } else { 1239 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1240 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1241 auto SDV = 1242 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1243 DAG.AddDbgValue(SDV, false); 1244 } 1245 } 1246 DDIV.clear(); 1247 } 1248 1249 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1250 assert(!DDI.getDI()->hasArgList() && 1251 "Not implemented for variadic dbg_values"); 1252 Value *V = DDI.getDI()->getValue(0); 1253 DILocalVariable *Var = DDI.getDI()->getVariable(); 1254 DIExpression *Expr = DDI.getDI()->getExpression(); 1255 DebugLoc DL = DDI.getdl(); 1256 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1257 unsigned SDOrder = DDI.getSDNodeOrder(); 1258 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1259 // that DW_OP_stack_value is desired. 1260 assert(isa<DbgValueInst>(DDI.getDI())); 1261 bool StackValue = true; 1262 1263 // Can this Value can be encoded without any further work? 1264 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1265 return; 1266 1267 // Attempt to salvage back through as many instructions as possible. Bail if 1268 // a non-instruction is seen, such as a constant expression or global 1269 // variable. FIXME: Further work could recover those too. 1270 while (isa<Instruction>(V)) { 1271 Instruction &VAsInst = *cast<Instruction>(V); 1272 // Temporary "0", awaiting real implementation. 1273 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue, 0); 1274 1275 // If we cannot salvage any further, and haven't yet found a suitable debug 1276 // expression, bail out. 1277 if (!NewExpr) 1278 break; 1279 1280 // New value and expr now represent this debuginfo. 1281 V = VAsInst.getOperand(0); 1282 Expr = NewExpr; 1283 1284 // Some kind of simplification occurred: check whether the operand of the 1285 // salvaged debug expression can be encoded in this DAG. 1286 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1287 /*IsVariadic=*/false)) { 1288 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1289 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1290 return; 1291 } 1292 } 1293 1294 // This was the final opportunity to salvage this debug information, and it 1295 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1296 // any earlier variable location. 1297 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1298 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1299 DAG.AddDbgValue(SDV, false); 1300 1301 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1302 << "\n"); 1303 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1304 << "\n"); 1305 } 1306 1307 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1308 DILocalVariable *Var, 1309 DIExpression *Expr, DebugLoc dl, 1310 DebugLoc InstDL, unsigned Order, 1311 bool IsVariadic) { 1312 if (Values.empty()) 1313 return true; 1314 SmallVector<SDDbgOperand> LocationOps; 1315 SmallVector<SDNode *> Dependencies; 1316 for (const Value *V : Values) { 1317 // Constant value. 1318 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1319 isa<ConstantPointerNull>(V)) { 1320 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1321 continue; 1322 } 1323 1324 // If the Value is a frame index, we can create a FrameIndex debug value 1325 // without relying on the DAG at all. 1326 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1327 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1328 if (SI != FuncInfo.StaticAllocaMap.end()) { 1329 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1330 continue; 1331 } 1332 } 1333 1334 // Do not use getValue() in here; we don't want to generate code at 1335 // this point if it hasn't been done yet. 1336 SDValue N = NodeMap[V]; 1337 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1338 N = UnusedArgNodeMap[V]; 1339 if (N.getNode()) { 1340 // Only emit func arg dbg value for non-variadic dbg.values for now. 1341 if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1342 return true; 1343 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1344 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1345 // describe stack slot locations. 1346 // 1347 // Consider "int x = 0; int *px = &x;". There are two kinds of 1348 // interesting debug values here after optimization: 1349 // 1350 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1351 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1352 // 1353 // Both describe the direct values of their associated variables. 1354 Dependencies.push_back(N.getNode()); 1355 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1356 continue; 1357 } 1358 LocationOps.emplace_back( 1359 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1360 continue; 1361 } 1362 1363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1364 // Special rules apply for the first dbg.values of parameter variables in a 1365 // function. Identify them by the fact they reference Argument Values, that 1366 // they're parameters, and they are parameters of the current function. We 1367 // need to let them dangle until they get an SDNode. 1368 bool IsParamOfFunc = 1369 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1370 if (IsParamOfFunc) 1371 return false; 1372 1373 // The value is not used in this block yet (or it would have an SDNode). 1374 // We still want the value to appear for the user if possible -- if it has 1375 // an associated VReg, we can refer to that instead. 1376 auto VMI = FuncInfo.ValueMap.find(V); 1377 if (VMI != FuncInfo.ValueMap.end()) { 1378 unsigned Reg = VMI->second; 1379 // If this is a PHI node, it may be split up into several MI PHI nodes 1380 // (in FunctionLoweringInfo::set). 1381 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1382 V->getType(), None); 1383 if (RFV.occupiesMultipleRegs()) { 1384 // FIXME: We could potentially support variadic dbg_values here. 1385 if (IsVariadic) 1386 return false; 1387 unsigned Offset = 0; 1388 unsigned BitsToDescribe = 0; 1389 if (auto VarSize = Var->getSizeInBits()) 1390 BitsToDescribe = *VarSize; 1391 if (auto Fragment = Expr->getFragmentInfo()) 1392 BitsToDescribe = Fragment->SizeInBits; 1393 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1394 // Bail out if all bits are described already. 1395 if (Offset >= BitsToDescribe) 1396 break; 1397 // TODO: handle scalable vectors. 1398 unsigned RegisterSize = RegAndSize.second; 1399 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1400 ? BitsToDescribe - Offset 1401 : RegisterSize; 1402 auto FragmentExpr = DIExpression::createFragmentExpression( 1403 Expr, Offset, FragmentSize); 1404 if (!FragmentExpr) 1405 continue; 1406 SDDbgValue *SDV = DAG.getVRegDbgValue( 1407 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1408 DAG.AddDbgValue(SDV, false); 1409 Offset += RegisterSize; 1410 } 1411 return true; 1412 } 1413 // We can use simple vreg locations for variadic dbg_values as well. 1414 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1415 continue; 1416 } 1417 // We failed to create a SDDbgOperand for V. 1418 return false; 1419 } 1420 1421 // We have created a SDDbgOperand for each Value in Values. 1422 // Should use Order instead of SDNodeOrder? 1423 assert(!LocationOps.empty()); 1424 SDDbgValue *SDV = 1425 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1426 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1427 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1428 return true; 1429 } 1430 1431 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1432 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1433 for (auto &Pair : DanglingDebugInfoMap) 1434 for (auto &DDI : Pair.second) 1435 salvageUnresolvedDbgValue(DDI); 1436 clearDanglingDebugInfo(); 1437 } 1438 1439 /// getCopyFromRegs - If there was virtual register allocated for the value V 1440 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1441 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1442 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1443 SDValue Result; 1444 1445 if (It != FuncInfo.ValueMap.end()) { 1446 Register InReg = It->second; 1447 1448 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1449 DAG.getDataLayout(), InReg, Ty, 1450 None); // This is not an ABI copy. 1451 SDValue Chain = DAG.getEntryNode(); 1452 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1453 V); 1454 resolveDanglingDebugInfo(V, Result); 1455 } 1456 1457 return Result; 1458 } 1459 1460 /// getValue - Return an SDValue for the given Value. 1461 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1462 // If we already have an SDValue for this value, use it. It's important 1463 // to do this first, so that we don't create a CopyFromReg if we already 1464 // have a regular SDValue. 1465 SDValue &N = NodeMap[V]; 1466 if (N.getNode()) return N; 1467 1468 // If there's a virtual register allocated and initialized for this 1469 // value, use it. 1470 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1471 return copyFromReg; 1472 1473 // Otherwise create a new SDValue and remember it. 1474 SDValue Val = getValueImpl(V); 1475 NodeMap[V] = Val; 1476 resolveDanglingDebugInfo(V, Val); 1477 return Val; 1478 } 1479 1480 /// getNonRegisterValue - Return an SDValue for the given Value, but 1481 /// don't look in FuncInfo.ValueMap for a virtual register. 1482 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1483 // If we already have an SDValue for this value, use it. 1484 SDValue &N = NodeMap[V]; 1485 if (N.getNode()) { 1486 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1487 // Remove the debug location from the node as the node is about to be used 1488 // in a location which may differ from the original debug location. This 1489 // is relevant to Constant and ConstantFP nodes because they can appear 1490 // as constant expressions inside PHI nodes. 1491 N->setDebugLoc(DebugLoc()); 1492 } 1493 return N; 1494 } 1495 1496 // Otherwise create a new SDValue and remember it. 1497 SDValue Val = getValueImpl(V); 1498 NodeMap[V] = Val; 1499 resolveDanglingDebugInfo(V, Val); 1500 return Val; 1501 } 1502 1503 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1504 /// Create an SDValue for the given value. 1505 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1506 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1507 1508 if (const Constant *C = dyn_cast<Constant>(V)) { 1509 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1510 1511 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1512 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1513 1514 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1515 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1516 1517 if (isa<ConstantPointerNull>(C)) { 1518 unsigned AS = V->getType()->getPointerAddressSpace(); 1519 return DAG.getConstant(0, getCurSDLoc(), 1520 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1521 } 1522 1523 if (match(C, m_VScale(DAG.getDataLayout()))) 1524 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1525 1526 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1527 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1528 1529 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1530 return DAG.getUNDEF(VT); 1531 1532 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1533 visit(CE->getOpcode(), *CE); 1534 SDValue N1 = NodeMap[V]; 1535 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1536 return N1; 1537 } 1538 1539 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1540 SmallVector<SDValue, 4> Constants; 1541 for (const Use &U : C->operands()) { 1542 SDNode *Val = getValue(U).getNode(); 1543 // If the operand is an empty aggregate, there are no values. 1544 if (!Val) continue; 1545 // Add each leaf value from the operand to the Constants list 1546 // to form a flattened list of all the values. 1547 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1548 Constants.push_back(SDValue(Val, i)); 1549 } 1550 1551 return DAG.getMergeValues(Constants, getCurSDLoc()); 1552 } 1553 1554 if (const ConstantDataSequential *CDS = 1555 dyn_cast<ConstantDataSequential>(C)) { 1556 SmallVector<SDValue, 4> Ops; 1557 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1558 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1559 // Add each leaf value from the operand to the Constants list 1560 // to form a flattened list of all the values. 1561 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1562 Ops.push_back(SDValue(Val, i)); 1563 } 1564 1565 if (isa<ArrayType>(CDS->getType())) 1566 return DAG.getMergeValues(Ops, getCurSDLoc()); 1567 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1568 } 1569 1570 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1571 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1572 "Unknown struct or array constant!"); 1573 1574 SmallVector<EVT, 4> ValueVTs; 1575 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1576 unsigned NumElts = ValueVTs.size(); 1577 if (NumElts == 0) 1578 return SDValue(); // empty struct 1579 SmallVector<SDValue, 4> Constants(NumElts); 1580 for (unsigned i = 0; i != NumElts; ++i) { 1581 EVT EltVT = ValueVTs[i]; 1582 if (isa<UndefValue>(C)) 1583 Constants[i] = DAG.getUNDEF(EltVT); 1584 else if (EltVT.isFloatingPoint()) 1585 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1586 else 1587 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1588 } 1589 1590 return DAG.getMergeValues(Constants, getCurSDLoc()); 1591 } 1592 1593 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1594 return DAG.getBlockAddress(BA, VT); 1595 1596 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1597 return getValue(Equiv->getGlobalValue()); 1598 1599 VectorType *VecTy = cast<VectorType>(V->getType()); 1600 1601 // Now that we know the number and type of the elements, get that number of 1602 // elements into the Ops array based on what kind of constant it is. 1603 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1604 SmallVector<SDValue, 16> Ops; 1605 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1606 for (unsigned i = 0; i != NumElements; ++i) 1607 Ops.push_back(getValue(CV->getOperand(i))); 1608 1609 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1610 } else if (isa<ConstantAggregateZero>(C)) { 1611 EVT EltVT = 1612 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1613 1614 SDValue Op; 1615 if (EltVT.isFloatingPoint()) 1616 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1617 else 1618 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1619 1620 if (isa<ScalableVectorType>(VecTy)) 1621 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1622 else { 1623 SmallVector<SDValue, 16> Ops; 1624 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1625 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1626 } 1627 } 1628 llvm_unreachable("Unknown vector constant"); 1629 } 1630 1631 // If this is a static alloca, generate it as the frameindex instead of 1632 // computation. 1633 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1634 DenseMap<const AllocaInst*, int>::iterator SI = 1635 FuncInfo.StaticAllocaMap.find(AI); 1636 if (SI != FuncInfo.StaticAllocaMap.end()) 1637 return DAG.getFrameIndex(SI->second, 1638 TLI.getFrameIndexTy(DAG.getDataLayout())); 1639 } 1640 1641 // If this is an instruction which fast-isel has deferred, select it now. 1642 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1643 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1644 1645 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1646 Inst->getType(), None); 1647 SDValue Chain = DAG.getEntryNode(); 1648 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1649 } 1650 1651 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1652 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1653 } 1654 llvm_unreachable("Can't get register for value!"); 1655 } 1656 1657 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1658 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1659 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1660 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1661 bool IsSEH = isAsynchronousEHPersonality(Pers); 1662 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1663 if (!IsSEH) 1664 CatchPadMBB->setIsEHScopeEntry(); 1665 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1666 if (IsMSVCCXX || IsCoreCLR) 1667 CatchPadMBB->setIsEHFuncletEntry(); 1668 } 1669 1670 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1671 // Update machine-CFG edge. 1672 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1673 FuncInfo.MBB->addSuccessor(TargetMBB); 1674 TargetMBB->setIsEHCatchretTarget(true); 1675 DAG.getMachineFunction().setHasEHCatchret(true); 1676 1677 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1678 bool IsSEH = isAsynchronousEHPersonality(Pers); 1679 if (IsSEH) { 1680 // If this is not a fall-through branch or optimizations are switched off, 1681 // emit the branch. 1682 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1683 TM.getOptLevel() == CodeGenOpt::None) 1684 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1685 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1686 return; 1687 } 1688 1689 // Figure out the funclet membership for the catchret's successor. 1690 // This will be used by the FuncletLayout pass to determine how to order the 1691 // BB's. 1692 // A 'catchret' returns to the outer scope's color. 1693 Value *ParentPad = I.getCatchSwitchParentPad(); 1694 const BasicBlock *SuccessorColor; 1695 if (isa<ConstantTokenNone>(ParentPad)) 1696 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1697 else 1698 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1699 assert(SuccessorColor && "No parent funclet for catchret!"); 1700 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1701 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1702 1703 // Create the terminator node. 1704 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1705 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1706 DAG.getBasicBlock(SuccessorColorMBB)); 1707 DAG.setRoot(Ret); 1708 } 1709 1710 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1711 // Don't emit any special code for the cleanuppad instruction. It just marks 1712 // the start of an EH scope/funclet. 1713 FuncInfo.MBB->setIsEHScopeEntry(); 1714 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1715 if (Pers != EHPersonality::Wasm_CXX) { 1716 FuncInfo.MBB->setIsEHFuncletEntry(); 1717 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1718 } 1719 } 1720 1721 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1722 // not match, it is OK to add only the first unwind destination catchpad to the 1723 // successors, because there will be at least one invoke instruction within the 1724 // catch scope that points to the next unwind destination, if one exists, so 1725 // CFGSort cannot mess up with BB sorting order. 1726 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1727 // call within them, and catchpads only consisting of 'catch (...)' have a 1728 // '__cxa_end_catch' call within them, both of which generate invokes in case 1729 // the next unwind destination exists, i.e., the next unwind destination is not 1730 // the caller.) 1731 // 1732 // Having at most one EH pad successor is also simpler and helps later 1733 // transformations. 1734 // 1735 // For example, 1736 // current: 1737 // invoke void @foo to ... unwind label %catch.dispatch 1738 // catch.dispatch: 1739 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1740 // catch.start: 1741 // ... 1742 // ... in this BB or some other child BB dominated by this BB there will be an 1743 // invoke that points to 'next' BB as an unwind destination 1744 // 1745 // next: ; We don't need to add this to 'current' BB's successor 1746 // ... 1747 static void findWasmUnwindDestinations( 1748 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1749 BranchProbability Prob, 1750 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1751 &UnwindDests) { 1752 while (EHPadBB) { 1753 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1754 if (isa<CleanupPadInst>(Pad)) { 1755 // Stop on cleanup pads. 1756 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1757 UnwindDests.back().first->setIsEHScopeEntry(); 1758 break; 1759 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1760 // Add the catchpad handlers to the possible destinations. We don't 1761 // continue to the unwind destination of the catchswitch for wasm. 1762 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1763 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1764 UnwindDests.back().first->setIsEHScopeEntry(); 1765 } 1766 break; 1767 } else { 1768 continue; 1769 } 1770 } 1771 } 1772 1773 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1774 /// many places it could ultimately go. In the IR, we have a single unwind 1775 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1776 /// This function skips over imaginary basic blocks that hold catchswitch 1777 /// instructions, and finds all the "real" machine 1778 /// basic block destinations. As those destinations may not be successors of 1779 /// EHPadBB, here we also calculate the edge probability to those destinations. 1780 /// The passed-in Prob is the edge probability to EHPadBB. 1781 static void findUnwindDestinations( 1782 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1783 BranchProbability Prob, 1784 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1785 &UnwindDests) { 1786 EHPersonality Personality = 1787 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1788 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1789 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1790 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1791 bool IsSEH = isAsynchronousEHPersonality(Personality); 1792 1793 if (IsWasmCXX) { 1794 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1795 assert(UnwindDests.size() <= 1 && 1796 "There should be at most one unwind destination for wasm"); 1797 return; 1798 } 1799 1800 while (EHPadBB) { 1801 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1802 BasicBlock *NewEHPadBB = nullptr; 1803 if (isa<LandingPadInst>(Pad)) { 1804 // Stop on landingpads. They are not funclets. 1805 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1806 break; 1807 } else if (isa<CleanupPadInst>(Pad)) { 1808 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1809 // personalities. 1810 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1811 UnwindDests.back().first->setIsEHScopeEntry(); 1812 UnwindDests.back().first->setIsEHFuncletEntry(); 1813 break; 1814 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1815 // Add the catchpad handlers to the possible destinations. 1816 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1817 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1818 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1819 if (IsMSVCCXX || IsCoreCLR) 1820 UnwindDests.back().first->setIsEHFuncletEntry(); 1821 if (!IsSEH) 1822 UnwindDests.back().first->setIsEHScopeEntry(); 1823 } 1824 NewEHPadBB = CatchSwitch->getUnwindDest(); 1825 } else { 1826 continue; 1827 } 1828 1829 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1830 if (BPI && NewEHPadBB) 1831 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1832 EHPadBB = NewEHPadBB; 1833 } 1834 } 1835 1836 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1837 // Update successor info. 1838 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1839 auto UnwindDest = I.getUnwindDest(); 1840 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1841 BranchProbability UnwindDestProb = 1842 (BPI && UnwindDest) 1843 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1844 : BranchProbability::getZero(); 1845 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1846 for (auto &UnwindDest : UnwindDests) { 1847 UnwindDest.first->setIsEHPad(); 1848 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1849 } 1850 FuncInfo.MBB->normalizeSuccProbs(); 1851 1852 // Create the terminator node. 1853 SDValue Ret = 1854 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1855 DAG.setRoot(Ret); 1856 } 1857 1858 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1859 report_fatal_error("visitCatchSwitch not yet implemented!"); 1860 } 1861 1862 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1863 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1864 auto &DL = DAG.getDataLayout(); 1865 SDValue Chain = getControlRoot(); 1866 SmallVector<ISD::OutputArg, 8> Outs; 1867 SmallVector<SDValue, 8> OutVals; 1868 1869 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1870 // lower 1871 // 1872 // %val = call <ty> @llvm.experimental.deoptimize() 1873 // ret <ty> %val 1874 // 1875 // differently. 1876 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1877 LowerDeoptimizingReturn(); 1878 return; 1879 } 1880 1881 if (!FuncInfo.CanLowerReturn) { 1882 unsigned DemoteReg = FuncInfo.DemoteRegister; 1883 const Function *F = I.getParent()->getParent(); 1884 1885 // Emit a store of the return value through the virtual register. 1886 // Leave Outs empty so that LowerReturn won't try to load return 1887 // registers the usual way. 1888 SmallVector<EVT, 1> PtrValueVTs; 1889 ComputeValueVTs(TLI, DL, 1890 F->getReturnType()->getPointerTo( 1891 DAG.getDataLayout().getAllocaAddrSpace()), 1892 PtrValueVTs); 1893 1894 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1895 DemoteReg, PtrValueVTs[0]); 1896 SDValue RetOp = getValue(I.getOperand(0)); 1897 1898 SmallVector<EVT, 4> ValueVTs, MemVTs; 1899 SmallVector<uint64_t, 4> Offsets; 1900 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1901 &Offsets); 1902 unsigned NumValues = ValueVTs.size(); 1903 1904 SmallVector<SDValue, 4> Chains(NumValues); 1905 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1906 for (unsigned i = 0; i != NumValues; ++i) { 1907 // An aggregate return value cannot wrap around the address space, so 1908 // offsets to its parts don't wrap either. 1909 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1910 TypeSize::Fixed(Offsets[i])); 1911 1912 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1913 if (MemVTs[i] != ValueVTs[i]) 1914 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1915 Chains[i] = DAG.getStore( 1916 Chain, getCurSDLoc(), Val, 1917 // FIXME: better loc info would be nice. 1918 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1919 commonAlignment(BaseAlign, Offsets[i])); 1920 } 1921 1922 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1923 MVT::Other, Chains); 1924 } else if (I.getNumOperands() != 0) { 1925 SmallVector<EVT, 4> ValueVTs; 1926 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1927 unsigned NumValues = ValueVTs.size(); 1928 if (NumValues) { 1929 SDValue RetOp = getValue(I.getOperand(0)); 1930 1931 const Function *F = I.getParent()->getParent(); 1932 1933 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1934 I.getOperand(0)->getType(), F->getCallingConv(), 1935 /*IsVarArg*/ false); 1936 1937 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1938 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1939 Attribute::SExt)) 1940 ExtendKind = ISD::SIGN_EXTEND; 1941 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1942 Attribute::ZExt)) 1943 ExtendKind = ISD::ZERO_EXTEND; 1944 1945 LLVMContext &Context = F->getContext(); 1946 bool RetInReg = F->getAttributes().hasAttribute( 1947 AttributeList::ReturnIndex, Attribute::InReg); 1948 1949 for (unsigned j = 0; j != NumValues; ++j) { 1950 EVT VT = ValueVTs[j]; 1951 1952 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1953 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1954 1955 CallingConv::ID CC = F->getCallingConv(); 1956 1957 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1958 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1959 SmallVector<SDValue, 4> Parts(NumParts); 1960 getCopyToParts(DAG, getCurSDLoc(), 1961 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1962 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1963 1964 // 'inreg' on function refers to return value 1965 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1966 if (RetInReg) 1967 Flags.setInReg(); 1968 1969 if (I.getOperand(0)->getType()->isPointerTy()) { 1970 Flags.setPointer(); 1971 Flags.setPointerAddrSpace( 1972 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1973 } 1974 1975 if (NeedsRegBlock) { 1976 Flags.setInConsecutiveRegs(); 1977 if (j == NumValues - 1) 1978 Flags.setInConsecutiveRegsLast(); 1979 } 1980 1981 // Propagate extension type if any 1982 if (ExtendKind == ISD::SIGN_EXTEND) 1983 Flags.setSExt(); 1984 else if (ExtendKind == ISD::ZERO_EXTEND) 1985 Flags.setZExt(); 1986 1987 for (unsigned i = 0; i < NumParts; ++i) { 1988 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1989 VT, /*isfixed=*/true, 0, 0)); 1990 OutVals.push_back(Parts[i]); 1991 } 1992 } 1993 } 1994 } 1995 1996 // Push in swifterror virtual register as the last element of Outs. This makes 1997 // sure swifterror virtual register will be returned in the swifterror 1998 // physical register. 1999 const Function *F = I.getParent()->getParent(); 2000 if (TLI.supportSwiftError() && 2001 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2002 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2003 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2004 Flags.setSwiftError(); 2005 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 2006 EVT(TLI.getPointerTy(DL)) /*argvt*/, 2007 true /*isfixed*/, 1 /*origidx*/, 2008 0 /*partOffs*/)); 2009 // Create SDNode for the swifterror virtual register. 2010 OutVals.push_back( 2011 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2012 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2013 EVT(TLI.getPointerTy(DL)))); 2014 } 2015 2016 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2017 CallingConv::ID CallConv = 2018 DAG.getMachineFunction().getFunction().getCallingConv(); 2019 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2020 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2021 2022 // Verify that the target's LowerReturn behaved as expected. 2023 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2024 "LowerReturn didn't return a valid chain!"); 2025 2026 // Update the DAG with the new chain value resulting from return lowering. 2027 DAG.setRoot(Chain); 2028 } 2029 2030 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2031 /// created for it, emit nodes to copy the value into the virtual 2032 /// registers. 2033 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2034 // Skip empty types 2035 if (V->getType()->isEmptyTy()) 2036 return; 2037 2038 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2039 if (VMI != FuncInfo.ValueMap.end()) { 2040 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2041 CopyValueToVirtualRegister(V, VMI->second); 2042 } 2043 } 2044 2045 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2046 /// the current basic block, add it to ValueMap now so that we'll get a 2047 /// CopyTo/FromReg. 2048 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2049 // No need to export constants. 2050 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2051 2052 // Already exported? 2053 if (FuncInfo.isExportedInst(V)) return; 2054 2055 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2056 CopyValueToVirtualRegister(V, Reg); 2057 } 2058 2059 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2060 const BasicBlock *FromBB) { 2061 // The operands of the setcc have to be in this block. We don't know 2062 // how to export them from some other block. 2063 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2064 // Can export from current BB. 2065 if (VI->getParent() == FromBB) 2066 return true; 2067 2068 // Is already exported, noop. 2069 return FuncInfo.isExportedInst(V); 2070 } 2071 2072 // If this is an argument, we can export it if the BB is the entry block or 2073 // if it is already exported. 2074 if (isa<Argument>(V)) { 2075 if (FromBB->isEntryBlock()) 2076 return true; 2077 2078 // Otherwise, can only export this if it is already exported. 2079 return FuncInfo.isExportedInst(V); 2080 } 2081 2082 // Otherwise, constants can always be exported. 2083 return true; 2084 } 2085 2086 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2087 BranchProbability 2088 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2089 const MachineBasicBlock *Dst) const { 2090 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2091 const BasicBlock *SrcBB = Src->getBasicBlock(); 2092 const BasicBlock *DstBB = Dst->getBasicBlock(); 2093 if (!BPI) { 2094 // If BPI is not available, set the default probability as 1 / N, where N is 2095 // the number of successors. 2096 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2097 return BranchProbability(1, SuccSize); 2098 } 2099 return BPI->getEdgeProbability(SrcBB, DstBB); 2100 } 2101 2102 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2103 MachineBasicBlock *Dst, 2104 BranchProbability Prob) { 2105 if (!FuncInfo.BPI) 2106 Src->addSuccessorWithoutProb(Dst); 2107 else { 2108 if (Prob.isUnknown()) 2109 Prob = getEdgeProbability(Src, Dst); 2110 Src->addSuccessor(Dst, Prob); 2111 } 2112 } 2113 2114 static bool InBlock(const Value *V, const BasicBlock *BB) { 2115 if (const Instruction *I = dyn_cast<Instruction>(V)) 2116 return I->getParent() == BB; 2117 return true; 2118 } 2119 2120 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2121 /// This function emits a branch and is used at the leaves of an OR or an 2122 /// AND operator tree. 2123 void 2124 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2125 MachineBasicBlock *TBB, 2126 MachineBasicBlock *FBB, 2127 MachineBasicBlock *CurBB, 2128 MachineBasicBlock *SwitchBB, 2129 BranchProbability TProb, 2130 BranchProbability FProb, 2131 bool InvertCond) { 2132 const BasicBlock *BB = CurBB->getBasicBlock(); 2133 2134 // If the leaf of the tree is a comparison, merge the condition into 2135 // the caseblock. 2136 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2137 // The operands of the cmp have to be in this block. We don't know 2138 // how to export them from some other block. If this is the first block 2139 // of the sequence, no exporting is needed. 2140 if (CurBB == SwitchBB || 2141 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2142 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2143 ISD::CondCode Condition; 2144 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2145 ICmpInst::Predicate Pred = 2146 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2147 Condition = getICmpCondCode(Pred); 2148 } else { 2149 const FCmpInst *FC = cast<FCmpInst>(Cond); 2150 FCmpInst::Predicate Pred = 2151 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2152 Condition = getFCmpCondCode(Pred); 2153 if (TM.Options.NoNaNsFPMath) 2154 Condition = getFCmpCodeWithoutNaN(Condition); 2155 } 2156 2157 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2158 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2159 SL->SwitchCases.push_back(CB); 2160 return; 2161 } 2162 } 2163 2164 // Create a CaseBlock record representing this branch. 2165 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2166 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2167 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2168 SL->SwitchCases.push_back(CB); 2169 } 2170 2171 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2172 MachineBasicBlock *TBB, 2173 MachineBasicBlock *FBB, 2174 MachineBasicBlock *CurBB, 2175 MachineBasicBlock *SwitchBB, 2176 Instruction::BinaryOps Opc, 2177 BranchProbability TProb, 2178 BranchProbability FProb, 2179 bool InvertCond) { 2180 // Skip over not part of the tree and remember to invert op and operands at 2181 // next level. 2182 Value *NotCond; 2183 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2184 InBlock(NotCond, CurBB->getBasicBlock())) { 2185 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2186 !InvertCond); 2187 return; 2188 } 2189 2190 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2191 const Value *BOpOp0, *BOpOp1; 2192 // Compute the effective opcode for Cond, taking into account whether it needs 2193 // to be inverted, e.g. 2194 // and (not (or A, B)), C 2195 // gets lowered as 2196 // and (and (not A, not B), C) 2197 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2198 if (BOp) { 2199 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2200 ? Instruction::And 2201 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2202 ? Instruction::Or 2203 : (Instruction::BinaryOps)0); 2204 if (InvertCond) { 2205 if (BOpc == Instruction::And) 2206 BOpc = Instruction::Or; 2207 else if (BOpc == Instruction::Or) 2208 BOpc = Instruction::And; 2209 } 2210 } 2211 2212 // If this node is not part of the or/and tree, emit it as a branch. 2213 // Note that all nodes in the tree should have same opcode. 2214 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2215 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2216 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2217 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2218 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2219 TProb, FProb, InvertCond); 2220 return; 2221 } 2222 2223 // Create TmpBB after CurBB. 2224 MachineFunction::iterator BBI(CurBB); 2225 MachineFunction &MF = DAG.getMachineFunction(); 2226 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2227 CurBB->getParent()->insert(++BBI, TmpBB); 2228 2229 if (Opc == Instruction::Or) { 2230 // Codegen X | Y as: 2231 // BB1: 2232 // jmp_if_X TBB 2233 // jmp TmpBB 2234 // TmpBB: 2235 // jmp_if_Y TBB 2236 // jmp FBB 2237 // 2238 2239 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2240 // The requirement is that 2241 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2242 // = TrueProb for original BB. 2243 // Assuming the original probabilities are A and B, one choice is to set 2244 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2245 // A/(1+B) and 2B/(1+B). This choice assumes that 2246 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2247 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2248 // TmpBB, but the math is more complicated. 2249 2250 auto NewTrueProb = TProb / 2; 2251 auto NewFalseProb = TProb / 2 + FProb; 2252 // Emit the LHS condition. 2253 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2254 NewFalseProb, InvertCond); 2255 2256 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2257 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2258 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2259 // Emit the RHS condition into TmpBB. 2260 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2261 Probs[1], InvertCond); 2262 } else { 2263 assert(Opc == Instruction::And && "Unknown merge op!"); 2264 // Codegen X & Y as: 2265 // BB1: 2266 // jmp_if_X TmpBB 2267 // jmp FBB 2268 // TmpBB: 2269 // jmp_if_Y TBB 2270 // jmp FBB 2271 // 2272 // This requires creation of TmpBB after CurBB. 2273 2274 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2275 // The requirement is that 2276 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2277 // = FalseProb for original BB. 2278 // Assuming the original probabilities are A and B, one choice is to set 2279 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2280 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2281 // TrueProb for BB1 * FalseProb for TmpBB. 2282 2283 auto NewTrueProb = TProb + FProb / 2; 2284 auto NewFalseProb = FProb / 2; 2285 // Emit the LHS condition. 2286 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2287 NewFalseProb, InvertCond); 2288 2289 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2290 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2291 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2292 // Emit the RHS condition into TmpBB. 2293 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2294 Probs[1], InvertCond); 2295 } 2296 } 2297 2298 /// If the set of cases should be emitted as a series of branches, return true. 2299 /// If we should emit this as a bunch of and/or'd together conditions, return 2300 /// false. 2301 bool 2302 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2303 if (Cases.size() != 2) return true; 2304 2305 // If this is two comparisons of the same values or'd or and'd together, they 2306 // will get folded into a single comparison, so don't emit two blocks. 2307 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2308 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2309 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2310 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2311 return false; 2312 } 2313 2314 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2315 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2316 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2317 Cases[0].CC == Cases[1].CC && 2318 isa<Constant>(Cases[0].CmpRHS) && 2319 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2320 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2321 return false; 2322 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2323 return false; 2324 } 2325 2326 return true; 2327 } 2328 2329 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2330 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2331 2332 // Update machine-CFG edges. 2333 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2334 2335 if (I.isUnconditional()) { 2336 // Update machine-CFG edges. 2337 BrMBB->addSuccessor(Succ0MBB); 2338 2339 // If this is not a fall-through branch or optimizations are switched off, 2340 // emit the branch. 2341 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2342 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2343 MVT::Other, getControlRoot(), 2344 DAG.getBasicBlock(Succ0MBB))); 2345 2346 return; 2347 } 2348 2349 // If this condition is one of the special cases we handle, do special stuff 2350 // now. 2351 const Value *CondVal = I.getCondition(); 2352 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2353 2354 // If this is a series of conditions that are or'd or and'd together, emit 2355 // this as a sequence of branches instead of setcc's with and/or operations. 2356 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2357 // unpredictable branches, and vector extracts because those jumps are likely 2358 // expensive for any target), this should improve performance. 2359 // For example, instead of something like: 2360 // cmp A, B 2361 // C = seteq 2362 // cmp D, E 2363 // F = setle 2364 // or C, F 2365 // jnz foo 2366 // Emit: 2367 // cmp A, B 2368 // je foo 2369 // cmp D, E 2370 // jle foo 2371 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2372 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2373 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2374 Value *Vec; 2375 const Value *BOp0, *BOp1; 2376 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2377 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2378 Opcode = Instruction::And; 2379 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2380 Opcode = Instruction::Or; 2381 2382 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2383 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2384 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2385 getEdgeProbability(BrMBB, Succ0MBB), 2386 getEdgeProbability(BrMBB, Succ1MBB), 2387 /*InvertCond=*/false); 2388 // If the compares in later blocks need to use values not currently 2389 // exported from this block, export them now. This block should always 2390 // be the first entry. 2391 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2392 2393 // Allow some cases to be rejected. 2394 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2395 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2396 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2397 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2398 } 2399 2400 // Emit the branch for this block. 2401 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2402 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2403 return; 2404 } 2405 2406 // Okay, we decided not to do this, remove any inserted MBB's and clear 2407 // SwitchCases. 2408 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2409 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2410 2411 SL->SwitchCases.clear(); 2412 } 2413 } 2414 2415 // Create a CaseBlock record representing this branch. 2416 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2417 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2418 2419 // Use visitSwitchCase to actually insert the fast branch sequence for this 2420 // cond branch. 2421 visitSwitchCase(CB, BrMBB); 2422 } 2423 2424 /// visitSwitchCase - Emits the necessary code to represent a single node in 2425 /// the binary search tree resulting from lowering a switch instruction. 2426 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2427 MachineBasicBlock *SwitchBB) { 2428 SDValue Cond; 2429 SDValue CondLHS = getValue(CB.CmpLHS); 2430 SDLoc dl = CB.DL; 2431 2432 if (CB.CC == ISD::SETTRUE) { 2433 // Branch or fall through to TrueBB. 2434 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2435 SwitchBB->normalizeSuccProbs(); 2436 if (CB.TrueBB != NextBlock(SwitchBB)) { 2437 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2438 DAG.getBasicBlock(CB.TrueBB))); 2439 } 2440 return; 2441 } 2442 2443 auto &TLI = DAG.getTargetLoweringInfo(); 2444 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2445 2446 // Build the setcc now. 2447 if (!CB.CmpMHS) { 2448 // Fold "(X == true)" to X and "(X == false)" to !X to 2449 // handle common cases produced by branch lowering. 2450 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2451 CB.CC == ISD::SETEQ) 2452 Cond = CondLHS; 2453 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2454 CB.CC == ISD::SETEQ) { 2455 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2456 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2457 } else { 2458 SDValue CondRHS = getValue(CB.CmpRHS); 2459 2460 // If a pointer's DAG type is larger than its memory type then the DAG 2461 // values are zero-extended. This breaks signed comparisons so truncate 2462 // back to the underlying type before doing the compare. 2463 if (CondLHS.getValueType() != MemVT) { 2464 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2465 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2466 } 2467 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2468 } 2469 } else { 2470 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2471 2472 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2473 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2474 2475 SDValue CmpOp = getValue(CB.CmpMHS); 2476 EVT VT = CmpOp.getValueType(); 2477 2478 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2479 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2480 ISD::SETLE); 2481 } else { 2482 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2483 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2484 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2485 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2486 } 2487 } 2488 2489 // Update successor info 2490 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2491 // TrueBB and FalseBB are always different unless the incoming IR is 2492 // degenerate. This only happens when running llc on weird IR. 2493 if (CB.TrueBB != CB.FalseBB) 2494 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2495 SwitchBB->normalizeSuccProbs(); 2496 2497 // If the lhs block is the next block, invert the condition so that we can 2498 // fall through to the lhs instead of the rhs block. 2499 if (CB.TrueBB == NextBlock(SwitchBB)) { 2500 std::swap(CB.TrueBB, CB.FalseBB); 2501 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2502 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2503 } 2504 2505 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2506 MVT::Other, getControlRoot(), Cond, 2507 DAG.getBasicBlock(CB.TrueBB)); 2508 2509 // Insert the false branch. Do this even if it's a fall through branch, 2510 // this makes it easier to do DAG optimizations which require inverting 2511 // the branch condition. 2512 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2513 DAG.getBasicBlock(CB.FalseBB)); 2514 2515 DAG.setRoot(BrCond); 2516 } 2517 2518 /// visitJumpTable - Emit JumpTable node in the current MBB 2519 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2520 // Emit the code for the jump table 2521 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2522 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2523 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2524 JT.Reg, PTy); 2525 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2526 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2527 MVT::Other, Index.getValue(1), 2528 Table, Index); 2529 DAG.setRoot(BrJumpTable); 2530 } 2531 2532 /// visitJumpTableHeader - This function emits necessary code to produce index 2533 /// in the JumpTable from switch case. 2534 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2535 JumpTableHeader &JTH, 2536 MachineBasicBlock *SwitchBB) { 2537 SDLoc dl = getCurSDLoc(); 2538 2539 // Subtract the lowest switch case value from the value being switched on. 2540 SDValue SwitchOp = getValue(JTH.SValue); 2541 EVT VT = SwitchOp.getValueType(); 2542 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2543 DAG.getConstant(JTH.First, dl, VT)); 2544 2545 // The SDNode we just created, which holds the value being switched on minus 2546 // the smallest case value, needs to be copied to a virtual register so it 2547 // can be used as an index into the jump table in a subsequent basic block. 2548 // This value may be smaller or larger than the target's pointer type, and 2549 // therefore require extension or truncating. 2550 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2551 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2552 2553 unsigned JumpTableReg = 2554 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2555 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2556 JumpTableReg, SwitchOp); 2557 JT.Reg = JumpTableReg; 2558 2559 if (!JTH.OmitRangeCheck) { 2560 // Emit the range check for the jump table, and branch to the default block 2561 // for the switch statement if the value being switched on exceeds the 2562 // largest case in the switch. 2563 SDValue CMP = DAG.getSetCC( 2564 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2565 Sub.getValueType()), 2566 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2567 2568 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2569 MVT::Other, CopyTo, CMP, 2570 DAG.getBasicBlock(JT.Default)); 2571 2572 // Avoid emitting unnecessary branches to the next block. 2573 if (JT.MBB != NextBlock(SwitchBB)) 2574 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2575 DAG.getBasicBlock(JT.MBB)); 2576 2577 DAG.setRoot(BrCond); 2578 } else { 2579 // Avoid emitting unnecessary branches to the next block. 2580 if (JT.MBB != NextBlock(SwitchBB)) 2581 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2582 DAG.getBasicBlock(JT.MBB))); 2583 else 2584 DAG.setRoot(CopyTo); 2585 } 2586 } 2587 2588 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2589 /// variable if there exists one. 2590 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2591 SDValue &Chain) { 2592 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2593 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2594 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2595 MachineFunction &MF = DAG.getMachineFunction(); 2596 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2597 MachineSDNode *Node = 2598 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2599 if (Global) { 2600 MachinePointerInfo MPInfo(Global); 2601 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2602 MachineMemOperand::MODereferenceable; 2603 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2604 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2605 DAG.setNodeMemRefs(Node, {MemRef}); 2606 } 2607 if (PtrTy != PtrMemTy) 2608 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2609 return SDValue(Node, 0); 2610 } 2611 2612 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2613 /// tail spliced into a stack protector check success bb. 2614 /// 2615 /// For a high level explanation of how this fits into the stack protector 2616 /// generation see the comment on the declaration of class 2617 /// StackProtectorDescriptor. 2618 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2619 MachineBasicBlock *ParentBB) { 2620 2621 // First create the loads to the guard/stack slot for the comparison. 2622 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2623 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2624 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2625 2626 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2627 int FI = MFI.getStackProtectorIndex(); 2628 2629 SDValue Guard; 2630 SDLoc dl = getCurSDLoc(); 2631 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2632 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2633 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2634 2635 // Generate code to load the content of the guard slot. 2636 SDValue GuardVal = DAG.getLoad( 2637 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2638 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2639 MachineMemOperand::MOVolatile); 2640 2641 if (TLI.useStackGuardXorFP()) 2642 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2643 2644 // Retrieve guard check function, nullptr if instrumentation is inlined. 2645 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2646 // The target provides a guard check function to validate the guard value. 2647 // Generate a call to that function with the content of the guard slot as 2648 // argument. 2649 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2650 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2651 2652 TargetLowering::ArgListTy Args; 2653 TargetLowering::ArgListEntry Entry; 2654 Entry.Node = GuardVal; 2655 Entry.Ty = FnTy->getParamType(0); 2656 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2657 Entry.IsInReg = true; 2658 Args.push_back(Entry); 2659 2660 TargetLowering::CallLoweringInfo CLI(DAG); 2661 CLI.setDebugLoc(getCurSDLoc()) 2662 .setChain(DAG.getEntryNode()) 2663 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2664 getValue(GuardCheckFn), std::move(Args)); 2665 2666 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2667 DAG.setRoot(Result.second); 2668 return; 2669 } 2670 2671 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2672 // Otherwise, emit a volatile load to retrieve the stack guard value. 2673 SDValue Chain = DAG.getEntryNode(); 2674 if (TLI.useLoadStackGuardNode()) { 2675 Guard = getLoadStackGuard(DAG, dl, Chain); 2676 } else { 2677 const Value *IRGuard = TLI.getSDagStackGuard(M); 2678 SDValue GuardPtr = getValue(IRGuard); 2679 2680 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2681 MachinePointerInfo(IRGuard, 0), Align, 2682 MachineMemOperand::MOVolatile); 2683 } 2684 2685 // Perform the comparison via a getsetcc. 2686 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2687 *DAG.getContext(), 2688 Guard.getValueType()), 2689 Guard, GuardVal, ISD::SETNE); 2690 2691 // If the guard/stackslot do not equal, branch to failure MBB. 2692 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2693 MVT::Other, GuardVal.getOperand(0), 2694 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2695 // Otherwise branch to success MBB. 2696 SDValue Br = DAG.getNode(ISD::BR, dl, 2697 MVT::Other, BrCond, 2698 DAG.getBasicBlock(SPD.getSuccessMBB())); 2699 2700 DAG.setRoot(Br); 2701 } 2702 2703 /// Codegen the failure basic block for a stack protector check. 2704 /// 2705 /// A failure stack protector machine basic block consists simply of a call to 2706 /// __stack_chk_fail(). 2707 /// 2708 /// For a high level explanation of how this fits into the stack protector 2709 /// generation see the comment on the declaration of class 2710 /// StackProtectorDescriptor. 2711 void 2712 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2713 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2714 TargetLowering::MakeLibCallOptions CallOptions; 2715 CallOptions.setDiscardResult(true); 2716 SDValue Chain = 2717 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2718 None, CallOptions, getCurSDLoc()).second; 2719 // On PS4, the "return address" must still be within the calling function, 2720 // even if it's at the very end, so emit an explicit TRAP here. 2721 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2722 if (TM.getTargetTriple().isPS4CPU()) 2723 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2724 // WebAssembly needs an unreachable instruction after a non-returning call, 2725 // because the function return type can be different from __stack_chk_fail's 2726 // return type (void). 2727 if (TM.getTargetTriple().isWasm()) 2728 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2729 2730 DAG.setRoot(Chain); 2731 } 2732 2733 /// visitBitTestHeader - This function emits necessary code to produce value 2734 /// suitable for "bit tests" 2735 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2736 MachineBasicBlock *SwitchBB) { 2737 SDLoc dl = getCurSDLoc(); 2738 2739 // Subtract the minimum value. 2740 SDValue SwitchOp = getValue(B.SValue); 2741 EVT VT = SwitchOp.getValueType(); 2742 SDValue RangeSub = 2743 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2744 2745 // Determine the type of the test operands. 2746 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2747 bool UsePtrType = false; 2748 if (!TLI.isTypeLegal(VT)) { 2749 UsePtrType = true; 2750 } else { 2751 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2752 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2753 // Switch table case range are encoded into series of masks. 2754 // Just use pointer type, it's guaranteed to fit. 2755 UsePtrType = true; 2756 break; 2757 } 2758 } 2759 SDValue Sub = RangeSub; 2760 if (UsePtrType) { 2761 VT = TLI.getPointerTy(DAG.getDataLayout()); 2762 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2763 } 2764 2765 B.RegVT = VT.getSimpleVT(); 2766 B.Reg = FuncInfo.CreateReg(B.RegVT); 2767 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2768 2769 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2770 2771 if (!B.OmitRangeCheck) 2772 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2773 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2774 SwitchBB->normalizeSuccProbs(); 2775 2776 SDValue Root = CopyTo; 2777 if (!B.OmitRangeCheck) { 2778 // Conditional branch to the default block. 2779 SDValue RangeCmp = DAG.getSetCC(dl, 2780 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2781 RangeSub.getValueType()), 2782 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2783 ISD::SETUGT); 2784 2785 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2786 DAG.getBasicBlock(B.Default)); 2787 } 2788 2789 // Avoid emitting unnecessary branches to the next block. 2790 if (MBB != NextBlock(SwitchBB)) 2791 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2792 2793 DAG.setRoot(Root); 2794 } 2795 2796 /// visitBitTestCase - this function produces one "bit test" 2797 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2798 MachineBasicBlock* NextMBB, 2799 BranchProbability BranchProbToNext, 2800 unsigned Reg, 2801 BitTestCase &B, 2802 MachineBasicBlock *SwitchBB) { 2803 SDLoc dl = getCurSDLoc(); 2804 MVT VT = BB.RegVT; 2805 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2806 SDValue Cmp; 2807 unsigned PopCount = countPopulation(B.Mask); 2808 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2809 if (PopCount == 1) { 2810 // Testing for a single bit; just compare the shift count with what it 2811 // would need to be to shift a 1 bit in that position. 2812 Cmp = DAG.getSetCC( 2813 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2814 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2815 ISD::SETEQ); 2816 } else if (PopCount == BB.Range) { 2817 // There is only one zero bit in the range, test for it directly. 2818 Cmp = DAG.getSetCC( 2819 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2820 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2821 ISD::SETNE); 2822 } else { 2823 // Make desired shift 2824 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2825 DAG.getConstant(1, dl, VT), ShiftOp); 2826 2827 // Emit bit tests and jumps 2828 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2829 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2830 Cmp = DAG.getSetCC( 2831 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2832 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2833 } 2834 2835 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2836 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2837 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2838 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2839 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2840 // one as they are relative probabilities (and thus work more like weights), 2841 // and hence we need to normalize them to let the sum of them become one. 2842 SwitchBB->normalizeSuccProbs(); 2843 2844 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2845 MVT::Other, getControlRoot(), 2846 Cmp, DAG.getBasicBlock(B.TargetBB)); 2847 2848 // Avoid emitting unnecessary branches to the next block. 2849 if (NextMBB != NextBlock(SwitchBB)) 2850 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2851 DAG.getBasicBlock(NextMBB)); 2852 2853 DAG.setRoot(BrAnd); 2854 } 2855 2856 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2857 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2858 2859 // Retrieve successors. Look through artificial IR level blocks like 2860 // catchswitch for successors. 2861 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2862 const BasicBlock *EHPadBB = I.getSuccessor(1); 2863 2864 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2865 // have to do anything here to lower funclet bundles. 2866 assert(!I.hasOperandBundlesOtherThan( 2867 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2868 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2869 LLVMContext::OB_cfguardtarget, 2870 LLVMContext::OB_clang_arc_attachedcall}) && 2871 "Cannot lower invokes with arbitrary operand bundles yet!"); 2872 2873 const Value *Callee(I.getCalledOperand()); 2874 const Function *Fn = dyn_cast<Function>(Callee); 2875 if (isa<InlineAsm>(Callee)) 2876 visitInlineAsm(I, EHPadBB); 2877 else if (Fn && Fn->isIntrinsic()) { 2878 switch (Fn->getIntrinsicID()) { 2879 default: 2880 llvm_unreachable("Cannot invoke this intrinsic"); 2881 case Intrinsic::donothing: 2882 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2883 case Intrinsic::seh_try_begin: 2884 case Intrinsic::seh_scope_begin: 2885 case Intrinsic::seh_try_end: 2886 case Intrinsic::seh_scope_end: 2887 break; 2888 case Intrinsic::experimental_patchpoint_void: 2889 case Intrinsic::experimental_patchpoint_i64: 2890 visitPatchpoint(I, EHPadBB); 2891 break; 2892 case Intrinsic::experimental_gc_statepoint: 2893 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2894 break; 2895 case Intrinsic::wasm_rethrow: { 2896 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2897 // special because it can be invoked, so we manually lower it to a DAG 2898 // node here. 2899 SmallVector<SDValue, 8> Ops; 2900 Ops.push_back(getRoot()); // inchain 2901 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2902 Ops.push_back( 2903 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2904 TLI.getPointerTy(DAG.getDataLayout()))); 2905 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2906 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2907 break; 2908 } 2909 } 2910 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2911 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2912 // Eventually we will support lowering the @llvm.experimental.deoptimize 2913 // intrinsic, and right now there are no plans to support other intrinsics 2914 // with deopt state. 2915 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2916 } else { 2917 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2918 } 2919 2920 // If the value of the invoke is used outside of its defining block, make it 2921 // available as a virtual register. 2922 // We already took care of the exported value for the statepoint instruction 2923 // during call to the LowerStatepoint. 2924 if (!isa<GCStatepointInst>(I)) { 2925 CopyToExportRegsIfNeeded(&I); 2926 } 2927 2928 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2929 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2930 BranchProbability EHPadBBProb = 2931 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2932 : BranchProbability::getZero(); 2933 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2934 2935 // Update successor info. 2936 addSuccessorWithProb(InvokeMBB, Return); 2937 for (auto &UnwindDest : UnwindDests) { 2938 UnwindDest.first->setIsEHPad(); 2939 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2940 } 2941 InvokeMBB->normalizeSuccProbs(); 2942 2943 // Drop into normal successor. 2944 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2945 DAG.getBasicBlock(Return))); 2946 } 2947 2948 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2949 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2950 2951 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2952 // have to do anything here to lower funclet bundles. 2953 assert(!I.hasOperandBundlesOtherThan( 2954 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2955 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2956 2957 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2958 visitInlineAsm(I); 2959 CopyToExportRegsIfNeeded(&I); 2960 2961 // Retrieve successors. 2962 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2963 2964 // Update successor info. 2965 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2966 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2967 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2968 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2969 Target->setIsInlineAsmBrIndirectTarget(); 2970 } 2971 CallBrMBB->normalizeSuccProbs(); 2972 2973 // Drop into default successor. 2974 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2975 MVT::Other, getControlRoot(), 2976 DAG.getBasicBlock(Return))); 2977 } 2978 2979 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2980 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2981 } 2982 2983 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2984 assert(FuncInfo.MBB->isEHPad() && 2985 "Call to landingpad not in landing pad!"); 2986 2987 // If there aren't registers to copy the values into (e.g., during SjLj 2988 // exceptions), then don't bother to create these DAG nodes. 2989 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2990 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2991 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2992 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2993 return; 2994 2995 // If landingpad's return type is token type, we don't create DAG nodes 2996 // for its exception pointer and selector value. The extraction of exception 2997 // pointer or selector value from token type landingpads is not currently 2998 // supported. 2999 if (LP.getType()->isTokenTy()) 3000 return; 3001 3002 SmallVector<EVT, 2> ValueVTs; 3003 SDLoc dl = getCurSDLoc(); 3004 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3005 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3006 3007 // Get the two live-in registers as SDValues. The physregs have already been 3008 // copied into virtual registers. 3009 SDValue Ops[2]; 3010 if (FuncInfo.ExceptionPointerVirtReg) { 3011 Ops[0] = DAG.getZExtOrTrunc( 3012 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3013 FuncInfo.ExceptionPointerVirtReg, 3014 TLI.getPointerTy(DAG.getDataLayout())), 3015 dl, ValueVTs[0]); 3016 } else { 3017 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3018 } 3019 Ops[1] = DAG.getZExtOrTrunc( 3020 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3021 FuncInfo.ExceptionSelectorVirtReg, 3022 TLI.getPointerTy(DAG.getDataLayout())), 3023 dl, ValueVTs[1]); 3024 3025 // Merge into one. 3026 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3027 DAG.getVTList(ValueVTs), Ops); 3028 setValue(&LP, Res); 3029 } 3030 3031 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3032 MachineBasicBlock *Last) { 3033 // Update JTCases. 3034 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 3035 if (SL->JTCases[i].first.HeaderBB == First) 3036 SL->JTCases[i].first.HeaderBB = Last; 3037 3038 // Update BitTestCases. 3039 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 3040 if (SL->BitTestCases[i].Parent == First) 3041 SL->BitTestCases[i].Parent = Last; 3042 } 3043 3044 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3045 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3046 3047 // Update machine-CFG edges with unique successors. 3048 SmallSet<BasicBlock*, 32> Done; 3049 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3050 BasicBlock *BB = I.getSuccessor(i); 3051 bool Inserted = Done.insert(BB).second; 3052 if (!Inserted) 3053 continue; 3054 3055 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3056 addSuccessorWithProb(IndirectBrMBB, Succ); 3057 } 3058 IndirectBrMBB->normalizeSuccProbs(); 3059 3060 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3061 MVT::Other, getControlRoot(), 3062 getValue(I.getAddress()))); 3063 } 3064 3065 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3066 if (!DAG.getTarget().Options.TrapUnreachable) 3067 return; 3068 3069 // We may be able to ignore unreachable behind a noreturn call. 3070 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3071 const BasicBlock &BB = *I.getParent(); 3072 if (&I != &BB.front()) { 3073 BasicBlock::const_iterator PredI = 3074 std::prev(BasicBlock::const_iterator(&I)); 3075 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3076 if (Call->doesNotReturn()) 3077 return; 3078 } 3079 } 3080 } 3081 3082 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3083 } 3084 3085 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3086 SDNodeFlags Flags; 3087 3088 SDValue Op = getValue(I.getOperand(0)); 3089 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3090 Op, Flags); 3091 setValue(&I, UnNodeValue); 3092 } 3093 3094 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3095 SDNodeFlags Flags; 3096 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3097 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3098 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3099 } 3100 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3101 Flags.setExact(ExactOp->isExact()); 3102 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3103 Flags.copyFMF(*FPOp); 3104 3105 SDValue Op1 = getValue(I.getOperand(0)); 3106 SDValue Op2 = getValue(I.getOperand(1)); 3107 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3108 Op1, Op2, Flags); 3109 setValue(&I, BinNodeValue); 3110 } 3111 3112 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3113 SDValue Op1 = getValue(I.getOperand(0)); 3114 SDValue Op2 = getValue(I.getOperand(1)); 3115 3116 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3117 Op1.getValueType(), DAG.getDataLayout()); 3118 3119 // Coerce the shift amount to the right type if we can. 3120 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3121 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3122 unsigned Op2Size = Op2.getValueSizeInBits(); 3123 SDLoc DL = getCurSDLoc(); 3124 3125 // If the operand is smaller than the shift count type, promote it. 3126 if (ShiftSize > Op2Size) 3127 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3128 3129 // If the operand is larger than the shift count type but the shift 3130 // count type has enough bits to represent any shift value, truncate 3131 // it now. This is a common case and it exposes the truncate to 3132 // optimization early. 3133 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3134 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3135 // Otherwise we'll need to temporarily settle for some other convenient 3136 // type. Type legalization will make adjustments once the shiftee is split. 3137 else 3138 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3139 } 3140 3141 bool nuw = false; 3142 bool nsw = false; 3143 bool exact = false; 3144 3145 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3146 3147 if (const OverflowingBinaryOperator *OFBinOp = 3148 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3149 nuw = OFBinOp->hasNoUnsignedWrap(); 3150 nsw = OFBinOp->hasNoSignedWrap(); 3151 } 3152 if (const PossiblyExactOperator *ExactOp = 3153 dyn_cast<const PossiblyExactOperator>(&I)) 3154 exact = ExactOp->isExact(); 3155 } 3156 SDNodeFlags Flags; 3157 Flags.setExact(exact); 3158 Flags.setNoSignedWrap(nsw); 3159 Flags.setNoUnsignedWrap(nuw); 3160 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3161 Flags); 3162 setValue(&I, Res); 3163 } 3164 3165 void SelectionDAGBuilder::visitSDiv(const User &I) { 3166 SDValue Op1 = getValue(I.getOperand(0)); 3167 SDValue Op2 = getValue(I.getOperand(1)); 3168 3169 SDNodeFlags Flags; 3170 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3171 cast<PossiblyExactOperator>(&I)->isExact()); 3172 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3173 Op2, Flags)); 3174 } 3175 3176 void SelectionDAGBuilder::visitICmp(const User &I) { 3177 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3178 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3179 predicate = IC->getPredicate(); 3180 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3181 predicate = ICmpInst::Predicate(IC->getPredicate()); 3182 SDValue Op1 = getValue(I.getOperand(0)); 3183 SDValue Op2 = getValue(I.getOperand(1)); 3184 ISD::CondCode Opcode = getICmpCondCode(predicate); 3185 3186 auto &TLI = DAG.getTargetLoweringInfo(); 3187 EVT MemVT = 3188 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3189 3190 // If a pointer's DAG type is larger than its memory type then the DAG values 3191 // are zero-extended. This breaks signed comparisons so truncate back to the 3192 // underlying type before doing the compare. 3193 if (Op1.getValueType() != MemVT) { 3194 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3195 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3196 } 3197 3198 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3199 I.getType()); 3200 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3201 } 3202 3203 void SelectionDAGBuilder::visitFCmp(const User &I) { 3204 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3205 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3206 predicate = FC->getPredicate(); 3207 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3208 predicate = FCmpInst::Predicate(FC->getPredicate()); 3209 SDValue Op1 = getValue(I.getOperand(0)); 3210 SDValue Op2 = getValue(I.getOperand(1)); 3211 3212 ISD::CondCode Condition = getFCmpCondCode(predicate); 3213 auto *FPMO = cast<FPMathOperator>(&I); 3214 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3215 Condition = getFCmpCodeWithoutNaN(Condition); 3216 3217 SDNodeFlags Flags; 3218 Flags.copyFMF(*FPMO); 3219 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3220 3221 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3222 I.getType()); 3223 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3224 } 3225 3226 // Check if the condition of the select has one use or two users that are both 3227 // selects with the same condition. 3228 static bool hasOnlySelectUsers(const Value *Cond) { 3229 return llvm::all_of(Cond->users(), [](const Value *V) { 3230 return isa<SelectInst>(V); 3231 }); 3232 } 3233 3234 void SelectionDAGBuilder::visitSelect(const User &I) { 3235 SmallVector<EVT, 4> ValueVTs; 3236 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3237 ValueVTs); 3238 unsigned NumValues = ValueVTs.size(); 3239 if (NumValues == 0) return; 3240 3241 SmallVector<SDValue, 4> Values(NumValues); 3242 SDValue Cond = getValue(I.getOperand(0)); 3243 SDValue LHSVal = getValue(I.getOperand(1)); 3244 SDValue RHSVal = getValue(I.getOperand(2)); 3245 SmallVector<SDValue, 1> BaseOps(1, Cond); 3246 ISD::NodeType OpCode = 3247 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3248 3249 bool IsUnaryAbs = false; 3250 bool Negate = false; 3251 3252 SDNodeFlags Flags; 3253 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3254 Flags.copyFMF(*FPOp); 3255 3256 // Min/max matching is only viable if all output VTs are the same. 3257 if (is_splat(ValueVTs)) { 3258 EVT VT = ValueVTs[0]; 3259 LLVMContext &Ctx = *DAG.getContext(); 3260 auto &TLI = DAG.getTargetLoweringInfo(); 3261 3262 // We care about the legality of the operation after it has been type 3263 // legalized. 3264 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3265 VT = TLI.getTypeToTransformTo(Ctx, VT); 3266 3267 // If the vselect is legal, assume we want to leave this as a vector setcc + 3268 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3269 // min/max is legal on the scalar type. 3270 bool UseScalarMinMax = VT.isVector() && 3271 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3272 3273 Value *LHS, *RHS; 3274 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3275 ISD::NodeType Opc = ISD::DELETED_NODE; 3276 switch (SPR.Flavor) { 3277 case SPF_UMAX: Opc = ISD::UMAX; break; 3278 case SPF_UMIN: Opc = ISD::UMIN; break; 3279 case SPF_SMAX: Opc = ISD::SMAX; break; 3280 case SPF_SMIN: Opc = ISD::SMIN; break; 3281 case SPF_FMINNUM: 3282 switch (SPR.NaNBehavior) { 3283 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3284 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3285 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3286 case SPNB_RETURNS_ANY: { 3287 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3288 Opc = ISD::FMINNUM; 3289 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3290 Opc = ISD::FMINIMUM; 3291 else if (UseScalarMinMax) 3292 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3293 ISD::FMINNUM : ISD::FMINIMUM; 3294 break; 3295 } 3296 } 3297 break; 3298 case SPF_FMAXNUM: 3299 switch (SPR.NaNBehavior) { 3300 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3301 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3302 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3303 case SPNB_RETURNS_ANY: 3304 3305 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3306 Opc = ISD::FMAXNUM; 3307 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3308 Opc = ISD::FMAXIMUM; 3309 else if (UseScalarMinMax) 3310 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3311 ISD::FMAXNUM : ISD::FMAXIMUM; 3312 break; 3313 } 3314 break; 3315 case SPF_NABS: 3316 Negate = true; 3317 LLVM_FALLTHROUGH; 3318 case SPF_ABS: 3319 IsUnaryAbs = true; 3320 Opc = ISD::ABS; 3321 break; 3322 default: break; 3323 } 3324 3325 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3326 (TLI.isOperationLegalOrCustom(Opc, VT) || 3327 (UseScalarMinMax && 3328 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3329 // If the underlying comparison instruction is used by any other 3330 // instruction, the consumed instructions won't be destroyed, so it is 3331 // not profitable to convert to a min/max. 3332 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3333 OpCode = Opc; 3334 LHSVal = getValue(LHS); 3335 RHSVal = getValue(RHS); 3336 BaseOps.clear(); 3337 } 3338 3339 if (IsUnaryAbs) { 3340 OpCode = Opc; 3341 LHSVal = getValue(LHS); 3342 BaseOps.clear(); 3343 } 3344 } 3345 3346 if (IsUnaryAbs) { 3347 for (unsigned i = 0; i != NumValues; ++i) { 3348 SDLoc dl = getCurSDLoc(); 3349 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3350 Values[i] = 3351 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3352 if (Negate) 3353 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3354 Values[i]); 3355 } 3356 } else { 3357 for (unsigned i = 0; i != NumValues; ++i) { 3358 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3359 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3360 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3361 Values[i] = DAG.getNode( 3362 OpCode, getCurSDLoc(), 3363 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3364 } 3365 } 3366 3367 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3368 DAG.getVTList(ValueVTs), Values)); 3369 } 3370 3371 void SelectionDAGBuilder::visitTrunc(const User &I) { 3372 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3373 SDValue N = getValue(I.getOperand(0)); 3374 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3375 I.getType()); 3376 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3377 } 3378 3379 void SelectionDAGBuilder::visitZExt(const User &I) { 3380 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3381 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3382 SDValue N = getValue(I.getOperand(0)); 3383 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3384 I.getType()); 3385 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3386 } 3387 3388 void SelectionDAGBuilder::visitSExt(const User &I) { 3389 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3390 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3391 SDValue N = getValue(I.getOperand(0)); 3392 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3393 I.getType()); 3394 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3395 } 3396 3397 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3398 // FPTrunc is never a no-op cast, no need to check 3399 SDValue N = getValue(I.getOperand(0)); 3400 SDLoc dl = getCurSDLoc(); 3401 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3402 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3403 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3404 DAG.getTargetConstant( 3405 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3406 } 3407 3408 void SelectionDAGBuilder::visitFPExt(const User &I) { 3409 // FPExt is never a no-op cast, no need to check 3410 SDValue N = getValue(I.getOperand(0)); 3411 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3412 I.getType()); 3413 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3414 } 3415 3416 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3417 // FPToUI is never a no-op cast, no need to check 3418 SDValue N = getValue(I.getOperand(0)); 3419 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3420 I.getType()); 3421 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3422 } 3423 3424 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3425 // FPToSI is never a no-op cast, no need to check 3426 SDValue N = getValue(I.getOperand(0)); 3427 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3428 I.getType()); 3429 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3430 } 3431 3432 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3433 // UIToFP is never a no-op cast, no need to check 3434 SDValue N = getValue(I.getOperand(0)); 3435 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3436 I.getType()); 3437 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3438 } 3439 3440 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3441 // SIToFP is never a no-op cast, no need to check 3442 SDValue N = getValue(I.getOperand(0)); 3443 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3444 I.getType()); 3445 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3446 } 3447 3448 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3449 // What to do depends on the size of the integer and the size of the pointer. 3450 // We can either truncate, zero extend, or no-op, accordingly. 3451 SDValue N = getValue(I.getOperand(0)); 3452 auto &TLI = DAG.getTargetLoweringInfo(); 3453 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3454 I.getType()); 3455 EVT PtrMemVT = 3456 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3457 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3458 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3459 setValue(&I, N); 3460 } 3461 3462 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3463 // What to do depends on the size of the integer and the size of the pointer. 3464 // We can either truncate, zero extend, or no-op, accordingly. 3465 SDValue N = getValue(I.getOperand(0)); 3466 auto &TLI = DAG.getTargetLoweringInfo(); 3467 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3468 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3469 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3470 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3471 setValue(&I, N); 3472 } 3473 3474 void SelectionDAGBuilder::visitBitCast(const User &I) { 3475 SDValue N = getValue(I.getOperand(0)); 3476 SDLoc dl = getCurSDLoc(); 3477 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3478 I.getType()); 3479 3480 // BitCast assures us that source and destination are the same size so this is 3481 // either a BITCAST or a no-op. 3482 if (DestVT != N.getValueType()) 3483 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3484 DestVT, N)); // convert types. 3485 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3486 // might fold any kind of constant expression to an integer constant and that 3487 // is not what we are looking for. Only recognize a bitcast of a genuine 3488 // constant integer as an opaque constant. 3489 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3490 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3491 /*isOpaque*/true)); 3492 else 3493 setValue(&I, N); // noop cast. 3494 } 3495 3496 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3497 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3498 const Value *SV = I.getOperand(0); 3499 SDValue N = getValue(SV); 3500 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3501 3502 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3503 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3504 3505 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3506 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3507 3508 setValue(&I, N); 3509 } 3510 3511 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3512 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3513 SDValue InVec = getValue(I.getOperand(0)); 3514 SDValue InVal = getValue(I.getOperand(1)); 3515 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3516 TLI.getVectorIdxTy(DAG.getDataLayout())); 3517 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3518 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3519 InVec, InVal, InIdx)); 3520 } 3521 3522 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3523 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3524 SDValue InVec = getValue(I.getOperand(0)); 3525 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3526 TLI.getVectorIdxTy(DAG.getDataLayout())); 3527 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3528 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3529 InVec, InIdx)); 3530 } 3531 3532 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3533 SDValue Src1 = getValue(I.getOperand(0)); 3534 SDValue Src2 = getValue(I.getOperand(1)); 3535 ArrayRef<int> Mask; 3536 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3537 Mask = SVI->getShuffleMask(); 3538 else 3539 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3540 SDLoc DL = getCurSDLoc(); 3541 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3542 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3543 EVT SrcVT = Src1.getValueType(); 3544 3545 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3546 VT.isScalableVector()) { 3547 // Canonical splat form of first element of first input vector. 3548 SDValue FirstElt = 3549 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3550 DAG.getVectorIdxConstant(0, DL)); 3551 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3552 return; 3553 } 3554 3555 // For now, we only handle splats for scalable vectors. 3556 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3557 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3558 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3559 3560 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3561 unsigned MaskNumElts = Mask.size(); 3562 3563 if (SrcNumElts == MaskNumElts) { 3564 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3565 return; 3566 } 3567 3568 // Normalize the shuffle vector since mask and vector length don't match. 3569 if (SrcNumElts < MaskNumElts) { 3570 // Mask is longer than the source vectors. We can use concatenate vector to 3571 // make the mask and vectors lengths match. 3572 3573 if (MaskNumElts % SrcNumElts == 0) { 3574 // Mask length is a multiple of the source vector length. 3575 // Check if the shuffle is some kind of concatenation of the input 3576 // vectors. 3577 unsigned NumConcat = MaskNumElts / SrcNumElts; 3578 bool IsConcat = true; 3579 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3580 for (unsigned i = 0; i != MaskNumElts; ++i) { 3581 int Idx = Mask[i]; 3582 if (Idx < 0) 3583 continue; 3584 // Ensure the indices in each SrcVT sized piece are sequential and that 3585 // the same source is used for the whole piece. 3586 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3587 (ConcatSrcs[i / SrcNumElts] >= 0 && 3588 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3589 IsConcat = false; 3590 break; 3591 } 3592 // Remember which source this index came from. 3593 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3594 } 3595 3596 // The shuffle is concatenating multiple vectors together. Just emit 3597 // a CONCAT_VECTORS operation. 3598 if (IsConcat) { 3599 SmallVector<SDValue, 8> ConcatOps; 3600 for (auto Src : ConcatSrcs) { 3601 if (Src < 0) 3602 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3603 else if (Src == 0) 3604 ConcatOps.push_back(Src1); 3605 else 3606 ConcatOps.push_back(Src2); 3607 } 3608 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3609 return; 3610 } 3611 } 3612 3613 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3614 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3615 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3616 PaddedMaskNumElts); 3617 3618 // Pad both vectors with undefs to make them the same length as the mask. 3619 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3620 3621 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3622 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3623 MOps1[0] = Src1; 3624 MOps2[0] = Src2; 3625 3626 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3627 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3628 3629 // Readjust mask for new input vector length. 3630 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3631 for (unsigned i = 0; i != MaskNumElts; ++i) { 3632 int Idx = Mask[i]; 3633 if (Idx >= (int)SrcNumElts) 3634 Idx -= SrcNumElts - PaddedMaskNumElts; 3635 MappedOps[i] = Idx; 3636 } 3637 3638 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3639 3640 // If the concatenated vector was padded, extract a subvector with the 3641 // correct number of elements. 3642 if (MaskNumElts != PaddedMaskNumElts) 3643 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3644 DAG.getVectorIdxConstant(0, DL)); 3645 3646 setValue(&I, Result); 3647 return; 3648 } 3649 3650 if (SrcNumElts > MaskNumElts) { 3651 // Analyze the access pattern of the vector to see if we can extract 3652 // two subvectors and do the shuffle. 3653 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3654 bool CanExtract = true; 3655 for (int Idx : Mask) { 3656 unsigned Input = 0; 3657 if (Idx < 0) 3658 continue; 3659 3660 if (Idx >= (int)SrcNumElts) { 3661 Input = 1; 3662 Idx -= SrcNumElts; 3663 } 3664 3665 // If all the indices come from the same MaskNumElts sized portion of 3666 // the sources we can use extract. Also make sure the extract wouldn't 3667 // extract past the end of the source. 3668 int NewStartIdx = alignDown(Idx, MaskNumElts); 3669 if (NewStartIdx + MaskNumElts > SrcNumElts || 3670 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3671 CanExtract = false; 3672 // Make sure we always update StartIdx as we use it to track if all 3673 // elements are undef. 3674 StartIdx[Input] = NewStartIdx; 3675 } 3676 3677 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3678 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3679 return; 3680 } 3681 if (CanExtract) { 3682 // Extract appropriate subvector and generate a vector shuffle 3683 for (unsigned Input = 0; Input < 2; ++Input) { 3684 SDValue &Src = Input == 0 ? Src1 : Src2; 3685 if (StartIdx[Input] < 0) 3686 Src = DAG.getUNDEF(VT); 3687 else { 3688 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3689 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3690 } 3691 } 3692 3693 // Calculate new mask. 3694 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3695 for (int &Idx : MappedOps) { 3696 if (Idx >= (int)SrcNumElts) 3697 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3698 else if (Idx >= 0) 3699 Idx -= StartIdx[0]; 3700 } 3701 3702 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3703 return; 3704 } 3705 } 3706 3707 // We can't use either concat vectors or extract subvectors so fall back to 3708 // replacing the shuffle with extract and build vector. 3709 // to insert and build vector. 3710 EVT EltVT = VT.getVectorElementType(); 3711 SmallVector<SDValue,8> Ops; 3712 for (int Idx : Mask) { 3713 SDValue Res; 3714 3715 if (Idx < 0) { 3716 Res = DAG.getUNDEF(EltVT); 3717 } else { 3718 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3719 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3720 3721 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3722 DAG.getVectorIdxConstant(Idx, DL)); 3723 } 3724 3725 Ops.push_back(Res); 3726 } 3727 3728 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3729 } 3730 3731 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3732 ArrayRef<unsigned> Indices; 3733 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3734 Indices = IV->getIndices(); 3735 else 3736 Indices = cast<ConstantExpr>(&I)->getIndices(); 3737 3738 const Value *Op0 = I.getOperand(0); 3739 const Value *Op1 = I.getOperand(1); 3740 Type *AggTy = I.getType(); 3741 Type *ValTy = Op1->getType(); 3742 bool IntoUndef = isa<UndefValue>(Op0); 3743 bool FromUndef = isa<UndefValue>(Op1); 3744 3745 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3746 3747 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3748 SmallVector<EVT, 4> AggValueVTs; 3749 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3750 SmallVector<EVT, 4> ValValueVTs; 3751 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3752 3753 unsigned NumAggValues = AggValueVTs.size(); 3754 unsigned NumValValues = ValValueVTs.size(); 3755 SmallVector<SDValue, 4> Values(NumAggValues); 3756 3757 // Ignore an insertvalue that produces an empty object 3758 if (!NumAggValues) { 3759 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3760 return; 3761 } 3762 3763 SDValue Agg = getValue(Op0); 3764 unsigned i = 0; 3765 // Copy the beginning value(s) from the original aggregate. 3766 for (; i != LinearIndex; ++i) 3767 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3768 SDValue(Agg.getNode(), Agg.getResNo() + i); 3769 // Copy values from the inserted value(s). 3770 if (NumValValues) { 3771 SDValue Val = getValue(Op1); 3772 for (; i != LinearIndex + NumValValues; ++i) 3773 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3774 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3775 } 3776 // Copy remaining value(s) from the original aggregate. 3777 for (; i != NumAggValues; ++i) 3778 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3779 SDValue(Agg.getNode(), Agg.getResNo() + i); 3780 3781 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3782 DAG.getVTList(AggValueVTs), Values)); 3783 } 3784 3785 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3786 ArrayRef<unsigned> Indices; 3787 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3788 Indices = EV->getIndices(); 3789 else 3790 Indices = cast<ConstantExpr>(&I)->getIndices(); 3791 3792 const Value *Op0 = I.getOperand(0); 3793 Type *AggTy = Op0->getType(); 3794 Type *ValTy = I.getType(); 3795 bool OutOfUndef = isa<UndefValue>(Op0); 3796 3797 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3798 3799 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3800 SmallVector<EVT, 4> ValValueVTs; 3801 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3802 3803 unsigned NumValValues = ValValueVTs.size(); 3804 3805 // Ignore a extractvalue that produces an empty object 3806 if (!NumValValues) { 3807 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3808 return; 3809 } 3810 3811 SmallVector<SDValue, 4> Values(NumValValues); 3812 3813 SDValue Agg = getValue(Op0); 3814 // Copy out the selected value(s). 3815 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3816 Values[i - LinearIndex] = 3817 OutOfUndef ? 3818 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3819 SDValue(Agg.getNode(), Agg.getResNo() + i); 3820 3821 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3822 DAG.getVTList(ValValueVTs), Values)); 3823 } 3824 3825 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3826 Value *Op0 = I.getOperand(0); 3827 // Note that the pointer operand may be a vector of pointers. Take the scalar 3828 // element which holds a pointer. 3829 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3830 SDValue N = getValue(Op0); 3831 SDLoc dl = getCurSDLoc(); 3832 auto &TLI = DAG.getTargetLoweringInfo(); 3833 3834 // Normalize Vector GEP - all scalar operands should be converted to the 3835 // splat vector. 3836 bool IsVectorGEP = I.getType()->isVectorTy(); 3837 ElementCount VectorElementCount = 3838 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3839 : ElementCount::getFixed(0); 3840 3841 if (IsVectorGEP && !N.getValueType().isVector()) { 3842 LLVMContext &Context = *DAG.getContext(); 3843 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3844 if (VectorElementCount.isScalable()) 3845 N = DAG.getSplatVector(VT, dl, N); 3846 else 3847 N = DAG.getSplatBuildVector(VT, dl, N); 3848 } 3849 3850 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3851 GTI != E; ++GTI) { 3852 const Value *Idx = GTI.getOperand(); 3853 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3854 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3855 if (Field) { 3856 // N = N + Offset 3857 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3858 3859 // In an inbounds GEP with an offset that is nonnegative even when 3860 // interpreted as signed, assume there is no unsigned overflow. 3861 SDNodeFlags Flags; 3862 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3863 Flags.setNoUnsignedWrap(true); 3864 3865 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3866 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3867 } 3868 } else { 3869 // IdxSize is the width of the arithmetic according to IR semantics. 3870 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3871 // (and fix up the result later). 3872 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3873 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3874 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3875 // We intentionally mask away the high bits here; ElementSize may not 3876 // fit in IdxTy. 3877 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3878 bool ElementScalable = ElementSize.isScalable(); 3879 3880 // If this is a scalar constant or a splat vector of constants, 3881 // handle it quickly. 3882 const auto *C = dyn_cast<Constant>(Idx); 3883 if (C && isa<VectorType>(C->getType())) 3884 C = C->getSplatValue(); 3885 3886 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3887 if (CI && CI->isZero()) 3888 continue; 3889 if (CI && !ElementScalable) { 3890 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3891 LLVMContext &Context = *DAG.getContext(); 3892 SDValue OffsVal; 3893 if (IsVectorGEP) 3894 OffsVal = DAG.getConstant( 3895 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3896 else 3897 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3898 3899 // In an inbounds GEP with an offset that is nonnegative even when 3900 // interpreted as signed, assume there is no unsigned overflow. 3901 SDNodeFlags Flags; 3902 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3903 Flags.setNoUnsignedWrap(true); 3904 3905 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3906 3907 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3908 continue; 3909 } 3910 3911 // N = N + Idx * ElementMul; 3912 SDValue IdxN = getValue(Idx); 3913 3914 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3915 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3916 VectorElementCount); 3917 if (VectorElementCount.isScalable()) 3918 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3919 else 3920 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3921 } 3922 3923 // If the index is smaller or larger than intptr_t, truncate or extend 3924 // it. 3925 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3926 3927 if (ElementScalable) { 3928 EVT VScaleTy = N.getValueType().getScalarType(); 3929 SDValue VScale = DAG.getNode( 3930 ISD::VSCALE, dl, VScaleTy, 3931 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3932 if (IsVectorGEP) 3933 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3934 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3935 } else { 3936 // If this is a multiply by a power of two, turn it into a shl 3937 // immediately. This is a very common case. 3938 if (ElementMul != 1) { 3939 if (ElementMul.isPowerOf2()) { 3940 unsigned Amt = ElementMul.logBase2(); 3941 IdxN = DAG.getNode(ISD::SHL, dl, 3942 N.getValueType(), IdxN, 3943 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3944 } else { 3945 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3946 IdxN.getValueType()); 3947 IdxN = DAG.getNode(ISD::MUL, dl, 3948 N.getValueType(), IdxN, Scale); 3949 } 3950 } 3951 } 3952 3953 N = DAG.getNode(ISD::ADD, dl, 3954 N.getValueType(), N, IdxN); 3955 } 3956 } 3957 3958 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3959 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3960 if (IsVectorGEP) { 3961 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3962 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3963 } 3964 3965 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3966 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3967 3968 setValue(&I, N); 3969 } 3970 3971 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3972 // If this is a fixed sized alloca in the entry block of the function, 3973 // allocate it statically on the stack. 3974 if (FuncInfo.StaticAllocaMap.count(&I)) 3975 return; // getValue will auto-populate this. 3976 3977 SDLoc dl = getCurSDLoc(); 3978 Type *Ty = I.getAllocatedType(); 3979 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3980 auto &DL = DAG.getDataLayout(); 3981 uint64_t TySize = DL.getTypeAllocSize(Ty); 3982 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3983 3984 SDValue AllocSize = getValue(I.getArraySize()); 3985 3986 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3987 if (AllocSize.getValueType() != IntPtr) 3988 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3989 3990 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3991 AllocSize, 3992 DAG.getConstant(TySize, dl, IntPtr)); 3993 3994 // Handle alignment. If the requested alignment is less than or equal to 3995 // the stack alignment, ignore it. If the size is greater than or equal to 3996 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3997 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3998 if (*Alignment <= StackAlign) 3999 Alignment = None; 4000 4001 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4002 // Round the size of the allocation up to the stack alignment size 4003 // by add SA-1 to the size. This doesn't overflow because we're computing 4004 // an address inside an alloca. 4005 SDNodeFlags Flags; 4006 Flags.setNoUnsignedWrap(true); 4007 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4008 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4009 4010 // Mask out the low bits for alignment purposes. 4011 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4012 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4013 4014 SDValue Ops[] = { 4015 getRoot(), AllocSize, 4016 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4017 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4018 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4019 setValue(&I, DSA); 4020 DAG.setRoot(DSA.getValue(1)); 4021 4022 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4023 } 4024 4025 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4026 if (I.isAtomic()) 4027 return visitAtomicLoad(I); 4028 4029 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4030 const Value *SV = I.getOperand(0); 4031 if (TLI.supportSwiftError()) { 4032 // Swifterror values can come from either a function parameter with 4033 // swifterror attribute or an alloca with swifterror attribute. 4034 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4035 if (Arg->hasSwiftErrorAttr()) 4036 return visitLoadFromSwiftError(I); 4037 } 4038 4039 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4040 if (Alloca->isSwiftError()) 4041 return visitLoadFromSwiftError(I); 4042 } 4043 } 4044 4045 SDValue Ptr = getValue(SV); 4046 4047 Type *Ty = I.getType(); 4048 Align Alignment = I.getAlign(); 4049 4050 AAMDNodes AAInfo; 4051 I.getAAMetadata(AAInfo); 4052 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4053 4054 SmallVector<EVT, 4> ValueVTs, MemVTs; 4055 SmallVector<uint64_t, 4> Offsets; 4056 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4057 unsigned NumValues = ValueVTs.size(); 4058 if (NumValues == 0) 4059 return; 4060 4061 bool isVolatile = I.isVolatile(); 4062 4063 SDValue Root; 4064 bool ConstantMemory = false; 4065 if (isVolatile) 4066 // Serialize volatile loads with other side effects. 4067 Root = getRoot(); 4068 else if (NumValues > MaxParallelChains) 4069 Root = getMemoryRoot(); 4070 else if (AA && 4071 AA->pointsToConstantMemory(MemoryLocation( 4072 SV, 4073 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4074 AAInfo))) { 4075 // Do not serialize (non-volatile) loads of constant memory with anything. 4076 Root = DAG.getEntryNode(); 4077 ConstantMemory = true; 4078 } else { 4079 // Do not serialize non-volatile loads against each other. 4080 Root = DAG.getRoot(); 4081 } 4082 4083 SDLoc dl = getCurSDLoc(); 4084 4085 if (isVolatile) 4086 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4087 4088 // An aggregate load cannot wrap around the address space, so offsets to its 4089 // parts don't wrap either. 4090 SDNodeFlags Flags; 4091 Flags.setNoUnsignedWrap(true); 4092 4093 SmallVector<SDValue, 4> Values(NumValues); 4094 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4095 EVT PtrVT = Ptr.getValueType(); 4096 4097 MachineMemOperand::Flags MMOFlags 4098 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4099 4100 unsigned ChainI = 0; 4101 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4102 // Serializing loads here may result in excessive register pressure, and 4103 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4104 // could recover a bit by hoisting nodes upward in the chain by recognizing 4105 // they are side-effect free or do not alias. The optimizer should really 4106 // avoid this case by converting large object/array copies to llvm.memcpy 4107 // (MaxParallelChains should always remain as failsafe). 4108 if (ChainI == MaxParallelChains) { 4109 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4110 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4111 makeArrayRef(Chains.data(), ChainI)); 4112 Root = Chain; 4113 ChainI = 0; 4114 } 4115 SDValue A = DAG.getNode(ISD::ADD, dl, 4116 PtrVT, Ptr, 4117 DAG.getConstant(Offsets[i], dl, PtrVT), 4118 Flags); 4119 4120 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4121 MachinePointerInfo(SV, Offsets[i]), Alignment, 4122 MMOFlags, AAInfo, Ranges); 4123 Chains[ChainI] = L.getValue(1); 4124 4125 if (MemVTs[i] != ValueVTs[i]) 4126 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4127 4128 Values[i] = L; 4129 } 4130 4131 if (!ConstantMemory) { 4132 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4133 makeArrayRef(Chains.data(), ChainI)); 4134 if (isVolatile) 4135 DAG.setRoot(Chain); 4136 else 4137 PendingLoads.push_back(Chain); 4138 } 4139 4140 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4141 DAG.getVTList(ValueVTs), Values)); 4142 } 4143 4144 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4145 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4146 "call visitStoreToSwiftError when backend supports swifterror"); 4147 4148 SmallVector<EVT, 4> ValueVTs; 4149 SmallVector<uint64_t, 4> Offsets; 4150 const Value *SrcV = I.getOperand(0); 4151 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4152 SrcV->getType(), ValueVTs, &Offsets); 4153 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4154 "expect a single EVT for swifterror"); 4155 4156 SDValue Src = getValue(SrcV); 4157 // Create a virtual register, then update the virtual register. 4158 Register VReg = 4159 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4160 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4161 // Chain can be getRoot or getControlRoot. 4162 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4163 SDValue(Src.getNode(), Src.getResNo())); 4164 DAG.setRoot(CopyNode); 4165 } 4166 4167 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4168 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4169 "call visitLoadFromSwiftError when backend supports swifterror"); 4170 4171 assert(!I.isVolatile() && 4172 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4173 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4174 "Support volatile, non temporal, invariant for load_from_swift_error"); 4175 4176 const Value *SV = I.getOperand(0); 4177 Type *Ty = I.getType(); 4178 AAMDNodes AAInfo; 4179 I.getAAMetadata(AAInfo); 4180 assert( 4181 (!AA || 4182 !AA->pointsToConstantMemory(MemoryLocation( 4183 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4184 AAInfo))) && 4185 "load_from_swift_error should not be constant memory"); 4186 4187 SmallVector<EVT, 4> ValueVTs; 4188 SmallVector<uint64_t, 4> Offsets; 4189 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4190 ValueVTs, &Offsets); 4191 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4192 "expect a single EVT for swifterror"); 4193 4194 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4195 SDValue L = DAG.getCopyFromReg( 4196 getRoot(), getCurSDLoc(), 4197 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4198 4199 setValue(&I, L); 4200 } 4201 4202 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4203 if (I.isAtomic()) 4204 return visitAtomicStore(I); 4205 4206 const Value *SrcV = I.getOperand(0); 4207 const Value *PtrV = I.getOperand(1); 4208 4209 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4210 if (TLI.supportSwiftError()) { 4211 // Swifterror values can come from either a function parameter with 4212 // swifterror attribute or an alloca with swifterror attribute. 4213 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4214 if (Arg->hasSwiftErrorAttr()) 4215 return visitStoreToSwiftError(I); 4216 } 4217 4218 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4219 if (Alloca->isSwiftError()) 4220 return visitStoreToSwiftError(I); 4221 } 4222 } 4223 4224 SmallVector<EVT, 4> ValueVTs, MemVTs; 4225 SmallVector<uint64_t, 4> Offsets; 4226 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4227 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4228 unsigned NumValues = ValueVTs.size(); 4229 if (NumValues == 0) 4230 return; 4231 4232 // Get the lowered operands. Note that we do this after 4233 // checking if NumResults is zero, because with zero results 4234 // the operands won't have values in the map. 4235 SDValue Src = getValue(SrcV); 4236 SDValue Ptr = getValue(PtrV); 4237 4238 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4239 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4240 SDLoc dl = getCurSDLoc(); 4241 Align Alignment = I.getAlign(); 4242 AAMDNodes AAInfo; 4243 I.getAAMetadata(AAInfo); 4244 4245 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4246 4247 // An aggregate load cannot wrap around the address space, so offsets to its 4248 // parts don't wrap either. 4249 SDNodeFlags Flags; 4250 Flags.setNoUnsignedWrap(true); 4251 4252 unsigned ChainI = 0; 4253 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4254 // See visitLoad comments. 4255 if (ChainI == MaxParallelChains) { 4256 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4257 makeArrayRef(Chains.data(), ChainI)); 4258 Root = Chain; 4259 ChainI = 0; 4260 } 4261 SDValue Add = 4262 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4263 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4264 if (MemVTs[i] != ValueVTs[i]) 4265 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4266 SDValue St = 4267 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4268 Alignment, MMOFlags, AAInfo); 4269 Chains[ChainI] = St; 4270 } 4271 4272 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4273 makeArrayRef(Chains.data(), ChainI)); 4274 DAG.setRoot(StoreNode); 4275 } 4276 4277 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4278 bool IsCompressing) { 4279 SDLoc sdl = getCurSDLoc(); 4280 4281 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4282 MaybeAlign &Alignment) { 4283 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4284 Src0 = I.getArgOperand(0); 4285 Ptr = I.getArgOperand(1); 4286 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4287 Mask = I.getArgOperand(3); 4288 }; 4289 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4290 MaybeAlign &Alignment) { 4291 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4292 Src0 = I.getArgOperand(0); 4293 Ptr = I.getArgOperand(1); 4294 Mask = I.getArgOperand(2); 4295 Alignment = None; 4296 }; 4297 4298 Value *PtrOperand, *MaskOperand, *Src0Operand; 4299 MaybeAlign Alignment; 4300 if (IsCompressing) 4301 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4302 else 4303 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4304 4305 SDValue Ptr = getValue(PtrOperand); 4306 SDValue Src0 = getValue(Src0Operand); 4307 SDValue Mask = getValue(MaskOperand); 4308 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4309 4310 EVT VT = Src0.getValueType(); 4311 if (!Alignment) 4312 Alignment = DAG.getEVTAlign(VT); 4313 4314 AAMDNodes AAInfo; 4315 I.getAAMetadata(AAInfo); 4316 4317 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4318 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4319 // TODO: Make MachineMemOperands aware of scalable 4320 // vectors. 4321 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4322 SDValue StoreNode = 4323 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4324 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4325 DAG.setRoot(StoreNode); 4326 setValue(&I, StoreNode); 4327 } 4328 4329 // Get a uniform base for the Gather/Scatter intrinsic. 4330 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4331 // We try to represent it as a base pointer + vector of indices. 4332 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4333 // The first operand of the GEP may be a single pointer or a vector of pointers 4334 // Example: 4335 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4336 // or 4337 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4338 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4339 // 4340 // When the first GEP operand is a single pointer - it is the uniform base we 4341 // are looking for. If first operand of the GEP is a splat vector - we 4342 // extract the splat value and use it as a uniform base. 4343 // In all other cases the function returns 'false'. 4344 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4345 ISD::MemIndexType &IndexType, SDValue &Scale, 4346 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4347 SelectionDAG& DAG = SDB->DAG; 4348 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4349 const DataLayout &DL = DAG.getDataLayout(); 4350 4351 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4352 4353 // Handle splat constant pointer. 4354 if (auto *C = dyn_cast<Constant>(Ptr)) { 4355 C = C->getSplatValue(); 4356 if (!C) 4357 return false; 4358 4359 Base = SDB->getValue(C); 4360 4361 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4362 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4363 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4364 IndexType = ISD::SIGNED_SCALED; 4365 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4366 return true; 4367 } 4368 4369 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4370 if (!GEP || GEP->getParent() != CurBB) 4371 return false; 4372 4373 if (GEP->getNumOperands() != 2) 4374 return false; 4375 4376 const Value *BasePtr = GEP->getPointerOperand(); 4377 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4378 4379 // Make sure the base is scalar and the index is a vector. 4380 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4381 return false; 4382 4383 Base = SDB->getValue(BasePtr); 4384 Index = SDB->getValue(IndexVal); 4385 IndexType = ISD::SIGNED_SCALED; 4386 Scale = DAG.getTargetConstant( 4387 DL.getTypeAllocSize(GEP->getResultElementType()), 4388 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4389 return true; 4390 } 4391 4392 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4393 SDLoc sdl = getCurSDLoc(); 4394 4395 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4396 const Value *Ptr = I.getArgOperand(1); 4397 SDValue Src0 = getValue(I.getArgOperand(0)); 4398 SDValue Mask = getValue(I.getArgOperand(3)); 4399 EVT VT = Src0.getValueType(); 4400 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4401 ->getMaybeAlignValue() 4402 .getValueOr(DAG.getEVTAlign(VT)); 4403 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4404 4405 AAMDNodes AAInfo; 4406 I.getAAMetadata(AAInfo); 4407 4408 SDValue Base; 4409 SDValue Index; 4410 ISD::MemIndexType IndexType; 4411 SDValue Scale; 4412 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4413 I.getParent()); 4414 4415 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4416 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4417 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4418 // TODO: Make MachineMemOperands aware of scalable 4419 // vectors. 4420 MemoryLocation::UnknownSize, Alignment, AAInfo); 4421 if (!UniformBase) { 4422 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4423 Index = getValue(Ptr); 4424 IndexType = ISD::SIGNED_UNSCALED; 4425 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4426 } 4427 4428 EVT IdxVT = Index.getValueType(); 4429 EVT EltTy = IdxVT.getVectorElementType(); 4430 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4431 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4432 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4433 } 4434 4435 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4436 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4437 Ops, MMO, IndexType, false); 4438 DAG.setRoot(Scatter); 4439 setValue(&I, Scatter); 4440 } 4441 4442 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4443 SDLoc sdl = getCurSDLoc(); 4444 4445 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4446 MaybeAlign &Alignment) { 4447 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4448 Ptr = I.getArgOperand(0); 4449 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4450 Mask = I.getArgOperand(2); 4451 Src0 = I.getArgOperand(3); 4452 }; 4453 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4454 MaybeAlign &Alignment) { 4455 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4456 Ptr = I.getArgOperand(0); 4457 Alignment = None; 4458 Mask = I.getArgOperand(1); 4459 Src0 = I.getArgOperand(2); 4460 }; 4461 4462 Value *PtrOperand, *MaskOperand, *Src0Operand; 4463 MaybeAlign Alignment; 4464 if (IsExpanding) 4465 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4466 else 4467 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4468 4469 SDValue Ptr = getValue(PtrOperand); 4470 SDValue Src0 = getValue(Src0Operand); 4471 SDValue Mask = getValue(MaskOperand); 4472 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4473 4474 EVT VT = Src0.getValueType(); 4475 if (!Alignment) 4476 Alignment = DAG.getEVTAlign(VT); 4477 4478 AAMDNodes AAInfo; 4479 I.getAAMetadata(AAInfo); 4480 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4481 4482 // Do not serialize masked loads of constant memory with anything. 4483 MemoryLocation ML; 4484 if (VT.isScalableVector()) 4485 ML = MemoryLocation::getAfter(PtrOperand); 4486 else 4487 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4488 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4489 AAInfo); 4490 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4491 4492 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4493 4494 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4495 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4496 // TODO: Make MachineMemOperands aware of scalable 4497 // vectors. 4498 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4499 4500 SDValue Load = 4501 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4502 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4503 if (AddToChain) 4504 PendingLoads.push_back(Load.getValue(1)); 4505 setValue(&I, Load); 4506 } 4507 4508 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4509 SDLoc sdl = getCurSDLoc(); 4510 4511 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4512 const Value *Ptr = I.getArgOperand(0); 4513 SDValue Src0 = getValue(I.getArgOperand(3)); 4514 SDValue Mask = getValue(I.getArgOperand(2)); 4515 4516 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4517 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4518 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4519 ->getMaybeAlignValue() 4520 .getValueOr(DAG.getEVTAlign(VT)); 4521 4522 AAMDNodes AAInfo; 4523 I.getAAMetadata(AAInfo); 4524 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4525 4526 SDValue Root = DAG.getRoot(); 4527 SDValue Base; 4528 SDValue Index; 4529 ISD::MemIndexType IndexType; 4530 SDValue Scale; 4531 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4532 I.getParent()); 4533 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4534 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4535 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4536 // TODO: Make MachineMemOperands aware of scalable 4537 // vectors. 4538 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4539 4540 if (!UniformBase) { 4541 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4542 Index = getValue(Ptr); 4543 IndexType = ISD::SIGNED_UNSCALED; 4544 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4545 } 4546 4547 EVT IdxVT = Index.getValueType(); 4548 EVT EltTy = IdxVT.getVectorElementType(); 4549 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4550 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4551 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4552 } 4553 4554 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4555 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4556 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4557 4558 PendingLoads.push_back(Gather.getValue(1)); 4559 setValue(&I, Gather); 4560 } 4561 4562 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4563 SDLoc dl = getCurSDLoc(); 4564 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4565 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4566 SyncScope::ID SSID = I.getSyncScopeID(); 4567 4568 SDValue InChain = getRoot(); 4569 4570 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4571 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4572 4573 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4574 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4575 4576 MachineFunction &MF = DAG.getMachineFunction(); 4577 MachineMemOperand *MMO = MF.getMachineMemOperand( 4578 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4579 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4580 FailureOrdering); 4581 4582 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4583 dl, MemVT, VTs, InChain, 4584 getValue(I.getPointerOperand()), 4585 getValue(I.getCompareOperand()), 4586 getValue(I.getNewValOperand()), MMO); 4587 4588 SDValue OutChain = L.getValue(2); 4589 4590 setValue(&I, L); 4591 DAG.setRoot(OutChain); 4592 } 4593 4594 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4595 SDLoc dl = getCurSDLoc(); 4596 ISD::NodeType NT; 4597 switch (I.getOperation()) { 4598 default: llvm_unreachable("Unknown atomicrmw operation"); 4599 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4600 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4601 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4602 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4603 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4604 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4605 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4606 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4607 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4608 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4609 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4610 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4611 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4612 } 4613 AtomicOrdering Ordering = I.getOrdering(); 4614 SyncScope::ID SSID = I.getSyncScopeID(); 4615 4616 SDValue InChain = getRoot(); 4617 4618 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4619 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4620 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4621 4622 MachineFunction &MF = DAG.getMachineFunction(); 4623 MachineMemOperand *MMO = MF.getMachineMemOperand( 4624 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4625 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4626 4627 SDValue L = 4628 DAG.getAtomic(NT, dl, MemVT, InChain, 4629 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4630 MMO); 4631 4632 SDValue OutChain = L.getValue(1); 4633 4634 setValue(&I, L); 4635 DAG.setRoot(OutChain); 4636 } 4637 4638 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4639 SDLoc dl = getCurSDLoc(); 4640 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4641 SDValue Ops[3]; 4642 Ops[0] = getRoot(); 4643 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4644 TLI.getFenceOperandTy(DAG.getDataLayout())); 4645 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4646 TLI.getFenceOperandTy(DAG.getDataLayout())); 4647 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4648 } 4649 4650 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4651 SDLoc dl = getCurSDLoc(); 4652 AtomicOrdering Order = I.getOrdering(); 4653 SyncScope::ID SSID = I.getSyncScopeID(); 4654 4655 SDValue InChain = getRoot(); 4656 4657 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4658 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4659 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4660 4661 if (!TLI.supportsUnalignedAtomics() && 4662 I.getAlignment() < MemVT.getSizeInBits() / 8) 4663 report_fatal_error("Cannot generate unaligned atomic load"); 4664 4665 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4666 4667 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4668 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4669 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4670 4671 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4672 4673 SDValue Ptr = getValue(I.getPointerOperand()); 4674 4675 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4676 // TODO: Once this is better exercised by tests, it should be merged with 4677 // the normal path for loads to prevent future divergence. 4678 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4679 if (MemVT != VT) 4680 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4681 4682 setValue(&I, L); 4683 SDValue OutChain = L.getValue(1); 4684 if (!I.isUnordered()) 4685 DAG.setRoot(OutChain); 4686 else 4687 PendingLoads.push_back(OutChain); 4688 return; 4689 } 4690 4691 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4692 Ptr, MMO); 4693 4694 SDValue OutChain = L.getValue(1); 4695 if (MemVT != VT) 4696 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4697 4698 setValue(&I, L); 4699 DAG.setRoot(OutChain); 4700 } 4701 4702 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4703 SDLoc dl = getCurSDLoc(); 4704 4705 AtomicOrdering Ordering = I.getOrdering(); 4706 SyncScope::ID SSID = I.getSyncScopeID(); 4707 4708 SDValue InChain = getRoot(); 4709 4710 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4711 EVT MemVT = 4712 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4713 4714 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4715 report_fatal_error("Cannot generate unaligned atomic store"); 4716 4717 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4718 4719 MachineFunction &MF = DAG.getMachineFunction(); 4720 MachineMemOperand *MMO = MF.getMachineMemOperand( 4721 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4722 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4723 4724 SDValue Val = getValue(I.getValueOperand()); 4725 if (Val.getValueType() != MemVT) 4726 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4727 SDValue Ptr = getValue(I.getPointerOperand()); 4728 4729 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4730 // TODO: Once this is better exercised by tests, it should be merged with 4731 // the normal path for stores to prevent future divergence. 4732 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4733 DAG.setRoot(S); 4734 return; 4735 } 4736 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4737 Ptr, Val, MMO); 4738 4739 4740 DAG.setRoot(OutChain); 4741 } 4742 4743 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4744 /// node. 4745 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4746 unsigned Intrinsic) { 4747 // Ignore the callsite's attributes. A specific call site may be marked with 4748 // readnone, but the lowering code will expect the chain based on the 4749 // definition. 4750 const Function *F = I.getCalledFunction(); 4751 bool HasChain = !F->doesNotAccessMemory(); 4752 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4753 4754 // Build the operand list. 4755 SmallVector<SDValue, 8> Ops; 4756 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4757 if (OnlyLoad) { 4758 // We don't need to serialize loads against other loads. 4759 Ops.push_back(DAG.getRoot()); 4760 } else { 4761 Ops.push_back(getRoot()); 4762 } 4763 } 4764 4765 // Info is set by getTgtMemInstrinsic 4766 TargetLowering::IntrinsicInfo Info; 4767 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4768 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4769 DAG.getMachineFunction(), 4770 Intrinsic); 4771 4772 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4773 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4774 Info.opc == ISD::INTRINSIC_W_CHAIN) 4775 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4776 TLI.getPointerTy(DAG.getDataLayout()))); 4777 4778 // Add all operands of the call to the operand list. 4779 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4780 const Value *Arg = I.getArgOperand(i); 4781 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4782 Ops.push_back(getValue(Arg)); 4783 continue; 4784 } 4785 4786 // Use TargetConstant instead of a regular constant for immarg. 4787 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4788 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4789 assert(CI->getBitWidth() <= 64 && 4790 "large intrinsic immediates not handled"); 4791 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4792 } else { 4793 Ops.push_back( 4794 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4795 } 4796 } 4797 4798 SmallVector<EVT, 4> ValueVTs; 4799 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4800 4801 if (HasChain) 4802 ValueVTs.push_back(MVT::Other); 4803 4804 SDVTList VTs = DAG.getVTList(ValueVTs); 4805 4806 // Propagate fast-math-flags from IR to node(s). 4807 SDNodeFlags Flags; 4808 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4809 Flags.copyFMF(*FPMO); 4810 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4811 4812 // Create the node. 4813 SDValue Result; 4814 if (IsTgtIntrinsic) { 4815 // This is target intrinsic that touches memory 4816 AAMDNodes AAInfo; 4817 I.getAAMetadata(AAInfo); 4818 Result = 4819 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4820 MachinePointerInfo(Info.ptrVal, Info.offset), 4821 Info.align, Info.flags, Info.size, AAInfo); 4822 } else if (!HasChain) { 4823 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4824 } else if (!I.getType()->isVoidTy()) { 4825 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4826 } else { 4827 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4828 } 4829 4830 if (HasChain) { 4831 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4832 if (OnlyLoad) 4833 PendingLoads.push_back(Chain); 4834 else 4835 DAG.setRoot(Chain); 4836 } 4837 4838 if (!I.getType()->isVoidTy()) { 4839 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4840 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4841 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4842 } else 4843 Result = lowerRangeToAssertZExt(DAG, I, Result); 4844 4845 MaybeAlign Alignment = I.getRetAlign(); 4846 if (!Alignment) 4847 Alignment = F->getAttributes().getRetAlignment(); 4848 // Insert `assertalign` node if there's an alignment. 4849 if (InsertAssertAlign && Alignment) { 4850 Result = 4851 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4852 } 4853 4854 setValue(&I, Result); 4855 } 4856 } 4857 4858 /// GetSignificand - Get the significand and build it into a floating-point 4859 /// number with exponent of 1: 4860 /// 4861 /// Op = (Op & 0x007fffff) | 0x3f800000; 4862 /// 4863 /// where Op is the hexadecimal representation of floating point value. 4864 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4865 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4866 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4867 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4868 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4869 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4870 } 4871 4872 /// GetExponent - Get the exponent: 4873 /// 4874 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4875 /// 4876 /// where Op is the hexadecimal representation of floating point value. 4877 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4878 const TargetLowering &TLI, const SDLoc &dl) { 4879 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4880 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4881 SDValue t1 = DAG.getNode( 4882 ISD::SRL, dl, MVT::i32, t0, 4883 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4884 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4885 DAG.getConstant(127, dl, MVT::i32)); 4886 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4887 } 4888 4889 /// getF32Constant - Get 32-bit floating point constant. 4890 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4891 const SDLoc &dl) { 4892 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4893 MVT::f32); 4894 } 4895 4896 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4897 SelectionDAG &DAG) { 4898 // TODO: What fast-math-flags should be set on the floating-point nodes? 4899 4900 // IntegerPartOfX = ((int32_t)(t0); 4901 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4902 4903 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4904 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4905 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4906 4907 // IntegerPartOfX <<= 23; 4908 IntegerPartOfX = DAG.getNode( 4909 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4910 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4911 DAG.getDataLayout()))); 4912 4913 SDValue TwoToFractionalPartOfX; 4914 if (LimitFloatPrecision <= 6) { 4915 // For floating-point precision of 6: 4916 // 4917 // TwoToFractionalPartOfX = 4918 // 0.997535578f + 4919 // (0.735607626f + 0.252464424f * x) * x; 4920 // 4921 // error 0.0144103317, which is 6 bits 4922 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4923 getF32Constant(DAG, 0x3e814304, dl)); 4924 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4925 getF32Constant(DAG, 0x3f3c50c8, dl)); 4926 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4927 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4928 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4929 } else if (LimitFloatPrecision <= 12) { 4930 // For floating-point precision of 12: 4931 // 4932 // TwoToFractionalPartOfX = 4933 // 0.999892986f + 4934 // (0.696457318f + 4935 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4936 // 4937 // error 0.000107046256, which is 13 to 14 bits 4938 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4939 getF32Constant(DAG, 0x3da235e3, dl)); 4940 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4941 getF32Constant(DAG, 0x3e65b8f3, dl)); 4942 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4943 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4944 getF32Constant(DAG, 0x3f324b07, dl)); 4945 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4946 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4947 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4948 } else { // LimitFloatPrecision <= 18 4949 // For floating-point precision of 18: 4950 // 4951 // TwoToFractionalPartOfX = 4952 // 0.999999982f + 4953 // (0.693148872f + 4954 // (0.240227044f + 4955 // (0.554906021e-1f + 4956 // (0.961591928e-2f + 4957 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4958 // error 2.47208000*10^(-7), which is better than 18 bits 4959 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4960 getF32Constant(DAG, 0x3924b03e, dl)); 4961 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4962 getF32Constant(DAG, 0x3ab24b87, dl)); 4963 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4964 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4965 getF32Constant(DAG, 0x3c1d8c17, dl)); 4966 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4967 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4968 getF32Constant(DAG, 0x3d634a1d, dl)); 4969 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4970 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4971 getF32Constant(DAG, 0x3e75fe14, dl)); 4972 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4973 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4974 getF32Constant(DAG, 0x3f317234, dl)); 4975 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4976 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4977 getF32Constant(DAG, 0x3f800000, dl)); 4978 } 4979 4980 // Add the exponent into the result in integer domain. 4981 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4982 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4983 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4984 } 4985 4986 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4987 /// limited-precision mode. 4988 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4989 const TargetLowering &TLI, SDNodeFlags Flags) { 4990 if (Op.getValueType() == MVT::f32 && 4991 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4992 4993 // Put the exponent in the right bit position for later addition to the 4994 // final result: 4995 // 4996 // t0 = Op * log2(e) 4997 4998 // TODO: What fast-math-flags should be set here? 4999 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5000 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5001 return getLimitedPrecisionExp2(t0, dl, DAG); 5002 } 5003 5004 // No special expansion. 5005 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5006 } 5007 5008 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5009 /// limited-precision mode. 5010 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5011 const TargetLowering &TLI, SDNodeFlags Flags) { 5012 // TODO: What fast-math-flags should be set on the floating-point nodes? 5013 5014 if (Op.getValueType() == MVT::f32 && 5015 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5016 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5017 5018 // Scale the exponent by log(2). 5019 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5020 SDValue LogOfExponent = 5021 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5022 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5023 5024 // Get the significand and build it into a floating-point number with 5025 // exponent of 1. 5026 SDValue X = GetSignificand(DAG, Op1, dl); 5027 5028 SDValue LogOfMantissa; 5029 if (LimitFloatPrecision <= 6) { 5030 // For floating-point precision of 6: 5031 // 5032 // LogofMantissa = 5033 // -1.1609546f + 5034 // (1.4034025f - 0.23903021f * x) * x; 5035 // 5036 // error 0.0034276066, which is better than 8 bits 5037 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5038 getF32Constant(DAG, 0xbe74c456, dl)); 5039 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5040 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5041 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5042 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5043 getF32Constant(DAG, 0x3f949a29, dl)); 5044 } else if (LimitFloatPrecision <= 12) { 5045 // For floating-point precision of 12: 5046 // 5047 // LogOfMantissa = 5048 // -1.7417939f + 5049 // (2.8212026f + 5050 // (-1.4699568f + 5051 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5052 // 5053 // error 0.000061011436, which is 14 bits 5054 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5055 getF32Constant(DAG, 0xbd67b6d6, dl)); 5056 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5057 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5058 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5059 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5060 getF32Constant(DAG, 0x3fbc278b, dl)); 5061 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5062 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5063 getF32Constant(DAG, 0x40348e95, dl)); 5064 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5065 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5066 getF32Constant(DAG, 0x3fdef31a, dl)); 5067 } else { // LimitFloatPrecision <= 18 5068 // For floating-point precision of 18: 5069 // 5070 // LogOfMantissa = 5071 // -2.1072184f + 5072 // (4.2372794f + 5073 // (-3.7029485f + 5074 // (2.2781945f + 5075 // (-0.87823314f + 5076 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5077 // 5078 // error 0.0000023660568, which is better than 18 bits 5079 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5080 getF32Constant(DAG, 0xbc91e5ac, dl)); 5081 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5082 getF32Constant(DAG, 0x3e4350aa, dl)); 5083 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5084 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5085 getF32Constant(DAG, 0x3f60d3e3, dl)); 5086 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5087 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5088 getF32Constant(DAG, 0x4011cdf0, dl)); 5089 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5090 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5091 getF32Constant(DAG, 0x406cfd1c, dl)); 5092 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5093 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5094 getF32Constant(DAG, 0x408797cb, dl)); 5095 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5096 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5097 getF32Constant(DAG, 0x4006dcab, dl)); 5098 } 5099 5100 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5101 } 5102 5103 // No special expansion. 5104 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5105 } 5106 5107 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5108 /// limited-precision mode. 5109 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5110 const TargetLowering &TLI, SDNodeFlags Flags) { 5111 // TODO: What fast-math-flags should be set on the floating-point nodes? 5112 5113 if (Op.getValueType() == MVT::f32 && 5114 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5115 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5116 5117 // Get the exponent. 5118 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5119 5120 // Get the significand and build it into a floating-point number with 5121 // exponent of 1. 5122 SDValue X = GetSignificand(DAG, Op1, dl); 5123 5124 // Different possible minimax approximations of significand in 5125 // floating-point for various degrees of accuracy over [1,2]. 5126 SDValue Log2ofMantissa; 5127 if (LimitFloatPrecision <= 6) { 5128 // For floating-point precision of 6: 5129 // 5130 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5131 // 5132 // error 0.0049451742, which is more than 7 bits 5133 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5134 getF32Constant(DAG, 0xbeb08fe0, dl)); 5135 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5136 getF32Constant(DAG, 0x40019463, dl)); 5137 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5138 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5139 getF32Constant(DAG, 0x3fd6633d, dl)); 5140 } else if (LimitFloatPrecision <= 12) { 5141 // For floating-point precision of 12: 5142 // 5143 // Log2ofMantissa = 5144 // -2.51285454f + 5145 // (4.07009056f + 5146 // (-2.12067489f + 5147 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5148 // 5149 // error 0.0000876136000, which is better than 13 bits 5150 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5151 getF32Constant(DAG, 0xbda7262e, dl)); 5152 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5153 getF32Constant(DAG, 0x3f25280b, dl)); 5154 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5155 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5156 getF32Constant(DAG, 0x4007b923, dl)); 5157 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5158 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5159 getF32Constant(DAG, 0x40823e2f, dl)); 5160 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5161 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5162 getF32Constant(DAG, 0x4020d29c, dl)); 5163 } else { // LimitFloatPrecision <= 18 5164 // For floating-point precision of 18: 5165 // 5166 // Log2ofMantissa = 5167 // -3.0400495f + 5168 // (6.1129976f + 5169 // (-5.3420409f + 5170 // (3.2865683f + 5171 // (-1.2669343f + 5172 // (0.27515199f - 5173 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5174 // 5175 // error 0.0000018516, which is better than 18 bits 5176 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5177 getF32Constant(DAG, 0xbcd2769e, dl)); 5178 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5179 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5180 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5181 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5182 getF32Constant(DAG, 0x3fa22ae7, dl)); 5183 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5184 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5185 getF32Constant(DAG, 0x40525723, dl)); 5186 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5187 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5188 getF32Constant(DAG, 0x40aaf200, dl)); 5189 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5190 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5191 getF32Constant(DAG, 0x40c39dad, dl)); 5192 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5193 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5194 getF32Constant(DAG, 0x4042902c, dl)); 5195 } 5196 5197 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5198 } 5199 5200 // No special expansion. 5201 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5202 } 5203 5204 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5205 /// limited-precision mode. 5206 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5207 const TargetLowering &TLI, SDNodeFlags Flags) { 5208 // TODO: What fast-math-flags should be set on the floating-point nodes? 5209 5210 if (Op.getValueType() == MVT::f32 && 5211 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5212 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5213 5214 // Scale the exponent by log10(2) [0.30102999f]. 5215 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5216 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5217 getF32Constant(DAG, 0x3e9a209a, dl)); 5218 5219 // Get the significand and build it into a floating-point number with 5220 // exponent of 1. 5221 SDValue X = GetSignificand(DAG, Op1, dl); 5222 5223 SDValue Log10ofMantissa; 5224 if (LimitFloatPrecision <= 6) { 5225 // For floating-point precision of 6: 5226 // 5227 // Log10ofMantissa = 5228 // -0.50419619f + 5229 // (0.60948995f - 0.10380950f * x) * x; 5230 // 5231 // error 0.0014886165, which is 6 bits 5232 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5233 getF32Constant(DAG, 0xbdd49a13, dl)); 5234 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5235 getF32Constant(DAG, 0x3f1c0789, dl)); 5236 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5237 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5238 getF32Constant(DAG, 0x3f011300, dl)); 5239 } else if (LimitFloatPrecision <= 12) { 5240 // For floating-point precision of 12: 5241 // 5242 // Log10ofMantissa = 5243 // -0.64831180f + 5244 // (0.91751397f + 5245 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5246 // 5247 // error 0.00019228036, which is better than 12 bits 5248 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5249 getF32Constant(DAG, 0x3d431f31, dl)); 5250 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5251 getF32Constant(DAG, 0x3ea21fb2, dl)); 5252 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5253 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5254 getF32Constant(DAG, 0x3f6ae232, dl)); 5255 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5256 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5257 getF32Constant(DAG, 0x3f25f7c3, dl)); 5258 } else { // LimitFloatPrecision <= 18 5259 // For floating-point precision of 18: 5260 // 5261 // Log10ofMantissa = 5262 // -0.84299375f + 5263 // (1.5327582f + 5264 // (-1.0688956f + 5265 // (0.49102474f + 5266 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5267 // 5268 // error 0.0000037995730, which is better than 18 bits 5269 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5270 getF32Constant(DAG, 0x3c5d51ce, dl)); 5271 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5272 getF32Constant(DAG, 0x3e00685a, dl)); 5273 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5274 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5275 getF32Constant(DAG, 0x3efb6798, dl)); 5276 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5277 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5278 getF32Constant(DAG, 0x3f88d192, dl)); 5279 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5280 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5281 getF32Constant(DAG, 0x3fc4316c, dl)); 5282 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5283 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5284 getF32Constant(DAG, 0x3f57ce70, dl)); 5285 } 5286 5287 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5288 } 5289 5290 // No special expansion. 5291 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5292 } 5293 5294 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5295 /// limited-precision mode. 5296 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5297 const TargetLowering &TLI, SDNodeFlags Flags) { 5298 if (Op.getValueType() == MVT::f32 && 5299 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5300 return getLimitedPrecisionExp2(Op, dl, DAG); 5301 5302 // No special expansion. 5303 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5304 } 5305 5306 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5307 /// limited-precision mode with x == 10.0f. 5308 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5309 SelectionDAG &DAG, const TargetLowering &TLI, 5310 SDNodeFlags Flags) { 5311 bool IsExp10 = false; 5312 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5313 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5314 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5315 APFloat Ten(10.0f); 5316 IsExp10 = LHSC->isExactlyValue(Ten); 5317 } 5318 } 5319 5320 // TODO: What fast-math-flags should be set on the FMUL node? 5321 if (IsExp10) { 5322 // Put the exponent in the right bit position for later addition to the 5323 // final result: 5324 // 5325 // #define LOG2OF10 3.3219281f 5326 // t0 = Op * LOG2OF10; 5327 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5328 getF32Constant(DAG, 0x40549a78, dl)); 5329 return getLimitedPrecisionExp2(t0, dl, DAG); 5330 } 5331 5332 // No special expansion. 5333 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5334 } 5335 5336 /// ExpandPowI - Expand a llvm.powi intrinsic. 5337 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5338 SelectionDAG &DAG) { 5339 // If RHS is a constant, we can expand this out to a multiplication tree, 5340 // otherwise we end up lowering to a call to __powidf2 (for example). When 5341 // optimizing for size, we only want to do this if the expansion would produce 5342 // a small number of multiplies, otherwise we do the full expansion. 5343 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5344 // Get the exponent as a positive value. 5345 unsigned Val = RHSC->getSExtValue(); 5346 if ((int)Val < 0) Val = -Val; 5347 5348 // powi(x, 0) -> 1.0 5349 if (Val == 0) 5350 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5351 5352 bool OptForSize = DAG.shouldOptForSize(); 5353 if (!OptForSize || 5354 // If optimizing for size, don't insert too many multiplies. 5355 // This inserts up to 5 multiplies. 5356 countPopulation(Val) + Log2_32(Val) < 7) { 5357 // We use the simple binary decomposition method to generate the multiply 5358 // sequence. There are more optimal ways to do this (for example, 5359 // powi(x,15) generates one more multiply than it should), but this has 5360 // the benefit of being both really simple and much better than a libcall. 5361 SDValue Res; // Logically starts equal to 1.0 5362 SDValue CurSquare = LHS; 5363 // TODO: Intrinsics should have fast-math-flags that propagate to these 5364 // nodes. 5365 while (Val) { 5366 if (Val & 1) { 5367 if (Res.getNode()) 5368 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5369 else 5370 Res = CurSquare; // 1.0*CurSquare. 5371 } 5372 5373 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5374 CurSquare, CurSquare); 5375 Val >>= 1; 5376 } 5377 5378 // If the original was negative, invert the result, producing 1/(x*x*x). 5379 if (RHSC->getSExtValue() < 0) 5380 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5381 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5382 return Res; 5383 } 5384 } 5385 5386 // Otherwise, expand to a libcall. 5387 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5388 } 5389 5390 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5391 SDValue LHS, SDValue RHS, SDValue Scale, 5392 SelectionDAG &DAG, const TargetLowering &TLI) { 5393 EVT VT = LHS.getValueType(); 5394 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5395 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5396 LLVMContext &Ctx = *DAG.getContext(); 5397 5398 // If the type is legal but the operation isn't, this node might survive all 5399 // the way to operation legalization. If we end up there and we do not have 5400 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5401 // node. 5402 5403 // Coax the legalizer into expanding the node during type legalization instead 5404 // by bumping the size by one bit. This will force it to Promote, enabling the 5405 // early expansion and avoiding the need to expand later. 5406 5407 // We don't have to do this if Scale is 0; that can always be expanded, unless 5408 // it's a saturating signed operation. Those can experience true integer 5409 // division overflow, a case which we must avoid. 5410 5411 // FIXME: We wouldn't have to do this (or any of the early 5412 // expansion/promotion) if it was possible to expand a libcall of an 5413 // illegal type during operation legalization. But it's not, so things 5414 // get a bit hacky. 5415 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5416 if ((ScaleInt > 0 || (Saturating && Signed)) && 5417 (TLI.isTypeLegal(VT) || 5418 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5419 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5420 Opcode, VT, ScaleInt); 5421 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5422 EVT PromVT; 5423 if (VT.isScalarInteger()) 5424 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5425 else if (VT.isVector()) { 5426 PromVT = VT.getVectorElementType(); 5427 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5428 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5429 } else 5430 llvm_unreachable("Wrong VT for DIVFIX?"); 5431 if (Signed) { 5432 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5433 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5434 } else { 5435 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5436 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5437 } 5438 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5439 // For saturating operations, we need to shift up the LHS to get the 5440 // proper saturation width, and then shift down again afterwards. 5441 if (Saturating) 5442 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5443 DAG.getConstant(1, DL, ShiftTy)); 5444 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5445 if (Saturating) 5446 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5447 DAG.getConstant(1, DL, ShiftTy)); 5448 return DAG.getZExtOrTrunc(Res, DL, VT); 5449 } 5450 } 5451 5452 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5453 } 5454 5455 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5456 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5457 static void 5458 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5459 const SDValue &N) { 5460 switch (N.getOpcode()) { 5461 case ISD::CopyFromReg: { 5462 SDValue Op = N.getOperand(1); 5463 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5464 Op.getValueType().getSizeInBits()); 5465 return; 5466 } 5467 case ISD::BITCAST: 5468 case ISD::AssertZext: 5469 case ISD::AssertSext: 5470 case ISD::TRUNCATE: 5471 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5472 return; 5473 case ISD::BUILD_PAIR: 5474 case ISD::BUILD_VECTOR: 5475 case ISD::CONCAT_VECTORS: 5476 for (SDValue Op : N->op_values()) 5477 getUnderlyingArgRegs(Regs, Op); 5478 return; 5479 default: 5480 return; 5481 } 5482 } 5483 5484 /// If the DbgValueInst is a dbg_value of a function argument, create the 5485 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5486 /// instruction selection, they will be inserted to the entry BB. 5487 /// We don't currently support this for variadic dbg_values, as they shouldn't 5488 /// appear for function arguments or in the prologue. 5489 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5490 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5491 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5492 const Argument *Arg = dyn_cast<Argument>(V); 5493 if (!Arg) 5494 return false; 5495 5496 if (!IsDbgDeclare) { 5497 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5498 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5499 // the entry block. 5500 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5501 if (!IsInEntryBlock) 5502 return false; 5503 5504 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5505 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5506 // variable that also is a param. 5507 // 5508 // Although, if we are at the top of the entry block already, we can still 5509 // emit using ArgDbgValue. This might catch some situations when the 5510 // dbg.value refers to an argument that isn't used in the entry block, so 5511 // any CopyToReg node would be optimized out and the only way to express 5512 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5513 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5514 // we should only emit as ArgDbgValue if the Variable is an argument to the 5515 // current function, and the dbg.value intrinsic is found in the entry 5516 // block. 5517 bool VariableIsFunctionInputArg = Variable->isParameter() && 5518 !DL->getInlinedAt(); 5519 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5520 if (!IsInPrologue && !VariableIsFunctionInputArg) 5521 return false; 5522 5523 // Here we assume that a function argument on IR level only can be used to 5524 // describe one input parameter on source level. If we for example have 5525 // source code like this 5526 // 5527 // struct A { long x, y; }; 5528 // void foo(struct A a, long b) { 5529 // ... 5530 // b = a.x; 5531 // ... 5532 // } 5533 // 5534 // and IR like this 5535 // 5536 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5537 // entry: 5538 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5539 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5540 // call void @llvm.dbg.value(metadata i32 %b, "b", 5541 // ... 5542 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5543 // ... 5544 // 5545 // then the last dbg.value is describing a parameter "b" using a value that 5546 // is an argument. But since we already has used %a1 to describe a parameter 5547 // we should not handle that last dbg.value here (that would result in an 5548 // incorrect hoisting of the DBG_VALUE to the function entry). 5549 // Notice that we allow one dbg.value per IR level argument, to accommodate 5550 // for the situation with fragments above. 5551 if (VariableIsFunctionInputArg) { 5552 unsigned ArgNo = Arg->getArgNo(); 5553 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5554 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5555 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5556 return false; 5557 FuncInfo.DescribedArgs.set(ArgNo); 5558 } 5559 } 5560 5561 MachineFunction &MF = DAG.getMachineFunction(); 5562 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5563 5564 bool IsIndirect = false; 5565 Optional<MachineOperand> Op; 5566 // Some arguments' frame index is recorded during argument lowering. 5567 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5568 if (FI != std::numeric_limits<int>::max()) 5569 Op = MachineOperand::CreateFI(FI); 5570 5571 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5572 if (!Op && N.getNode()) { 5573 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5574 Register Reg; 5575 if (ArgRegsAndSizes.size() == 1) 5576 Reg = ArgRegsAndSizes.front().first; 5577 5578 if (Reg && Reg.isVirtual()) { 5579 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5580 Register PR = RegInfo.getLiveInPhysReg(Reg); 5581 if (PR) 5582 Reg = PR; 5583 } 5584 if (Reg) { 5585 Op = MachineOperand::CreateReg(Reg, false); 5586 IsIndirect = IsDbgDeclare; 5587 } 5588 } 5589 5590 if (!Op && N.getNode()) { 5591 // Check if frame index is available. 5592 SDValue LCandidate = peekThroughBitcasts(N); 5593 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5594 if (FrameIndexSDNode *FINode = 5595 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5596 Op = MachineOperand::CreateFI(FINode->getIndex()); 5597 } 5598 5599 if (!Op) { 5600 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5601 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5602 SplitRegs) { 5603 unsigned Offset = 0; 5604 for (auto RegAndSize : SplitRegs) { 5605 // If the expression is already a fragment, the current register 5606 // offset+size might extend beyond the fragment. In this case, only 5607 // the register bits that are inside the fragment are relevant. 5608 int RegFragmentSizeInBits = RegAndSize.second; 5609 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5610 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5611 // The register is entirely outside the expression fragment, 5612 // so is irrelevant for debug info. 5613 if (Offset >= ExprFragmentSizeInBits) 5614 break; 5615 // The register is partially outside the expression fragment, only 5616 // the low bits within the fragment are relevant for debug info. 5617 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5618 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5619 } 5620 } 5621 5622 auto FragmentExpr = DIExpression::createFragmentExpression( 5623 Expr, Offset, RegFragmentSizeInBits); 5624 Offset += RegAndSize.second; 5625 // If a valid fragment expression cannot be created, the variable's 5626 // correct value cannot be determined and so it is set as Undef. 5627 if (!FragmentExpr) { 5628 SDDbgValue *SDV = DAG.getConstantDbgValue( 5629 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5630 DAG.AddDbgValue(SDV, false); 5631 continue; 5632 } 5633 FuncInfo.ArgDbgValues.push_back( 5634 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5635 RegAndSize.first, Variable, *FragmentExpr)); 5636 } 5637 }; 5638 5639 // Check if ValueMap has reg number. 5640 DenseMap<const Value *, Register>::const_iterator 5641 VMI = FuncInfo.ValueMap.find(V); 5642 if (VMI != FuncInfo.ValueMap.end()) { 5643 const auto &TLI = DAG.getTargetLoweringInfo(); 5644 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5645 V->getType(), None); 5646 if (RFV.occupiesMultipleRegs()) { 5647 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5648 return true; 5649 } 5650 5651 Op = MachineOperand::CreateReg(VMI->second, false); 5652 IsIndirect = IsDbgDeclare; 5653 } else if (ArgRegsAndSizes.size() > 1) { 5654 // This was split due to the calling convention, and no virtual register 5655 // mapping exists for the value. 5656 splitMultiRegDbgValue(ArgRegsAndSizes); 5657 return true; 5658 } 5659 } 5660 5661 if (!Op) 5662 return false; 5663 5664 assert(Variable->isValidLocationForIntrinsic(DL) && 5665 "Expected inlined-at fields to agree"); 5666 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5667 FuncInfo.ArgDbgValues.push_back( 5668 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5669 *Op, Variable, Expr)); 5670 5671 return true; 5672 } 5673 5674 /// Return the appropriate SDDbgValue based on N. 5675 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5676 DILocalVariable *Variable, 5677 DIExpression *Expr, 5678 const DebugLoc &dl, 5679 unsigned DbgSDNodeOrder) { 5680 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5681 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5682 // stack slot locations. 5683 // 5684 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5685 // debug values here after optimization: 5686 // 5687 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5688 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5689 // 5690 // Both describe the direct values of their associated variables. 5691 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5692 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5693 } 5694 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5695 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5696 } 5697 5698 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5699 switch (Intrinsic) { 5700 case Intrinsic::smul_fix: 5701 return ISD::SMULFIX; 5702 case Intrinsic::umul_fix: 5703 return ISD::UMULFIX; 5704 case Intrinsic::smul_fix_sat: 5705 return ISD::SMULFIXSAT; 5706 case Intrinsic::umul_fix_sat: 5707 return ISD::UMULFIXSAT; 5708 case Intrinsic::sdiv_fix: 5709 return ISD::SDIVFIX; 5710 case Intrinsic::udiv_fix: 5711 return ISD::UDIVFIX; 5712 case Intrinsic::sdiv_fix_sat: 5713 return ISD::SDIVFIXSAT; 5714 case Intrinsic::udiv_fix_sat: 5715 return ISD::UDIVFIXSAT; 5716 default: 5717 llvm_unreachable("Unhandled fixed point intrinsic"); 5718 } 5719 } 5720 5721 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5722 const char *FunctionName) { 5723 assert(FunctionName && "FunctionName must not be nullptr"); 5724 SDValue Callee = DAG.getExternalSymbol( 5725 FunctionName, 5726 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5727 LowerCallTo(I, Callee, I.isTailCall()); 5728 } 5729 5730 /// Given a @llvm.call.preallocated.setup, return the corresponding 5731 /// preallocated call. 5732 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5733 assert(cast<CallBase>(PreallocatedSetup) 5734 ->getCalledFunction() 5735 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5736 "expected call_preallocated_setup Value"); 5737 for (auto *U : PreallocatedSetup->users()) { 5738 auto *UseCall = cast<CallBase>(U); 5739 const Function *Fn = UseCall->getCalledFunction(); 5740 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5741 return UseCall; 5742 } 5743 } 5744 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5745 } 5746 5747 /// Lower the call to the specified intrinsic function. 5748 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5749 unsigned Intrinsic) { 5750 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5751 SDLoc sdl = getCurSDLoc(); 5752 DebugLoc dl = getCurDebugLoc(); 5753 SDValue Res; 5754 5755 SDNodeFlags Flags; 5756 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5757 Flags.copyFMF(*FPOp); 5758 5759 switch (Intrinsic) { 5760 default: 5761 // By default, turn this into a target intrinsic node. 5762 visitTargetIntrinsic(I, Intrinsic); 5763 return; 5764 case Intrinsic::vscale: { 5765 match(&I, m_VScale(DAG.getDataLayout())); 5766 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5767 setValue(&I, 5768 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5769 return; 5770 } 5771 case Intrinsic::vastart: visitVAStart(I); return; 5772 case Intrinsic::vaend: visitVAEnd(I); return; 5773 case Intrinsic::vacopy: visitVACopy(I); return; 5774 case Intrinsic::returnaddress: 5775 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5776 TLI.getPointerTy(DAG.getDataLayout()), 5777 getValue(I.getArgOperand(0)))); 5778 return; 5779 case Intrinsic::addressofreturnaddress: 5780 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5781 TLI.getPointerTy(DAG.getDataLayout()))); 5782 return; 5783 case Intrinsic::sponentry: 5784 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5785 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5786 return; 5787 case Intrinsic::frameaddress: 5788 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5789 TLI.getFrameIndexTy(DAG.getDataLayout()), 5790 getValue(I.getArgOperand(0)))); 5791 return; 5792 case Intrinsic::read_volatile_register: 5793 case Intrinsic::read_register: { 5794 Value *Reg = I.getArgOperand(0); 5795 SDValue Chain = getRoot(); 5796 SDValue RegName = 5797 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5798 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5799 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5800 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5801 setValue(&I, Res); 5802 DAG.setRoot(Res.getValue(1)); 5803 return; 5804 } 5805 case Intrinsic::write_register: { 5806 Value *Reg = I.getArgOperand(0); 5807 Value *RegValue = I.getArgOperand(1); 5808 SDValue Chain = getRoot(); 5809 SDValue RegName = 5810 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5811 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5812 RegName, getValue(RegValue))); 5813 return; 5814 } 5815 case Intrinsic::memcpy: { 5816 const auto &MCI = cast<MemCpyInst>(I); 5817 SDValue Op1 = getValue(I.getArgOperand(0)); 5818 SDValue Op2 = getValue(I.getArgOperand(1)); 5819 SDValue Op3 = getValue(I.getArgOperand(2)); 5820 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5821 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5822 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5823 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5824 bool isVol = MCI.isVolatile(); 5825 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5826 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5827 // node. 5828 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5829 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5830 /* AlwaysInline */ false, isTC, 5831 MachinePointerInfo(I.getArgOperand(0)), 5832 MachinePointerInfo(I.getArgOperand(1))); 5833 updateDAGForMaybeTailCall(MC); 5834 return; 5835 } 5836 case Intrinsic::memcpy_inline: { 5837 const auto &MCI = cast<MemCpyInlineInst>(I); 5838 SDValue Dst = getValue(I.getArgOperand(0)); 5839 SDValue Src = getValue(I.getArgOperand(1)); 5840 SDValue Size = getValue(I.getArgOperand(2)); 5841 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5842 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5843 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5844 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5845 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5846 bool isVol = MCI.isVolatile(); 5847 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5848 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5849 // node. 5850 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5851 /* AlwaysInline */ true, isTC, 5852 MachinePointerInfo(I.getArgOperand(0)), 5853 MachinePointerInfo(I.getArgOperand(1))); 5854 updateDAGForMaybeTailCall(MC); 5855 return; 5856 } 5857 case Intrinsic::memset: { 5858 const auto &MSI = cast<MemSetInst>(I); 5859 SDValue Op1 = getValue(I.getArgOperand(0)); 5860 SDValue Op2 = getValue(I.getArgOperand(1)); 5861 SDValue Op3 = getValue(I.getArgOperand(2)); 5862 // @llvm.memset defines 0 and 1 to both mean no alignment. 5863 Align Alignment = MSI.getDestAlign().valueOrOne(); 5864 bool isVol = MSI.isVolatile(); 5865 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5866 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5867 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5868 MachinePointerInfo(I.getArgOperand(0))); 5869 updateDAGForMaybeTailCall(MS); 5870 return; 5871 } 5872 case Intrinsic::memmove: { 5873 const auto &MMI = cast<MemMoveInst>(I); 5874 SDValue Op1 = getValue(I.getArgOperand(0)); 5875 SDValue Op2 = getValue(I.getArgOperand(1)); 5876 SDValue Op3 = getValue(I.getArgOperand(2)); 5877 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5878 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5879 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5880 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5881 bool isVol = MMI.isVolatile(); 5882 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5883 // FIXME: Support passing different dest/src alignments to the memmove DAG 5884 // node. 5885 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5886 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5887 isTC, MachinePointerInfo(I.getArgOperand(0)), 5888 MachinePointerInfo(I.getArgOperand(1))); 5889 updateDAGForMaybeTailCall(MM); 5890 return; 5891 } 5892 case Intrinsic::memcpy_element_unordered_atomic: { 5893 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5894 SDValue Dst = getValue(MI.getRawDest()); 5895 SDValue Src = getValue(MI.getRawSource()); 5896 SDValue Length = getValue(MI.getLength()); 5897 5898 unsigned DstAlign = MI.getDestAlignment(); 5899 unsigned SrcAlign = MI.getSourceAlignment(); 5900 Type *LengthTy = MI.getLength()->getType(); 5901 unsigned ElemSz = MI.getElementSizeInBytes(); 5902 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5903 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5904 SrcAlign, Length, LengthTy, ElemSz, isTC, 5905 MachinePointerInfo(MI.getRawDest()), 5906 MachinePointerInfo(MI.getRawSource())); 5907 updateDAGForMaybeTailCall(MC); 5908 return; 5909 } 5910 case Intrinsic::memmove_element_unordered_atomic: { 5911 auto &MI = cast<AtomicMemMoveInst>(I); 5912 SDValue Dst = getValue(MI.getRawDest()); 5913 SDValue Src = getValue(MI.getRawSource()); 5914 SDValue Length = getValue(MI.getLength()); 5915 5916 unsigned DstAlign = MI.getDestAlignment(); 5917 unsigned SrcAlign = MI.getSourceAlignment(); 5918 Type *LengthTy = MI.getLength()->getType(); 5919 unsigned ElemSz = MI.getElementSizeInBytes(); 5920 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5921 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5922 SrcAlign, Length, LengthTy, ElemSz, isTC, 5923 MachinePointerInfo(MI.getRawDest()), 5924 MachinePointerInfo(MI.getRawSource())); 5925 updateDAGForMaybeTailCall(MC); 5926 return; 5927 } 5928 case Intrinsic::memset_element_unordered_atomic: { 5929 auto &MI = cast<AtomicMemSetInst>(I); 5930 SDValue Dst = getValue(MI.getRawDest()); 5931 SDValue Val = getValue(MI.getValue()); 5932 SDValue Length = getValue(MI.getLength()); 5933 5934 unsigned DstAlign = MI.getDestAlignment(); 5935 Type *LengthTy = MI.getLength()->getType(); 5936 unsigned ElemSz = MI.getElementSizeInBytes(); 5937 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5938 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5939 LengthTy, ElemSz, isTC, 5940 MachinePointerInfo(MI.getRawDest())); 5941 updateDAGForMaybeTailCall(MC); 5942 return; 5943 } 5944 case Intrinsic::call_preallocated_setup: { 5945 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5946 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5947 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5948 getRoot(), SrcValue); 5949 setValue(&I, Res); 5950 DAG.setRoot(Res); 5951 return; 5952 } 5953 case Intrinsic::call_preallocated_arg: { 5954 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5955 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5956 SDValue Ops[3]; 5957 Ops[0] = getRoot(); 5958 Ops[1] = SrcValue; 5959 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5960 MVT::i32); // arg index 5961 SDValue Res = DAG.getNode( 5962 ISD::PREALLOCATED_ARG, sdl, 5963 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5964 setValue(&I, Res); 5965 DAG.setRoot(Res.getValue(1)); 5966 return; 5967 } 5968 case Intrinsic::dbg_addr: 5969 case Intrinsic::dbg_declare: { 5970 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 5971 // they are non-variadic. 5972 const auto &DI = cast<DbgVariableIntrinsic>(I); 5973 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 5974 DILocalVariable *Variable = DI.getVariable(); 5975 DIExpression *Expression = DI.getExpression(); 5976 dropDanglingDebugInfo(Variable, Expression); 5977 assert(Variable && "Missing variable"); 5978 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5979 << "\n"); 5980 // Check if address has undef value. 5981 const Value *Address = DI.getVariableLocationOp(0); 5982 if (!Address || isa<UndefValue>(Address) || 5983 (Address->use_empty() && !isa<Argument>(Address))) { 5984 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5985 << " (bad/undef/unused-arg address)\n"); 5986 return; 5987 } 5988 5989 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5990 5991 // Check if this variable can be described by a frame index, typically 5992 // either as a static alloca or a byval parameter. 5993 int FI = std::numeric_limits<int>::max(); 5994 if (const auto *AI = 5995 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5996 if (AI->isStaticAlloca()) { 5997 auto I = FuncInfo.StaticAllocaMap.find(AI); 5998 if (I != FuncInfo.StaticAllocaMap.end()) 5999 FI = I->second; 6000 } 6001 } else if (const auto *Arg = dyn_cast<Argument>( 6002 Address->stripInBoundsConstantOffsets())) { 6003 FI = FuncInfo.getArgumentFrameIndex(Arg); 6004 } 6005 6006 // llvm.dbg.addr is control dependent and always generates indirect 6007 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6008 // the MachineFunction variable table. 6009 if (FI != std::numeric_limits<int>::max()) { 6010 if (Intrinsic == Intrinsic::dbg_addr) { 6011 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6012 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6013 dl, SDNodeOrder); 6014 DAG.AddDbgValue(SDV, isParameter); 6015 } else { 6016 LLVM_DEBUG(dbgs() << "Skipping " << DI 6017 << " (variable info stashed in MF side table)\n"); 6018 } 6019 return; 6020 } 6021 6022 SDValue &N = NodeMap[Address]; 6023 if (!N.getNode() && isa<Argument>(Address)) 6024 // Check unused arguments map. 6025 N = UnusedArgNodeMap[Address]; 6026 SDDbgValue *SDV; 6027 if (N.getNode()) { 6028 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6029 Address = BCI->getOperand(0); 6030 // Parameters are handled specially. 6031 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6032 if (isParameter && FINode) { 6033 // Byval parameter. We have a frame index at this point. 6034 SDV = 6035 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6036 /*IsIndirect*/ true, dl, SDNodeOrder); 6037 } else if (isa<Argument>(Address)) { 6038 // Address is an argument, so try to emit its dbg value using 6039 // virtual register info from the FuncInfo.ValueMap. 6040 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6041 return; 6042 } else { 6043 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6044 true, dl, SDNodeOrder); 6045 } 6046 DAG.AddDbgValue(SDV, isParameter); 6047 } else { 6048 // If Address is an argument then try to emit its dbg value using 6049 // virtual register info from the FuncInfo.ValueMap. 6050 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6051 N)) { 6052 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6053 << " (could not emit func-arg dbg_value)\n"); 6054 } 6055 } 6056 return; 6057 } 6058 case Intrinsic::dbg_label: { 6059 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6060 DILabel *Label = DI.getLabel(); 6061 assert(Label && "Missing label"); 6062 6063 SDDbgLabel *SDV; 6064 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6065 DAG.AddDbgLabel(SDV); 6066 return; 6067 } 6068 case Intrinsic::dbg_value: { 6069 const DbgValueInst &DI = cast<DbgValueInst>(I); 6070 assert(DI.getVariable() && "Missing variable"); 6071 6072 DILocalVariable *Variable = DI.getVariable(); 6073 DIExpression *Expression = DI.getExpression(); 6074 dropDanglingDebugInfo(Variable, Expression); 6075 SmallVector<Value *, 4> Values(DI.getValues()); 6076 if (Values.empty()) 6077 return; 6078 6079 if (std::count(Values.begin(), Values.end(), nullptr)) 6080 return; 6081 6082 bool IsVariadic = DI.hasArgList(); 6083 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6084 SDNodeOrder, IsVariadic)) 6085 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6086 return; 6087 } 6088 6089 case Intrinsic::eh_typeid_for: { 6090 // Find the type id for the given typeinfo. 6091 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6092 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6093 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6094 setValue(&I, Res); 6095 return; 6096 } 6097 6098 case Intrinsic::eh_return_i32: 6099 case Intrinsic::eh_return_i64: 6100 DAG.getMachineFunction().setCallsEHReturn(true); 6101 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6102 MVT::Other, 6103 getControlRoot(), 6104 getValue(I.getArgOperand(0)), 6105 getValue(I.getArgOperand(1)))); 6106 return; 6107 case Intrinsic::eh_unwind_init: 6108 DAG.getMachineFunction().setCallsUnwindInit(true); 6109 return; 6110 case Intrinsic::eh_dwarf_cfa: 6111 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6112 TLI.getPointerTy(DAG.getDataLayout()), 6113 getValue(I.getArgOperand(0)))); 6114 return; 6115 case Intrinsic::eh_sjlj_callsite: { 6116 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6117 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6118 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6119 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6120 6121 MMI.setCurrentCallSite(CI->getZExtValue()); 6122 return; 6123 } 6124 case Intrinsic::eh_sjlj_functioncontext: { 6125 // Get and store the index of the function context. 6126 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6127 AllocaInst *FnCtx = 6128 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6129 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6130 MFI.setFunctionContextIndex(FI); 6131 return; 6132 } 6133 case Intrinsic::eh_sjlj_setjmp: { 6134 SDValue Ops[2]; 6135 Ops[0] = getRoot(); 6136 Ops[1] = getValue(I.getArgOperand(0)); 6137 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6138 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6139 setValue(&I, Op.getValue(0)); 6140 DAG.setRoot(Op.getValue(1)); 6141 return; 6142 } 6143 case Intrinsic::eh_sjlj_longjmp: 6144 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6145 getRoot(), getValue(I.getArgOperand(0)))); 6146 return; 6147 case Intrinsic::eh_sjlj_setup_dispatch: 6148 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6149 getRoot())); 6150 return; 6151 case Intrinsic::masked_gather: 6152 visitMaskedGather(I); 6153 return; 6154 case Intrinsic::masked_load: 6155 visitMaskedLoad(I); 6156 return; 6157 case Intrinsic::masked_scatter: 6158 visitMaskedScatter(I); 6159 return; 6160 case Intrinsic::masked_store: 6161 visitMaskedStore(I); 6162 return; 6163 case Intrinsic::masked_expandload: 6164 visitMaskedLoad(I, true /* IsExpanding */); 6165 return; 6166 case Intrinsic::masked_compressstore: 6167 visitMaskedStore(I, true /* IsCompressing */); 6168 return; 6169 case Intrinsic::powi: 6170 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6171 getValue(I.getArgOperand(1)), DAG)); 6172 return; 6173 case Intrinsic::log: 6174 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6175 return; 6176 case Intrinsic::log2: 6177 setValue(&I, 6178 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6179 return; 6180 case Intrinsic::log10: 6181 setValue(&I, 6182 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6183 return; 6184 case Intrinsic::exp: 6185 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6186 return; 6187 case Intrinsic::exp2: 6188 setValue(&I, 6189 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6190 return; 6191 case Intrinsic::pow: 6192 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6193 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6194 return; 6195 case Intrinsic::sqrt: 6196 case Intrinsic::fabs: 6197 case Intrinsic::sin: 6198 case Intrinsic::cos: 6199 case Intrinsic::floor: 6200 case Intrinsic::ceil: 6201 case Intrinsic::trunc: 6202 case Intrinsic::rint: 6203 case Intrinsic::nearbyint: 6204 case Intrinsic::round: 6205 case Intrinsic::roundeven: 6206 case Intrinsic::canonicalize: { 6207 unsigned Opcode; 6208 switch (Intrinsic) { 6209 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6210 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6211 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6212 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6213 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6214 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6215 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6216 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6217 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6218 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6219 case Intrinsic::round: Opcode = ISD::FROUND; break; 6220 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6221 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6222 } 6223 6224 setValue(&I, DAG.getNode(Opcode, sdl, 6225 getValue(I.getArgOperand(0)).getValueType(), 6226 getValue(I.getArgOperand(0)), Flags)); 6227 return; 6228 } 6229 case Intrinsic::lround: 6230 case Intrinsic::llround: 6231 case Intrinsic::lrint: 6232 case Intrinsic::llrint: { 6233 unsigned Opcode; 6234 switch (Intrinsic) { 6235 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6236 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6237 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6238 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6239 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6240 } 6241 6242 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6243 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6244 getValue(I.getArgOperand(0)))); 6245 return; 6246 } 6247 case Intrinsic::minnum: 6248 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6249 getValue(I.getArgOperand(0)).getValueType(), 6250 getValue(I.getArgOperand(0)), 6251 getValue(I.getArgOperand(1)), Flags)); 6252 return; 6253 case Intrinsic::maxnum: 6254 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6255 getValue(I.getArgOperand(0)).getValueType(), 6256 getValue(I.getArgOperand(0)), 6257 getValue(I.getArgOperand(1)), Flags)); 6258 return; 6259 case Intrinsic::minimum: 6260 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6261 getValue(I.getArgOperand(0)).getValueType(), 6262 getValue(I.getArgOperand(0)), 6263 getValue(I.getArgOperand(1)), Flags)); 6264 return; 6265 case Intrinsic::maximum: 6266 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6267 getValue(I.getArgOperand(0)).getValueType(), 6268 getValue(I.getArgOperand(0)), 6269 getValue(I.getArgOperand(1)), Flags)); 6270 return; 6271 case Intrinsic::copysign: 6272 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6273 getValue(I.getArgOperand(0)).getValueType(), 6274 getValue(I.getArgOperand(0)), 6275 getValue(I.getArgOperand(1)), Flags)); 6276 return; 6277 case Intrinsic::fma: 6278 setValue(&I, DAG.getNode( 6279 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6280 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6281 getValue(I.getArgOperand(2)), Flags)); 6282 return; 6283 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6284 case Intrinsic::INTRINSIC: 6285 #include "llvm/IR/ConstrainedOps.def" 6286 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6287 return; 6288 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6289 #include "llvm/IR/VPIntrinsics.def" 6290 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6291 return; 6292 case Intrinsic::fmuladd: { 6293 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6294 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6295 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6296 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6297 getValue(I.getArgOperand(0)).getValueType(), 6298 getValue(I.getArgOperand(0)), 6299 getValue(I.getArgOperand(1)), 6300 getValue(I.getArgOperand(2)), Flags)); 6301 } else { 6302 // TODO: Intrinsic calls should have fast-math-flags. 6303 SDValue Mul = DAG.getNode( 6304 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6305 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6306 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6307 getValue(I.getArgOperand(0)).getValueType(), 6308 Mul, getValue(I.getArgOperand(2)), Flags); 6309 setValue(&I, Add); 6310 } 6311 return; 6312 } 6313 case Intrinsic::convert_to_fp16: 6314 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6315 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6316 getValue(I.getArgOperand(0)), 6317 DAG.getTargetConstant(0, sdl, 6318 MVT::i32)))); 6319 return; 6320 case Intrinsic::convert_from_fp16: 6321 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6322 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6323 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6324 getValue(I.getArgOperand(0))))); 6325 return; 6326 case Intrinsic::fptosi_sat: { 6327 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6328 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6329 getValue(I.getArgOperand(0)), 6330 DAG.getValueType(VT.getScalarType()))); 6331 return; 6332 } 6333 case Intrinsic::fptoui_sat: { 6334 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6335 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6336 getValue(I.getArgOperand(0)), 6337 DAG.getValueType(VT.getScalarType()))); 6338 return; 6339 } 6340 case Intrinsic::set_rounding: 6341 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6342 {getRoot(), getValue(I.getArgOperand(0))}); 6343 setValue(&I, Res); 6344 DAG.setRoot(Res.getValue(0)); 6345 return; 6346 case Intrinsic::pcmarker: { 6347 SDValue Tmp = getValue(I.getArgOperand(0)); 6348 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6349 return; 6350 } 6351 case Intrinsic::readcyclecounter: { 6352 SDValue Op = getRoot(); 6353 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6354 DAG.getVTList(MVT::i64, MVT::Other), Op); 6355 setValue(&I, Res); 6356 DAG.setRoot(Res.getValue(1)); 6357 return; 6358 } 6359 case Intrinsic::bitreverse: 6360 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6361 getValue(I.getArgOperand(0)).getValueType(), 6362 getValue(I.getArgOperand(0)))); 6363 return; 6364 case Intrinsic::bswap: 6365 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6366 getValue(I.getArgOperand(0)).getValueType(), 6367 getValue(I.getArgOperand(0)))); 6368 return; 6369 case Intrinsic::cttz: { 6370 SDValue Arg = getValue(I.getArgOperand(0)); 6371 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6372 EVT Ty = Arg.getValueType(); 6373 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6374 sdl, Ty, Arg)); 6375 return; 6376 } 6377 case Intrinsic::ctlz: { 6378 SDValue Arg = getValue(I.getArgOperand(0)); 6379 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6380 EVT Ty = Arg.getValueType(); 6381 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6382 sdl, Ty, Arg)); 6383 return; 6384 } 6385 case Intrinsic::ctpop: { 6386 SDValue Arg = getValue(I.getArgOperand(0)); 6387 EVT Ty = Arg.getValueType(); 6388 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6389 return; 6390 } 6391 case Intrinsic::fshl: 6392 case Intrinsic::fshr: { 6393 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6394 SDValue X = getValue(I.getArgOperand(0)); 6395 SDValue Y = getValue(I.getArgOperand(1)); 6396 SDValue Z = getValue(I.getArgOperand(2)); 6397 EVT VT = X.getValueType(); 6398 6399 if (X == Y) { 6400 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6401 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6402 } else { 6403 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6404 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6405 } 6406 return; 6407 } 6408 case Intrinsic::sadd_sat: { 6409 SDValue Op1 = getValue(I.getArgOperand(0)); 6410 SDValue Op2 = getValue(I.getArgOperand(1)); 6411 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6412 return; 6413 } 6414 case Intrinsic::uadd_sat: { 6415 SDValue Op1 = getValue(I.getArgOperand(0)); 6416 SDValue Op2 = getValue(I.getArgOperand(1)); 6417 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6418 return; 6419 } 6420 case Intrinsic::ssub_sat: { 6421 SDValue Op1 = getValue(I.getArgOperand(0)); 6422 SDValue Op2 = getValue(I.getArgOperand(1)); 6423 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6424 return; 6425 } 6426 case Intrinsic::usub_sat: { 6427 SDValue Op1 = getValue(I.getArgOperand(0)); 6428 SDValue Op2 = getValue(I.getArgOperand(1)); 6429 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6430 return; 6431 } 6432 case Intrinsic::sshl_sat: { 6433 SDValue Op1 = getValue(I.getArgOperand(0)); 6434 SDValue Op2 = getValue(I.getArgOperand(1)); 6435 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6436 return; 6437 } 6438 case Intrinsic::ushl_sat: { 6439 SDValue Op1 = getValue(I.getArgOperand(0)); 6440 SDValue Op2 = getValue(I.getArgOperand(1)); 6441 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6442 return; 6443 } 6444 case Intrinsic::smul_fix: 6445 case Intrinsic::umul_fix: 6446 case Intrinsic::smul_fix_sat: 6447 case Intrinsic::umul_fix_sat: { 6448 SDValue Op1 = getValue(I.getArgOperand(0)); 6449 SDValue Op2 = getValue(I.getArgOperand(1)); 6450 SDValue Op3 = getValue(I.getArgOperand(2)); 6451 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6452 Op1.getValueType(), Op1, Op2, Op3)); 6453 return; 6454 } 6455 case Intrinsic::sdiv_fix: 6456 case Intrinsic::udiv_fix: 6457 case Intrinsic::sdiv_fix_sat: 6458 case Intrinsic::udiv_fix_sat: { 6459 SDValue Op1 = getValue(I.getArgOperand(0)); 6460 SDValue Op2 = getValue(I.getArgOperand(1)); 6461 SDValue Op3 = getValue(I.getArgOperand(2)); 6462 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6463 Op1, Op2, Op3, DAG, TLI)); 6464 return; 6465 } 6466 case Intrinsic::smax: { 6467 SDValue Op1 = getValue(I.getArgOperand(0)); 6468 SDValue Op2 = getValue(I.getArgOperand(1)); 6469 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6470 return; 6471 } 6472 case Intrinsic::smin: { 6473 SDValue Op1 = getValue(I.getArgOperand(0)); 6474 SDValue Op2 = getValue(I.getArgOperand(1)); 6475 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6476 return; 6477 } 6478 case Intrinsic::umax: { 6479 SDValue Op1 = getValue(I.getArgOperand(0)); 6480 SDValue Op2 = getValue(I.getArgOperand(1)); 6481 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6482 return; 6483 } 6484 case Intrinsic::umin: { 6485 SDValue Op1 = getValue(I.getArgOperand(0)); 6486 SDValue Op2 = getValue(I.getArgOperand(1)); 6487 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6488 return; 6489 } 6490 case Intrinsic::abs: { 6491 // TODO: Preserve "int min is poison" arg in SDAG? 6492 SDValue Op1 = getValue(I.getArgOperand(0)); 6493 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6494 return; 6495 } 6496 case Intrinsic::stacksave: { 6497 SDValue Op = getRoot(); 6498 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6499 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6500 setValue(&I, Res); 6501 DAG.setRoot(Res.getValue(1)); 6502 return; 6503 } 6504 case Intrinsic::stackrestore: 6505 Res = getValue(I.getArgOperand(0)); 6506 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6507 return; 6508 case Intrinsic::get_dynamic_area_offset: { 6509 SDValue Op = getRoot(); 6510 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6511 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6512 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6513 // target. 6514 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6515 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6516 " intrinsic!"); 6517 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6518 Op); 6519 DAG.setRoot(Op); 6520 setValue(&I, Res); 6521 return; 6522 } 6523 case Intrinsic::stackguard: { 6524 MachineFunction &MF = DAG.getMachineFunction(); 6525 const Module &M = *MF.getFunction().getParent(); 6526 SDValue Chain = getRoot(); 6527 if (TLI.useLoadStackGuardNode()) { 6528 Res = getLoadStackGuard(DAG, sdl, Chain); 6529 } else { 6530 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6531 const Value *Global = TLI.getSDagStackGuard(M); 6532 Align Align = DL->getPrefTypeAlign(Global->getType()); 6533 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6534 MachinePointerInfo(Global, 0), Align, 6535 MachineMemOperand::MOVolatile); 6536 } 6537 if (TLI.useStackGuardXorFP()) 6538 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6539 DAG.setRoot(Chain); 6540 setValue(&I, Res); 6541 return; 6542 } 6543 case Intrinsic::stackprotector: { 6544 // Emit code into the DAG to store the stack guard onto the stack. 6545 MachineFunction &MF = DAG.getMachineFunction(); 6546 MachineFrameInfo &MFI = MF.getFrameInfo(); 6547 SDValue Src, Chain = getRoot(); 6548 6549 if (TLI.useLoadStackGuardNode()) 6550 Src = getLoadStackGuard(DAG, sdl, Chain); 6551 else 6552 Src = getValue(I.getArgOperand(0)); // The guard's value. 6553 6554 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6555 6556 int FI = FuncInfo.StaticAllocaMap[Slot]; 6557 MFI.setStackProtectorIndex(FI); 6558 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6559 6560 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6561 6562 // Store the stack protector onto the stack. 6563 Res = DAG.getStore( 6564 Chain, sdl, Src, FIN, 6565 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6566 MaybeAlign(), MachineMemOperand::MOVolatile); 6567 setValue(&I, Res); 6568 DAG.setRoot(Res); 6569 return; 6570 } 6571 case Intrinsic::objectsize: 6572 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6573 6574 case Intrinsic::is_constant: 6575 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6576 6577 case Intrinsic::annotation: 6578 case Intrinsic::ptr_annotation: 6579 case Intrinsic::launder_invariant_group: 6580 case Intrinsic::strip_invariant_group: 6581 // Drop the intrinsic, but forward the value 6582 setValue(&I, getValue(I.getOperand(0))); 6583 return; 6584 6585 case Intrinsic::assume: 6586 case Intrinsic::experimental_noalias_scope_decl: 6587 case Intrinsic::var_annotation: 6588 case Intrinsic::sideeffect: 6589 // Discard annotate attributes, noalias scope declarations, assumptions, and 6590 // artificial side-effects. 6591 return; 6592 6593 case Intrinsic::codeview_annotation: { 6594 // Emit a label associated with this metadata. 6595 MachineFunction &MF = DAG.getMachineFunction(); 6596 MCSymbol *Label = 6597 MF.getMMI().getContext().createTempSymbol("annotation", true); 6598 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6599 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6600 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6601 DAG.setRoot(Res); 6602 return; 6603 } 6604 6605 case Intrinsic::init_trampoline: { 6606 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6607 6608 SDValue Ops[6]; 6609 Ops[0] = getRoot(); 6610 Ops[1] = getValue(I.getArgOperand(0)); 6611 Ops[2] = getValue(I.getArgOperand(1)); 6612 Ops[3] = getValue(I.getArgOperand(2)); 6613 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6614 Ops[5] = DAG.getSrcValue(F); 6615 6616 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6617 6618 DAG.setRoot(Res); 6619 return; 6620 } 6621 case Intrinsic::adjust_trampoline: 6622 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6623 TLI.getPointerTy(DAG.getDataLayout()), 6624 getValue(I.getArgOperand(0)))); 6625 return; 6626 case Intrinsic::gcroot: { 6627 assert(DAG.getMachineFunction().getFunction().hasGC() && 6628 "only valid in functions with gc specified, enforced by Verifier"); 6629 assert(GFI && "implied by previous"); 6630 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6631 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6632 6633 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6634 GFI->addStackRoot(FI->getIndex(), TypeMap); 6635 return; 6636 } 6637 case Intrinsic::gcread: 6638 case Intrinsic::gcwrite: 6639 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6640 case Intrinsic::flt_rounds: 6641 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6642 setValue(&I, Res); 6643 DAG.setRoot(Res.getValue(1)); 6644 return; 6645 6646 case Intrinsic::expect: 6647 // Just replace __builtin_expect(exp, c) with EXP. 6648 setValue(&I, getValue(I.getArgOperand(0))); 6649 return; 6650 6651 case Intrinsic::ubsantrap: 6652 case Intrinsic::debugtrap: 6653 case Intrinsic::trap: { 6654 StringRef TrapFuncName = 6655 I.getAttributes() 6656 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6657 .getValueAsString(); 6658 if (TrapFuncName.empty()) { 6659 switch (Intrinsic) { 6660 case Intrinsic::trap: 6661 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6662 break; 6663 case Intrinsic::debugtrap: 6664 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6665 break; 6666 case Intrinsic::ubsantrap: 6667 DAG.setRoot(DAG.getNode( 6668 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6669 DAG.getTargetConstant( 6670 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6671 MVT::i32))); 6672 break; 6673 default: llvm_unreachable("unknown trap intrinsic"); 6674 } 6675 return; 6676 } 6677 TargetLowering::ArgListTy Args; 6678 if (Intrinsic == Intrinsic::ubsantrap) { 6679 Args.push_back(TargetLoweringBase::ArgListEntry()); 6680 Args[0].Val = I.getArgOperand(0); 6681 Args[0].Node = getValue(Args[0].Val); 6682 Args[0].Ty = Args[0].Val->getType(); 6683 } 6684 6685 TargetLowering::CallLoweringInfo CLI(DAG); 6686 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6687 CallingConv::C, I.getType(), 6688 DAG.getExternalSymbol(TrapFuncName.data(), 6689 TLI.getPointerTy(DAG.getDataLayout())), 6690 std::move(Args)); 6691 6692 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6693 DAG.setRoot(Result.second); 6694 return; 6695 } 6696 6697 case Intrinsic::uadd_with_overflow: 6698 case Intrinsic::sadd_with_overflow: 6699 case Intrinsic::usub_with_overflow: 6700 case Intrinsic::ssub_with_overflow: 6701 case Intrinsic::umul_with_overflow: 6702 case Intrinsic::smul_with_overflow: { 6703 ISD::NodeType Op; 6704 switch (Intrinsic) { 6705 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6706 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6707 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6708 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6709 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6710 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6711 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6712 } 6713 SDValue Op1 = getValue(I.getArgOperand(0)); 6714 SDValue Op2 = getValue(I.getArgOperand(1)); 6715 6716 EVT ResultVT = Op1.getValueType(); 6717 EVT OverflowVT = MVT::i1; 6718 if (ResultVT.isVector()) 6719 OverflowVT = EVT::getVectorVT( 6720 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6721 6722 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6723 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6724 return; 6725 } 6726 case Intrinsic::prefetch: { 6727 SDValue Ops[5]; 6728 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6729 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6730 Ops[0] = DAG.getRoot(); 6731 Ops[1] = getValue(I.getArgOperand(0)); 6732 Ops[2] = getValue(I.getArgOperand(1)); 6733 Ops[3] = getValue(I.getArgOperand(2)); 6734 Ops[4] = getValue(I.getArgOperand(3)); 6735 SDValue Result = DAG.getMemIntrinsicNode( 6736 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6737 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6738 /* align */ None, Flags); 6739 6740 // Chain the prefetch in parallell with any pending loads, to stay out of 6741 // the way of later optimizations. 6742 PendingLoads.push_back(Result); 6743 Result = getRoot(); 6744 DAG.setRoot(Result); 6745 return; 6746 } 6747 case Intrinsic::lifetime_start: 6748 case Intrinsic::lifetime_end: { 6749 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6750 // Stack coloring is not enabled in O0, discard region information. 6751 if (TM.getOptLevel() == CodeGenOpt::None) 6752 return; 6753 6754 const int64_t ObjectSize = 6755 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6756 Value *const ObjectPtr = I.getArgOperand(1); 6757 SmallVector<const Value *, 4> Allocas; 6758 getUnderlyingObjects(ObjectPtr, Allocas); 6759 6760 for (const Value *Alloca : Allocas) { 6761 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6762 6763 // Could not find an Alloca. 6764 if (!LifetimeObject) 6765 continue; 6766 6767 // First check that the Alloca is static, otherwise it won't have a 6768 // valid frame index. 6769 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6770 if (SI == FuncInfo.StaticAllocaMap.end()) 6771 return; 6772 6773 const int FrameIndex = SI->second; 6774 int64_t Offset; 6775 if (GetPointerBaseWithConstantOffset( 6776 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6777 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6778 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6779 Offset); 6780 DAG.setRoot(Res); 6781 } 6782 return; 6783 } 6784 case Intrinsic::pseudoprobe: { 6785 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6786 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6787 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6788 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6789 DAG.setRoot(Res); 6790 return; 6791 } 6792 case Intrinsic::invariant_start: 6793 // Discard region information. 6794 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6795 return; 6796 case Intrinsic::invariant_end: 6797 // Discard region information. 6798 return; 6799 case Intrinsic::clear_cache: 6800 /// FunctionName may be null. 6801 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6802 lowerCallToExternalSymbol(I, FunctionName); 6803 return; 6804 case Intrinsic::donothing: 6805 case Intrinsic::seh_try_begin: 6806 case Intrinsic::seh_scope_begin: 6807 case Intrinsic::seh_try_end: 6808 case Intrinsic::seh_scope_end: 6809 // ignore 6810 return; 6811 case Intrinsic::experimental_stackmap: 6812 visitStackmap(I); 6813 return; 6814 case Intrinsic::experimental_patchpoint_void: 6815 case Intrinsic::experimental_patchpoint_i64: 6816 visitPatchpoint(I); 6817 return; 6818 case Intrinsic::experimental_gc_statepoint: 6819 LowerStatepoint(cast<GCStatepointInst>(I)); 6820 return; 6821 case Intrinsic::experimental_gc_result: 6822 visitGCResult(cast<GCResultInst>(I)); 6823 return; 6824 case Intrinsic::experimental_gc_relocate: 6825 visitGCRelocate(cast<GCRelocateInst>(I)); 6826 return; 6827 case Intrinsic::instrprof_increment: 6828 llvm_unreachable("instrprof failed to lower an increment"); 6829 case Intrinsic::instrprof_value_profile: 6830 llvm_unreachable("instrprof failed to lower a value profiling call"); 6831 case Intrinsic::localescape: { 6832 MachineFunction &MF = DAG.getMachineFunction(); 6833 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6834 6835 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6836 // is the same on all targets. 6837 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6838 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6839 if (isa<ConstantPointerNull>(Arg)) 6840 continue; // Skip null pointers. They represent a hole in index space. 6841 AllocaInst *Slot = cast<AllocaInst>(Arg); 6842 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6843 "can only escape static allocas"); 6844 int FI = FuncInfo.StaticAllocaMap[Slot]; 6845 MCSymbol *FrameAllocSym = 6846 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6847 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6848 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6849 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6850 .addSym(FrameAllocSym) 6851 .addFrameIndex(FI); 6852 } 6853 6854 return; 6855 } 6856 6857 case Intrinsic::localrecover: { 6858 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6859 MachineFunction &MF = DAG.getMachineFunction(); 6860 6861 // Get the symbol that defines the frame offset. 6862 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6863 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6864 unsigned IdxVal = 6865 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6866 MCSymbol *FrameAllocSym = 6867 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6868 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6869 6870 Value *FP = I.getArgOperand(1); 6871 SDValue FPVal = getValue(FP); 6872 EVT PtrVT = FPVal.getValueType(); 6873 6874 // Create a MCSymbol for the label to avoid any target lowering 6875 // that would make this PC relative. 6876 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6877 SDValue OffsetVal = 6878 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6879 6880 // Add the offset to the FP. 6881 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6882 setValue(&I, Add); 6883 6884 return; 6885 } 6886 6887 case Intrinsic::eh_exceptionpointer: 6888 case Intrinsic::eh_exceptioncode: { 6889 // Get the exception pointer vreg, copy from it, and resize it to fit. 6890 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6891 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6892 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6893 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6894 SDValue N = 6895 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6896 if (Intrinsic == Intrinsic::eh_exceptioncode) 6897 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6898 setValue(&I, N); 6899 return; 6900 } 6901 case Intrinsic::xray_customevent: { 6902 // Here we want to make sure that the intrinsic behaves as if it has a 6903 // specific calling convention, and only for x86_64. 6904 // FIXME: Support other platforms later. 6905 const auto &Triple = DAG.getTarget().getTargetTriple(); 6906 if (Triple.getArch() != Triple::x86_64) 6907 return; 6908 6909 SDLoc DL = getCurSDLoc(); 6910 SmallVector<SDValue, 8> Ops; 6911 6912 // We want to say that we always want the arguments in registers. 6913 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6914 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6915 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6916 SDValue Chain = getRoot(); 6917 Ops.push_back(LogEntryVal); 6918 Ops.push_back(StrSizeVal); 6919 Ops.push_back(Chain); 6920 6921 // We need to enforce the calling convention for the callsite, so that 6922 // argument ordering is enforced correctly, and that register allocation can 6923 // see that some registers may be assumed clobbered and have to preserve 6924 // them across calls to the intrinsic. 6925 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6926 DL, NodeTys, Ops); 6927 SDValue patchableNode = SDValue(MN, 0); 6928 DAG.setRoot(patchableNode); 6929 setValue(&I, patchableNode); 6930 return; 6931 } 6932 case Intrinsic::xray_typedevent: { 6933 // Here we want to make sure that the intrinsic behaves as if it has a 6934 // specific calling convention, and only for x86_64. 6935 // FIXME: Support other platforms later. 6936 const auto &Triple = DAG.getTarget().getTargetTriple(); 6937 if (Triple.getArch() != Triple::x86_64) 6938 return; 6939 6940 SDLoc DL = getCurSDLoc(); 6941 SmallVector<SDValue, 8> Ops; 6942 6943 // We want to say that we always want the arguments in registers. 6944 // It's unclear to me how manipulating the selection DAG here forces callers 6945 // to provide arguments in registers instead of on the stack. 6946 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6947 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6948 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6949 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6950 SDValue Chain = getRoot(); 6951 Ops.push_back(LogTypeId); 6952 Ops.push_back(LogEntryVal); 6953 Ops.push_back(StrSizeVal); 6954 Ops.push_back(Chain); 6955 6956 // We need to enforce the calling convention for the callsite, so that 6957 // argument ordering is enforced correctly, and that register allocation can 6958 // see that some registers may be assumed clobbered and have to preserve 6959 // them across calls to the intrinsic. 6960 MachineSDNode *MN = DAG.getMachineNode( 6961 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6962 SDValue patchableNode = SDValue(MN, 0); 6963 DAG.setRoot(patchableNode); 6964 setValue(&I, patchableNode); 6965 return; 6966 } 6967 case Intrinsic::experimental_deoptimize: 6968 LowerDeoptimizeCall(&I); 6969 return; 6970 case Intrinsic::experimental_stepvector: 6971 visitStepVector(I); 6972 return; 6973 case Intrinsic::vector_reduce_fadd: 6974 case Intrinsic::vector_reduce_fmul: 6975 case Intrinsic::vector_reduce_add: 6976 case Intrinsic::vector_reduce_mul: 6977 case Intrinsic::vector_reduce_and: 6978 case Intrinsic::vector_reduce_or: 6979 case Intrinsic::vector_reduce_xor: 6980 case Intrinsic::vector_reduce_smax: 6981 case Intrinsic::vector_reduce_smin: 6982 case Intrinsic::vector_reduce_umax: 6983 case Intrinsic::vector_reduce_umin: 6984 case Intrinsic::vector_reduce_fmax: 6985 case Intrinsic::vector_reduce_fmin: 6986 visitVectorReduce(I, Intrinsic); 6987 return; 6988 6989 case Intrinsic::icall_branch_funnel: { 6990 SmallVector<SDValue, 16> Ops; 6991 Ops.push_back(getValue(I.getArgOperand(0))); 6992 6993 int64_t Offset; 6994 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6995 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6996 if (!Base) 6997 report_fatal_error( 6998 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6999 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 7000 7001 struct BranchFunnelTarget { 7002 int64_t Offset; 7003 SDValue Target; 7004 }; 7005 SmallVector<BranchFunnelTarget, 8> Targets; 7006 7007 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 7008 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7009 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7010 if (ElemBase != Base) 7011 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7012 "to the same GlobalValue"); 7013 7014 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7015 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7016 if (!GA) 7017 report_fatal_error( 7018 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7019 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7020 GA->getGlobal(), getCurSDLoc(), 7021 Val.getValueType(), GA->getOffset())}); 7022 } 7023 llvm::sort(Targets, 7024 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7025 return T1.Offset < T2.Offset; 7026 }); 7027 7028 for (auto &T : Targets) { 7029 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 7030 Ops.push_back(T.Target); 7031 } 7032 7033 Ops.push_back(DAG.getRoot()); // Chain 7034 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 7035 getCurSDLoc(), MVT::Other, Ops), 7036 0); 7037 DAG.setRoot(N); 7038 setValue(&I, N); 7039 HasTailCall = true; 7040 return; 7041 } 7042 7043 case Intrinsic::wasm_landingpad_index: 7044 // Information this intrinsic contained has been transferred to 7045 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7046 // delete it now. 7047 return; 7048 7049 case Intrinsic::aarch64_settag: 7050 case Intrinsic::aarch64_settag_zero: { 7051 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7052 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7053 SDValue Val = TSI.EmitTargetCodeForSetTag( 7054 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 7055 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7056 ZeroMemory); 7057 DAG.setRoot(Val); 7058 setValue(&I, Val); 7059 return; 7060 } 7061 case Intrinsic::ptrmask: { 7062 SDValue Ptr = getValue(I.getOperand(0)); 7063 SDValue Const = getValue(I.getOperand(1)); 7064 7065 EVT PtrVT = Ptr.getValueType(); 7066 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 7067 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 7068 return; 7069 } 7070 case Intrinsic::get_active_lane_mask: { 7071 auto DL = getCurSDLoc(); 7072 SDValue Index = getValue(I.getOperand(0)); 7073 SDValue TripCount = getValue(I.getOperand(1)); 7074 Type *ElementTy = I.getOperand(0)->getType(); 7075 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7076 unsigned VecWidth = VT.getVectorNumElements(); 7077 7078 SmallVector<SDValue, 16> OpsTripCount; 7079 SmallVector<SDValue, 16> OpsIndex; 7080 SmallVector<SDValue, 16> OpsStepConstants; 7081 for (unsigned i = 0; i < VecWidth; i++) { 7082 OpsTripCount.push_back(TripCount); 7083 OpsIndex.push_back(Index); 7084 OpsStepConstants.push_back( 7085 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 7086 } 7087 7088 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 7089 7090 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 7091 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 7092 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 7093 SDValue VectorInduction = DAG.getNode( 7094 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 7095 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 7096 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 7097 VectorTripCount, ISD::CondCode::SETULT); 7098 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 7099 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 7100 SetCC)); 7101 return; 7102 } 7103 case Intrinsic::experimental_vector_insert: { 7104 auto DL = getCurSDLoc(); 7105 7106 SDValue Vec = getValue(I.getOperand(0)); 7107 SDValue SubVec = getValue(I.getOperand(1)); 7108 SDValue Index = getValue(I.getOperand(2)); 7109 7110 // The intrinsic's index type is i64, but the SDNode requires an index type 7111 // suitable for the target. Convert the index as required. 7112 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7113 if (Index.getValueType() != VectorIdxTy) 7114 Index = DAG.getVectorIdxConstant( 7115 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7116 7117 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7118 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec, 7119 Index)); 7120 return; 7121 } 7122 case Intrinsic::experimental_vector_extract: { 7123 auto DL = getCurSDLoc(); 7124 7125 SDValue Vec = getValue(I.getOperand(0)); 7126 SDValue Index = getValue(I.getOperand(1)); 7127 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7128 7129 // The intrinsic's index type is i64, but the SDNode requires an index type 7130 // suitable for the target. Convert the index as required. 7131 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7132 if (Index.getValueType() != VectorIdxTy) 7133 Index = DAG.getVectorIdxConstant( 7134 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7135 7136 setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index)); 7137 return; 7138 } 7139 case Intrinsic::experimental_vector_reverse: 7140 visitVectorReverse(I); 7141 return; 7142 case Intrinsic::experimental_vector_splice: 7143 visitVectorSplice(I); 7144 return; 7145 } 7146 } 7147 7148 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7149 const ConstrainedFPIntrinsic &FPI) { 7150 SDLoc sdl = getCurSDLoc(); 7151 7152 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7153 SmallVector<EVT, 4> ValueVTs; 7154 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7155 ValueVTs.push_back(MVT::Other); // Out chain 7156 7157 // We do not need to serialize constrained FP intrinsics against 7158 // each other or against (nonvolatile) loads, so they can be 7159 // chained like loads. 7160 SDValue Chain = DAG.getRoot(); 7161 SmallVector<SDValue, 4> Opers; 7162 Opers.push_back(Chain); 7163 if (FPI.isUnaryOp()) { 7164 Opers.push_back(getValue(FPI.getArgOperand(0))); 7165 } else if (FPI.isTernaryOp()) { 7166 Opers.push_back(getValue(FPI.getArgOperand(0))); 7167 Opers.push_back(getValue(FPI.getArgOperand(1))); 7168 Opers.push_back(getValue(FPI.getArgOperand(2))); 7169 } else { 7170 Opers.push_back(getValue(FPI.getArgOperand(0))); 7171 Opers.push_back(getValue(FPI.getArgOperand(1))); 7172 } 7173 7174 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7175 assert(Result.getNode()->getNumValues() == 2); 7176 7177 // Push node to the appropriate list so that future instructions can be 7178 // chained up correctly. 7179 SDValue OutChain = Result.getValue(1); 7180 switch (EB) { 7181 case fp::ExceptionBehavior::ebIgnore: 7182 // The only reason why ebIgnore nodes still need to be chained is that 7183 // they might depend on the current rounding mode, and therefore must 7184 // not be moved across instruction that may change that mode. 7185 LLVM_FALLTHROUGH; 7186 case fp::ExceptionBehavior::ebMayTrap: 7187 // These must not be moved across calls or instructions that may change 7188 // floating-point exception masks. 7189 PendingConstrainedFP.push_back(OutChain); 7190 break; 7191 case fp::ExceptionBehavior::ebStrict: 7192 // These must not be moved across calls or instructions that may change 7193 // floating-point exception masks or read floating-point exception flags. 7194 // In addition, they cannot be optimized out even if unused. 7195 PendingConstrainedFPStrict.push_back(OutChain); 7196 break; 7197 } 7198 }; 7199 7200 SDVTList VTs = DAG.getVTList(ValueVTs); 7201 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7202 7203 SDNodeFlags Flags; 7204 if (EB == fp::ExceptionBehavior::ebIgnore) 7205 Flags.setNoFPExcept(true); 7206 7207 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7208 Flags.copyFMF(*FPOp); 7209 7210 unsigned Opcode; 7211 switch (FPI.getIntrinsicID()) { 7212 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7213 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7214 case Intrinsic::INTRINSIC: \ 7215 Opcode = ISD::STRICT_##DAGN; \ 7216 break; 7217 #include "llvm/IR/ConstrainedOps.def" 7218 case Intrinsic::experimental_constrained_fmuladd: { 7219 Opcode = ISD::STRICT_FMA; 7220 // Break fmuladd into fmul and fadd. 7221 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7222 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7223 ValueVTs[0])) { 7224 Opers.pop_back(); 7225 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7226 pushOutChain(Mul, EB); 7227 Opcode = ISD::STRICT_FADD; 7228 Opers.clear(); 7229 Opers.push_back(Mul.getValue(1)); 7230 Opers.push_back(Mul.getValue(0)); 7231 Opers.push_back(getValue(FPI.getArgOperand(2))); 7232 } 7233 break; 7234 } 7235 } 7236 7237 // A few strict DAG nodes carry additional operands that are not 7238 // set up by the default code above. 7239 switch (Opcode) { 7240 default: break; 7241 case ISD::STRICT_FP_ROUND: 7242 Opers.push_back( 7243 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7244 break; 7245 case ISD::STRICT_FSETCC: 7246 case ISD::STRICT_FSETCCS: { 7247 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7248 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7249 if (TM.Options.NoNaNsFPMath) 7250 Condition = getFCmpCodeWithoutNaN(Condition); 7251 Opers.push_back(DAG.getCondCode(Condition)); 7252 break; 7253 } 7254 } 7255 7256 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7257 pushOutChain(Result, EB); 7258 7259 SDValue FPResult = Result.getValue(0); 7260 setValue(&FPI, FPResult); 7261 } 7262 7263 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7264 Optional<unsigned> ResOPC; 7265 switch (VPIntrin.getIntrinsicID()) { 7266 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN: 7267 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID; 7268 #define END_REGISTER_VP_INTRINSIC(...) break; 7269 #include "llvm/IR/VPIntrinsics.def" 7270 } 7271 7272 if (!ResOPC.hasValue()) 7273 llvm_unreachable( 7274 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7275 7276 return ResOPC.getValue(); 7277 } 7278 7279 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7280 const VPIntrinsic &VPIntrin) { 7281 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7282 7283 SmallVector<EVT, 4> ValueVTs; 7284 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7285 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7286 SDVTList VTs = DAG.getVTList(ValueVTs); 7287 7288 // Request operands. 7289 SmallVector<SDValue, 7> OpValues; 7290 for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i) 7291 OpValues.push_back(getValue(VPIntrin.getArgOperand(i))); 7292 7293 SDLoc DL = getCurSDLoc(); 7294 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7295 setValue(&VPIntrin, Result); 7296 } 7297 7298 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7299 const BasicBlock *EHPadBB, 7300 MCSymbol *&BeginLabel) { 7301 MachineFunction &MF = DAG.getMachineFunction(); 7302 MachineModuleInfo &MMI = MF.getMMI(); 7303 7304 // Insert a label before the invoke call to mark the try range. This can be 7305 // used to detect deletion of the invoke via the MachineModuleInfo. 7306 BeginLabel = MMI.getContext().createTempSymbol(); 7307 7308 // For SjLj, keep track of which landing pads go with which invokes 7309 // so as to maintain the ordering of pads in the LSDA. 7310 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7311 if (CallSiteIndex) { 7312 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7313 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7314 7315 // Now that the call site is handled, stop tracking it. 7316 MMI.setCurrentCallSite(0); 7317 } 7318 7319 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7320 } 7321 7322 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7323 const BasicBlock *EHPadBB, 7324 MCSymbol *BeginLabel) { 7325 assert(BeginLabel && "BeginLabel should've been set"); 7326 7327 MachineFunction &MF = DAG.getMachineFunction(); 7328 MachineModuleInfo &MMI = MF.getMMI(); 7329 7330 // Insert a label at the end of the invoke call to mark the try range. This 7331 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7332 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7333 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7334 7335 // Inform MachineModuleInfo of range. 7336 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7337 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7338 // actually use outlined funclets and their LSDA info style. 7339 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7340 assert(II && "II should've been set"); 7341 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7342 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7343 } else if (!isScopedEHPersonality(Pers)) { 7344 assert(EHPadBB); 7345 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7346 } 7347 7348 return Chain; 7349 } 7350 7351 std::pair<SDValue, SDValue> 7352 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7353 const BasicBlock *EHPadBB) { 7354 MCSymbol *BeginLabel = nullptr; 7355 7356 if (EHPadBB) { 7357 // Both PendingLoads and PendingExports must be flushed here; 7358 // this call might not return. 7359 (void)getRoot(); 7360 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7361 CLI.setChain(getRoot()); 7362 } 7363 7364 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7365 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7366 7367 assert((CLI.IsTailCall || Result.second.getNode()) && 7368 "Non-null chain expected with non-tail call!"); 7369 assert((Result.second.getNode() || !Result.first.getNode()) && 7370 "Null value expected with tail call!"); 7371 7372 if (!Result.second.getNode()) { 7373 // As a special case, a null chain means that a tail call has been emitted 7374 // and the DAG root is already updated. 7375 HasTailCall = true; 7376 7377 // Since there's no actual continuation from this block, nothing can be 7378 // relying on us setting vregs for them. 7379 PendingExports.clear(); 7380 } else { 7381 DAG.setRoot(Result.second); 7382 } 7383 7384 if (EHPadBB) { 7385 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7386 BeginLabel)); 7387 } 7388 7389 return Result; 7390 } 7391 7392 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7393 bool isTailCall, 7394 const BasicBlock *EHPadBB) { 7395 auto &DL = DAG.getDataLayout(); 7396 FunctionType *FTy = CB.getFunctionType(); 7397 Type *RetTy = CB.getType(); 7398 7399 TargetLowering::ArgListTy Args; 7400 Args.reserve(CB.arg_size()); 7401 7402 const Value *SwiftErrorVal = nullptr; 7403 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7404 7405 if (isTailCall) { 7406 // Avoid emitting tail calls in functions with the disable-tail-calls 7407 // attribute. 7408 auto *Caller = CB.getParent()->getParent(); 7409 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7410 "true") 7411 isTailCall = false; 7412 7413 // We can't tail call inside a function with a swifterror argument. Lowering 7414 // does not support this yet. It would have to move into the swifterror 7415 // register before the call. 7416 if (TLI.supportSwiftError() && 7417 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7418 isTailCall = false; 7419 } 7420 7421 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7422 TargetLowering::ArgListEntry Entry; 7423 const Value *V = *I; 7424 7425 // Skip empty types 7426 if (V->getType()->isEmptyTy()) 7427 continue; 7428 7429 SDValue ArgNode = getValue(V); 7430 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7431 7432 Entry.setAttributes(&CB, I - CB.arg_begin()); 7433 7434 // Use swifterror virtual register as input to the call. 7435 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7436 SwiftErrorVal = V; 7437 // We find the virtual register for the actual swifterror argument. 7438 // Instead of using the Value, we use the virtual register instead. 7439 Entry.Node = 7440 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7441 EVT(TLI.getPointerTy(DL))); 7442 } 7443 7444 Args.push_back(Entry); 7445 7446 // If we have an explicit sret argument that is an Instruction, (i.e., it 7447 // might point to function-local memory), we can't meaningfully tail-call. 7448 if (Entry.IsSRet && isa<Instruction>(V)) 7449 isTailCall = false; 7450 } 7451 7452 // If call site has a cfguardtarget operand bundle, create and add an 7453 // additional ArgListEntry. 7454 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7455 TargetLowering::ArgListEntry Entry; 7456 Value *V = Bundle->Inputs[0]; 7457 SDValue ArgNode = getValue(V); 7458 Entry.Node = ArgNode; 7459 Entry.Ty = V->getType(); 7460 Entry.IsCFGuardTarget = true; 7461 Args.push_back(Entry); 7462 } 7463 7464 // Check if target-independent constraints permit a tail call here. 7465 // Target-dependent constraints are checked within TLI->LowerCallTo. 7466 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7467 isTailCall = false; 7468 7469 // Disable tail calls if there is an swifterror argument. Targets have not 7470 // been updated to support tail calls. 7471 if (TLI.supportSwiftError() && SwiftErrorVal) 7472 isTailCall = false; 7473 7474 TargetLowering::CallLoweringInfo CLI(DAG); 7475 CLI.setDebugLoc(getCurSDLoc()) 7476 .setChain(getRoot()) 7477 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7478 .setTailCall(isTailCall) 7479 .setConvergent(CB.isConvergent()) 7480 .setIsPreallocated( 7481 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7482 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7483 7484 if (Result.first.getNode()) { 7485 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7486 setValue(&CB, Result.first); 7487 } 7488 7489 // The last element of CLI.InVals has the SDValue for swifterror return. 7490 // Here we copy it to a virtual register and update SwiftErrorMap for 7491 // book-keeping. 7492 if (SwiftErrorVal && TLI.supportSwiftError()) { 7493 // Get the last element of InVals. 7494 SDValue Src = CLI.InVals.back(); 7495 Register VReg = 7496 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7497 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7498 DAG.setRoot(CopyNode); 7499 } 7500 } 7501 7502 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7503 SelectionDAGBuilder &Builder) { 7504 // Check to see if this load can be trivially constant folded, e.g. if the 7505 // input is from a string literal. 7506 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7507 // Cast pointer to the type we really want to load. 7508 Type *LoadTy = 7509 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7510 if (LoadVT.isVector()) 7511 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7512 7513 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7514 PointerType::getUnqual(LoadTy)); 7515 7516 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7517 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7518 return Builder.getValue(LoadCst); 7519 } 7520 7521 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7522 // still constant memory, the input chain can be the entry node. 7523 SDValue Root; 7524 bool ConstantMemory = false; 7525 7526 // Do not serialize (non-volatile) loads of constant memory with anything. 7527 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7528 Root = Builder.DAG.getEntryNode(); 7529 ConstantMemory = true; 7530 } else { 7531 // Do not serialize non-volatile loads against each other. 7532 Root = Builder.DAG.getRoot(); 7533 } 7534 7535 SDValue Ptr = Builder.getValue(PtrVal); 7536 SDValue LoadVal = 7537 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7538 MachinePointerInfo(PtrVal), Align(1)); 7539 7540 if (!ConstantMemory) 7541 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7542 return LoadVal; 7543 } 7544 7545 /// Record the value for an instruction that produces an integer result, 7546 /// converting the type where necessary. 7547 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7548 SDValue Value, 7549 bool IsSigned) { 7550 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7551 I.getType(), true); 7552 if (IsSigned) 7553 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7554 else 7555 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7556 setValue(&I, Value); 7557 } 7558 7559 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7560 /// true and lower it. Otherwise return false, and it will be lowered like a 7561 /// normal call. 7562 /// The caller already checked that \p I calls the appropriate LibFunc with a 7563 /// correct prototype. 7564 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7565 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7566 const Value *Size = I.getArgOperand(2); 7567 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7568 if (CSize && CSize->getZExtValue() == 0) { 7569 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7570 I.getType(), true); 7571 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7572 return true; 7573 } 7574 7575 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7576 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7577 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7578 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7579 if (Res.first.getNode()) { 7580 processIntegerCallValue(I, Res.first, true); 7581 PendingLoads.push_back(Res.second); 7582 return true; 7583 } 7584 7585 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7586 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7587 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7588 return false; 7589 7590 // If the target has a fast compare for the given size, it will return a 7591 // preferred load type for that size. Require that the load VT is legal and 7592 // that the target supports unaligned loads of that type. Otherwise, return 7593 // INVALID. 7594 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7595 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7596 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7597 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7598 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7599 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7600 // TODO: Check alignment of src and dest ptrs. 7601 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7602 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7603 if (!TLI.isTypeLegal(LVT) || 7604 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7605 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7606 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7607 } 7608 7609 return LVT; 7610 }; 7611 7612 // This turns into unaligned loads. We only do this if the target natively 7613 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7614 // we'll only produce a small number of byte loads. 7615 MVT LoadVT; 7616 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7617 switch (NumBitsToCompare) { 7618 default: 7619 return false; 7620 case 16: 7621 LoadVT = MVT::i16; 7622 break; 7623 case 32: 7624 LoadVT = MVT::i32; 7625 break; 7626 case 64: 7627 case 128: 7628 case 256: 7629 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7630 break; 7631 } 7632 7633 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7634 return false; 7635 7636 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7637 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7638 7639 // Bitcast to a wide integer type if the loads are vectors. 7640 if (LoadVT.isVector()) { 7641 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7642 LoadL = DAG.getBitcast(CmpVT, LoadL); 7643 LoadR = DAG.getBitcast(CmpVT, LoadR); 7644 } 7645 7646 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7647 processIntegerCallValue(I, Cmp, false); 7648 return true; 7649 } 7650 7651 /// See if we can lower a memchr call into an optimized form. If so, return 7652 /// true and lower it. Otherwise return false, and it will be lowered like a 7653 /// normal call. 7654 /// The caller already checked that \p I calls the appropriate LibFunc with a 7655 /// correct prototype. 7656 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7657 const Value *Src = I.getArgOperand(0); 7658 const Value *Char = I.getArgOperand(1); 7659 const Value *Length = I.getArgOperand(2); 7660 7661 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7662 std::pair<SDValue, SDValue> Res = 7663 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7664 getValue(Src), getValue(Char), getValue(Length), 7665 MachinePointerInfo(Src)); 7666 if (Res.first.getNode()) { 7667 setValue(&I, Res.first); 7668 PendingLoads.push_back(Res.second); 7669 return true; 7670 } 7671 7672 return false; 7673 } 7674 7675 /// See if we can lower a mempcpy call into an optimized form. If so, return 7676 /// true and lower it. Otherwise return false, and it will be lowered like a 7677 /// normal call. 7678 /// The caller already checked that \p I calls the appropriate LibFunc with a 7679 /// correct prototype. 7680 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7681 SDValue Dst = getValue(I.getArgOperand(0)); 7682 SDValue Src = getValue(I.getArgOperand(1)); 7683 SDValue Size = getValue(I.getArgOperand(2)); 7684 7685 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7686 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7687 // DAG::getMemcpy needs Alignment to be defined. 7688 Align Alignment = std::min(DstAlign, SrcAlign); 7689 7690 bool isVol = false; 7691 SDLoc sdl = getCurSDLoc(); 7692 7693 // In the mempcpy context we need to pass in a false value for isTailCall 7694 // because the return pointer needs to be adjusted by the size of 7695 // the copied memory. 7696 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7697 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7698 /*isTailCall=*/false, 7699 MachinePointerInfo(I.getArgOperand(0)), 7700 MachinePointerInfo(I.getArgOperand(1))); 7701 assert(MC.getNode() != nullptr && 7702 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7703 DAG.setRoot(MC); 7704 7705 // Check if Size needs to be truncated or extended. 7706 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7707 7708 // Adjust return pointer to point just past the last dst byte. 7709 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7710 Dst, Size); 7711 setValue(&I, DstPlusSize); 7712 return true; 7713 } 7714 7715 /// See if we can lower a strcpy call into an optimized form. If so, return 7716 /// true and lower it, otherwise return false and it will be lowered like a 7717 /// normal call. 7718 /// The caller already checked that \p I calls the appropriate LibFunc with a 7719 /// correct prototype. 7720 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7721 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7722 7723 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7724 std::pair<SDValue, SDValue> Res = 7725 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7726 getValue(Arg0), getValue(Arg1), 7727 MachinePointerInfo(Arg0), 7728 MachinePointerInfo(Arg1), isStpcpy); 7729 if (Res.first.getNode()) { 7730 setValue(&I, Res.first); 7731 DAG.setRoot(Res.second); 7732 return true; 7733 } 7734 7735 return false; 7736 } 7737 7738 /// See if we can lower a strcmp call into an optimized form. If so, return 7739 /// true and lower it, otherwise return false and it will be lowered like a 7740 /// normal call. 7741 /// The caller already checked that \p I calls the appropriate LibFunc with a 7742 /// correct prototype. 7743 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7744 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7745 7746 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7747 std::pair<SDValue, SDValue> Res = 7748 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7749 getValue(Arg0), getValue(Arg1), 7750 MachinePointerInfo(Arg0), 7751 MachinePointerInfo(Arg1)); 7752 if (Res.first.getNode()) { 7753 processIntegerCallValue(I, Res.first, true); 7754 PendingLoads.push_back(Res.second); 7755 return true; 7756 } 7757 7758 return false; 7759 } 7760 7761 /// See if we can lower a strlen call into an optimized form. If so, return 7762 /// true and lower it, otherwise return false and it will be lowered like a 7763 /// normal call. 7764 /// The caller already checked that \p I calls the appropriate LibFunc with a 7765 /// correct prototype. 7766 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7767 const Value *Arg0 = I.getArgOperand(0); 7768 7769 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7770 std::pair<SDValue, SDValue> Res = 7771 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7772 getValue(Arg0), MachinePointerInfo(Arg0)); 7773 if (Res.first.getNode()) { 7774 processIntegerCallValue(I, Res.first, false); 7775 PendingLoads.push_back(Res.second); 7776 return true; 7777 } 7778 7779 return false; 7780 } 7781 7782 /// See if we can lower a strnlen call into an optimized form. If so, return 7783 /// true and lower it, otherwise return false and it will be lowered like a 7784 /// normal call. 7785 /// The caller already checked that \p I calls the appropriate LibFunc with a 7786 /// correct prototype. 7787 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7788 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7789 7790 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7791 std::pair<SDValue, SDValue> Res = 7792 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7793 getValue(Arg0), getValue(Arg1), 7794 MachinePointerInfo(Arg0)); 7795 if (Res.first.getNode()) { 7796 processIntegerCallValue(I, Res.first, false); 7797 PendingLoads.push_back(Res.second); 7798 return true; 7799 } 7800 7801 return false; 7802 } 7803 7804 /// See if we can lower a unary floating-point operation into an SDNode with 7805 /// the specified Opcode. If so, return true and lower it, otherwise return 7806 /// false and it will be lowered like a normal call. 7807 /// The caller already checked that \p I calls the appropriate LibFunc with a 7808 /// correct prototype. 7809 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7810 unsigned Opcode) { 7811 // We already checked this call's prototype; verify it doesn't modify errno. 7812 if (!I.onlyReadsMemory()) 7813 return false; 7814 7815 SDNodeFlags Flags; 7816 Flags.copyFMF(cast<FPMathOperator>(I)); 7817 7818 SDValue Tmp = getValue(I.getArgOperand(0)); 7819 setValue(&I, 7820 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7821 return true; 7822 } 7823 7824 /// See if we can lower a binary floating-point operation into an SDNode with 7825 /// the specified Opcode. If so, return true and lower it. Otherwise return 7826 /// false, and it will be lowered like a normal call. 7827 /// The caller already checked that \p I calls the appropriate LibFunc with a 7828 /// correct prototype. 7829 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7830 unsigned Opcode) { 7831 // We already checked this call's prototype; verify it doesn't modify errno. 7832 if (!I.onlyReadsMemory()) 7833 return false; 7834 7835 SDNodeFlags Flags; 7836 Flags.copyFMF(cast<FPMathOperator>(I)); 7837 7838 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7839 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7840 EVT VT = Tmp0.getValueType(); 7841 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7842 return true; 7843 } 7844 7845 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7846 // Handle inline assembly differently. 7847 if (I.isInlineAsm()) { 7848 visitInlineAsm(I); 7849 return; 7850 } 7851 7852 if (Function *F = I.getCalledFunction()) { 7853 if (F->isDeclaration()) { 7854 // Is this an LLVM intrinsic or a target-specific intrinsic? 7855 unsigned IID = F->getIntrinsicID(); 7856 if (!IID) 7857 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7858 IID = II->getIntrinsicID(F); 7859 7860 if (IID) { 7861 visitIntrinsicCall(I, IID); 7862 return; 7863 } 7864 } 7865 7866 // Check for well-known libc/libm calls. If the function is internal, it 7867 // can't be a library call. Don't do the check if marked as nobuiltin for 7868 // some reason or the call site requires strict floating point semantics. 7869 LibFunc Func; 7870 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7871 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7872 LibInfo->hasOptimizedCodeGen(Func)) { 7873 switch (Func) { 7874 default: break; 7875 case LibFunc_bcmp: 7876 if (visitMemCmpBCmpCall(I)) 7877 return; 7878 break; 7879 case LibFunc_copysign: 7880 case LibFunc_copysignf: 7881 case LibFunc_copysignl: 7882 // We already checked this call's prototype; verify it doesn't modify 7883 // errno. 7884 if (I.onlyReadsMemory()) { 7885 SDValue LHS = getValue(I.getArgOperand(0)); 7886 SDValue RHS = getValue(I.getArgOperand(1)); 7887 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7888 LHS.getValueType(), LHS, RHS)); 7889 return; 7890 } 7891 break; 7892 case LibFunc_fabs: 7893 case LibFunc_fabsf: 7894 case LibFunc_fabsl: 7895 if (visitUnaryFloatCall(I, ISD::FABS)) 7896 return; 7897 break; 7898 case LibFunc_fmin: 7899 case LibFunc_fminf: 7900 case LibFunc_fminl: 7901 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7902 return; 7903 break; 7904 case LibFunc_fmax: 7905 case LibFunc_fmaxf: 7906 case LibFunc_fmaxl: 7907 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7908 return; 7909 break; 7910 case LibFunc_sin: 7911 case LibFunc_sinf: 7912 case LibFunc_sinl: 7913 if (visitUnaryFloatCall(I, ISD::FSIN)) 7914 return; 7915 break; 7916 case LibFunc_cos: 7917 case LibFunc_cosf: 7918 case LibFunc_cosl: 7919 if (visitUnaryFloatCall(I, ISD::FCOS)) 7920 return; 7921 break; 7922 case LibFunc_sqrt: 7923 case LibFunc_sqrtf: 7924 case LibFunc_sqrtl: 7925 case LibFunc_sqrt_finite: 7926 case LibFunc_sqrtf_finite: 7927 case LibFunc_sqrtl_finite: 7928 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7929 return; 7930 break; 7931 case LibFunc_floor: 7932 case LibFunc_floorf: 7933 case LibFunc_floorl: 7934 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7935 return; 7936 break; 7937 case LibFunc_nearbyint: 7938 case LibFunc_nearbyintf: 7939 case LibFunc_nearbyintl: 7940 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7941 return; 7942 break; 7943 case LibFunc_ceil: 7944 case LibFunc_ceilf: 7945 case LibFunc_ceill: 7946 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7947 return; 7948 break; 7949 case LibFunc_rint: 7950 case LibFunc_rintf: 7951 case LibFunc_rintl: 7952 if (visitUnaryFloatCall(I, ISD::FRINT)) 7953 return; 7954 break; 7955 case LibFunc_round: 7956 case LibFunc_roundf: 7957 case LibFunc_roundl: 7958 if (visitUnaryFloatCall(I, ISD::FROUND)) 7959 return; 7960 break; 7961 case LibFunc_trunc: 7962 case LibFunc_truncf: 7963 case LibFunc_truncl: 7964 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7965 return; 7966 break; 7967 case LibFunc_log2: 7968 case LibFunc_log2f: 7969 case LibFunc_log2l: 7970 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7971 return; 7972 break; 7973 case LibFunc_exp2: 7974 case LibFunc_exp2f: 7975 case LibFunc_exp2l: 7976 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7977 return; 7978 break; 7979 case LibFunc_memcmp: 7980 if (visitMemCmpBCmpCall(I)) 7981 return; 7982 break; 7983 case LibFunc_mempcpy: 7984 if (visitMemPCpyCall(I)) 7985 return; 7986 break; 7987 case LibFunc_memchr: 7988 if (visitMemChrCall(I)) 7989 return; 7990 break; 7991 case LibFunc_strcpy: 7992 if (visitStrCpyCall(I, false)) 7993 return; 7994 break; 7995 case LibFunc_stpcpy: 7996 if (visitStrCpyCall(I, true)) 7997 return; 7998 break; 7999 case LibFunc_strcmp: 8000 if (visitStrCmpCall(I)) 8001 return; 8002 break; 8003 case LibFunc_strlen: 8004 if (visitStrLenCall(I)) 8005 return; 8006 break; 8007 case LibFunc_strnlen: 8008 if (visitStrNLenCall(I)) 8009 return; 8010 break; 8011 } 8012 } 8013 } 8014 8015 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8016 // have to do anything here to lower funclet bundles. 8017 // CFGuardTarget bundles are lowered in LowerCallTo. 8018 assert(!I.hasOperandBundlesOtherThan( 8019 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8020 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8021 LLVMContext::OB_clang_arc_attachedcall}) && 8022 "Cannot lower calls with arbitrary operand bundles!"); 8023 8024 SDValue Callee = getValue(I.getCalledOperand()); 8025 8026 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8027 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8028 else 8029 // Check if we can potentially perform a tail call. More detailed checking 8030 // is be done within LowerCallTo, after more information about the call is 8031 // known. 8032 LowerCallTo(I, Callee, I.isTailCall()); 8033 } 8034 8035 namespace { 8036 8037 /// AsmOperandInfo - This contains information for each constraint that we are 8038 /// lowering. 8039 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8040 public: 8041 /// CallOperand - If this is the result output operand or a clobber 8042 /// this is null, otherwise it is the incoming operand to the CallInst. 8043 /// This gets modified as the asm is processed. 8044 SDValue CallOperand; 8045 8046 /// AssignedRegs - If this is a register or register class operand, this 8047 /// contains the set of register corresponding to the operand. 8048 RegsForValue AssignedRegs; 8049 8050 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8051 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8052 } 8053 8054 /// Whether or not this operand accesses memory 8055 bool hasMemory(const TargetLowering &TLI) const { 8056 // Indirect operand accesses access memory. 8057 if (isIndirect) 8058 return true; 8059 8060 for (const auto &Code : Codes) 8061 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8062 return true; 8063 8064 return false; 8065 } 8066 8067 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8068 /// corresponds to. If there is no Value* for this operand, it returns 8069 /// MVT::Other. 8070 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8071 const DataLayout &DL) const { 8072 if (!CallOperandVal) return MVT::Other; 8073 8074 if (isa<BasicBlock>(CallOperandVal)) 8075 return TLI.getProgramPointerTy(DL); 8076 8077 llvm::Type *OpTy = CallOperandVal->getType(); 8078 8079 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8080 // If this is an indirect operand, the operand is a pointer to the 8081 // accessed type. 8082 if (isIndirect) { 8083 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 8084 if (!PtrTy) 8085 report_fatal_error("Indirect operand for inline asm not a pointer!"); 8086 OpTy = PtrTy->getElementType(); 8087 } 8088 8089 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8090 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8091 if (STy->getNumElements() == 1) 8092 OpTy = STy->getElementType(0); 8093 8094 // If OpTy is not a single value, it may be a struct/union that we 8095 // can tile with integers. 8096 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8097 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8098 switch (BitSize) { 8099 default: break; 8100 case 1: 8101 case 8: 8102 case 16: 8103 case 32: 8104 case 64: 8105 case 128: 8106 OpTy = IntegerType::get(Context, BitSize); 8107 break; 8108 } 8109 } 8110 8111 return TLI.getValueType(DL, OpTy, true); 8112 } 8113 }; 8114 8115 8116 } // end anonymous namespace 8117 8118 /// Make sure that the output operand \p OpInfo and its corresponding input 8119 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8120 /// out). 8121 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8122 SDISelAsmOperandInfo &MatchingOpInfo, 8123 SelectionDAG &DAG) { 8124 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8125 return; 8126 8127 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8128 const auto &TLI = DAG.getTargetLoweringInfo(); 8129 8130 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8131 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8132 OpInfo.ConstraintVT); 8133 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8134 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8135 MatchingOpInfo.ConstraintVT); 8136 if ((OpInfo.ConstraintVT.isInteger() != 8137 MatchingOpInfo.ConstraintVT.isInteger()) || 8138 (MatchRC.second != InputRC.second)) { 8139 // FIXME: error out in a more elegant fashion 8140 report_fatal_error("Unsupported asm: input constraint" 8141 " with a matching output constraint of" 8142 " incompatible type!"); 8143 } 8144 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8145 } 8146 8147 /// Get a direct memory input to behave well as an indirect operand. 8148 /// This may introduce stores, hence the need for a \p Chain. 8149 /// \return The (possibly updated) chain. 8150 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8151 SDISelAsmOperandInfo &OpInfo, 8152 SelectionDAG &DAG) { 8153 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8154 8155 // If we don't have an indirect input, put it in the constpool if we can, 8156 // otherwise spill it to a stack slot. 8157 // TODO: This isn't quite right. We need to handle these according to 8158 // the addressing mode that the constraint wants. Also, this may take 8159 // an additional register for the computation and we don't want that 8160 // either. 8161 8162 // If the operand is a float, integer, or vector constant, spill to a 8163 // constant pool entry to get its address. 8164 const Value *OpVal = OpInfo.CallOperandVal; 8165 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8166 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8167 OpInfo.CallOperand = DAG.getConstantPool( 8168 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8169 return Chain; 8170 } 8171 8172 // Otherwise, create a stack slot and emit a store to it before the asm. 8173 Type *Ty = OpVal->getType(); 8174 auto &DL = DAG.getDataLayout(); 8175 uint64_t TySize = DL.getTypeAllocSize(Ty); 8176 MachineFunction &MF = DAG.getMachineFunction(); 8177 int SSFI = MF.getFrameInfo().CreateStackObject( 8178 TySize, DL.getPrefTypeAlign(Ty), false); 8179 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8180 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8181 MachinePointerInfo::getFixedStack(MF, SSFI), 8182 TLI.getMemValueType(DL, Ty)); 8183 OpInfo.CallOperand = StackSlot; 8184 8185 return Chain; 8186 } 8187 8188 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8189 /// specified operand. We prefer to assign virtual registers, to allow the 8190 /// register allocator to handle the assignment process. However, if the asm 8191 /// uses features that we can't model on machineinstrs, we have SDISel do the 8192 /// allocation. This produces generally horrible, but correct, code. 8193 /// 8194 /// OpInfo describes the operand 8195 /// RefOpInfo describes the matching operand if any, the operand otherwise 8196 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8197 SDISelAsmOperandInfo &OpInfo, 8198 SDISelAsmOperandInfo &RefOpInfo) { 8199 LLVMContext &Context = *DAG.getContext(); 8200 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8201 8202 MachineFunction &MF = DAG.getMachineFunction(); 8203 SmallVector<unsigned, 4> Regs; 8204 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8205 8206 // No work to do for memory operations. 8207 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8208 return; 8209 8210 // If this is a constraint for a single physreg, or a constraint for a 8211 // register class, find it. 8212 unsigned AssignedReg; 8213 const TargetRegisterClass *RC; 8214 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8215 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8216 // RC is unset only on failure. Return immediately. 8217 if (!RC) 8218 return; 8219 8220 // Get the actual register value type. This is important, because the user 8221 // may have asked for (e.g.) the AX register in i32 type. We need to 8222 // remember that AX is actually i16 to get the right extension. 8223 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8224 8225 if (OpInfo.ConstraintVT != MVT::Other) { 8226 // If this is an FP operand in an integer register (or visa versa), or more 8227 // generally if the operand value disagrees with the register class we plan 8228 // to stick it in, fix the operand type. 8229 // 8230 // If this is an input value, the bitcast to the new type is done now. 8231 // Bitcast for output value is done at the end of visitInlineAsm(). 8232 if ((OpInfo.Type == InlineAsm::isOutput || 8233 OpInfo.Type == InlineAsm::isInput) && 8234 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8235 // Try to convert to the first EVT that the reg class contains. If the 8236 // types are identical size, use a bitcast to convert (e.g. two differing 8237 // vector types). Note: output bitcast is done at the end of 8238 // visitInlineAsm(). 8239 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8240 // Exclude indirect inputs while they are unsupported because the code 8241 // to perform the load is missing and thus OpInfo.CallOperand still 8242 // refers to the input address rather than the pointed-to value. 8243 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8244 OpInfo.CallOperand = 8245 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8246 OpInfo.ConstraintVT = RegVT; 8247 // If the operand is an FP value and we want it in integer registers, 8248 // use the corresponding integer type. This turns an f64 value into 8249 // i64, which can be passed with two i32 values on a 32-bit machine. 8250 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8251 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8252 if (OpInfo.Type == InlineAsm::isInput) 8253 OpInfo.CallOperand = 8254 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8255 OpInfo.ConstraintVT = VT; 8256 } 8257 } 8258 } 8259 8260 // No need to allocate a matching input constraint since the constraint it's 8261 // matching to has already been allocated. 8262 if (OpInfo.isMatchingInputConstraint()) 8263 return; 8264 8265 EVT ValueVT = OpInfo.ConstraintVT; 8266 if (OpInfo.ConstraintVT == MVT::Other) 8267 ValueVT = RegVT; 8268 8269 // Initialize NumRegs. 8270 unsigned NumRegs = 1; 8271 if (OpInfo.ConstraintVT != MVT::Other) 8272 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8273 8274 // If this is a constraint for a specific physical register, like {r17}, 8275 // assign it now. 8276 8277 // If this associated to a specific register, initialize iterator to correct 8278 // place. If virtual, make sure we have enough registers 8279 8280 // Initialize iterator if necessary 8281 TargetRegisterClass::iterator I = RC->begin(); 8282 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8283 8284 // Do not check for single registers. 8285 if (AssignedReg) { 8286 for (; *I != AssignedReg; ++I) 8287 assert(I != RC->end() && "AssignedReg should be member of RC"); 8288 } 8289 8290 for (; NumRegs; --NumRegs, ++I) { 8291 assert(I != RC->end() && "Ran out of registers to allocate!"); 8292 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8293 Regs.push_back(R); 8294 } 8295 8296 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8297 } 8298 8299 static unsigned 8300 findMatchingInlineAsmOperand(unsigned OperandNo, 8301 const std::vector<SDValue> &AsmNodeOperands) { 8302 // Scan until we find the definition we already emitted of this operand. 8303 unsigned CurOp = InlineAsm::Op_FirstOperand; 8304 for (; OperandNo; --OperandNo) { 8305 // Advance to the next operand. 8306 unsigned OpFlag = 8307 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8308 assert((InlineAsm::isRegDefKind(OpFlag) || 8309 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8310 InlineAsm::isMemKind(OpFlag)) && 8311 "Skipped past definitions?"); 8312 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8313 } 8314 return CurOp; 8315 } 8316 8317 namespace { 8318 8319 class ExtraFlags { 8320 unsigned Flags = 0; 8321 8322 public: 8323 explicit ExtraFlags(const CallBase &Call) { 8324 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8325 if (IA->hasSideEffects()) 8326 Flags |= InlineAsm::Extra_HasSideEffects; 8327 if (IA->isAlignStack()) 8328 Flags |= InlineAsm::Extra_IsAlignStack; 8329 if (Call.isConvergent()) 8330 Flags |= InlineAsm::Extra_IsConvergent; 8331 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8332 } 8333 8334 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8335 // Ideally, we would only check against memory constraints. However, the 8336 // meaning of an Other constraint can be target-specific and we can't easily 8337 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8338 // for Other constraints as well. 8339 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8340 OpInfo.ConstraintType == TargetLowering::C_Other) { 8341 if (OpInfo.Type == InlineAsm::isInput) 8342 Flags |= InlineAsm::Extra_MayLoad; 8343 else if (OpInfo.Type == InlineAsm::isOutput) 8344 Flags |= InlineAsm::Extra_MayStore; 8345 else if (OpInfo.Type == InlineAsm::isClobber) 8346 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8347 } 8348 } 8349 8350 unsigned get() const { return Flags; } 8351 }; 8352 8353 } // end anonymous namespace 8354 8355 /// visitInlineAsm - Handle a call to an InlineAsm object. 8356 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8357 const BasicBlock *EHPadBB) { 8358 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8359 8360 /// ConstraintOperands - Information about all of the constraints. 8361 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8362 8363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8364 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8365 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8366 8367 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8368 // AsmDialect, MayLoad, MayStore). 8369 bool HasSideEffect = IA->hasSideEffects(); 8370 ExtraFlags ExtraInfo(Call); 8371 8372 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8373 unsigned ResNo = 0; // ResNo - The result number of the next output. 8374 unsigned NumMatchingOps = 0; 8375 for (auto &T : TargetConstraints) { 8376 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8377 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8378 8379 // Compute the value type for each operand. 8380 if (OpInfo.Type == InlineAsm::isInput || 8381 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8382 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8383 8384 // Process the call argument. BasicBlocks are labels, currently appearing 8385 // only in asm's. 8386 if (isa<CallBrInst>(Call) && 8387 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8388 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8389 NumMatchingOps) && 8390 (NumMatchingOps == 0 || 8391 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8392 NumMatchingOps))) { 8393 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8394 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8395 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8396 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8397 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8398 } else { 8399 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8400 } 8401 8402 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8403 DAG.getDataLayout()); 8404 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8405 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8406 // The return value of the call is this value. As such, there is no 8407 // corresponding argument. 8408 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8409 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8410 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8411 DAG.getDataLayout(), STy->getElementType(ResNo)); 8412 } else { 8413 assert(ResNo == 0 && "Asm only has one result!"); 8414 OpInfo.ConstraintVT = 8415 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8416 } 8417 ++ResNo; 8418 } else { 8419 OpInfo.ConstraintVT = MVT::Other; 8420 } 8421 8422 if (OpInfo.hasMatchingInput()) 8423 ++NumMatchingOps; 8424 8425 if (!HasSideEffect) 8426 HasSideEffect = OpInfo.hasMemory(TLI); 8427 8428 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8429 // FIXME: Could we compute this on OpInfo rather than T? 8430 8431 // Compute the constraint code and ConstraintType to use. 8432 TLI.ComputeConstraintToUse(T, SDValue()); 8433 8434 if (T.ConstraintType == TargetLowering::C_Immediate && 8435 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8436 // We've delayed emitting a diagnostic like the "n" constraint because 8437 // inlining could cause an integer showing up. 8438 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8439 "' expects an integer constant " 8440 "expression"); 8441 8442 ExtraInfo.update(T); 8443 } 8444 8445 // We won't need to flush pending loads if this asm doesn't touch 8446 // memory and is nonvolatile. 8447 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8448 8449 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8450 if (EmitEHLabels) { 8451 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8452 } 8453 bool IsCallBr = isa<CallBrInst>(Call); 8454 8455 if (IsCallBr || EmitEHLabels) { 8456 // If this is a callbr or invoke we need to flush pending exports since 8457 // inlineasm_br and invoke are terminators. 8458 // We need to do this before nodes are glued to the inlineasm_br node. 8459 Chain = getControlRoot(); 8460 } 8461 8462 MCSymbol *BeginLabel = nullptr; 8463 if (EmitEHLabels) { 8464 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8465 } 8466 8467 // Second pass over the constraints: compute which constraint option to use. 8468 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8469 // If this is an output operand with a matching input operand, look up the 8470 // matching input. If their types mismatch, e.g. one is an integer, the 8471 // other is floating point, or their sizes are different, flag it as an 8472 // error. 8473 if (OpInfo.hasMatchingInput()) { 8474 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8475 patchMatchingInput(OpInfo, Input, DAG); 8476 } 8477 8478 // Compute the constraint code and ConstraintType to use. 8479 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8480 8481 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8482 OpInfo.Type == InlineAsm::isClobber) 8483 continue; 8484 8485 // If this is a memory input, and if the operand is not indirect, do what we 8486 // need to provide an address for the memory input. 8487 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8488 !OpInfo.isIndirect) { 8489 assert((OpInfo.isMultipleAlternative || 8490 (OpInfo.Type == InlineAsm::isInput)) && 8491 "Can only indirectify direct input operands!"); 8492 8493 // Memory operands really want the address of the value. 8494 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8495 8496 // There is no longer a Value* corresponding to this operand. 8497 OpInfo.CallOperandVal = nullptr; 8498 8499 // It is now an indirect operand. 8500 OpInfo.isIndirect = true; 8501 } 8502 8503 } 8504 8505 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8506 std::vector<SDValue> AsmNodeOperands; 8507 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8508 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8509 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8510 8511 // If we have a !srcloc metadata node associated with it, we want to attach 8512 // this to the ultimately generated inline asm machineinstr. To do this, we 8513 // pass in the third operand as this (potentially null) inline asm MDNode. 8514 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8515 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8516 8517 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8518 // bits as operand 3. 8519 AsmNodeOperands.push_back(DAG.getTargetConstant( 8520 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8521 8522 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8523 // this, assign virtual and physical registers for inputs and otput. 8524 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8525 // Assign Registers. 8526 SDISelAsmOperandInfo &RefOpInfo = 8527 OpInfo.isMatchingInputConstraint() 8528 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8529 : OpInfo; 8530 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8531 8532 auto DetectWriteToReservedRegister = [&]() { 8533 const MachineFunction &MF = DAG.getMachineFunction(); 8534 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8535 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8536 if (Register::isPhysicalRegister(Reg) && 8537 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8538 const char *RegName = TRI.getName(Reg); 8539 emitInlineAsmError(Call, "write to reserved register '" + 8540 Twine(RegName) + "'"); 8541 return true; 8542 } 8543 } 8544 return false; 8545 }; 8546 8547 switch (OpInfo.Type) { 8548 case InlineAsm::isOutput: 8549 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8550 unsigned ConstraintID = 8551 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8552 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8553 "Failed to convert memory constraint code to constraint id."); 8554 8555 // Add information to the INLINEASM node to know about this output. 8556 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8557 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8558 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8559 MVT::i32)); 8560 AsmNodeOperands.push_back(OpInfo.CallOperand); 8561 } else { 8562 // Otherwise, this outputs to a register (directly for C_Register / 8563 // C_RegisterClass, and a target-defined fashion for 8564 // C_Immediate/C_Other). Find a register that we can use. 8565 if (OpInfo.AssignedRegs.Regs.empty()) { 8566 emitInlineAsmError( 8567 Call, "couldn't allocate output register for constraint '" + 8568 Twine(OpInfo.ConstraintCode) + "'"); 8569 return; 8570 } 8571 8572 if (DetectWriteToReservedRegister()) 8573 return; 8574 8575 // Add information to the INLINEASM node to know that this register is 8576 // set. 8577 OpInfo.AssignedRegs.AddInlineAsmOperands( 8578 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8579 : InlineAsm::Kind_RegDef, 8580 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8581 } 8582 break; 8583 8584 case InlineAsm::isInput: { 8585 SDValue InOperandVal = OpInfo.CallOperand; 8586 8587 if (OpInfo.isMatchingInputConstraint()) { 8588 // If this is required to match an output register we have already set, 8589 // just use its register. 8590 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8591 AsmNodeOperands); 8592 unsigned OpFlag = 8593 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8594 if (InlineAsm::isRegDefKind(OpFlag) || 8595 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8596 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8597 if (OpInfo.isIndirect) { 8598 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8599 emitInlineAsmError(Call, "inline asm not supported yet: " 8600 "don't know how to handle tied " 8601 "indirect register inputs"); 8602 return; 8603 } 8604 8605 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8606 SmallVector<unsigned, 4> Regs; 8607 8608 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8609 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8610 MachineRegisterInfo &RegInfo = 8611 DAG.getMachineFunction().getRegInfo(); 8612 for (unsigned i = 0; i != NumRegs; ++i) 8613 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8614 } else { 8615 emitInlineAsmError(Call, 8616 "inline asm error: This value type register " 8617 "class is not natively supported!"); 8618 return; 8619 } 8620 8621 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8622 8623 SDLoc dl = getCurSDLoc(); 8624 // Use the produced MatchedRegs object to 8625 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8626 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8627 true, OpInfo.getMatchedOperand(), dl, 8628 DAG, AsmNodeOperands); 8629 break; 8630 } 8631 8632 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8633 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8634 "Unexpected number of operands"); 8635 // Add information to the INLINEASM node to know about this input. 8636 // See InlineAsm.h isUseOperandTiedToDef. 8637 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8638 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8639 OpInfo.getMatchedOperand()); 8640 AsmNodeOperands.push_back(DAG.getTargetConstant( 8641 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8642 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8643 break; 8644 } 8645 8646 // Treat indirect 'X' constraint as memory. 8647 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8648 OpInfo.isIndirect) 8649 OpInfo.ConstraintType = TargetLowering::C_Memory; 8650 8651 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8652 OpInfo.ConstraintType == TargetLowering::C_Other) { 8653 std::vector<SDValue> Ops; 8654 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8655 Ops, DAG); 8656 if (Ops.empty()) { 8657 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8658 if (isa<ConstantSDNode>(InOperandVal)) { 8659 emitInlineAsmError(Call, "value out of range for constraint '" + 8660 Twine(OpInfo.ConstraintCode) + "'"); 8661 return; 8662 } 8663 8664 emitInlineAsmError(Call, 8665 "invalid operand for inline asm constraint '" + 8666 Twine(OpInfo.ConstraintCode) + "'"); 8667 return; 8668 } 8669 8670 // Add information to the INLINEASM node to know about this input. 8671 unsigned ResOpType = 8672 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8673 AsmNodeOperands.push_back(DAG.getTargetConstant( 8674 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8675 llvm::append_range(AsmNodeOperands, Ops); 8676 break; 8677 } 8678 8679 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8680 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8681 assert(InOperandVal.getValueType() == 8682 TLI.getPointerTy(DAG.getDataLayout()) && 8683 "Memory operands expect pointer values"); 8684 8685 unsigned ConstraintID = 8686 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8687 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8688 "Failed to convert memory constraint code to constraint id."); 8689 8690 // Add information to the INLINEASM node to know about this input. 8691 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8692 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8693 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8694 getCurSDLoc(), 8695 MVT::i32)); 8696 AsmNodeOperands.push_back(InOperandVal); 8697 break; 8698 } 8699 8700 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8701 OpInfo.ConstraintType == TargetLowering::C_Register) && 8702 "Unknown constraint type!"); 8703 8704 // TODO: Support this. 8705 if (OpInfo.isIndirect) { 8706 emitInlineAsmError( 8707 Call, "Don't know how to handle indirect register inputs yet " 8708 "for constraint '" + 8709 Twine(OpInfo.ConstraintCode) + "'"); 8710 return; 8711 } 8712 8713 // Copy the input into the appropriate registers. 8714 if (OpInfo.AssignedRegs.Regs.empty()) { 8715 emitInlineAsmError(Call, 8716 "couldn't allocate input reg for constraint '" + 8717 Twine(OpInfo.ConstraintCode) + "'"); 8718 return; 8719 } 8720 8721 if (DetectWriteToReservedRegister()) 8722 return; 8723 8724 SDLoc dl = getCurSDLoc(); 8725 8726 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8727 &Call); 8728 8729 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8730 dl, DAG, AsmNodeOperands); 8731 break; 8732 } 8733 case InlineAsm::isClobber: 8734 // Add the clobbered value to the operand list, so that the register 8735 // allocator is aware that the physreg got clobbered. 8736 if (!OpInfo.AssignedRegs.Regs.empty()) 8737 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8738 false, 0, getCurSDLoc(), DAG, 8739 AsmNodeOperands); 8740 break; 8741 } 8742 } 8743 8744 // Finish up input operands. Set the input chain and add the flag last. 8745 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8746 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8747 8748 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8749 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8750 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8751 Flag = Chain.getValue(1); 8752 8753 // Do additional work to generate outputs. 8754 8755 SmallVector<EVT, 1> ResultVTs; 8756 SmallVector<SDValue, 1> ResultValues; 8757 SmallVector<SDValue, 8> OutChains; 8758 8759 llvm::Type *CallResultType = Call.getType(); 8760 ArrayRef<Type *> ResultTypes; 8761 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8762 ResultTypes = StructResult->elements(); 8763 else if (!CallResultType->isVoidTy()) 8764 ResultTypes = makeArrayRef(CallResultType); 8765 8766 auto CurResultType = ResultTypes.begin(); 8767 auto handleRegAssign = [&](SDValue V) { 8768 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8769 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8770 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8771 ++CurResultType; 8772 // If the type of the inline asm call site return value is different but has 8773 // same size as the type of the asm output bitcast it. One example of this 8774 // is for vectors with different width / number of elements. This can 8775 // happen for register classes that can contain multiple different value 8776 // types. The preg or vreg allocated may not have the same VT as was 8777 // expected. 8778 // 8779 // This can also happen for a return value that disagrees with the register 8780 // class it is put in, eg. a double in a general-purpose register on a 8781 // 32-bit machine. 8782 if (ResultVT != V.getValueType() && 8783 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8784 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8785 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8786 V.getValueType().isInteger()) { 8787 // If a result value was tied to an input value, the computed result 8788 // may have a wider width than the expected result. Extract the 8789 // relevant portion. 8790 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8791 } 8792 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8793 ResultVTs.push_back(ResultVT); 8794 ResultValues.push_back(V); 8795 }; 8796 8797 // Deal with output operands. 8798 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8799 if (OpInfo.Type == InlineAsm::isOutput) { 8800 SDValue Val; 8801 // Skip trivial output operands. 8802 if (OpInfo.AssignedRegs.Regs.empty()) 8803 continue; 8804 8805 switch (OpInfo.ConstraintType) { 8806 case TargetLowering::C_Register: 8807 case TargetLowering::C_RegisterClass: 8808 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8809 Chain, &Flag, &Call); 8810 break; 8811 case TargetLowering::C_Immediate: 8812 case TargetLowering::C_Other: 8813 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8814 OpInfo, DAG); 8815 break; 8816 case TargetLowering::C_Memory: 8817 break; // Already handled. 8818 case TargetLowering::C_Unknown: 8819 assert(false && "Unexpected unknown constraint"); 8820 } 8821 8822 // Indirect output manifest as stores. Record output chains. 8823 if (OpInfo.isIndirect) { 8824 const Value *Ptr = OpInfo.CallOperandVal; 8825 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8826 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8827 MachinePointerInfo(Ptr)); 8828 OutChains.push_back(Store); 8829 } else { 8830 // generate CopyFromRegs to associated registers. 8831 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8832 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8833 for (const SDValue &V : Val->op_values()) 8834 handleRegAssign(V); 8835 } else 8836 handleRegAssign(Val); 8837 } 8838 } 8839 } 8840 8841 // Set results. 8842 if (!ResultValues.empty()) { 8843 assert(CurResultType == ResultTypes.end() && 8844 "Mismatch in number of ResultTypes"); 8845 assert(ResultValues.size() == ResultTypes.size() && 8846 "Mismatch in number of output operands in asm result"); 8847 8848 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8849 DAG.getVTList(ResultVTs), ResultValues); 8850 setValue(&Call, V); 8851 } 8852 8853 // Collect store chains. 8854 if (!OutChains.empty()) 8855 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8856 8857 if (EmitEHLabels) { 8858 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 8859 } 8860 8861 // Only Update Root if inline assembly has a memory effect. 8862 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 8863 EmitEHLabels) 8864 DAG.setRoot(Chain); 8865 } 8866 8867 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8868 const Twine &Message) { 8869 LLVMContext &Ctx = *DAG.getContext(); 8870 Ctx.emitError(&Call, Message); 8871 8872 // Make sure we leave the DAG in a valid state 8873 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8874 SmallVector<EVT, 1> ValueVTs; 8875 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8876 8877 if (ValueVTs.empty()) 8878 return; 8879 8880 SmallVector<SDValue, 1> Ops; 8881 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8882 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8883 8884 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8885 } 8886 8887 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8888 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8889 MVT::Other, getRoot(), 8890 getValue(I.getArgOperand(0)), 8891 DAG.getSrcValue(I.getArgOperand(0)))); 8892 } 8893 8894 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8895 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8896 const DataLayout &DL = DAG.getDataLayout(); 8897 SDValue V = DAG.getVAArg( 8898 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8899 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8900 DL.getABITypeAlign(I.getType()).value()); 8901 DAG.setRoot(V.getValue(1)); 8902 8903 if (I.getType()->isPointerTy()) 8904 V = DAG.getPtrExtOrTrunc( 8905 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8906 setValue(&I, V); 8907 } 8908 8909 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8910 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8911 MVT::Other, getRoot(), 8912 getValue(I.getArgOperand(0)), 8913 DAG.getSrcValue(I.getArgOperand(0)))); 8914 } 8915 8916 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8917 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8918 MVT::Other, getRoot(), 8919 getValue(I.getArgOperand(0)), 8920 getValue(I.getArgOperand(1)), 8921 DAG.getSrcValue(I.getArgOperand(0)), 8922 DAG.getSrcValue(I.getArgOperand(1)))); 8923 } 8924 8925 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8926 const Instruction &I, 8927 SDValue Op) { 8928 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8929 if (!Range) 8930 return Op; 8931 8932 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8933 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8934 return Op; 8935 8936 APInt Lo = CR.getUnsignedMin(); 8937 if (!Lo.isMinValue()) 8938 return Op; 8939 8940 APInt Hi = CR.getUnsignedMax(); 8941 unsigned Bits = std::max(Hi.getActiveBits(), 8942 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8943 8944 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8945 8946 SDLoc SL = getCurSDLoc(); 8947 8948 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8949 DAG.getValueType(SmallVT)); 8950 unsigned NumVals = Op.getNode()->getNumValues(); 8951 if (NumVals == 1) 8952 return ZExt; 8953 8954 SmallVector<SDValue, 4> Ops; 8955 8956 Ops.push_back(ZExt); 8957 for (unsigned I = 1; I != NumVals; ++I) 8958 Ops.push_back(Op.getValue(I)); 8959 8960 return DAG.getMergeValues(Ops, SL); 8961 } 8962 8963 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8964 /// the call being lowered. 8965 /// 8966 /// This is a helper for lowering intrinsics that follow a target calling 8967 /// convention or require stack pointer adjustment. Only a subset of the 8968 /// intrinsic's operands need to participate in the calling convention. 8969 void SelectionDAGBuilder::populateCallLoweringInfo( 8970 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8971 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8972 bool IsPatchPoint) { 8973 TargetLowering::ArgListTy Args; 8974 Args.reserve(NumArgs); 8975 8976 // Populate the argument list. 8977 // Attributes for args start at offset 1, after the return attribute. 8978 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8979 ArgI != ArgE; ++ArgI) { 8980 const Value *V = Call->getOperand(ArgI); 8981 8982 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8983 8984 TargetLowering::ArgListEntry Entry; 8985 Entry.Node = getValue(V); 8986 Entry.Ty = V->getType(); 8987 Entry.setAttributes(Call, ArgI); 8988 Args.push_back(Entry); 8989 } 8990 8991 CLI.setDebugLoc(getCurSDLoc()) 8992 .setChain(getRoot()) 8993 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8994 .setDiscardResult(Call->use_empty()) 8995 .setIsPatchPoint(IsPatchPoint) 8996 .setIsPreallocated( 8997 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8998 } 8999 9000 /// Add a stack map intrinsic call's live variable operands to a stackmap 9001 /// or patchpoint target node's operand list. 9002 /// 9003 /// Constants are converted to TargetConstants purely as an optimization to 9004 /// avoid constant materialization and register allocation. 9005 /// 9006 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9007 /// generate addess computation nodes, and so FinalizeISel can convert the 9008 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9009 /// address materialization and register allocation, but may also be required 9010 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9011 /// alloca in the entry block, then the runtime may assume that the alloca's 9012 /// StackMap location can be read immediately after compilation and that the 9013 /// location is valid at any point during execution (this is similar to the 9014 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9015 /// only available in a register, then the runtime would need to trap when 9016 /// execution reaches the StackMap in order to read the alloca's location. 9017 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9018 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9019 SelectionDAGBuilder &Builder) { 9020 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 9021 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 9022 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 9023 Ops.push_back( 9024 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 9025 Ops.push_back( 9026 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 9027 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 9028 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 9029 Ops.push_back(Builder.DAG.getTargetFrameIndex( 9030 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 9031 } else 9032 Ops.push_back(OpVal); 9033 } 9034 } 9035 9036 /// Lower llvm.experimental.stackmap directly to its target opcode. 9037 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9038 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 9039 // [live variables...]) 9040 9041 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9042 9043 SDValue Chain, InFlag, Callee, NullPtr; 9044 SmallVector<SDValue, 32> Ops; 9045 9046 SDLoc DL = getCurSDLoc(); 9047 Callee = getValue(CI.getCalledOperand()); 9048 NullPtr = DAG.getIntPtrConstant(0, DL, true); 9049 9050 // The stackmap intrinsic only records the live variables (the arguments 9051 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9052 // intrinsic, this won't be lowered to a function call. This means we don't 9053 // have to worry about calling conventions and target specific lowering code. 9054 // Instead we perform the call lowering right here. 9055 // 9056 // chain, flag = CALLSEQ_START(chain, 0, 0) 9057 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9058 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9059 // 9060 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9061 InFlag = Chain.getValue(1); 9062 9063 // Add the <id> and <numBytes> constants. 9064 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 9065 Ops.push_back(DAG.getTargetConstant( 9066 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 9067 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 9068 Ops.push_back(DAG.getTargetConstant( 9069 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 9070 MVT::i32)); 9071 9072 // Push live variables for the stack map. 9073 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9074 9075 // We are not pushing any register mask info here on the operands list, 9076 // because the stackmap doesn't clobber anything. 9077 9078 // Push the chain and the glue flag. 9079 Ops.push_back(Chain); 9080 Ops.push_back(InFlag); 9081 9082 // Create the STACKMAP node. 9083 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9084 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9085 Chain = SDValue(SM, 0); 9086 InFlag = Chain.getValue(1); 9087 9088 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9089 9090 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9091 9092 // Set the root to the target-lowered call chain. 9093 DAG.setRoot(Chain); 9094 9095 // Inform the Frame Information that we have a stackmap in this function. 9096 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9097 } 9098 9099 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9100 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9101 const BasicBlock *EHPadBB) { 9102 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9103 // i32 <numBytes>, 9104 // i8* <target>, 9105 // i32 <numArgs>, 9106 // [Args...], 9107 // [live variables...]) 9108 9109 CallingConv::ID CC = CB.getCallingConv(); 9110 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9111 bool HasDef = !CB.getType()->isVoidTy(); 9112 SDLoc dl = getCurSDLoc(); 9113 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9114 9115 // Handle immediate and symbolic callees. 9116 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9117 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9118 /*isTarget=*/true); 9119 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9120 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9121 SDLoc(SymbolicCallee), 9122 SymbolicCallee->getValueType(0)); 9123 9124 // Get the real number of arguments participating in the call <numArgs> 9125 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9126 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9127 9128 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9129 // Intrinsics include all meta-operands up to but not including CC. 9130 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9131 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9132 "Not enough arguments provided to the patchpoint intrinsic"); 9133 9134 // For AnyRegCC the arguments are lowered later on manually. 9135 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9136 Type *ReturnTy = 9137 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9138 9139 TargetLowering::CallLoweringInfo CLI(DAG); 9140 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9141 ReturnTy, true); 9142 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9143 9144 SDNode *CallEnd = Result.second.getNode(); 9145 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9146 CallEnd = CallEnd->getOperand(0).getNode(); 9147 9148 /// Get a call instruction from the call sequence chain. 9149 /// Tail calls are not allowed. 9150 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9151 "Expected a callseq node."); 9152 SDNode *Call = CallEnd->getOperand(0).getNode(); 9153 bool HasGlue = Call->getGluedNode(); 9154 9155 // Replace the target specific call node with the patchable intrinsic. 9156 SmallVector<SDValue, 8> Ops; 9157 9158 // Add the <id> and <numBytes> constants. 9159 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9160 Ops.push_back(DAG.getTargetConstant( 9161 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9162 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9163 Ops.push_back(DAG.getTargetConstant( 9164 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9165 MVT::i32)); 9166 9167 // Add the callee. 9168 Ops.push_back(Callee); 9169 9170 // Adjust <numArgs> to account for any arguments that have been passed on the 9171 // stack instead. 9172 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9173 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9174 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9175 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9176 9177 // Add the calling convention 9178 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9179 9180 // Add the arguments we omitted previously. The register allocator should 9181 // place these in any free register. 9182 if (IsAnyRegCC) 9183 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9184 Ops.push_back(getValue(CB.getArgOperand(i))); 9185 9186 // Push the arguments from the call instruction up to the register mask. 9187 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9188 Ops.append(Call->op_begin() + 2, e); 9189 9190 // Push live variables for the stack map. 9191 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9192 9193 // Push the register mask info. 9194 if (HasGlue) 9195 Ops.push_back(*(Call->op_end()-2)); 9196 else 9197 Ops.push_back(*(Call->op_end()-1)); 9198 9199 // Push the chain (this is originally the first operand of the call, but 9200 // becomes now the last or second to last operand). 9201 Ops.push_back(*(Call->op_begin())); 9202 9203 // Push the glue flag (last operand). 9204 if (HasGlue) 9205 Ops.push_back(*(Call->op_end()-1)); 9206 9207 SDVTList NodeTys; 9208 if (IsAnyRegCC && HasDef) { 9209 // Create the return types based on the intrinsic definition 9210 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9211 SmallVector<EVT, 3> ValueVTs; 9212 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9213 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9214 9215 // There is always a chain and a glue type at the end 9216 ValueVTs.push_back(MVT::Other); 9217 ValueVTs.push_back(MVT::Glue); 9218 NodeTys = DAG.getVTList(ValueVTs); 9219 } else 9220 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9221 9222 // Replace the target specific call node with a PATCHPOINT node. 9223 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9224 dl, NodeTys, Ops); 9225 9226 // Update the NodeMap. 9227 if (HasDef) { 9228 if (IsAnyRegCC) 9229 setValue(&CB, SDValue(MN, 0)); 9230 else 9231 setValue(&CB, Result.first); 9232 } 9233 9234 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9235 // call sequence. Furthermore the location of the chain and glue can change 9236 // when the AnyReg calling convention is used and the intrinsic returns a 9237 // value. 9238 if (IsAnyRegCC && HasDef) { 9239 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9240 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9241 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9242 } else 9243 DAG.ReplaceAllUsesWith(Call, MN); 9244 DAG.DeleteNode(Call); 9245 9246 // Inform the Frame Information that we have a patchpoint in this function. 9247 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9248 } 9249 9250 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9251 unsigned Intrinsic) { 9252 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9253 SDValue Op1 = getValue(I.getArgOperand(0)); 9254 SDValue Op2; 9255 if (I.getNumArgOperands() > 1) 9256 Op2 = getValue(I.getArgOperand(1)); 9257 SDLoc dl = getCurSDLoc(); 9258 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9259 SDValue Res; 9260 SDNodeFlags SDFlags; 9261 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9262 SDFlags.copyFMF(*FPMO); 9263 9264 switch (Intrinsic) { 9265 case Intrinsic::vector_reduce_fadd: 9266 if (SDFlags.hasAllowReassociation()) 9267 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9268 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9269 SDFlags); 9270 else 9271 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9272 break; 9273 case Intrinsic::vector_reduce_fmul: 9274 if (SDFlags.hasAllowReassociation()) 9275 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9276 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9277 SDFlags); 9278 else 9279 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9280 break; 9281 case Intrinsic::vector_reduce_add: 9282 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9283 break; 9284 case Intrinsic::vector_reduce_mul: 9285 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9286 break; 9287 case Intrinsic::vector_reduce_and: 9288 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9289 break; 9290 case Intrinsic::vector_reduce_or: 9291 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9292 break; 9293 case Intrinsic::vector_reduce_xor: 9294 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9295 break; 9296 case Intrinsic::vector_reduce_smax: 9297 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9298 break; 9299 case Intrinsic::vector_reduce_smin: 9300 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9301 break; 9302 case Intrinsic::vector_reduce_umax: 9303 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9304 break; 9305 case Intrinsic::vector_reduce_umin: 9306 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9307 break; 9308 case Intrinsic::vector_reduce_fmax: 9309 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9310 break; 9311 case Intrinsic::vector_reduce_fmin: 9312 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9313 break; 9314 default: 9315 llvm_unreachable("Unhandled vector reduce intrinsic"); 9316 } 9317 setValue(&I, Res); 9318 } 9319 9320 /// Returns an AttributeList representing the attributes applied to the return 9321 /// value of the given call. 9322 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9323 SmallVector<Attribute::AttrKind, 2> Attrs; 9324 if (CLI.RetSExt) 9325 Attrs.push_back(Attribute::SExt); 9326 if (CLI.RetZExt) 9327 Attrs.push_back(Attribute::ZExt); 9328 if (CLI.IsInReg) 9329 Attrs.push_back(Attribute::InReg); 9330 9331 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9332 Attrs); 9333 } 9334 9335 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9336 /// implementation, which just calls LowerCall. 9337 /// FIXME: When all targets are 9338 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9339 std::pair<SDValue, SDValue> 9340 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9341 // Handle the incoming return values from the call. 9342 CLI.Ins.clear(); 9343 Type *OrigRetTy = CLI.RetTy; 9344 SmallVector<EVT, 4> RetTys; 9345 SmallVector<uint64_t, 4> Offsets; 9346 auto &DL = CLI.DAG.getDataLayout(); 9347 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9348 9349 if (CLI.IsPostTypeLegalization) { 9350 // If we are lowering a libcall after legalization, split the return type. 9351 SmallVector<EVT, 4> OldRetTys; 9352 SmallVector<uint64_t, 4> OldOffsets; 9353 RetTys.swap(OldRetTys); 9354 Offsets.swap(OldOffsets); 9355 9356 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9357 EVT RetVT = OldRetTys[i]; 9358 uint64_t Offset = OldOffsets[i]; 9359 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9360 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9361 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9362 RetTys.append(NumRegs, RegisterVT); 9363 for (unsigned j = 0; j != NumRegs; ++j) 9364 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9365 } 9366 } 9367 9368 SmallVector<ISD::OutputArg, 4> Outs; 9369 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9370 9371 bool CanLowerReturn = 9372 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9373 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9374 9375 SDValue DemoteStackSlot; 9376 int DemoteStackIdx = -100; 9377 if (!CanLowerReturn) { 9378 // FIXME: equivalent assert? 9379 // assert(!CS.hasInAllocaArgument() && 9380 // "sret demotion is incompatible with inalloca"); 9381 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9382 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9383 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9384 DemoteStackIdx = 9385 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9386 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9387 DL.getAllocaAddrSpace()); 9388 9389 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9390 ArgListEntry Entry; 9391 Entry.Node = DemoteStackSlot; 9392 Entry.Ty = StackSlotPtrType; 9393 Entry.IsSExt = false; 9394 Entry.IsZExt = false; 9395 Entry.IsInReg = false; 9396 Entry.IsSRet = true; 9397 Entry.IsNest = false; 9398 Entry.IsByVal = false; 9399 Entry.IsByRef = false; 9400 Entry.IsReturned = false; 9401 Entry.IsSwiftSelf = false; 9402 Entry.IsSwiftAsync = false; 9403 Entry.IsSwiftError = false; 9404 Entry.IsCFGuardTarget = false; 9405 Entry.Alignment = Alignment; 9406 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9407 CLI.NumFixedArgs += 1; 9408 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9409 9410 // sret demotion isn't compatible with tail-calls, since the sret argument 9411 // points into the callers stack frame. 9412 CLI.IsTailCall = false; 9413 } else { 9414 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9415 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9416 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9417 ISD::ArgFlagsTy Flags; 9418 if (NeedsRegBlock) { 9419 Flags.setInConsecutiveRegs(); 9420 if (I == RetTys.size() - 1) 9421 Flags.setInConsecutiveRegsLast(); 9422 } 9423 EVT VT = RetTys[I]; 9424 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9425 CLI.CallConv, VT); 9426 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9427 CLI.CallConv, VT); 9428 for (unsigned i = 0; i != NumRegs; ++i) { 9429 ISD::InputArg MyFlags; 9430 MyFlags.Flags = Flags; 9431 MyFlags.VT = RegisterVT; 9432 MyFlags.ArgVT = VT; 9433 MyFlags.Used = CLI.IsReturnValueUsed; 9434 if (CLI.RetTy->isPointerTy()) { 9435 MyFlags.Flags.setPointer(); 9436 MyFlags.Flags.setPointerAddrSpace( 9437 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9438 } 9439 if (CLI.RetSExt) 9440 MyFlags.Flags.setSExt(); 9441 if (CLI.RetZExt) 9442 MyFlags.Flags.setZExt(); 9443 if (CLI.IsInReg) 9444 MyFlags.Flags.setInReg(); 9445 CLI.Ins.push_back(MyFlags); 9446 } 9447 } 9448 } 9449 9450 // We push in swifterror return as the last element of CLI.Ins. 9451 ArgListTy &Args = CLI.getArgs(); 9452 if (supportSwiftError()) { 9453 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9454 if (Args[i].IsSwiftError) { 9455 ISD::InputArg MyFlags; 9456 MyFlags.VT = getPointerTy(DL); 9457 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9458 MyFlags.Flags.setSwiftError(); 9459 CLI.Ins.push_back(MyFlags); 9460 } 9461 } 9462 } 9463 9464 // Handle all of the outgoing arguments. 9465 CLI.Outs.clear(); 9466 CLI.OutVals.clear(); 9467 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9468 SmallVector<EVT, 4> ValueVTs; 9469 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9470 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9471 Type *FinalType = Args[i].Ty; 9472 if (Args[i].IsByVal) 9473 FinalType = Args[i].IndirectType; 9474 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9475 FinalType, CLI.CallConv, CLI.IsVarArg); 9476 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9477 ++Value) { 9478 EVT VT = ValueVTs[Value]; 9479 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9480 SDValue Op = SDValue(Args[i].Node.getNode(), 9481 Args[i].Node.getResNo() + Value); 9482 ISD::ArgFlagsTy Flags; 9483 9484 // Certain targets (such as MIPS), may have a different ABI alignment 9485 // for a type depending on the context. Give the target a chance to 9486 // specify the alignment it wants. 9487 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9488 Flags.setOrigAlign(OriginalAlignment); 9489 9490 if (Args[i].Ty->isPointerTy()) { 9491 Flags.setPointer(); 9492 Flags.setPointerAddrSpace( 9493 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9494 } 9495 if (Args[i].IsZExt) 9496 Flags.setZExt(); 9497 if (Args[i].IsSExt) 9498 Flags.setSExt(); 9499 if (Args[i].IsInReg) { 9500 // If we are using vectorcall calling convention, a structure that is 9501 // passed InReg - is surely an HVA 9502 if (CLI.CallConv == CallingConv::X86_VectorCall && 9503 isa<StructType>(FinalType)) { 9504 // The first value of a structure is marked 9505 if (0 == Value) 9506 Flags.setHvaStart(); 9507 Flags.setHva(); 9508 } 9509 // Set InReg Flag 9510 Flags.setInReg(); 9511 } 9512 if (Args[i].IsSRet) 9513 Flags.setSRet(); 9514 if (Args[i].IsSwiftSelf) 9515 Flags.setSwiftSelf(); 9516 if (Args[i].IsSwiftAsync) 9517 Flags.setSwiftAsync(); 9518 if (Args[i].IsSwiftError) 9519 Flags.setSwiftError(); 9520 if (Args[i].IsCFGuardTarget) 9521 Flags.setCFGuardTarget(); 9522 if (Args[i].IsByVal) 9523 Flags.setByVal(); 9524 if (Args[i].IsByRef) 9525 Flags.setByRef(); 9526 if (Args[i].IsPreallocated) { 9527 Flags.setPreallocated(); 9528 // Set the byval flag for CCAssignFn callbacks that don't know about 9529 // preallocated. This way we can know how many bytes we should've 9530 // allocated and how many bytes a callee cleanup function will pop. If 9531 // we port preallocated to more targets, we'll have to add custom 9532 // preallocated handling in the various CC lowering callbacks. 9533 Flags.setByVal(); 9534 } 9535 if (Args[i].IsInAlloca) { 9536 Flags.setInAlloca(); 9537 // Set the byval flag for CCAssignFn callbacks that don't know about 9538 // inalloca. This way we can know how many bytes we should've allocated 9539 // and how many bytes a callee cleanup function will pop. If we port 9540 // inalloca to more targets, we'll have to add custom inalloca handling 9541 // in the various CC lowering callbacks. 9542 Flags.setByVal(); 9543 } 9544 Align MemAlign; 9545 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9546 Type *ElementTy = Args[i].IndirectType; 9547 assert(ElementTy && "Indirect type not set in ArgListEntry"); 9548 9549 unsigned FrameSize = DL.getTypeAllocSize(ElementTy); 9550 Flags.setByValSize(FrameSize); 9551 9552 // info is not there but there are cases it cannot get right. 9553 if (auto MA = Args[i].Alignment) 9554 MemAlign = *MA; 9555 else 9556 MemAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9557 } else if (auto MA = Args[i].Alignment) { 9558 MemAlign = *MA; 9559 } else { 9560 MemAlign = OriginalAlignment; 9561 } 9562 Flags.setMemAlign(MemAlign); 9563 if (Args[i].IsNest) 9564 Flags.setNest(); 9565 if (NeedsRegBlock) 9566 Flags.setInConsecutiveRegs(); 9567 9568 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9569 CLI.CallConv, VT); 9570 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9571 CLI.CallConv, VT); 9572 SmallVector<SDValue, 4> Parts(NumParts); 9573 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9574 9575 if (Args[i].IsSExt) 9576 ExtendKind = ISD::SIGN_EXTEND; 9577 else if (Args[i].IsZExt) 9578 ExtendKind = ISD::ZERO_EXTEND; 9579 9580 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9581 // for now. 9582 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9583 CanLowerReturn) { 9584 assert((CLI.RetTy == Args[i].Ty || 9585 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9586 CLI.RetTy->getPointerAddressSpace() == 9587 Args[i].Ty->getPointerAddressSpace())) && 9588 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9589 // Before passing 'returned' to the target lowering code, ensure that 9590 // either the register MVT and the actual EVT are the same size or that 9591 // the return value and argument are extended in the same way; in these 9592 // cases it's safe to pass the argument register value unchanged as the 9593 // return register value (although it's at the target's option whether 9594 // to do so) 9595 // TODO: allow code generation to take advantage of partially preserved 9596 // registers rather than clobbering the entire register when the 9597 // parameter extension method is not compatible with the return 9598 // extension method 9599 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9600 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9601 CLI.RetZExt == Args[i].IsZExt)) 9602 Flags.setReturned(); 9603 } 9604 9605 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9606 CLI.CallConv, ExtendKind); 9607 9608 for (unsigned j = 0; j != NumParts; ++j) { 9609 // if it isn't first piece, alignment must be 1 9610 // For scalable vectors the scalable part is currently handled 9611 // by individual targets, so we just use the known minimum size here. 9612 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9613 i < CLI.NumFixedArgs, i, 9614 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9615 if (NumParts > 1 && j == 0) 9616 MyFlags.Flags.setSplit(); 9617 else if (j != 0) { 9618 MyFlags.Flags.setOrigAlign(Align(1)); 9619 if (j == NumParts - 1) 9620 MyFlags.Flags.setSplitEnd(); 9621 } 9622 9623 CLI.Outs.push_back(MyFlags); 9624 CLI.OutVals.push_back(Parts[j]); 9625 } 9626 9627 if (NeedsRegBlock && Value == NumValues - 1) 9628 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9629 } 9630 } 9631 9632 SmallVector<SDValue, 4> InVals; 9633 CLI.Chain = LowerCall(CLI, InVals); 9634 9635 // Update CLI.InVals to use outside of this function. 9636 CLI.InVals = InVals; 9637 9638 // Verify that the target's LowerCall behaved as expected. 9639 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9640 "LowerCall didn't return a valid chain!"); 9641 assert((!CLI.IsTailCall || InVals.empty()) && 9642 "LowerCall emitted a return value for a tail call!"); 9643 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9644 "LowerCall didn't emit the correct number of values!"); 9645 9646 // For a tail call, the return value is merely live-out and there aren't 9647 // any nodes in the DAG representing it. Return a special value to 9648 // indicate that a tail call has been emitted and no more Instructions 9649 // should be processed in the current block. 9650 if (CLI.IsTailCall) { 9651 CLI.DAG.setRoot(CLI.Chain); 9652 return std::make_pair(SDValue(), SDValue()); 9653 } 9654 9655 #ifndef NDEBUG 9656 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9657 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9658 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9659 "LowerCall emitted a value with the wrong type!"); 9660 } 9661 #endif 9662 9663 SmallVector<SDValue, 4> ReturnValues; 9664 if (!CanLowerReturn) { 9665 // The instruction result is the result of loading from the 9666 // hidden sret parameter. 9667 SmallVector<EVT, 1> PVTs; 9668 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9669 9670 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9671 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9672 EVT PtrVT = PVTs[0]; 9673 9674 unsigned NumValues = RetTys.size(); 9675 ReturnValues.resize(NumValues); 9676 SmallVector<SDValue, 4> Chains(NumValues); 9677 9678 // An aggregate return value cannot wrap around the address space, so 9679 // offsets to its parts don't wrap either. 9680 SDNodeFlags Flags; 9681 Flags.setNoUnsignedWrap(true); 9682 9683 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9684 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9685 for (unsigned i = 0; i < NumValues; ++i) { 9686 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9687 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9688 PtrVT), Flags); 9689 SDValue L = CLI.DAG.getLoad( 9690 RetTys[i], CLI.DL, CLI.Chain, Add, 9691 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9692 DemoteStackIdx, Offsets[i]), 9693 HiddenSRetAlign); 9694 ReturnValues[i] = L; 9695 Chains[i] = L.getValue(1); 9696 } 9697 9698 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9699 } else { 9700 // Collect the legal value parts into potentially illegal values 9701 // that correspond to the original function's return values. 9702 Optional<ISD::NodeType> AssertOp; 9703 if (CLI.RetSExt) 9704 AssertOp = ISD::AssertSext; 9705 else if (CLI.RetZExt) 9706 AssertOp = ISD::AssertZext; 9707 unsigned CurReg = 0; 9708 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9709 EVT VT = RetTys[I]; 9710 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9711 CLI.CallConv, VT); 9712 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9713 CLI.CallConv, VT); 9714 9715 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9716 NumRegs, RegisterVT, VT, nullptr, 9717 CLI.CallConv, AssertOp)); 9718 CurReg += NumRegs; 9719 } 9720 9721 // For a function returning void, there is no return value. We can't create 9722 // such a node, so we just return a null return value in that case. In 9723 // that case, nothing will actually look at the value. 9724 if (ReturnValues.empty()) 9725 return std::make_pair(SDValue(), CLI.Chain); 9726 } 9727 9728 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9729 CLI.DAG.getVTList(RetTys), ReturnValues); 9730 return std::make_pair(Res, CLI.Chain); 9731 } 9732 9733 /// Places new result values for the node in Results (their number 9734 /// and types must exactly match those of the original return values of 9735 /// the node), or leaves Results empty, which indicates that the node is not 9736 /// to be custom lowered after all. 9737 void TargetLowering::LowerOperationWrapper(SDNode *N, 9738 SmallVectorImpl<SDValue> &Results, 9739 SelectionDAG &DAG) const { 9740 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9741 9742 if (!Res.getNode()) 9743 return; 9744 9745 // If the original node has one result, take the return value from 9746 // LowerOperation as is. It might not be result number 0. 9747 if (N->getNumValues() == 1) { 9748 Results.push_back(Res); 9749 return; 9750 } 9751 9752 // If the original node has multiple results, then the return node should 9753 // have the same number of results. 9754 assert((N->getNumValues() == Res->getNumValues()) && 9755 "Lowering returned the wrong number of results!"); 9756 9757 // Places new result values base on N result number. 9758 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9759 Results.push_back(Res.getValue(I)); 9760 } 9761 9762 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9763 llvm_unreachable("LowerOperation not implemented for this target!"); 9764 } 9765 9766 void 9767 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9768 SDValue Op = getNonRegisterValue(V); 9769 assert((Op.getOpcode() != ISD::CopyFromReg || 9770 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9771 "Copy from a reg to the same reg!"); 9772 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9773 9774 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9775 // If this is an InlineAsm we have to match the registers required, not the 9776 // notional registers required by the type. 9777 9778 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9779 None); // This is not an ABI copy. 9780 SDValue Chain = DAG.getEntryNode(); 9781 9782 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9783 FuncInfo.PreferredExtendType.end()) 9784 ? ISD::ANY_EXTEND 9785 : FuncInfo.PreferredExtendType[V]; 9786 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9787 PendingExports.push_back(Chain); 9788 } 9789 9790 #include "llvm/CodeGen/SelectionDAGISel.h" 9791 9792 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9793 /// entry block, return true. This includes arguments used by switches, since 9794 /// the switch may expand into multiple basic blocks. 9795 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9796 // With FastISel active, we may be splitting blocks, so force creation 9797 // of virtual registers for all non-dead arguments. 9798 if (FastISel) 9799 return A->use_empty(); 9800 9801 const BasicBlock &Entry = A->getParent()->front(); 9802 for (const User *U : A->users()) 9803 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9804 return false; // Use not in entry block. 9805 9806 return true; 9807 } 9808 9809 using ArgCopyElisionMapTy = 9810 DenseMap<const Argument *, 9811 std::pair<const AllocaInst *, const StoreInst *>>; 9812 9813 /// Scan the entry block of the function in FuncInfo for arguments that look 9814 /// like copies into a local alloca. Record any copied arguments in 9815 /// ArgCopyElisionCandidates. 9816 static void 9817 findArgumentCopyElisionCandidates(const DataLayout &DL, 9818 FunctionLoweringInfo *FuncInfo, 9819 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9820 // Record the state of every static alloca used in the entry block. Argument 9821 // allocas are all used in the entry block, so we need approximately as many 9822 // entries as we have arguments. 9823 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9824 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9825 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9826 StaticAllocas.reserve(NumArgs * 2); 9827 9828 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9829 if (!V) 9830 return nullptr; 9831 V = V->stripPointerCasts(); 9832 const auto *AI = dyn_cast<AllocaInst>(V); 9833 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9834 return nullptr; 9835 auto Iter = StaticAllocas.insert({AI, Unknown}); 9836 return &Iter.first->second; 9837 }; 9838 9839 // Look for stores of arguments to static allocas. Look through bitcasts and 9840 // GEPs to handle type coercions, as long as the alloca is fully initialized 9841 // by the store. Any non-store use of an alloca escapes it and any subsequent 9842 // unanalyzed store might write it. 9843 // FIXME: Handle structs initialized with multiple stores. 9844 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9845 // Look for stores, and handle non-store uses conservatively. 9846 const auto *SI = dyn_cast<StoreInst>(&I); 9847 if (!SI) { 9848 // We will look through cast uses, so ignore them completely. 9849 if (I.isCast()) 9850 continue; 9851 // Ignore debug info and pseudo op intrinsics, they don't escape or store 9852 // to allocas. 9853 if (I.isDebugOrPseudoInst()) 9854 continue; 9855 // This is an unknown instruction. Assume it escapes or writes to all 9856 // static alloca operands. 9857 for (const Use &U : I.operands()) { 9858 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9859 *Info = StaticAllocaInfo::Clobbered; 9860 } 9861 continue; 9862 } 9863 9864 // If the stored value is a static alloca, mark it as escaped. 9865 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9866 *Info = StaticAllocaInfo::Clobbered; 9867 9868 // Check if the destination is a static alloca. 9869 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9870 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9871 if (!Info) 9872 continue; 9873 const AllocaInst *AI = cast<AllocaInst>(Dst); 9874 9875 // Skip allocas that have been initialized or clobbered. 9876 if (*Info != StaticAllocaInfo::Unknown) 9877 continue; 9878 9879 // Check if the stored value is an argument, and that this store fully 9880 // initializes the alloca. Don't elide copies from the same argument twice. 9881 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9882 const auto *Arg = dyn_cast<Argument>(Val); 9883 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9884 Arg->getType()->isEmptyTy() || 9885 DL.getTypeStoreSize(Arg->getType()) != 9886 DL.getTypeAllocSize(AI->getAllocatedType()) || 9887 ArgCopyElisionCandidates.count(Arg)) { 9888 *Info = StaticAllocaInfo::Clobbered; 9889 continue; 9890 } 9891 9892 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9893 << '\n'); 9894 9895 // Mark this alloca and store for argument copy elision. 9896 *Info = StaticAllocaInfo::Elidable; 9897 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9898 9899 // Stop scanning if we've seen all arguments. This will happen early in -O0 9900 // builds, which is useful, because -O0 builds have large entry blocks and 9901 // many allocas. 9902 if (ArgCopyElisionCandidates.size() == NumArgs) 9903 break; 9904 } 9905 } 9906 9907 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9908 /// ArgVal is a load from a suitable fixed stack object. 9909 static void tryToElideArgumentCopy( 9910 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9911 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9912 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9913 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9914 SDValue ArgVal, bool &ArgHasUses) { 9915 // Check if this is a load from a fixed stack object. 9916 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9917 if (!LNode) 9918 return; 9919 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9920 if (!FINode) 9921 return; 9922 9923 // Check that the fixed stack object is the right size and alignment. 9924 // Look at the alignment that the user wrote on the alloca instead of looking 9925 // at the stack object. 9926 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9927 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9928 const AllocaInst *AI = ArgCopyIter->second.first; 9929 int FixedIndex = FINode->getIndex(); 9930 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9931 int OldIndex = AllocaIndex; 9932 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9933 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9934 LLVM_DEBUG( 9935 dbgs() << " argument copy elision failed due to bad fixed stack " 9936 "object size\n"); 9937 return; 9938 } 9939 Align RequiredAlignment = AI->getAlign(); 9940 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9941 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9942 "greater than stack argument alignment (" 9943 << DebugStr(RequiredAlignment) << " vs " 9944 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9945 return; 9946 } 9947 9948 // Perform the elision. Delete the old stack object and replace its only use 9949 // in the variable info map. Mark the stack object as mutable. 9950 LLVM_DEBUG({ 9951 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9952 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9953 << '\n'; 9954 }); 9955 MFI.RemoveStackObject(OldIndex); 9956 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9957 AllocaIndex = FixedIndex; 9958 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9959 Chains.push_back(ArgVal.getValue(1)); 9960 9961 // Avoid emitting code for the store implementing the copy. 9962 const StoreInst *SI = ArgCopyIter->second.second; 9963 ElidedArgCopyInstrs.insert(SI); 9964 9965 // Check for uses of the argument again so that we can avoid exporting ArgVal 9966 // if it is't used by anything other than the store. 9967 for (const Value *U : Arg.users()) { 9968 if (U != SI) { 9969 ArgHasUses = true; 9970 break; 9971 } 9972 } 9973 } 9974 9975 void SelectionDAGISel::LowerArguments(const Function &F) { 9976 SelectionDAG &DAG = SDB->DAG; 9977 SDLoc dl = SDB->getCurSDLoc(); 9978 const DataLayout &DL = DAG.getDataLayout(); 9979 SmallVector<ISD::InputArg, 16> Ins; 9980 9981 // In Naked functions we aren't going to save any registers. 9982 if (F.hasFnAttribute(Attribute::Naked)) 9983 return; 9984 9985 if (!FuncInfo->CanLowerReturn) { 9986 // Put in an sret pointer parameter before all the other parameters. 9987 SmallVector<EVT, 1> ValueVTs; 9988 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9989 F.getReturnType()->getPointerTo( 9990 DAG.getDataLayout().getAllocaAddrSpace()), 9991 ValueVTs); 9992 9993 // NOTE: Assuming that a pointer will never break down to more than one VT 9994 // or one register. 9995 ISD::ArgFlagsTy Flags; 9996 Flags.setSRet(); 9997 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9998 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9999 ISD::InputArg::NoArgIndex, 0); 10000 Ins.push_back(RetArg); 10001 } 10002 10003 // Look for stores of arguments to static allocas. Mark such arguments with a 10004 // flag to ask the target to give us the memory location of that argument if 10005 // available. 10006 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10007 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10008 ArgCopyElisionCandidates); 10009 10010 // Set up the incoming argument description vector. 10011 for (const Argument &Arg : F.args()) { 10012 unsigned ArgNo = Arg.getArgNo(); 10013 SmallVector<EVT, 4> ValueVTs; 10014 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10015 bool isArgValueUsed = !Arg.use_empty(); 10016 unsigned PartBase = 0; 10017 Type *FinalType = Arg.getType(); 10018 if (Arg.hasAttribute(Attribute::ByVal)) 10019 FinalType = Arg.getParamByValType(); 10020 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10021 FinalType, F.getCallingConv(), F.isVarArg()); 10022 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10023 Value != NumValues; ++Value) { 10024 EVT VT = ValueVTs[Value]; 10025 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10026 ISD::ArgFlagsTy Flags; 10027 10028 10029 if (Arg.getType()->isPointerTy()) { 10030 Flags.setPointer(); 10031 Flags.setPointerAddrSpace( 10032 cast<PointerType>(Arg.getType())->getAddressSpace()); 10033 } 10034 if (Arg.hasAttribute(Attribute::ZExt)) 10035 Flags.setZExt(); 10036 if (Arg.hasAttribute(Attribute::SExt)) 10037 Flags.setSExt(); 10038 if (Arg.hasAttribute(Attribute::InReg)) { 10039 // If we are using vectorcall calling convention, a structure that is 10040 // passed InReg - is surely an HVA 10041 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10042 isa<StructType>(Arg.getType())) { 10043 // The first value of a structure is marked 10044 if (0 == Value) 10045 Flags.setHvaStart(); 10046 Flags.setHva(); 10047 } 10048 // Set InReg Flag 10049 Flags.setInReg(); 10050 } 10051 if (Arg.hasAttribute(Attribute::StructRet)) 10052 Flags.setSRet(); 10053 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10054 Flags.setSwiftSelf(); 10055 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10056 Flags.setSwiftAsync(); 10057 if (Arg.hasAttribute(Attribute::SwiftError)) 10058 Flags.setSwiftError(); 10059 if (Arg.hasAttribute(Attribute::ByVal)) 10060 Flags.setByVal(); 10061 if (Arg.hasAttribute(Attribute::ByRef)) 10062 Flags.setByRef(); 10063 if (Arg.hasAttribute(Attribute::InAlloca)) { 10064 Flags.setInAlloca(); 10065 // Set the byval flag for CCAssignFn callbacks that don't know about 10066 // inalloca. This way we can know how many bytes we should've allocated 10067 // and how many bytes a callee cleanup function will pop. If we port 10068 // inalloca to more targets, we'll have to add custom inalloca handling 10069 // in the various CC lowering callbacks. 10070 Flags.setByVal(); 10071 } 10072 if (Arg.hasAttribute(Attribute::Preallocated)) { 10073 Flags.setPreallocated(); 10074 // Set the byval flag for CCAssignFn callbacks that don't know about 10075 // preallocated. This way we can know how many bytes we should've 10076 // allocated and how many bytes a callee cleanup function will pop. If 10077 // we port preallocated to more targets, we'll have to add custom 10078 // preallocated handling in the various CC lowering callbacks. 10079 Flags.setByVal(); 10080 } 10081 10082 // Certain targets (such as MIPS), may have a different ABI alignment 10083 // for a type depending on the context. Give the target a chance to 10084 // specify the alignment it wants. 10085 const Align OriginalAlignment( 10086 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10087 Flags.setOrigAlign(OriginalAlignment); 10088 10089 Align MemAlign; 10090 Type *ArgMemTy = nullptr; 10091 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10092 Flags.isByRef()) { 10093 if (!ArgMemTy) 10094 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10095 10096 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10097 10098 // For in-memory arguments, size and alignment should be passed from FE. 10099 // BE will guess if this info is not there but there are cases it cannot 10100 // get right. 10101 if (auto ParamAlign = Arg.getParamStackAlign()) 10102 MemAlign = *ParamAlign; 10103 else if ((ParamAlign = Arg.getParamAlign())) 10104 MemAlign = *ParamAlign; 10105 else 10106 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10107 if (Flags.isByRef()) 10108 Flags.setByRefSize(MemSize); 10109 else 10110 Flags.setByValSize(MemSize); 10111 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10112 MemAlign = *ParamAlign; 10113 } else { 10114 MemAlign = OriginalAlignment; 10115 } 10116 Flags.setMemAlign(MemAlign); 10117 10118 if (Arg.hasAttribute(Attribute::Nest)) 10119 Flags.setNest(); 10120 if (NeedsRegBlock) 10121 Flags.setInConsecutiveRegs(); 10122 if (ArgCopyElisionCandidates.count(&Arg)) 10123 Flags.setCopyElisionCandidate(); 10124 if (Arg.hasAttribute(Attribute::Returned)) 10125 Flags.setReturned(); 10126 10127 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10128 *CurDAG->getContext(), F.getCallingConv(), VT); 10129 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10130 *CurDAG->getContext(), F.getCallingConv(), VT); 10131 for (unsigned i = 0; i != NumRegs; ++i) { 10132 // For scalable vectors, use the minimum size; individual targets 10133 // are responsible for handling scalable vector arguments and 10134 // return values. 10135 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10136 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10137 if (NumRegs > 1 && i == 0) 10138 MyFlags.Flags.setSplit(); 10139 // if it isn't first piece, alignment must be 1 10140 else if (i > 0) { 10141 MyFlags.Flags.setOrigAlign(Align(1)); 10142 if (i == NumRegs - 1) 10143 MyFlags.Flags.setSplitEnd(); 10144 } 10145 Ins.push_back(MyFlags); 10146 } 10147 if (NeedsRegBlock && Value == NumValues - 1) 10148 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10149 PartBase += VT.getStoreSize().getKnownMinSize(); 10150 } 10151 } 10152 10153 // Call the target to set up the argument values. 10154 SmallVector<SDValue, 8> InVals; 10155 SDValue NewRoot = TLI->LowerFormalArguments( 10156 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10157 10158 // Verify that the target's LowerFormalArguments behaved as expected. 10159 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10160 "LowerFormalArguments didn't return a valid chain!"); 10161 assert(InVals.size() == Ins.size() && 10162 "LowerFormalArguments didn't emit the correct number of values!"); 10163 LLVM_DEBUG({ 10164 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10165 assert(InVals[i].getNode() && 10166 "LowerFormalArguments emitted a null value!"); 10167 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10168 "LowerFormalArguments emitted a value with the wrong type!"); 10169 } 10170 }); 10171 10172 // Update the DAG with the new chain value resulting from argument lowering. 10173 DAG.setRoot(NewRoot); 10174 10175 // Set up the argument values. 10176 unsigned i = 0; 10177 if (!FuncInfo->CanLowerReturn) { 10178 // Create a virtual register for the sret pointer, and put in a copy 10179 // from the sret argument into it. 10180 SmallVector<EVT, 1> ValueVTs; 10181 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10182 F.getReturnType()->getPointerTo( 10183 DAG.getDataLayout().getAllocaAddrSpace()), 10184 ValueVTs); 10185 MVT VT = ValueVTs[0].getSimpleVT(); 10186 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10187 Optional<ISD::NodeType> AssertOp = None; 10188 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10189 nullptr, F.getCallingConv(), AssertOp); 10190 10191 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10192 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10193 Register SRetReg = 10194 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10195 FuncInfo->DemoteRegister = SRetReg; 10196 NewRoot = 10197 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10198 DAG.setRoot(NewRoot); 10199 10200 // i indexes lowered arguments. Bump it past the hidden sret argument. 10201 ++i; 10202 } 10203 10204 SmallVector<SDValue, 4> Chains; 10205 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10206 for (const Argument &Arg : F.args()) { 10207 SmallVector<SDValue, 4> ArgValues; 10208 SmallVector<EVT, 4> ValueVTs; 10209 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10210 unsigned NumValues = ValueVTs.size(); 10211 if (NumValues == 0) 10212 continue; 10213 10214 bool ArgHasUses = !Arg.use_empty(); 10215 10216 // Elide the copying store if the target loaded this argument from a 10217 // suitable fixed stack object. 10218 if (Ins[i].Flags.isCopyElisionCandidate()) { 10219 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10220 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10221 InVals[i], ArgHasUses); 10222 } 10223 10224 // If this argument is unused then remember its value. It is used to generate 10225 // debugging information. 10226 bool isSwiftErrorArg = 10227 TLI->supportSwiftError() && 10228 Arg.hasAttribute(Attribute::SwiftError); 10229 if (!ArgHasUses && !isSwiftErrorArg) { 10230 SDB->setUnusedArgValue(&Arg, InVals[i]); 10231 10232 // Also remember any frame index for use in FastISel. 10233 if (FrameIndexSDNode *FI = 10234 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10235 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10236 } 10237 10238 for (unsigned Val = 0; Val != NumValues; ++Val) { 10239 EVT VT = ValueVTs[Val]; 10240 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10241 F.getCallingConv(), VT); 10242 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10243 *CurDAG->getContext(), F.getCallingConv(), VT); 10244 10245 // Even an apparent 'unused' swifterror argument needs to be returned. So 10246 // we do generate a copy for it that can be used on return from the 10247 // function. 10248 if (ArgHasUses || isSwiftErrorArg) { 10249 Optional<ISD::NodeType> AssertOp; 10250 if (Arg.hasAttribute(Attribute::SExt)) 10251 AssertOp = ISD::AssertSext; 10252 else if (Arg.hasAttribute(Attribute::ZExt)) 10253 AssertOp = ISD::AssertZext; 10254 10255 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10256 PartVT, VT, nullptr, 10257 F.getCallingConv(), AssertOp)); 10258 } 10259 10260 i += NumParts; 10261 } 10262 10263 // We don't need to do anything else for unused arguments. 10264 if (ArgValues.empty()) 10265 continue; 10266 10267 // Note down frame index. 10268 if (FrameIndexSDNode *FI = 10269 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10270 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10271 10272 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10273 SDB->getCurSDLoc()); 10274 10275 SDB->setValue(&Arg, Res); 10276 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10277 // We want to associate the argument with the frame index, among 10278 // involved operands, that correspond to the lowest address. The 10279 // getCopyFromParts function, called earlier, is swapping the order of 10280 // the operands to BUILD_PAIR depending on endianness. The result of 10281 // that swapping is that the least significant bits of the argument will 10282 // be in the first operand of the BUILD_PAIR node, and the most 10283 // significant bits will be in the second operand. 10284 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10285 if (LoadSDNode *LNode = 10286 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10287 if (FrameIndexSDNode *FI = 10288 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10289 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10290 } 10291 10292 // Analyses past this point are naive and don't expect an assertion. 10293 if (Res.getOpcode() == ISD::AssertZext) 10294 Res = Res.getOperand(0); 10295 10296 // Update the SwiftErrorVRegDefMap. 10297 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10298 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10299 if (Register::isVirtualRegister(Reg)) 10300 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10301 Reg); 10302 } 10303 10304 // If this argument is live outside of the entry block, insert a copy from 10305 // wherever we got it to the vreg that other BB's will reference it as. 10306 if (Res.getOpcode() == ISD::CopyFromReg) { 10307 // If we can, though, try to skip creating an unnecessary vreg. 10308 // FIXME: This isn't very clean... it would be nice to make this more 10309 // general. 10310 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10311 if (Register::isVirtualRegister(Reg)) { 10312 FuncInfo->ValueMap[&Arg] = Reg; 10313 continue; 10314 } 10315 } 10316 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10317 FuncInfo->InitializeRegForValue(&Arg); 10318 SDB->CopyToExportRegsIfNeeded(&Arg); 10319 } 10320 } 10321 10322 if (!Chains.empty()) { 10323 Chains.push_back(NewRoot); 10324 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10325 } 10326 10327 DAG.setRoot(NewRoot); 10328 10329 assert(i == InVals.size() && "Argument register count mismatch!"); 10330 10331 // If any argument copy elisions occurred and we have debug info, update the 10332 // stale frame indices used in the dbg.declare variable info table. 10333 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10334 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10335 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10336 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10337 if (I != ArgCopyElisionFrameIndexMap.end()) 10338 VI.Slot = I->second; 10339 } 10340 } 10341 10342 // Finally, if the target has anything special to do, allow it to do so. 10343 emitFunctionEntryCode(); 10344 } 10345 10346 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10347 /// ensure constants are generated when needed. Remember the virtual registers 10348 /// that need to be added to the Machine PHI nodes as input. We cannot just 10349 /// directly add them, because expansion might result in multiple MBB's for one 10350 /// BB. As such, the start of the BB might correspond to a different MBB than 10351 /// the end. 10352 void 10353 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10354 const Instruction *TI = LLVMBB->getTerminator(); 10355 10356 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10357 10358 // Check PHI nodes in successors that expect a value to be available from this 10359 // block. 10360 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10361 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10362 if (!isa<PHINode>(SuccBB->begin())) continue; 10363 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10364 10365 // If this terminator has multiple identical successors (common for 10366 // switches), only handle each succ once. 10367 if (!SuccsHandled.insert(SuccMBB).second) 10368 continue; 10369 10370 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10371 10372 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10373 // nodes and Machine PHI nodes, but the incoming operands have not been 10374 // emitted yet. 10375 for (const PHINode &PN : SuccBB->phis()) { 10376 // Ignore dead phi's. 10377 if (PN.use_empty()) 10378 continue; 10379 10380 // Skip empty types 10381 if (PN.getType()->isEmptyTy()) 10382 continue; 10383 10384 unsigned Reg; 10385 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10386 10387 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10388 unsigned &RegOut = ConstantsOut[C]; 10389 if (RegOut == 0) { 10390 RegOut = FuncInfo.CreateRegs(C); 10391 CopyValueToVirtualRegister(C, RegOut); 10392 } 10393 Reg = RegOut; 10394 } else { 10395 DenseMap<const Value *, Register>::iterator I = 10396 FuncInfo.ValueMap.find(PHIOp); 10397 if (I != FuncInfo.ValueMap.end()) 10398 Reg = I->second; 10399 else { 10400 assert(isa<AllocaInst>(PHIOp) && 10401 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10402 "Didn't codegen value into a register!??"); 10403 Reg = FuncInfo.CreateRegs(PHIOp); 10404 CopyValueToVirtualRegister(PHIOp, Reg); 10405 } 10406 } 10407 10408 // Remember that this register needs to added to the machine PHI node as 10409 // the input for this MBB. 10410 SmallVector<EVT, 4> ValueVTs; 10411 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10412 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10413 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10414 EVT VT = ValueVTs[vti]; 10415 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10416 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10417 FuncInfo.PHINodesToUpdate.push_back( 10418 std::make_pair(&*MBBI++, Reg + i)); 10419 Reg += NumRegisters; 10420 } 10421 } 10422 } 10423 10424 ConstantsOut.clear(); 10425 } 10426 10427 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10428 /// is 0. 10429 MachineBasicBlock * 10430 SelectionDAGBuilder::StackProtectorDescriptor:: 10431 AddSuccessorMBB(const BasicBlock *BB, 10432 MachineBasicBlock *ParentMBB, 10433 bool IsLikely, 10434 MachineBasicBlock *SuccMBB) { 10435 // If SuccBB has not been created yet, create it. 10436 if (!SuccMBB) { 10437 MachineFunction *MF = ParentMBB->getParent(); 10438 MachineFunction::iterator BBI(ParentMBB); 10439 SuccMBB = MF->CreateMachineBasicBlock(BB); 10440 MF->insert(++BBI, SuccMBB); 10441 } 10442 // Add it as a successor of ParentMBB. 10443 ParentMBB->addSuccessor( 10444 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10445 return SuccMBB; 10446 } 10447 10448 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10449 MachineFunction::iterator I(MBB); 10450 if (++I == FuncInfo.MF->end()) 10451 return nullptr; 10452 return &*I; 10453 } 10454 10455 /// During lowering new call nodes can be created (such as memset, etc.). 10456 /// Those will become new roots of the current DAG, but complications arise 10457 /// when they are tail calls. In such cases, the call lowering will update 10458 /// the root, but the builder still needs to know that a tail call has been 10459 /// lowered in order to avoid generating an additional return. 10460 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10461 // If the node is null, we do have a tail call. 10462 if (MaybeTC.getNode() != nullptr) 10463 DAG.setRoot(MaybeTC); 10464 else 10465 HasTailCall = true; 10466 } 10467 10468 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10469 MachineBasicBlock *SwitchMBB, 10470 MachineBasicBlock *DefaultMBB) { 10471 MachineFunction *CurMF = FuncInfo.MF; 10472 MachineBasicBlock *NextMBB = nullptr; 10473 MachineFunction::iterator BBI(W.MBB); 10474 if (++BBI != FuncInfo.MF->end()) 10475 NextMBB = &*BBI; 10476 10477 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10478 10479 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10480 10481 if (Size == 2 && W.MBB == SwitchMBB) { 10482 // If any two of the cases has the same destination, and if one value 10483 // is the same as the other, but has one bit unset that the other has set, 10484 // use bit manipulation to do two compares at once. For example: 10485 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10486 // TODO: This could be extended to merge any 2 cases in switches with 3 10487 // cases. 10488 // TODO: Handle cases where W.CaseBB != SwitchBB. 10489 CaseCluster &Small = *W.FirstCluster; 10490 CaseCluster &Big = *W.LastCluster; 10491 10492 if (Small.Low == Small.High && Big.Low == Big.High && 10493 Small.MBB == Big.MBB) { 10494 const APInt &SmallValue = Small.Low->getValue(); 10495 const APInt &BigValue = Big.Low->getValue(); 10496 10497 // Check that there is only one bit different. 10498 APInt CommonBit = BigValue ^ SmallValue; 10499 if (CommonBit.isPowerOf2()) { 10500 SDValue CondLHS = getValue(Cond); 10501 EVT VT = CondLHS.getValueType(); 10502 SDLoc DL = getCurSDLoc(); 10503 10504 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10505 DAG.getConstant(CommonBit, DL, VT)); 10506 SDValue Cond = DAG.getSetCC( 10507 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10508 ISD::SETEQ); 10509 10510 // Update successor info. 10511 // Both Small and Big will jump to Small.BB, so we sum up the 10512 // probabilities. 10513 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10514 if (BPI) 10515 addSuccessorWithProb( 10516 SwitchMBB, DefaultMBB, 10517 // The default destination is the first successor in IR. 10518 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10519 else 10520 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10521 10522 // Insert the true branch. 10523 SDValue BrCond = 10524 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10525 DAG.getBasicBlock(Small.MBB)); 10526 // Insert the false branch. 10527 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10528 DAG.getBasicBlock(DefaultMBB)); 10529 10530 DAG.setRoot(BrCond); 10531 return; 10532 } 10533 } 10534 } 10535 10536 if (TM.getOptLevel() != CodeGenOpt::None) { 10537 // Here, we order cases by probability so the most likely case will be 10538 // checked first. However, two clusters can have the same probability in 10539 // which case their relative ordering is non-deterministic. So we use Low 10540 // as a tie-breaker as clusters are guaranteed to never overlap. 10541 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10542 [](const CaseCluster &a, const CaseCluster &b) { 10543 return a.Prob != b.Prob ? 10544 a.Prob > b.Prob : 10545 a.Low->getValue().slt(b.Low->getValue()); 10546 }); 10547 10548 // Rearrange the case blocks so that the last one falls through if possible 10549 // without changing the order of probabilities. 10550 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10551 --I; 10552 if (I->Prob > W.LastCluster->Prob) 10553 break; 10554 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10555 std::swap(*I, *W.LastCluster); 10556 break; 10557 } 10558 } 10559 } 10560 10561 // Compute total probability. 10562 BranchProbability DefaultProb = W.DefaultProb; 10563 BranchProbability UnhandledProbs = DefaultProb; 10564 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10565 UnhandledProbs += I->Prob; 10566 10567 MachineBasicBlock *CurMBB = W.MBB; 10568 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10569 bool FallthroughUnreachable = false; 10570 MachineBasicBlock *Fallthrough; 10571 if (I == W.LastCluster) { 10572 // For the last cluster, fall through to the default destination. 10573 Fallthrough = DefaultMBB; 10574 FallthroughUnreachable = isa<UnreachableInst>( 10575 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10576 } else { 10577 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10578 CurMF->insert(BBI, Fallthrough); 10579 // Put Cond in a virtual register to make it available from the new blocks. 10580 ExportFromCurrentBlock(Cond); 10581 } 10582 UnhandledProbs -= I->Prob; 10583 10584 switch (I->Kind) { 10585 case CC_JumpTable: { 10586 // FIXME: Optimize away range check based on pivot comparisons. 10587 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10588 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10589 10590 // The jump block hasn't been inserted yet; insert it here. 10591 MachineBasicBlock *JumpMBB = JT->MBB; 10592 CurMF->insert(BBI, JumpMBB); 10593 10594 auto JumpProb = I->Prob; 10595 auto FallthroughProb = UnhandledProbs; 10596 10597 // If the default statement is a target of the jump table, we evenly 10598 // distribute the default probability to successors of CurMBB. Also 10599 // update the probability on the edge from JumpMBB to Fallthrough. 10600 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10601 SE = JumpMBB->succ_end(); 10602 SI != SE; ++SI) { 10603 if (*SI == DefaultMBB) { 10604 JumpProb += DefaultProb / 2; 10605 FallthroughProb -= DefaultProb / 2; 10606 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10607 JumpMBB->normalizeSuccProbs(); 10608 break; 10609 } 10610 } 10611 10612 if (FallthroughUnreachable) { 10613 // Skip the range check if the fallthrough block is unreachable. 10614 JTH->OmitRangeCheck = true; 10615 } 10616 10617 if (!JTH->OmitRangeCheck) 10618 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10619 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10620 CurMBB->normalizeSuccProbs(); 10621 10622 // The jump table header will be inserted in our current block, do the 10623 // range check, and fall through to our fallthrough block. 10624 JTH->HeaderBB = CurMBB; 10625 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10626 10627 // If we're in the right place, emit the jump table header right now. 10628 if (CurMBB == SwitchMBB) { 10629 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10630 JTH->Emitted = true; 10631 } 10632 break; 10633 } 10634 case CC_BitTests: { 10635 // FIXME: Optimize away range check based on pivot comparisons. 10636 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10637 10638 // The bit test blocks haven't been inserted yet; insert them here. 10639 for (BitTestCase &BTC : BTB->Cases) 10640 CurMF->insert(BBI, BTC.ThisBB); 10641 10642 // Fill in fields of the BitTestBlock. 10643 BTB->Parent = CurMBB; 10644 BTB->Default = Fallthrough; 10645 10646 BTB->DefaultProb = UnhandledProbs; 10647 // If the cases in bit test don't form a contiguous range, we evenly 10648 // distribute the probability on the edge to Fallthrough to two 10649 // successors of CurMBB. 10650 if (!BTB->ContiguousRange) { 10651 BTB->Prob += DefaultProb / 2; 10652 BTB->DefaultProb -= DefaultProb / 2; 10653 } 10654 10655 if (FallthroughUnreachable) { 10656 // Skip the range check if the fallthrough block is unreachable. 10657 BTB->OmitRangeCheck = true; 10658 } 10659 10660 // If we're in the right place, emit the bit test header right now. 10661 if (CurMBB == SwitchMBB) { 10662 visitBitTestHeader(*BTB, SwitchMBB); 10663 BTB->Emitted = true; 10664 } 10665 break; 10666 } 10667 case CC_Range: { 10668 const Value *RHS, *LHS, *MHS; 10669 ISD::CondCode CC; 10670 if (I->Low == I->High) { 10671 // Check Cond == I->Low. 10672 CC = ISD::SETEQ; 10673 LHS = Cond; 10674 RHS=I->Low; 10675 MHS = nullptr; 10676 } else { 10677 // Check I->Low <= Cond <= I->High. 10678 CC = ISD::SETLE; 10679 LHS = I->Low; 10680 MHS = Cond; 10681 RHS = I->High; 10682 } 10683 10684 // If Fallthrough is unreachable, fold away the comparison. 10685 if (FallthroughUnreachable) 10686 CC = ISD::SETTRUE; 10687 10688 // The false probability is the sum of all unhandled cases. 10689 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10690 getCurSDLoc(), I->Prob, UnhandledProbs); 10691 10692 if (CurMBB == SwitchMBB) 10693 visitSwitchCase(CB, SwitchMBB); 10694 else 10695 SL->SwitchCases.push_back(CB); 10696 10697 break; 10698 } 10699 } 10700 CurMBB = Fallthrough; 10701 } 10702 } 10703 10704 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10705 CaseClusterIt First, 10706 CaseClusterIt Last) { 10707 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10708 if (X.Prob != CC.Prob) 10709 return X.Prob > CC.Prob; 10710 10711 // Ties are broken by comparing the case value. 10712 return X.Low->getValue().slt(CC.Low->getValue()); 10713 }); 10714 } 10715 10716 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10717 const SwitchWorkListItem &W, 10718 Value *Cond, 10719 MachineBasicBlock *SwitchMBB) { 10720 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10721 "Clusters not sorted?"); 10722 10723 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10724 10725 // Balance the tree based on branch probabilities to create a near-optimal (in 10726 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10727 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10728 CaseClusterIt LastLeft = W.FirstCluster; 10729 CaseClusterIt FirstRight = W.LastCluster; 10730 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10731 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10732 10733 // Move LastLeft and FirstRight towards each other from opposite directions to 10734 // find a partitioning of the clusters which balances the probability on both 10735 // sides. If LeftProb and RightProb are equal, alternate which side is 10736 // taken to ensure 0-probability nodes are distributed evenly. 10737 unsigned I = 0; 10738 while (LastLeft + 1 < FirstRight) { 10739 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10740 LeftProb += (++LastLeft)->Prob; 10741 else 10742 RightProb += (--FirstRight)->Prob; 10743 I++; 10744 } 10745 10746 while (true) { 10747 // Our binary search tree differs from a typical BST in that ours can have up 10748 // to three values in each leaf. The pivot selection above doesn't take that 10749 // into account, which means the tree might require more nodes and be less 10750 // efficient. We compensate for this here. 10751 10752 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10753 unsigned NumRight = W.LastCluster - FirstRight + 1; 10754 10755 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10756 // If one side has less than 3 clusters, and the other has more than 3, 10757 // consider taking a cluster from the other side. 10758 10759 if (NumLeft < NumRight) { 10760 // Consider moving the first cluster on the right to the left side. 10761 CaseCluster &CC = *FirstRight; 10762 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10763 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10764 if (LeftSideRank <= RightSideRank) { 10765 // Moving the cluster to the left does not demote it. 10766 ++LastLeft; 10767 ++FirstRight; 10768 continue; 10769 } 10770 } else { 10771 assert(NumRight < NumLeft); 10772 // Consider moving the last element on the left to the right side. 10773 CaseCluster &CC = *LastLeft; 10774 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10775 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10776 if (RightSideRank <= LeftSideRank) { 10777 // Moving the cluster to the right does not demot it. 10778 --LastLeft; 10779 --FirstRight; 10780 continue; 10781 } 10782 } 10783 } 10784 break; 10785 } 10786 10787 assert(LastLeft + 1 == FirstRight); 10788 assert(LastLeft >= W.FirstCluster); 10789 assert(FirstRight <= W.LastCluster); 10790 10791 // Use the first element on the right as pivot since we will make less-than 10792 // comparisons against it. 10793 CaseClusterIt PivotCluster = FirstRight; 10794 assert(PivotCluster > W.FirstCluster); 10795 assert(PivotCluster <= W.LastCluster); 10796 10797 CaseClusterIt FirstLeft = W.FirstCluster; 10798 CaseClusterIt LastRight = W.LastCluster; 10799 10800 const ConstantInt *Pivot = PivotCluster->Low; 10801 10802 // New blocks will be inserted immediately after the current one. 10803 MachineFunction::iterator BBI(W.MBB); 10804 ++BBI; 10805 10806 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10807 // we can branch to its destination directly if it's squeezed exactly in 10808 // between the known lower bound and Pivot - 1. 10809 MachineBasicBlock *LeftMBB; 10810 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10811 FirstLeft->Low == W.GE && 10812 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10813 LeftMBB = FirstLeft->MBB; 10814 } else { 10815 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10816 FuncInfo.MF->insert(BBI, LeftMBB); 10817 WorkList.push_back( 10818 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10819 // Put Cond in a virtual register to make it available from the new blocks. 10820 ExportFromCurrentBlock(Cond); 10821 } 10822 10823 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10824 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10825 // directly if RHS.High equals the current upper bound. 10826 MachineBasicBlock *RightMBB; 10827 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10828 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10829 RightMBB = FirstRight->MBB; 10830 } else { 10831 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10832 FuncInfo.MF->insert(BBI, RightMBB); 10833 WorkList.push_back( 10834 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10835 // Put Cond in a virtual register to make it available from the new blocks. 10836 ExportFromCurrentBlock(Cond); 10837 } 10838 10839 // Create the CaseBlock record that will be used to lower the branch. 10840 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10841 getCurSDLoc(), LeftProb, RightProb); 10842 10843 if (W.MBB == SwitchMBB) 10844 visitSwitchCase(CB, SwitchMBB); 10845 else 10846 SL->SwitchCases.push_back(CB); 10847 } 10848 10849 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10850 // from the swith statement. 10851 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10852 BranchProbability PeeledCaseProb) { 10853 if (PeeledCaseProb == BranchProbability::getOne()) 10854 return BranchProbability::getZero(); 10855 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10856 10857 uint32_t Numerator = CaseProb.getNumerator(); 10858 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10859 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10860 } 10861 10862 // Try to peel the top probability case if it exceeds the threshold. 10863 // Return current MachineBasicBlock for the switch statement if the peeling 10864 // does not occur. 10865 // If the peeling is performed, return the newly created MachineBasicBlock 10866 // for the peeled switch statement. Also update Clusters to remove the peeled 10867 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10868 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10869 const SwitchInst &SI, CaseClusterVector &Clusters, 10870 BranchProbability &PeeledCaseProb) { 10871 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10872 // Don't perform if there is only one cluster or optimizing for size. 10873 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10874 TM.getOptLevel() == CodeGenOpt::None || 10875 SwitchMBB->getParent()->getFunction().hasMinSize()) 10876 return SwitchMBB; 10877 10878 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10879 unsigned PeeledCaseIndex = 0; 10880 bool SwitchPeeled = false; 10881 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10882 CaseCluster &CC = Clusters[Index]; 10883 if (CC.Prob < TopCaseProb) 10884 continue; 10885 TopCaseProb = CC.Prob; 10886 PeeledCaseIndex = Index; 10887 SwitchPeeled = true; 10888 } 10889 if (!SwitchPeeled) 10890 return SwitchMBB; 10891 10892 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10893 << TopCaseProb << "\n"); 10894 10895 // Record the MBB for the peeled switch statement. 10896 MachineFunction::iterator BBI(SwitchMBB); 10897 ++BBI; 10898 MachineBasicBlock *PeeledSwitchMBB = 10899 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10900 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10901 10902 ExportFromCurrentBlock(SI.getCondition()); 10903 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10904 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10905 nullptr, nullptr, TopCaseProb.getCompl()}; 10906 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10907 10908 Clusters.erase(PeeledCaseIt); 10909 for (CaseCluster &CC : Clusters) { 10910 LLVM_DEBUG( 10911 dbgs() << "Scale the probablity for one cluster, before scaling: " 10912 << CC.Prob << "\n"); 10913 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10914 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10915 } 10916 PeeledCaseProb = TopCaseProb; 10917 return PeeledSwitchMBB; 10918 } 10919 10920 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10921 // Extract cases from the switch. 10922 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10923 CaseClusterVector Clusters; 10924 Clusters.reserve(SI.getNumCases()); 10925 for (auto I : SI.cases()) { 10926 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10927 const ConstantInt *CaseVal = I.getCaseValue(); 10928 BranchProbability Prob = 10929 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10930 : BranchProbability(1, SI.getNumCases() + 1); 10931 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10932 } 10933 10934 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10935 10936 // Cluster adjacent cases with the same destination. We do this at all 10937 // optimization levels because it's cheap to do and will make codegen faster 10938 // if there are many clusters. 10939 sortAndRangeify(Clusters); 10940 10941 // The branch probablity of the peeled case. 10942 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10943 MachineBasicBlock *PeeledSwitchMBB = 10944 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10945 10946 // If there is only the default destination, jump there directly. 10947 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10948 if (Clusters.empty()) { 10949 assert(PeeledSwitchMBB == SwitchMBB); 10950 SwitchMBB->addSuccessor(DefaultMBB); 10951 if (DefaultMBB != NextBlock(SwitchMBB)) { 10952 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10953 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10954 } 10955 return; 10956 } 10957 10958 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10959 SL->findBitTestClusters(Clusters, &SI); 10960 10961 LLVM_DEBUG({ 10962 dbgs() << "Case clusters: "; 10963 for (const CaseCluster &C : Clusters) { 10964 if (C.Kind == CC_JumpTable) 10965 dbgs() << "JT:"; 10966 if (C.Kind == CC_BitTests) 10967 dbgs() << "BT:"; 10968 10969 C.Low->getValue().print(dbgs(), true); 10970 if (C.Low != C.High) { 10971 dbgs() << '-'; 10972 C.High->getValue().print(dbgs(), true); 10973 } 10974 dbgs() << ' '; 10975 } 10976 dbgs() << '\n'; 10977 }); 10978 10979 assert(!Clusters.empty()); 10980 SwitchWorkList WorkList; 10981 CaseClusterIt First = Clusters.begin(); 10982 CaseClusterIt Last = Clusters.end() - 1; 10983 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10984 // Scale the branchprobability for DefaultMBB if the peel occurs and 10985 // DefaultMBB is not replaced. 10986 if (PeeledCaseProb != BranchProbability::getZero() && 10987 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10988 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10989 WorkList.push_back( 10990 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10991 10992 while (!WorkList.empty()) { 10993 SwitchWorkListItem W = WorkList.pop_back_val(); 10994 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10995 10996 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10997 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10998 // For optimized builds, lower large range as a balanced binary tree. 10999 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11000 continue; 11001 } 11002 11003 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11004 } 11005 } 11006 11007 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11008 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11009 auto DL = getCurSDLoc(); 11010 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11011 EVT OpVT = 11012 TLI.getTypeToTransformTo(*DAG.getContext(), ResultVT.getScalarType()); 11013 SDValue Step = DAG.getConstant(1, DL, OpVT); 11014 setValue(&I, DAG.getStepVector(DL, ResultVT, Step)); 11015 } 11016 11017 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11018 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11019 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11020 11021 SDLoc DL = getCurSDLoc(); 11022 SDValue V = getValue(I.getOperand(0)); 11023 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11024 11025 if (VT.isScalableVector()) { 11026 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11027 return; 11028 } 11029 11030 // Use VECTOR_SHUFFLE for the fixed-length vector 11031 // to maintain existing behavior. 11032 SmallVector<int, 8> Mask; 11033 unsigned NumElts = VT.getVectorMinNumElements(); 11034 for (unsigned i = 0; i != NumElts; ++i) 11035 Mask.push_back(NumElts - 1 - i); 11036 11037 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11038 } 11039 11040 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11041 SmallVector<EVT, 4> ValueVTs; 11042 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11043 ValueVTs); 11044 unsigned NumValues = ValueVTs.size(); 11045 if (NumValues == 0) return; 11046 11047 SmallVector<SDValue, 4> Values(NumValues); 11048 SDValue Op = getValue(I.getOperand(0)); 11049 11050 for (unsigned i = 0; i != NumValues; ++i) 11051 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11052 SDValue(Op.getNode(), Op.getResNo() + i)); 11053 11054 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11055 DAG.getVTList(ValueVTs), Values)); 11056 } 11057 11058 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11059 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11060 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11061 11062 SDLoc DL = getCurSDLoc(); 11063 SDValue V1 = getValue(I.getOperand(0)); 11064 SDValue V2 = getValue(I.getOperand(1)); 11065 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11066 11067 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11068 if (VT.isScalableVector()) { 11069 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11070 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11071 DAG.getConstant(Imm, DL, IdxVT))); 11072 return; 11073 } 11074 11075 unsigned NumElts = VT.getVectorNumElements(); 11076 11077 if ((-Imm > NumElts) || (Imm >= NumElts)) { 11078 // Result is undefined if immediate is out-of-bounds. 11079 setValue(&I, DAG.getUNDEF(VT)); 11080 return; 11081 } 11082 11083 uint64_t Idx = (NumElts + Imm) % NumElts; 11084 11085 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11086 SmallVector<int, 8> Mask; 11087 for (unsigned i = 0; i < NumElts; ++i) 11088 Mask.push_back(Idx + i); 11089 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11090 } 11091