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 break; 2884 case Intrinsic::experimental_patchpoint_void: 2885 case Intrinsic::experimental_patchpoint_i64: 2886 visitPatchpoint(I, EHPadBB); 2887 break; 2888 case Intrinsic::experimental_gc_statepoint: 2889 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2890 break; 2891 case Intrinsic::wasm_rethrow: { 2892 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2893 // special because it can be invoked, so we manually lower it to a DAG 2894 // node here. 2895 SmallVector<SDValue, 8> Ops; 2896 Ops.push_back(getRoot()); // inchain 2897 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2898 Ops.push_back( 2899 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2900 TLI.getPointerTy(DAG.getDataLayout()))); 2901 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2902 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2903 break; 2904 } 2905 } 2906 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2907 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2908 // Eventually we will support lowering the @llvm.experimental.deoptimize 2909 // intrinsic, and right now there are no plans to support other intrinsics 2910 // with deopt state. 2911 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2912 } else { 2913 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2914 } 2915 2916 // If the value of the invoke is used outside of its defining block, make it 2917 // available as a virtual register. 2918 // We already took care of the exported value for the statepoint instruction 2919 // during call to the LowerStatepoint. 2920 if (!isa<GCStatepointInst>(I)) { 2921 CopyToExportRegsIfNeeded(&I); 2922 } 2923 2924 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2925 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2926 BranchProbability EHPadBBProb = 2927 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2928 : BranchProbability::getZero(); 2929 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2930 2931 // Update successor info. 2932 addSuccessorWithProb(InvokeMBB, Return); 2933 for (auto &UnwindDest : UnwindDests) { 2934 UnwindDest.first->setIsEHPad(); 2935 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2936 } 2937 InvokeMBB->normalizeSuccProbs(); 2938 2939 // Drop into normal successor. 2940 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2941 DAG.getBasicBlock(Return))); 2942 } 2943 2944 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2945 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2946 2947 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2948 // have to do anything here to lower funclet bundles. 2949 assert(!I.hasOperandBundlesOtherThan( 2950 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2951 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2952 2953 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2954 visitInlineAsm(I); 2955 CopyToExportRegsIfNeeded(&I); 2956 2957 // Retrieve successors. 2958 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2959 2960 // Update successor info. 2961 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2962 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2963 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2964 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2965 Target->setIsInlineAsmBrIndirectTarget(); 2966 } 2967 CallBrMBB->normalizeSuccProbs(); 2968 2969 // Drop into default successor. 2970 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2971 MVT::Other, getControlRoot(), 2972 DAG.getBasicBlock(Return))); 2973 } 2974 2975 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2976 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2977 } 2978 2979 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2980 assert(FuncInfo.MBB->isEHPad() && 2981 "Call to landingpad not in landing pad!"); 2982 2983 // If there aren't registers to copy the values into (e.g., during SjLj 2984 // exceptions), then don't bother to create these DAG nodes. 2985 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2986 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2987 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2988 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2989 return; 2990 2991 // If landingpad's return type is token type, we don't create DAG nodes 2992 // for its exception pointer and selector value. The extraction of exception 2993 // pointer or selector value from token type landingpads is not currently 2994 // supported. 2995 if (LP.getType()->isTokenTy()) 2996 return; 2997 2998 SmallVector<EVT, 2> ValueVTs; 2999 SDLoc dl = getCurSDLoc(); 3000 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3001 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3002 3003 // Get the two live-in registers as SDValues. The physregs have already been 3004 // copied into virtual registers. 3005 SDValue Ops[2]; 3006 if (FuncInfo.ExceptionPointerVirtReg) { 3007 Ops[0] = DAG.getZExtOrTrunc( 3008 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3009 FuncInfo.ExceptionPointerVirtReg, 3010 TLI.getPointerTy(DAG.getDataLayout())), 3011 dl, ValueVTs[0]); 3012 } else { 3013 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3014 } 3015 Ops[1] = DAG.getZExtOrTrunc( 3016 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3017 FuncInfo.ExceptionSelectorVirtReg, 3018 TLI.getPointerTy(DAG.getDataLayout())), 3019 dl, ValueVTs[1]); 3020 3021 // Merge into one. 3022 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3023 DAG.getVTList(ValueVTs), Ops); 3024 setValue(&LP, Res); 3025 } 3026 3027 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3028 MachineBasicBlock *Last) { 3029 // Update JTCases. 3030 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 3031 if (SL->JTCases[i].first.HeaderBB == First) 3032 SL->JTCases[i].first.HeaderBB = Last; 3033 3034 // Update BitTestCases. 3035 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 3036 if (SL->BitTestCases[i].Parent == First) 3037 SL->BitTestCases[i].Parent = Last; 3038 } 3039 3040 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3041 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3042 3043 // Update machine-CFG edges with unique successors. 3044 SmallSet<BasicBlock*, 32> Done; 3045 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3046 BasicBlock *BB = I.getSuccessor(i); 3047 bool Inserted = Done.insert(BB).second; 3048 if (!Inserted) 3049 continue; 3050 3051 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3052 addSuccessorWithProb(IndirectBrMBB, Succ); 3053 } 3054 IndirectBrMBB->normalizeSuccProbs(); 3055 3056 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3057 MVT::Other, getControlRoot(), 3058 getValue(I.getAddress()))); 3059 } 3060 3061 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3062 if (!DAG.getTarget().Options.TrapUnreachable) 3063 return; 3064 3065 // We may be able to ignore unreachable behind a noreturn call. 3066 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3067 const BasicBlock &BB = *I.getParent(); 3068 if (&I != &BB.front()) { 3069 BasicBlock::const_iterator PredI = 3070 std::prev(BasicBlock::const_iterator(&I)); 3071 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3072 if (Call->doesNotReturn()) 3073 return; 3074 } 3075 } 3076 } 3077 3078 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3079 } 3080 3081 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3082 SDNodeFlags Flags; 3083 3084 SDValue Op = getValue(I.getOperand(0)); 3085 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3086 Op, Flags); 3087 setValue(&I, UnNodeValue); 3088 } 3089 3090 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3091 SDNodeFlags Flags; 3092 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3093 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3094 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3095 } 3096 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3097 Flags.setExact(ExactOp->isExact()); 3098 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3099 Flags.copyFMF(*FPOp); 3100 3101 SDValue Op1 = getValue(I.getOperand(0)); 3102 SDValue Op2 = getValue(I.getOperand(1)); 3103 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3104 Op1, Op2, Flags); 3105 setValue(&I, BinNodeValue); 3106 } 3107 3108 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3109 SDValue Op1 = getValue(I.getOperand(0)); 3110 SDValue Op2 = getValue(I.getOperand(1)); 3111 3112 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3113 Op1.getValueType(), DAG.getDataLayout()); 3114 3115 // Coerce the shift amount to the right type if we can. 3116 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3117 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3118 unsigned Op2Size = Op2.getValueSizeInBits(); 3119 SDLoc DL = getCurSDLoc(); 3120 3121 // If the operand is smaller than the shift count type, promote it. 3122 if (ShiftSize > Op2Size) 3123 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3124 3125 // If the operand is larger than the shift count type but the shift 3126 // count type has enough bits to represent any shift value, truncate 3127 // it now. This is a common case and it exposes the truncate to 3128 // optimization early. 3129 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3130 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3131 // Otherwise we'll need to temporarily settle for some other convenient 3132 // type. Type legalization will make adjustments once the shiftee is split. 3133 else 3134 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3135 } 3136 3137 bool nuw = false; 3138 bool nsw = false; 3139 bool exact = false; 3140 3141 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3142 3143 if (const OverflowingBinaryOperator *OFBinOp = 3144 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3145 nuw = OFBinOp->hasNoUnsignedWrap(); 3146 nsw = OFBinOp->hasNoSignedWrap(); 3147 } 3148 if (const PossiblyExactOperator *ExactOp = 3149 dyn_cast<const PossiblyExactOperator>(&I)) 3150 exact = ExactOp->isExact(); 3151 } 3152 SDNodeFlags Flags; 3153 Flags.setExact(exact); 3154 Flags.setNoSignedWrap(nsw); 3155 Flags.setNoUnsignedWrap(nuw); 3156 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3157 Flags); 3158 setValue(&I, Res); 3159 } 3160 3161 void SelectionDAGBuilder::visitSDiv(const User &I) { 3162 SDValue Op1 = getValue(I.getOperand(0)); 3163 SDValue Op2 = getValue(I.getOperand(1)); 3164 3165 SDNodeFlags Flags; 3166 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3167 cast<PossiblyExactOperator>(&I)->isExact()); 3168 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3169 Op2, Flags)); 3170 } 3171 3172 void SelectionDAGBuilder::visitICmp(const User &I) { 3173 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3174 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3175 predicate = IC->getPredicate(); 3176 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3177 predicate = ICmpInst::Predicate(IC->getPredicate()); 3178 SDValue Op1 = getValue(I.getOperand(0)); 3179 SDValue Op2 = getValue(I.getOperand(1)); 3180 ISD::CondCode Opcode = getICmpCondCode(predicate); 3181 3182 auto &TLI = DAG.getTargetLoweringInfo(); 3183 EVT MemVT = 3184 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3185 3186 // If a pointer's DAG type is larger than its memory type then the DAG values 3187 // are zero-extended. This breaks signed comparisons so truncate back to the 3188 // underlying type before doing the compare. 3189 if (Op1.getValueType() != MemVT) { 3190 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3191 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3192 } 3193 3194 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3195 I.getType()); 3196 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3197 } 3198 3199 void SelectionDAGBuilder::visitFCmp(const User &I) { 3200 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3201 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3202 predicate = FC->getPredicate(); 3203 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3204 predicate = FCmpInst::Predicate(FC->getPredicate()); 3205 SDValue Op1 = getValue(I.getOperand(0)); 3206 SDValue Op2 = getValue(I.getOperand(1)); 3207 3208 ISD::CondCode Condition = getFCmpCondCode(predicate); 3209 auto *FPMO = cast<FPMathOperator>(&I); 3210 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3211 Condition = getFCmpCodeWithoutNaN(Condition); 3212 3213 SDNodeFlags Flags; 3214 Flags.copyFMF(*FPMO); 3215 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3216 3217 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3218 I.getType()); 3219 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3220 } 3221 3222 // Check if the condition of the select has one use or two users that are both 3223 // selects with the same condition. 3224 static bool hasOnlySelectUsers(const Value *Cond) { 3225 return llvm::all_of(Cond->users(), [](const Value *V) { 3226 return isa<SelectInst>(V); 3227 }); 3228 } 3229 3230 void SelectionDAGBuilder::visitSelect(const User &I) { 3231 SmallVector<EVT, 4> ValueVTs; 3232 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3233 ValueVTs); 3234 unsigned NumValues = ValueVTs.size(); 3235 if (NumValues == 0) return; 3236 3237 SmallVector<SDValue, 4> Values(NumValues); 3238 SDValue Cond = getValue(I.getOperand(0)); 3239 SDValue LHSVal = getValue(I.getOperand(1)); 3240 SDValue RHSVal = getValue(I.getOperand(2)); 3241 SmallVector<SDValue, 1> BaseOps(1, Cond); 3242 ISD::NodeType OpCode = 3243 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3244 3245 bool IsUnaryAbs = false; 3246 bool Negate = false; 3247 3248 SDNodeFlags Flags; 3249 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3250 Flags.copyFMF(*FPOp); 3251 3252 // Min/max matching is only viable if all output VTs are the same. 3253 if (is_splat(ValueVTs)) { 3254 EVT VT = ValueVTs[0]; 3255 LLVMContext &Ctx = *DAG.getContext(); 3256 auto &TLI = DAG.getTargetLoweringInfo(); 3257 3258 // We care about the legality of the operation after it has been type 3259 // legalized. 3260 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3261 VT = TLI.getTypeToTransformTo(Ctx, VT); 3262 3263 // If the vselect is legal, assume we want to leave this as a vector setcc + 3264 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3265 // min/max is legal on the scalar type. 3266 bool UseScalarMinMax = VT.isVector() && 3267 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3268 3269 Value *LHS, *RHS; 3270 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3271 ISD::NodeType Opc = ISD::DELETED_NODE; 3272 switch (SPR.Flavor) { 3273 case SPF_UMAX: Opc = ISD::UMAX; break; 3274 case SPF_UMIN: Opc = ISD::UMIN; break; 3275 case SPF_SMAX: Opc = ISD::SMAX; break; 3276 case SPF_SMIN: Opc = ISD::SMIN; break; 3277 case SPF_FMINNUM: 3278 switch (SPR.NaNBehavior) { 3279 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3280 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3281 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3282 case SPNB_RETURNS_ANY: { 3283 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3284 Opc = ISD::FMINNUM; 3285 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3286 Opc = ISD::FMINIMUM; 3287 else if (UseScalarMinMax) 3288 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3289 ISD::FMINNUM : ISD::FMINIMUM; 3290 break; 3291 } 3292 } 3293 break; 3294 case SPF_FMAXNUM: 3295 switch (SPR.NaNBehavior) { 3296 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3297 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3298 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3299 case SPNB_RETURNS_ANY: 3300 3301 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3302 Opc = ISD::FMAXNUM; 3303 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3304 Opc = ISD::FMAXIMUM; 3305 else if (UseScalarMinMax) 3306 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3307 ISD::FMAXNUM : ISD::FMAXIMUM; 3308 break; 3309 } 3310 break; 3311 case SPF_NABS: 3312 Negate = true; 3313 LLVM_FALLTHROUGH; 3314 case SPF_ABS: 3315 IsUnaryAbs = true; 3316 Opc = ISD::ABS; 3317 break; 3318 default: break; 3319 } 3320 3321 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3322 (TLI.isOperationLegalOrCustom(Opc, VT) || 3323 (UseScalarMinMax && 3324 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3325 // If the underlying comparison instruction is used by any other 3326 // instruction, the consumed instructions won't be destroyed, so it is 3327 // not profitable to convert to a min/max. 3328 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3329 OpCode = Opc; 3330 LHSVal = getValue(LHS); 3331 RHSVal = getValue(RHS); 3332 BaseOps.clear(); 3333 } 3334 3335 if (IsUnaryAbs) { 3336 OpCode = Opc; 3337 LHSVal = getValue(LHS); 3338 BaseOps.clear(); 3339 } 3340 } 3341 3342 if (IsUnaryAbs) { 3343 for (unsigned i = 0; i != NumValues; ++i) { 3344 SDLoc dl = getCurSDLoc(); 3345 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3346 Values[i] = 3347 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3348 if (Negate) 3349 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3350 Values[i]); 3351 } 3352 } else { 3353 for (unsigned i = 0; i != NumValues; ++i) { 3354 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3355 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3356 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3357 Values[i] = DAG.getNode( 3358 OpCode, getCurSDLoc(), 3359 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3360 } 3361 } 3362 3363 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3364 DAG.getVTList(ValueVTs), Values)); 3365 } 3366 3367 void SelectionDAGBuilder::visitTrunc(const User &I) { 3368 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3369 SDValue N = getValue(I.getOperand(0)); 3370 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3371 I.getType()); 3372 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3373 } 3374 3375 void SelectionDAGBuilder::visitZExt(const User &I) { 3376 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3377 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3378 SDValue N = getValue(I.getOperand(0)); 3379 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3380 I.getType()); 3381 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3382 } 3383 3384 void SelectionDAGBuilder::visitSExt(const User &I) { 3385 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3386 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3387 SDValue N = getValue(I.getOperand(0)); 3388 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3389 I.getType()); 3390 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3391 } 3392 3393 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3394 // FPTrunc is never a no-op cast, no need to check 3395 SDValue N = getValue(I.getOperand(0)); 3396 SDLoc dl = getCurSDLoc(); 3397 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3398 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3399 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3400 DAG.getTargetConstant( 3401 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3402 } 3403 3404 void SelectionDAGBuilder::visitFPExt(const User &I) { 3405 // FPExt is never a no-op cast, no need to check 3406 SDValue N = getValue(I.getOperand(0)); 3407 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3408 I.getType()); 3409 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3410 } 3411 3412 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3413 // FPToUI is never a no-op cast, no need to check 3414 SDValue N = getValue(I.getOperand(0)); 3415 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3416 I.getType()); 3417 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3418 } 3419 3420 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3421 // FPToSI is never a no-op cast, no need to check 3422 SDValue N = getValue(I.getOperand(0)); 3423 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3424 I.getType()); 3425 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3426 } 3427 3428 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3429 // UIToFP is never a no-op cast, no need to check 3430 SDValue N = getValue(I.getOperand(0)); 3431 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3432 I.getType()); 3433 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3434 } 3435 3436 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3437 // SIToFP is never a no-op cast, no need to check 3438 SDValue N = getValue(I.getOperand(0)); 3439 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3440 I.getType()); 3441 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3442 } 3443 3444 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3445 // What to do depends on the size of the integer and the size of the pointer. 3446 // We can either truncate, zero extend, or no-op, accordingly. 3447 SDValue N = getValue(I.getOperand(0)); 3448 auto &TLI = DAG.getTargetLoweringInfo(); 3449 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3450 I.getType()); 3451 EVT PtrMemVT = 3452 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3453 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3454 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3455 setValue(&I, N); 3456 } 3457 3458 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3459 // What to do depends on the size of the integer and the size of the pointer. 3460 // We can either truncate, zero extend, or no-op, accordingly. 3461 SDValue N = getValue(I.getOperand(0)); 3462 auto &TLI = DAG.getTargetLoweringInfo(); 3463 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3464 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3465 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3466 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3467 setValue(&I, N); 3468 } 3469 3470 void SelectionDAGBuilder::visitBitCast(const User &I) { 3471 SDValue N = getValue(I.getOperand(0)); 3472 SDLoc dl = getCurSDLoc(); 3473 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3474 I.getType()); 3475 3476 // BitCast assures us that source and destination are the same size so this is 3477 // either a BITCAST or a no-op. 3478 if (DestVT != N.getValueType()) 3479 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3480 DestVT, N)); // convert types. 3481 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3482 // might fold any kind of constant expression to an integer constant and that 3483 // is not what we are looking for. Only recognize a bitcast of a genuine 3484 // constant integer as an opaque constant. 3485 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3486 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3487 /*isOpaque*/true)); 3488 else 3489 setValue(&I, N); // noop cast. 3490 } 3491 3492 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3493 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3494 const Value *SV = I.getOperand(0); 3495 SDValue N = getValue(SV); 3496 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3497 3498 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3499 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3500 3501 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3502 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3503 3504 setValue(&I, N); 3505 } 3506 3507 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3509 SDValue InVec = getValue(I.getOperand(0)); 3510 SDValue InVal = getValue(I.getOperand(1)); 3511 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3512 TLI.getVectorIdxTy(DAG.getDataLayout())); 3513 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3514 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3515 InVec, InVal, InIdx)); 3516 } 3517 3518 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3519 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3520 SDValue InVec = getValue(I.getOperand(0)); 3521 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3522 TLI.getVectorIdxTy(DAG.getDataLayout())); 3523 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3524 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3525 InVec, InIdx)); 3526 } 3527 3528 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3529 SDValue Src1 = getValue(I.getOperand(0)); 3530 SDValue Src2 = getValue(I.getOperand(1)); 3531 ArrayRef<int> Mask; 3532 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3533 Mask = SVI->getShuffleMask(); 3534 else 3535 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3536 SDLoc DL = getCurSDLoc(); 3537 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3538 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3539 EVT SrcVT = Src1.getValueType(); 3540 3541 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3542 VT.isScalableVector()) { 3543 // Canonical splat form of first element of first input vector. 3544 SDValue FirstElt = 3545 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3546 DAG.getVectorIdxConstant(0, DL)); 3547 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3548 return; 3549 } 3550 3551 // For now, we only handle splats for scalable vectors. 3552 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3553 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3554 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3555 3556 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3557 unsigned MaskNumElts = Mask.size(); 3558 3559 if (SrcNumElts == MaskNumElts) { 3560 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3561 return; 3562 } 3563 3564 // Normalize the shuffle vector since mask and vector length don't match. 3565 if (SrcNumElts < MaskNumElts) { 3566 // Mask is longer than the source vectors. We can use concatenate vector to 3567 // make the mask and vectors lengths match. 3568 3569 if (MaskNumElts % SrcNumElts == 0) { 3570 // Mask length is a multiple of the source vector length. 3571 // Check if the shuffle is some kind of concatenation of the input 3572 // vectors. 3573 unsigned NumConcat = MaskNumElts / SrcNumElts; 3574 bool IsConcat = true; 3575 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3576 for (unsigned i = 0; i != MaskNumElts; ++i) { 3577 int Idx = Mask[i]; 3578 if (Idx < 0) 3579 continue; 3580 // Ensure the indices in each SrcVT sized piece are sequential and that 3581 // the same source is used for the whole piece. 3582 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3583 (ConcatSrcs[i / SrcNumElts] >= 0 && 3584 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3585 IsConcat = false; 3586 break; 3587 } 3588 // Remember which source this index came from. 3589 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3590 } 3591 3592 // The shuffle is concatenating multiple vectors together. Just emit 3593 // a CONCAT_VECTORS operation. 3594 if (IsConcat) { 3595 SmallVector<SDValue, 8> ConcatOps; 3596 for (auto Src : ConcatSrcs) { 3597 if (Src < 0) 3598 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3599 else if (Src == 0) 3600 ConcatOps.push_back(Src1); 3601 else 3602 ConcatOps.push_back(Src2); 3603 } 3604 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3605 return; 3606 } 3607 } 3608 3609 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3610 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3611 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3612 PaddedMaskNumElts); 3613 3614 // Pad both vectors with undefs to make them the same length as the mask. 3615 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3616 3617 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3618 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3619 MOps1[0] = Src1; 3620 MOps2[0] = Src2; 3621 3622 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3623 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3624 3625 // Readjust mask for new input vector length. 3626 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3627 for (unsigned i = 0; i != MaskNumElts; ++i) { 3628 int Idx = Mask[i]; 3629 if (Idx >= (int)SrcNumElts) 3630 Idx -= SrcNumElts - PaddedMaskNumElts; 3631 MappedOps[i] = Idx; 3632 } 3633 3634 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3635 3636 // If the concatenated vector was padded, extract a subvector with the 3637 // correct number of elements. 3638 if (MaskNumElts != PaddedMaskNumElts) 3639 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3640 DAG.getVectorIdxConstant(0, DL)); 3641 3642 setValue(&I, Result); 3643 return; 3644 } 3645 3646 if (SrcNumElts > MaskNumElts) { 3647 // Analyze the access pattern of the vector to see if we can extract 3648 // two subvectors and do the shuffle. 3649 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3650 bool CanExtract = true; 3651 for (int Idx : Mask) { 3652 unsigned Input = 0; 3653 if (Idx < 0) 3654 continue; 3655 3656 if (Idx >= (int)SrcNumElts) { 3657 Input = 1; 3658 Idx -= SrcNumElts; 3659 } 3660 3661 // If all the indices come from the same MaskNumElts sized portion of 3662 // the sources we can use extract. Also make sure the extract wouldn't 3663 // extract past the end of the source. 3664 int NewStartIdx = alignDown(Idx, MaskNumElts); 3665 if (NewStartIdx + MaskNumElts > SrcNumElts || 3666 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3667 CanExtract = false; 3668 // Make sure we always update StartIdx as we use it to track if all 3669 // elements are undef. 3670 StartIdx[Input] = NewStartIdx; 3671 } 3672 3673 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3674 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3675 return; 3676 } 3677 if (CanExtract) { 3678 // Extract appropriate subvector and generate a vector shuffle 3679 for (unsigned Input = 0; Input < 2; ++Input) { 3680 SDValue &Src = Input == 0 ? Src1 : Src2; 3681 if (StartIdx[Input] < 0) 3682 Src = DAG.getUNDEF(VT); 3683 else { 3684 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3685 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3686 } 3687 } 3688 3689 // Calculate new mask. 3690 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3691 for (int &Idx : MappedOps) { 3692 if (Idx >= (int)SrcNumElts) 3693 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3694 else if (Idx >= 0) 3695 Idx -= StartIdx[0]; 3696 } 3697 3698 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3699 return; 3700 } 3701 } 3702 3703 // We can't use either concat vectors or extract subvectors so fall back to 3704 // replacing the shuffle with extract and build vector. 3705 // to insert and build vector. 3706 EVT EltVT = VT.getVectorElementType(); 3707 SmallVector<SDValue,8> Ops; 3708 for (int Idx : Mask) { 3709 SDValue Res; 3710 3711 if (Idx < 0) { 3712 Res = DAG.getUNDEF(EltVT); 3713 } else { 3714 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3715 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3716 3717 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3718 DAG.getVectorIdxConstant(Idx, DL)); 3719 } 3720 3721 Ops.push_back(Res); 3722 } 3723 3724 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3725 } 3726 3727 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3728 ArrayRef<unsigned> Indices; 3729 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3730 Indices = IV->getIndices(); 3731 else 3732 Indices = cast<ConstantExpr>(&I)->getIndices(); 3733 3734 const Value *Op0 = I.getOperand(0); 3735 const Value *Op1 = I.getOperand(1); 3736 Type *AggTy = I.getType(); 3737 Type *ValTy = Op1->getType(); 3738 bool IntoUndef = isa<UndefValue>(Op0); 3739 bool FromUndef = isa<UndefValue>(Op1); 3740 3741 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3742 3743 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3744 SmallVector<EVT, 4> AggValueVTs; 3745 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3746 SmallVector<EVT, 4> ValValueVTs; 3747 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3748 3749 unsigned NumAggValues = AggValueVTs.size(); 3750 unsigned NumValValues = ValValueVTs.size(); 3751 SmallVector<SDValue, 4> Values(NumAggValues); 3752 3753 // Ignore an insertvalue that produces an empty object 3754 if (!NumAggValues) { 3755 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3756 return; 3757 } 3758 3759 SDValue Agg = getValue(Op0); 3760 unsigned i = 0; 3761 // Copy the beginning value(s) from the original aggregate. 3762 for (; i != LinearIndex; ++i) 3763 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3764 SDValue(Agg.getNode(), Agg.getResNo() + i); 3765 // Copy values from the inserted value(s). 3766 if (NumValValues) { 3767 SDValue Val = getValue(Op1); 3768 for (; i != LinearIndex + NumValValues; ++i) 3769 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3770 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3771 } 3772 // Copy remaining value(s) from the original aggregate. 3773 for (; i != NumAggValues; ++i) 3774 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3775 SDValue(Agg.getNode(), Agg.getResNo() + i); 3776 3777 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3778 DAG.getVTList(AggValueVTs), Values)); 3779 } 3780 3781 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3782 ArrayRef<unsigned> Indices; 3783 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3784 Indices = EV->getIndices(); 3785 else 3786 Indices = cast<ConstantExpr>(&I)->getIndices(); 3787 3788 const Value *Op0 = I.getOperand(0); 3789 Type *AggTy = Op0->getType(); 3790 Type *ValTy = I.getType(); 3791 bool OutOfUndef = isa<UndefValue>(Op0); 3792 3793 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3794 3795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3796 SmallVector<EVT, 4> ValValueVTs; 3797 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3798 3799 unsigned NumValValues = ValValueVTs.size(); 3800 3801 // Ignore a extractvalue that produces an empty object 3802 if (!NumValValues) { 3803 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3804 return; 3805 } 3806 3807 SmallVector<SDValue, 4> Values(NumValValues); 3808 3809 SDValue Agg = getValue(Op0); 3810 // Copy out the selected value(s). 3811 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3812 Values[i - LinearIndex] = 3813 OutOfUndef ? 3814 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3815 SDValue(Agg.getNode(), Agg.getResNo() + i); 3816 3817 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3818 DAG.getVTList(ValValueVTs), Values)); 3819 } 3820 3821 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3822 Value *Op0 = I.getOperand(0); 3823 // Note that the pointer operand may be a vector of pointers. Take the scalar 3824 // element which holds a pointer. 3825 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3826 SDValue N = getValue(Op0); 3827 SDLoc dl = getCurSDLoc(); 3828 auto &TLI = DAG.getTargetLoweringInfo(); 3829 3830 // Normalize Vector GEP - all scalar operands should be converted to the 3831 // splat vector. 3832 bool IsVectorGEP = I.getType()->isVectorTy(); 3833 ElementCount VectorElementCount = 3834 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3835 : ElementCount::getFixed(0); 3836 3837 if (IsVectorGEP && !N.getValueType().isVector()) { 3838 LLVMContext &Context = *DAG.getContext(); 3839 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3840 if (VectorElementCount.isScalable()) 3841 N = DAG.getSplatVector(VT, dl, N); 3842 else 3843 N = DAG.getSplatBuildVector(VT, dl, N); 3844 } 3845 3846 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3847 GTI != E; ++GTI) { 3848 const Value *Idx = GTI.getOperand(); 3849 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3850 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3851 if (Field) { 3852 // N = N + Offset 3853 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3854 3855 // In an inbounds GEP with an offset that is nonnegative even when 3856 // interpreted as signed, assume there is no unsigned overflow. 3857 SDNodeFlags Flags; 3858 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3859 Flags.setNoUnsignedWrap(true); 3860 3861 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3862 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3863 } 3864 } else { 3865 // IdxSize is the width of the arithmetic according to IR semantics. 3866 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3867 // (and fix up the result later). 3868 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3869 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3870 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3871 // We intentionally mask away the high bits here; ElementSize may not 3872 // fit in IdxTy. 3873 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3874 bool ElementScalable = ElementSize.isScalable(); 3875 3876 // If this is a scalar constant or a splat vector of constants, 3877 // handle it quickly. 3878 const auto *C = dyn_cast<Constant>(Idx); 3879 if (C && isa<VectorType>(C->getType())) 3880 C = C->getSplatValue(); 3881 3882 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3883 if (CI && CI->isZero()) 3884 continue; 3885 if (CI && !ElementScalable) { 3886 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3887 LLVMContext &Context = *DAG.getContext(); 3888 SDValue OffsVal; 3889 if (IsVectorGEP) 3890 OffsVal = DAG.getConstant( 3891 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3892 else 3893 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3894 3895 // In an inbounds GEP with an offset that is nonnegative even when 3896 // interpreted as signed, assume there is no unsigned overflow. 3897 SDNodeFlags Flags; 3898 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3899 Flags.setNoUnsignedWrap(true); 3900 3901 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3902 3903 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3904 continue; 3905 } 3906 3907 // N = N + Idx * ElementMul; 3908 SDValue IdxN = getValue(Idx); 3909 3910 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3911 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3912 VectorElementCount); 3913 if (VectorElementCount.isScalable()) 3914 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3915 else 3916 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3917 } 3918 3919 // If the index is smaller or larger than intptr_t, truncate or extend 3920 // it. 3921 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3922 3923 if (ElementScalable) { 3924 EVT VScaleTy = N.getValueType().getScalarType(); 3925 SDValue VScale = DAG.getNode( 3926 ISD::VSCALE, dl, VScaleTy, 3927 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3928 if (IsVectorGEP) 3929 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3930 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3931 } else { 3932 // If this is a multiply by a power of two, turn it into a shl 3933 // immediately. This is a very common case. 3934 if (ElementMul != 1) { 3935 if (ElementMul.isPowerOf2()) { 3936 unsigned Amt = ElementMul.logBase2(); 3937 IdxN = DAG.getNode(ISD::SHL, dl, 3938 N.getValueType(), IdxN, 3939 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3940 } else { 3941 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3942 IdxN.getValueType()); 3943 IdxN = DAG.getNode(ISD::MUL, dl, 3944 N.getValueType(), IdxN, Scale); 3945 } 3946 } 3947 } 3948 3949 N = DAG.getNode(ISD::ADD, dl, 3950 N.getValueType(), N, IdxN); 3951 } 3952 } 3953 3954 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3955 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3956 if (IsVectorGEP) { 3957 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3958 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3959 } 3960 3961 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3962 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3963 3964 setValue(&I, N); 3965 } 3966 3967 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3968 // If this is a fixed sized alloca in the entry block of the function, 3969 // allocate it statically on the stack. 3970 if (FuncInfo.StaticAllocaMap.count(&I)) 3971 return; // getValue will auto-populate this. 3972 3973 SDLoc dl = getCurSDLoc(); 3974 Type *Ty = I.getAllocatedType(); 3975 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3976 auto &DL = DAG.getDataLayout(); 3977 uint64_t TySize = DL.getTypeAllocSize(Ty); 3978 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3979 3980 SDValue AllocSize = getValue(I.getArraySize()); 3981 3982 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3983 if (AllocSize.getValueType() != IntPtr) 3984 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3985 3986 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3987 AllocSize, 3988 DAG.getConstant(TySize, dl, IntPtr)); 3989 3990 // Handle alignment. If the requested alignment is less than or equal to 3991 // the stack alignment, ignore it. If the size is greater than or equal to 3992 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3993 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3994 if (*Alignment <= StackAlign) 3995 Alignment = None; 3996 3997 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3998 // Round the size of the allocation up to the stack alignment size 3999 // by add SA-1 to the size. This doesn't overflow because we're computing 4000 // an address inside an alloca. 4001 SDNodeFlags Flags; 4002 Flags.setNoUnsignedWrap(true); 4003 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4004 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4005 4006 // Mask out the low bits for alignment purposes. 4007 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4008 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4009 4010 SDValue Ops[] = { 4011 getRoot(), AllocSize, 4012 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4013 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4014 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4015 setValue(&I, DSA); 4016 DAG.setRoot(DSA.getValue(1)); 4017 4018 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4019 } 4020 4021 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4022 if (I.isAtomic()) 4023 return visitAtomicLoad(I); 4024 4025 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4026 const Value *SV = I.getOperand(0); 4027 if (TLI.supportSwiftError()) { 4028 // Swifterror values can come from either a function parameter with 4029 // swifterror attribute or an alloca with swifterror attribute. 4030 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4031 if (Arg->hasSwiftErrorAttr()) 4032 return visitLoadFromSwiftError(I); 4033 } 4034 4035 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4036 if (Alloca->isSwiftError()) 4037 return visitLoadFromSwiftError(I); 4038 } 4039 } 4040 4041 SDValue Ptr = getValue(SV); 4042 4043 Type *Ty = I.getType(); 4044 Align Alignment = I.getAlign(); 4045 4046 AAMDNodes AAInfo; 4047 I.getAAMetadata(AAInfo); 4048 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4049 4050 SmallVector<EVT, 4> ValueVTs, MemVTs; 4051 SmallVector<uint64_t, 4> Offsets; 4052 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4053 unsigned NumValues = ValueVTs.size(); 4054 if (NumValues == 0) 4055 return; 4056 4057 bool isVolatile = I.isVolatile(); 4058 4059 SDValue Root; 4060 bool ConstantMemory = false; 4061 if (isVolatile) 4062 // Serialize volatile loads with other side effects. 4063 Root = getRoot(); 4064 else if (NumValues > MaxParallelChains) 4065 Root = getMemoryRoot(); 4066 else if (AA && 4067 AA->pointsToConstantMemory(MemoryLocation( 4068 SV, 4069 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4070 AAInfo))) { 4071 // Do not serialize (non-volatile) loads of constant memory with anything. 4072 Root = DAG.getEntryNode(); 4073 ConstantMemory = true; 4074 } else { 4075 // Do not serialize non-volatile loads against each other. 4076 Root = DAG.getRoot(); 4077 } 4078 4079 SDLoc dl = getCurSDLoc(); 4080 4081 if (isVolatile) 4082 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4083 4084 // An aggregate load cannot wrap around the address space, so offsets to its 4085 // parts don't wrap either. 4086 SDNodeFlags Flags; 4087 Flags.setNoUnsignedWrap(true); 4088 4089 SmallVector<SDValue, 4> Values(NumValues); 4090 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4091 EVT PtrVT = Ptr.getValueType(); 4092 4093 MachineMemOperand::Flags MMOFlags 4094 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4095 4096 unsigned ChainI = 0; 4097 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4098 // Serializing loads here may result in excessive register pressure, and 4099 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4100 // could recover a bit by hoisting nodes upward in the chain by recognizing 4101 // they are side-effect free or do not alias. The optimizer should really 4102 // avoid this case by converting large object/array copies to llvm.memcpy 4103 // (MaxParallelChains should always remain as failsafe). 4104 if (ChainI == MaxParallelChains) { 4105 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4106 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4107 makeArrayRef(Chains.data(), ChainI)); 4108 Root = Chain; 4109 ChainI = 0; 4110 } 4111 SDValue A = DAG.getNode(ISD::ADD, dl, 4112 PtrVT, Ptr, 4113 DAG.getConstant(Offsets[i], dl, PtrVT), 4114 Flags); 4115 4116 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4117 MachinePointerInfo(SV, Offsets[i]), Alignment, 4118 MMOFlags, AAInfo, Ranges); 4119 Chains[ChainI] = L.getValue(1); 4120 4121 if (MemVTs[i] != ValueVTs[i]) 4122 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4123 4124 Values[i] = L; 4125 } 4126 4127 if (!ConstantMemory) { 4128 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4129 makeArrayRef(Chains.data(), ChainI)); 4130 if (isVolatile) 4131 DAG.setRoot(Chain); 4132 else 4133 PendingLoads.push_back(Chain); 4134 } 4135 4136 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4137 DAG.getVTList(ValueVTs), Values)); 4138 } 4139 4140 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4141 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4142 "call visitStoreToSwiftError when backend supports swifterror"); 4143 4144 SmallVector<EVT, 4> ValueVTs; 4145 SmallVector<uint64_t, 4> Offsets; 4146 const Value *SrcV = I.getOperand(0); 4147 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4148 SrcV->getType(), ValueVTs, &Offsets); 4149 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4150 "expect a single EVT for swifterror"); 4151 4152 SDValue Src = getValue(SrcV); 4153 // Create a virtual register, then update the virtual register. 4154 Register VReg = 4155 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4156 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4157 // Chain can be getRoot or getControlRoot. 4158 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4159 SDValue(Src.getNode(), Src.getResNo())); 4160 DAG.setRoot(CopyNode); 4161 } 4162 4163 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4164 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4165 "call visitLoadFromSwiftError when backend supports swifterror"); 4166 4167 assert(!I.isVolatile() && 4168 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4169 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4170 "Support volatile, non temporal, invariant for load_from_swift_error"); 4171 4172 const Value *SV = I.getOperand(0); 4173 Type *Ty = I.getType(); 4174 AAMDNodes AAInfo; 4175 I.getAAMetadata(AAInfo); 4176 assert( 4177 (!AA || 4178 !AA->pointsToConstantMemory(MemoryLocation( 4179 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4180 AAInfo))) && 4181 "load_from_swift_error should not be constant memory"); 4182 4183 SmallVector<EVT, 4> ValueVTs; 4184 SmallVector<uint64_t, 4> Offsets; 4185 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4186 ValueVTs, &Offsets); 4187 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4188 "expect a single EVT for swifterror"); 4189 4190 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4191 SDValue L = DAG.getCopyFromReg( 4192 getRoot(), getCurSDLoc(), 4193 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4194 4195 setValue(&I, L); 4196 } 4197 4198 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4199 if (I.isAtomic()) 4200 return visitAtomicStore(I); 4201 4202 const Value *SrcV = I.getOperand(0); 4203 const Value *PtrV = I.getOperand(1); 4204 4205 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4206 if (TLI.supportSwiftError()) { 4207 // Swifterror values can come from either a function parameter with 4208 // swifterror attribute or an alloca with swifterror attribute. 4209 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4210 if (Arg->hasSwiftErrorAttr()) 4211 return visitStoreToSwiftError(I); 4212 } 4213 4214 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4215 if (Alloca->isSwiftError()) 4216 return visitStoreToSwiftError(I); 4217 } 4218 } 4219 4220 SmallVector<EVT, 4> ValueVTs, MemVTs; 4221 SmallVector<uint64_t, 4> Offsets; 4222 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4223 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4224 unsigned NumValues = ValueVTs.size(); 4225 if (NumValues == 0) 4226 return; 4227 4228 // Get the lowered operands. Note that we do this after 4229 // checking if NumResults is zero, because with zero results 4230 // the operands won't have values in the map. 4231 SDValue Src = getValue(SrcV); 4232 SDValue Ptr = getValue(PtrV); 4233 4234 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4235 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4236 SDLoc dl = getCurSDLoc(); 4237 Align Alignment = I.getAlign(); 4238 AAMDNodes AAInfo; 4239 I.getAAMetadata(AAInfo); 4240 4241 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4242 4243 // An aggregate load cannot wrap around the address space, so offsets to its 4244 // parts don't wrap either. 4245 SDNodeFlags Flags; 4246 Flags.setNoUnsignedWrap(true); 4247 4248 unsigned ChainI = 0; 4249 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4250 // See visitLoad comments. 4251 if (ChainI == MaxParallelChains) { 4252 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4253 makeArrayRef(Chains.data(), ChainI)); 4254 Root = Chain; 4255 ChainI = 0; 4256 } 4257 SDValue Add = 4258 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4259 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4260 if (MemVTs[i] != ValueVTs[i]) 4261 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4262 SDValue St = 4263 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4264 Alignment, MMOFlags, AAInfo); 4265 Chains[ChainI] = St; 4266 } 4267 4268 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4269 makeArrayRef(Chains.data(), ChainI)); 4270 DAG.setRoot(StoreNode); 4271 } 4272 4273 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4274 bool IsCompressing) { 4275 SDLoc sdl = getCurSDLoc(); 4276 4277 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4278 MaybeAlign &Alignment) { 4279 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4280 Src0 = I.getArgOperand(0); 4281 Ptr = I.getArgOperand(1); 4282 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4283 Mask = I.getArgOperand(3); 4284 }; 4285 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4286 MaybeAlign &Alignment) { 4287 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4288 Src0 = I.getArgOperand(0); 4289 Ptr = I.getArgOperand(1); 4290 Mask = I.getArgOperand(2); 4291 Alignment = None; 4292 }; 4293 4294 Value *PtrOperand, *MaskOperand, *Src0Operand; 4295 MaybeAlign Alignment; 4296 if (IsCompressing) 4297 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4298 else 4299 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4300 4301 SDValue Ptr = getValue(PtrOperand); 4302 SDValue Src0 = getValue(Src0Operand); 4303 SDValue Mask = getValue(MaskOperand); 4304 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4305 4306 EVT VT = Src0.getValueType(); 4307 if (!Alignment) 4308 Alignment = DAG.getEVTAlign(VT); 4309 4310 AAMDNodes AAInfo; 4311 I.getAAMetadata(AAInfo); 4312 4313 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4314 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4315 // TODO: Make MachineMemOperands aware of scalable 4316 // vectors. 4317 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4318 SDValue StoreNode = 4319 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4320 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4321 DAG.setRoot(StoreNode); 4322 setValue(&I, StoreNode); 4323 } 4324 4325 // Get a uniform base for the Gather/Scatter intrinsic. 4326 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4327 // We try to represent it as a base pointer + vector of indices. 4328 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4329 // The first operand of the GEP may be a single pointer or a vector of pointers 4330 // Example: 4331 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4332 // or 4333 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4334 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4335 // 4336 // When the first GEP operand is a single pointer - it is the uniform base we 4337 // are looking for. If first operand of the GEP is a splat vector - we 4338 // extract the splat value and use it as a uniform base. 4339 // In all other cases the function returns 'false'. 4340 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4341 ISD::MemIndexType &IndexType, SDValue &Scale, 4342 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4343 SelectionDAG& DAG = SDB->DAG; 4344 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4345 const DataLayout &DL = DAG.getDataLayout(); 4346 4347 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4348 4349 // Handle splat constant pointer. 4350 if (auto *C = dyn_cast<Constant>(Ptr)) { 4351 C = C->getSplatValue(); 4352 if (!C) 4353 return false; 4354 4355 Base = SDB->getValue(C); 4356 4357 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4358 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4359 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4360 IndexType = ISD::SIGNED_SCALED; 4361 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4362 return true; 4363 } 4364 4365 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4366 if (!GEP || GEP->getParent() != CurBB) 4367 return false; 4368 4369 if (GEP->getNumOperands() != 2) 4370 return false; 4371 4372 const Value *BasePtr = GEP->getPointerOperand(); 4373 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4374 4375 // Make sure the base is scalar and the index is a vector. 4376 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4377 return false; 4378 4379 Base = SDB->getValue(BasePtr); 4380 Index = SDB->getValue(IndexVal); 4381 IndexType = ISD::SIGNED_SCALED; 4382 Scale = DAG.getTargetConstant( 4383 DL.getTypeAllocSize(GEP->getResultElementType()), 4384 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4385 return true; 4386 } 4387 4388 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4389 SDLoc sdl = getCurSDLoc(); 4390 4391 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4392 const Value *Ptr = I.getArgOperand(1); 4393 SDValue Src0 = getValue(I.getArgOperand(0)); 4394 SDValue Mask = getValue(I.getArgOperand(3)); 4395 EVT VT = Src0.getValueType(); 4396 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4397 ->getMaybeAlignValue() 4398 .getValueOr(DAG.getEVTAlign(VT)); 4399 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4400 4401 AAMDNodes AAInfo; 4402 I.getAAMetadata(AAInfo); 4403 4404 SDValue Base; 4405 SDValue Index; 4406 ISD::MemIndexType IndexType; 4407 SDValue Scale; 4408 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4409 I.getParent()); 4410 4411 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4412 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4413 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4414 // TODO: Make MachineMemOperands aware of scalable 4415 // vectors. 4416 MemoryLocation::UnknownSize, Alignment, AAInfo); 4417 if (!UniformBase) { 4418 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4419 Index = getValue(Ptr); 4420 IndexType = ISD::SIGNED_UNSCALED; 4421 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4422 } 4423 4424 EVT IdxVT = Index.getValueType(); 4425 EVT EltTy = IdxVT.getVectorElementType(); 4426 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4427 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4428 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4429 } 4430 4431 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4432 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4433 Ops, MMO, IndexType, false); 4434 DAG.setRoot(Scatter); 4435 setValue(&I, Scatter); 4436 } 4437 4438 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4439 SDLoc sdl = getCurSDLoc(); 4440 4441 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4442 MaybeAlign &Alignment) { 4443 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4444 Ptr = I.getArgOperand(0); 4445 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4446 Mask = I.getArgOperand(2); 4447 Src0 = I.getArgOperand(3); 4448 }; 4449 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4450 MaybeAlign &Alignment) { 4451 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4452 Ptr = I.getArgOperand(0); 4453 Alignment = None; 4454 Mask = I.getArgOperand(1); 4455 Src0 = I.getArgOperand(2); 4456 }; 4457 4458 Value *PtrOperand, *MaskOperand, *Src0Operand; 4459 MaybeAlign Alignment; 4460 if (IsExpanding) 4461 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4462 else 4463 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4464 4465 SDValue Ptr = getValue(PtrOperand); 4466 SDValue Src0 = getValue(Src0Operand); 4467 SDValue Mask = getValue(MaskOperand); 4468 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4469 4470 EVT VT = Src0.getValueType(); 4471 if (!Alignment) 4472 Alignment = DAG.getEVTAlign(VT); 4473 4474 AAMDNodes AAInfo; 4475 I.getAAMetadata(AAInfo); 4476 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4477 4478 // Do not serialize masked loads of constant memory with anything. 4479 MemoryLocation ML; 4480 if (VT.isScalableVector()) 4481 ML = MemoryLocation::getAfter(PtrOperand); 4482 else 4483 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4484 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4485 AAInfo); 4486 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4487 4488 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4489 4490 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4491 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4492 // TODO: Make MachineMemOperands aware of scalable 4493 // vectors. 4494 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4495 4496 SDValue Load = 4497 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4498 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4499 if (AddToChain) 4500 PendingLoads.push_back(Load.getValue(1)); 4501 setValue(&I, Load); 4502 } 4503 4504 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4505 SDLoc sdl = getCurSDLoc(); 4506 4507 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4508 const Value *Ptr = I.getArgOperand(0); 4509 SDValue Src0 = getValue(I.getArgOperand(3)); 4510 SDValue Mask = getValue(I.getArgOperand(2)); 4511 4512 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4513 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4514 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4515 ->getMaybeAlignValue() 4516 .getValueOr(DAG.getEVTAlign(VT)); 4517 4518 AAMDNodes AAInfo; 4519 I.getAAMetadata(AAInfo); 4520 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4521 4522 SDValue Root = DAG.getRoot(); 4523 SDValue Base; 4524 SDValue Index; 4525 ISD::MemIndexType IndexType; 4526 SDValue Scale; 4527 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4528 I.getParent()); 4529 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4530 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4531 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4532 // TODO: Make MachineMemOperands aware of scalable 4533 // vectors. 4534 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4535 4536 if (!UniformBase) { 4537 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4538 Index = getValue(Ptr); 4539 IndexType = ISD::SIGNED_UNSCALED; 4540 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4541 } 4542 4543 EVT IdxVT = Index.getValueType(); 4544 EVT EltTy = IdxVT.getVectorElementType(); 4545 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4546 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4547 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4548 } 4549 4550 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4551 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4552 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4553 4554 PendingLoads.push_back(Gather.getValue(1)); 4555 setValue(&I, Gather); 4556 } 4557 4558 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4559 SDLoc dl = getCurSDLoc(); 4560 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4561 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4562 SyncScope::ID SSID = I.getSyncScopeID(); 4563 4564 SDValue InChain = getRoot(); 4565 4566 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4567 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4568 4569 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4570 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4571 4572 MachineFunction &MF = DAG.getMachineFunction(); 4573 MachineMemOperand *MMO = MF.getMachineMemOperand( 4574 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4575 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4576 FailureOrdering); 4577 4578 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4579 dl, MemVT, VTs, InChain, 4580 getValue(I.getPointerOperand()), 4581 getValue(I.getCompareOperand()), 4582 getValue(I.getNewValOperand()), MMO); 4583 4584 SDValue OutChain = L.getValue(2); 4585 4586 setValue(&I, L); 4587 DAG.setRoot(OutChain); 4588 } 4589 4590 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4591 SDLoc dl = getCurSDLoc(); 4592 ISD::NodeType NT; 4593 switch (I.getOperation()) { 4594 default: llvm_unreachable("Unknown atomicrmw operation"); 4595 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4596 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4597 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4598 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4599 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4600 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4601 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4602 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4603 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4604 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4605 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4606 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4607 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4608 } 4609 AtomicOrdering Ordering = I.getOrdering(); 4610 SyncScope::ID SSID = I.getSyncScopeID(); 4611 4612 SDValue InChain = getRoot(); 4613 4614 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4615 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4616 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4617 4618 MachineFunction &MF = DAG.getMachineFunction(); 4619 MachineMemOperand *MMO = MF.getMachineMemOperand( 4620 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4621 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4622 4623 SDValue L = 4624 DAG.getAtomic(NT, dl, MemVT, InChain, 4625 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4626 MMO); 4627 4628 SDValue OutChain = L.getValue(1); 4629 4630 setValue(&I, L); 4631 DAG.setRoot(OutChain); 4632 } 4633 4634 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4635 SDLoc dl = getCurSDLoc(); 4636 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4637 SDValue Ops[3]; 4638 Ops[0] = getRoot(); 4639 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4640 TLI.getFenceOperandTy(DAG.getDataLayout())); 4641 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4642 TLI.getFenceOperandTy(DAG.getDataLayout())); 4643 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4644 } 4645 4646 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4647 SDLoc dl = getCurSDLoc(); 4648 AtomicOrdering Order = I.getOrdering(); 4649 SyncScope::ID SSID = I.getSyncScopeID(); 4650 4651 SDValue InChain = getRoot(); 4652 4653 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4654 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4655 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4656 4657 if (!TLI.supportsUnalignedAtomics() && 4658 I.getAlignment() < MemVT.getSizeInBits() / 8) 4659 report_fatal_error("Cannot generate unaligned atomic load"); 4660 4661 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4662 4663 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4664 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4665 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4666 4667 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4668 4669 SDValue Ptr = getValue(I.getPointerOperand()); 4670 4671 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4672 // TODO: Once this is better exercised by tests, it should be merged with 4673 // the normal path for loads to prevent future divergence. 4674 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4675 if (MemVT != VT) 4676 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4677 4678 setValue(&I, L); 4679 SDValue OutChain = L.getValue(1); 4680 if (!I.isUnordered()) 4681 DAG.setRoot(OutChain); 4682 else 4683 PendingLoads.push_back(OutChain); 4684 return; 4685 } 4686 4687 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4688 Ptr, MMO); 4689 4690 SDValue OutChain = L.getValue(1); 4691 if (MemVT != VT) 4692 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4693 4694 setValue(&I, L); 4695 DAG.setRoot(OutChain); 4696 } 4697 4698 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4699 SDLoc dl = getCurSDLoc(); 4700 4701 AtomicOrdering Ordering = I.getOrdering(); 4702 SyncScope::ID SSID = I.getSyncScopeID(); 4703 4704 SDValue InChain = getRoot(); 4705 4706 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4707 EVT MemVT = 4708 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4709 4710 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4711 report_fatal_error("Cannot generate unaligned atomic store"); 4712 4713 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4714 4715 MachineFunction &MF = DAG.getMachineFunction(); 4716 MachineMemOperand *MMO = MF.getMachineMemOperand( 4717 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4718 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4719 4720 SDValue Val = getValue(I.getValueOperand()); 4721 if (Val.getValueType() != MemVT) 4722 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4723 SDValue Ptr = getValue(I.getPointerOperand()); 4724 4725 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4726 // TODO: Once this is better exercised by tests, it should be merged with 4727 // the normal path for stores to prevent future divergence. 4728 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4729 DAG.setRoot(S); 4730 return; 4731 } 4732 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4733 Ptr, Val, MMO); 4734 4735 4736 DAG.setRoot(OutChain); 4737 } 4738 4739 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4740 /// node. 4741 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4742 unsigned Intrinsic) { 4743 // Ignore the callsite's attributes. A specific call site may be marked with 4744 // readnone, but the lowering code will expect the chain based on the 4745 // definition. 4746 const Function *F = I.getCalledFunction(); 4747 bool HasChain = !F->doesNotAccessMemory(); 4748 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4749 4750 // Build the operand list. 4751 SmallVector<SDValue, 8> Ops; 4752 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4753 if (OnlyLoad) { 4754 // We don't need to serialize loads against other loads. 4755 Ops.push_back(DAG.getRoot()); 4756 } else { 4757 Ops.push_back(getRoot()); 4758 } 4759 } 4760 4761 // Info is set by getTgtMemInstrinsic 4762 TargetLowering::IntrinsicInfo Info; 4763 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4764 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4765 DAG.getMachineFunction(), 4766 Intrinsic); 4767 4768 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4769 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4770 Info.opc == ISD::INTRINSIC_W_CHAIN) 4771 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4772 TLI.getPointerTy(DAG.getDataLayout()))); 4773 4774 // Add all operands of the call to the operand list. 4775 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4776 const Value *Arg = I.getArgOperand(i); 4777 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4778 Ops.push_back(getValue(Arg)); 4779 continue; 4780 } 4781 4782 // Use TargetConstant instead of a regular constant for immarg. 4783 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4784 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4785 assert(CI->getBitWidth() <= 64 && 4786 "large intrinsic immediates not handled"); 4787 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4788 } else { 4789 Ops.push_back( 4790 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4791 } 4792 } 4793 4794 SmallVector<EVT, 4> ValueVTs; 4795 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4796 4797 if (HasChain) 4798 ValueVTs.push_back(MVT::Other); 4799 4800 SDVTList VTs = DAG.getVTList(ValueVTs); 4801 4802 // Create the node. 4803 SDValue Result; 4804 if (IsTgtIntrinsic) { 4805 // This is target intrinsic that touches memory 4806 AAMDNodes AAInfo; 4807 I.getAAMetadata(AAInfo); 4808 Result = 4809 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4810 MachinePointerInfo(Info.ptrVal, Info.offset), 4811 Info.align, Info.flags, Info.size, AAInfo); 4812 } else if (!HasChain) { 4813 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4814 } else if (!I.getType()->isVoidTy()) { 4815 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4816 } else { 4817 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4818 } 4819 4820 if (HasChain) { 4821 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4822 if (OnlyLoad) 4823 PendingLoads.push_back(Chain); 4824 else 4825 DAG.setRoot(Chain); 4826 } 4827 4828 if (!I.getType()->isVoidTy()) { 4829 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4830 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4831 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4832 } else 4833 Result = lowerRangeToAssertZExt(DAG, I, Result); 4834 4835 MaybeAlign Alignment = I.getRetAlign(); 4836 if (!Alignment) 4837 Alignment = F->getAttributes().getRetAlignment(); 4838 // Insert `assertalign` node if there's an alignment. 4839 if (InsertAssertAlign && Alignment) { 4840 Result = 4841 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4842 } 4843 4844 setValue(&I, Result); 4845 } 4846 } 4847 4848 /// GetSignificand - Get the significand and build it into a floating-point 4849 /// number with exponent of 1: 4850 /// 4851 /// Op = (Op & 0x007fffff) | 0x3f800000; 4852 /// 4853 /// where Op is the hexadecimal representation of floating point value. 4854 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4855 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4856 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4857 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4858 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4859 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4860 } 4861 4862 /// GetExponent - Get the exponent: 4863 /// 4864 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4865 /// 4866 /// where Op is the hexadecimal representation of floating point value. 4867 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4868 const TargetLowering &TLI, const SDLoc &dl) { 4869 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4870 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4871 SDValue t1 = DAG.getNode( 4872 ISD::SRL, dl, MVT::i32, t0, 4873 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4874 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4875 DAG.getConstant(127, dl, MVT::i32)); 4876 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4877 } 4878 4879 /// getF32Constant - Get 32-bit floating point constant. 4880 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4881 const SDLoc &dl) { 4882 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4883 MVT::f32); 4884 } 4885 4886 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4887 SelectionDAG &DAG) { 4888 // TODO: What fast-math-flags should be set on the floating-point nodes? 4889 4890 // IntegerPartOfX = ((int32_t)(t0); 4891 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4892 4893 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4894 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4895 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4896 4897 // IntegerPartOfX <<= 23; 4898 IntegerPartOfX = DAG.getNode( 4899 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4900 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4901 DAG.getDataLayout()))); 4902 4903 SDValue TwoToFractionalPartOfX; 4904 if (LimitFloatPrecision <= 6) { 4905 // For floating-point precision of 6: 4906 // 4907 // TwoToFractionalPartOfX = 4908 // 0.997535578f + 4909 // (0.735607626f + 0.252464424f * x) * x; 4910 // 4911 // error 0.0144103317, which is 6 bits 4912 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4913 getF32Constant(DAG, 0x3e814304, dl)); 4914 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4915 getF32Constant(DAG, 0x3f3c50c8, dl)); 4916 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4917 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4918 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4919 } else if (LimitFloatPrecision <= 12) { 4920 // For floating-point precision of 12: 4921 // 4922 // TwoToFractionalPartOfX = 4923 // 0.999892986f + 4924 // (0.696457318f + 4925 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4926 // 4927 // error 0.000107046256, which is 13 to 14 bits 4928 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4929 getF32Constant(DAG, 0x3da235e3, dl)); 4930 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4931 getF32Constant(DAG, 0x3e65b8f3, dl)); 4932 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4933 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4934 getF32Constant(DAG, 0x3f324b07, dl)); 4935 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4936 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4937 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4938 } else { // LimitFloatPrecision <= 18 4939 // For floating-point precision of 18: 4940 // 4941 // TwoToFractionalPartOfX = 4942 // 0.999999982f + 4943 // (0.693148872f + 4944 // (0.240227044f + 4945 // (0.554906021e-1f + 4946 // (0.961591928e-2f + 4947 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4948 // error 2.47208000*10^(-7), which is better than 18 bits 4949 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4950 getF32Constant(DAG, 0x3924b03e, dl)); 4951 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4952 getF32Constant(DAG, 0x3ab24b87, dl)); 4953 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4954 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4955 getF32Constant(DAG, 0x3c1d8c17, dl)); 4956 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4957 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4958 getF32Constant(DAG, 0x3d634a1d, dl)); 4959 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4960 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4961 getF32Constant(DAG, 0x3e75fe14, dl)); 4962 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4963 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4964 getF32Constant(DAG, 0x3f317234, dl)); 4965 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4966 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4967 getF32Constant(DAG, 0x3f800000, dl)); 4968 } 4969 4970 // Add the exponent into the result in integer domain. 4971 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4972 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4973 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4974 } 4975 4976 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4977 /// limited-precision mode. 4978 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4979 const TargetLowering &TLI, SDNodeFlags Flags) { 4980 if (Op.getValueType() == MVT::f32 && 4981 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4982 4983 // Put the exponent in the right bit position for later addition to the 4984 // final result: 4985 // 4986 // t0 = Op * log2(e) 4987 4988 // TODO: What fast-math-flags should be set here? 4989 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4990 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4991 return getLimitedPrecisionExp2(t0, dl, DAG); 4992 } 4993 4994 // No special expansion. 4995 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 4996 } 4997 4998 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4999 /// limited-precision mode. 5000 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5001 const TargetLowering &TLI, SDNodeFlags Flags) { 5002 // TODO: What fast-math-flags should be set on the floating-point nodes? 5003 5004 if (Op.getValueType() == MVT::f32 && 5005 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5006 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5007 5008 // Scale the exponent by log(2). 5009 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5010 SDValue LogOfExponent = 5011 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5012 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5013 5014 // Get the significand and build it into a floating-point number with 5015 // exponent of 1. 5016 SDValue X = GetSignificand(DAG, Op1, dl); 5017 5018 SDValue LogOfMantissa; 5019 if (LimitFloatPrecision <= 6) { 5020 // For floating-point precision of 6: 5021 // 5022 // LogofMantissa = 5023 // -1.1609546f + 5024 // (1.4034025f - 0.23903021f * x) * x; 5025 // 5026 // error 0.0034276066, which is better than 8 bits 5027 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5028 getF32Constant(DAG, 0xbe74c456, dl)); 5029 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5030 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5031 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5032 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5033 getF32Constant(DAG, 0x3f949a29, dl)); 5034 } else if (LimitFloatPrecision <= 12) { 5035 // For floating-point precision of 12: 5036 // 5037 // LogOfMantissa = 5038 // -1.7417939f + 5039 // (2.8212026f + 5040 // (-1.4699568f + 5041 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5042 // 5043 // error 0.000061011436, which is 14 bits 5044 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5045 getF32Constant(DAG, 0xbd67b6d6, dl)); 5046 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5047 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5048 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5049 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5050 getF32Constant(DAG, 0x3fbc278b, dl)); 5051 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5052 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5053 getF32Constant(DAG, 0x40348e95, dl)); 5054 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5055 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5056 getF32Constant(DAG, 0x3fdef31a, dl)); 5057 } else { // LimitFloatPrecision <= 18 5058 // For floating-point precision of 18: 5059 // 5060 // LogOfMantissa = 5061 // -2.1072184f + 5062 // (4.2372794f + 5063 // (-3.7029485f + 5064 // (2.2781945f + 5065 // (-0.87823314f + 5066 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5067 // 5068 // error 0.0000023660568, which is better than 18 bits 5069 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5070 getF32Constant(DAG, 0xbc91e5ac, dl)); 5071 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5072 getF32Constant(DAG, 0x3e4350aa, dl)); 5073 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5074 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5075 getF32Constant(DAG, 0x3f60d3e3, dl)); 5076 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5077 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5078 getF32Constant(DAG, 0x4011cdf0, dl)); 5079 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5080 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5081 getF32Constant(DAG, 0x406cfd1c, dl)); 5082 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5083 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5084 getF32Constant(DAG, 0x408797cb, dl)); 5085 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5086 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5087 getF32Constant(DAG, 0x4006dcab, dl)); 5088 } 5089 5090 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5091 } 5092 5093 // No special expansion. 5094 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5095 } 5096 5097 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5098 /// limited-precision mode. 5099 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5100 const TargetLowering &TLI, SDNodeFlags Flags) { 5101 // TODO: What fast-math-flags should be set on the floating-point nodes? 5102 5103 if (Op.getValueType() == MVT::f32 && 5104 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5105 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5106 5107 // Get the exponent. 5108 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5109 5110 // Get the significand and build it into a floating-point number with 5111 // exponent of 1. 5112 SDValue X = GetSignificand(DAG, Op1, dl); 5113 5114 // Different possible minimax approximations of significand in 5115 // floating-point for various degrees of accuracy over [1,2]. 5116 SDValue Log2ofMantissa; 5117 if (LimitFloatPrecision <= 6) { 5118 // For floating-point precision of 6: 5119 // 5120 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5121 // 5122 // error 0.0049451742, which is more than 7 bits 5123 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5124 getF32Constant(DAG, 0xbeb08fe0, dl)); 5125 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5126 getF32Constant(DAG, 0x40019463, dl)); 5127 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5128 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5129 getF32Constant(DAG, 0x3fd6633d, dl)); 5130 } else if (LimitFloatPrecision <= 12) { 5131 // For floating-point precision of 12: 5132 // 5133 // Log2ofMantissa = 5134 // -2.51285454f + 5135 // (4.07009056f + 5136 // (-2.12067489f + 5137 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5138 // 5139 // error 0.0000876136000, which is better than 13 bits 5140 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5141 getF32Constant(DAG, 0xbda7262e, dl)); 5142 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5143 getF32Constant(DAG, 0x3f25280b, dl)); 5144 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5145 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5146 getF32Constant(DAG, 0x4007b923, dl)); 5147 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5148 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5149 getF32Constant(DAG, 0x40823e2f, dl)); 5150 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5151 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5152 getF32Constant(DAG, 0x4020d29c, dl)); 5153 } else { // LimitFloatPrecision <= 18 5154 // For floating-point precision of 18: 5155 // 5156 // Log2ofMantissa = 5157 // -3.0400495f + 5158 // (6.1129976f + 5159 // (-5.3420409f + 5160 // (3.2865683f + 5161 // (-1.2669343f + 5162 // (0.27515199f - 5163 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5164 // 5165 // error 0.0000018516, which is better than 18 bits 5166 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5167 getF32Constant(DAG, 0xbcd2769e, dl)); 5168 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5169 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5170 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5171 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5172 getF32Constant(DAG, 0x3fa22ae7, dl)); 5173 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5174 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5175 getF32Constant(DAG, 0x40525723, dl)); 5176 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5177 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5178 getF32Constant(DAG, 0x40aaf200, dl)); 5179 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5180 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5181 getF32Constant(DAG, 0x40c39dad, dl)); 5182 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5183 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5184 getF32Constant(DAG, 0x4042902c, dl)); 5185 } 5186 5187 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5188 } 5189 5190 // No special expansion. 5191 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5192 } 5193 5194 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5195 /// limited-precision mode. 5196 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5197 const TargetLowering &TLI, SDNodeFlags Flags) { 5198 // TODO: What fast-math-flags should be set on the floating-point nodes? 5199 5200 if (Op.getValueType() == MVT::f32 && 5201 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5202 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5203 5204 // Scale the exponent by log10(2) [0.30102999f]. 5205 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5206 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5207 getF32Constant(DAG, 0x3e9a209a, dl)); 5208 5209 // Get the significand and build it into a floating-point number with 5210 // exponent of 1. 5211 SDValue X = GetSignificand(DAG, Op1, dl); 5212 5213 SDValue Log10ofMantissa; 5214 if (LimitFloatPrecision <= 6) { 5215 // For floating-point precision of 6: 5216 // 5217 // Log10ofMantissa = 5218 // -0.50419619f + 5219 // (0.60948995f - 0.10380950f * x) * x; 5220 // 5221 // error 0.0014886165, which is 6 bits 5222 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5223 getF32Constant(DAG, 0xbdd49a13, dl)); 5224 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5225 getF32Constant(DAG, 0x3f1c0789, dl)); 5226 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5227 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5228 getF32Constant(DAG, 0x3f011300, dl)); 5229 } else if (LimitFloatPrecision <= 12) { 5230 // For floating-point precision of 12: 5231 // 5232 // Log10ofMantissa = 5233 // -0.64831180f + 5234 // (0.91751397f + 5235 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5236 // 5237 // error 0.00019228036, which is better than 12 bits 5238 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5239 getF32Constant(DAG, 0x3d431f31, dl)); 5240 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5241 getF32Constant(DAG, 0x3ea21fb2, dl)); 5242 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5243 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5244 getF32Constant(DAG, 0x3f6ae232, dl)); 5245 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5246 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5247 getF32Constant(DAG, 0x3f25f7c3, dl)); 5248 } else { // LimitFloatPrecision <= 18 5249 // For floating-point precision of 18: 5250 // 5251 // Log10ofMantissa = 5252 // -0.84299375f + 5253 // (1.5327582f + 5254 // (-1.0688956f + 5255 // (0.49102474f + 5256 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5257 // 5258 // error 0.0000037995730, which is better than 18 bits 5259 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5260 getF32Constant(DAG, 0x3c5d51ce, dl)); 5261 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5262 getF32Constant(DAG, 0x3e00685a, dl)); 5263 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5264 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5265 getF32Constant(DAG, 0x3efb6798, dl)); 5266 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5267 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5268 getF32Constant(DAG, 0x3f88d192, dl)); 5269 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5270 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5271 getF32Constant(DAG, 0x3fc4316c, dl)); 5272 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5273 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5274 getF32Constant(DAG, 0x3f57ce70, dl)); 5275 } 5276 5277 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5278 } 5279 5280 // No special expansion. 5281 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5282 } 5283 5284 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5285 /// limited-precision mode. 5286 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5287 const TargetLowering &TLI, SDNodeFlags Flags) { 5288 if (Op.getValueType() == MVT::f32 && 5289 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5290 return getLimitedPrecisionExp2(Op, dl, DAG); 5291 5292 // No special expansion. 5293 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5294 } 5295 5296 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5297 /// limited-precision mode with x == 10.0f. 5298 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5299 SelectionDAG &DAG, const TargetLowering &TLI, 5300 SDNodeFlags Flags) { 5301 bool IsExp10 = false; 5302 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5303 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5304 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5305 APFloat Ten(10.0f); 5306 IsExp10 = LHSC->isExactlyValue(Ten); 5307 } 5308 } 5309 5310 // TODO: What fast-math-flags should be set on the FMUL node? 5311 if (IsExp10) { 5312 // Put the exponent in the right bit position for later addition to the 5313 // final result: 5314 // 5315 // #define LOG2OF10 3.3219281f 5316 // t0 = Op * LOG2OF10; 5317 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5318 getF32Constant(DAG, 0x40549a78, dl)); 5319 return getLimitedPrecisionExp2(t0, dl, DAG); 5320 } 5321 5322 // No special expansion. 5323 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5324 } 5325 5326 /// ExpandPowI - Expand a llvm.powi intrinsic. 5327 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5328 SelectionDAG &DAG) { 5329 // If RHS is a constant, we can expand this out to a multiplication tree, 5330 // otherwise we end up lowering to a call to __powidf2 (for example). When 5331 // optimizing for size, we only want to do this if the expansion would produce 5332 // a small number of multiplies, otherwise we do the full expansion. 5333 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5334 // Get the exponent as a positive value. 5335 unsigned Val = RHSC->getSExtValue(); 5336 if ((int)Val < 0) Val = -Val; 5337 5338 // powi(x, 0) -> 1.0 5339 if (Val == 0) 5340 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5341 5342 bool OptForSize = DAG.shouldOptForSize(); 5343 if (!OptForSize || 5344 // If optimizing for size, don't insert too many multiplies. 5345 // This inserts up to 5 multiplies. 5346 countPopulation(Val) + Log2_32(Val) < 7) { 5347 // We use the simple binary decomposition method to generate the multiply 5348 // sequence. There are more optimal ways to do this (for example, 5349 // powi(x,15) generates one more multiply than it should), but this has 5350 // the benefit of being both really simple and much better than a libcall. 5351 SDValue Res; // Logically starts equal to 1.0 5352 SDValue CurSquare = LHS; 5353 // TODO: Intrinsics should have fast-math-flags that propagate to these 5354 // nodes. 5355 while (Val) { 5356 if (Val & 1) { 5357 if (Res.getNode()) 5358 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5359 else 5360 Res = CurSquare; // 1.0*CurSquare. 5361 } 5362 5363 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5364 CurSquare, CurSquare); 5365 Val >>= 1; 5366 } 5367 5368 // If the original was negative, invert the result, producing 1/(x*x*x). 5369 if (RHSC->getSExtValue() < 0) 5370 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5371 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5372 return Res; 5373 } 5374 } 5375 5376 // Otherwise, expand to a libcall. 5377 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5378 } 5379 5380 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5381 SDValue LHS, SDValue RHS, SDValue Scale, 5382 SelectionDAG &DAG, const TargetLowering &TLI) { 5383 EVT VT = LHS.getValueType(); 5384 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5385 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5386 LLVMContext &Ctx = *DAG.getContext(); 5387 5388 // If the type is legal but the operation isn't, this node might survive all 5389 // the way to operation legalization. If we end up there and we do not have 5390 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5391 // node. 5392 5393 // Coax the legalizer into expanding the node during type legalization instead 5394 // by bumping the size by one bit. This will force it to Promote, enabling the 5395 // early expansion and avoiding the need to expand later. 5396 5397 // We don't have to do this if Scale is 0; that can always be expanded, unless 5398 // it's a saturating signed operation. Those can experience true integer 5399 // division overflow, a case which we must avoid. 5400 5401 // FIXME: We wouldn't have to do this (or any of the early 5402 // expansion/promotion) if it was possible to expand a libcall of an 5403 // illegal type during operation legalization. But it's not, so things 5404 // get a bit hacky. 5405 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5406 if ((ScaleInt > 0 || (Saturating && Signed)) && 5407 (TLI.isTypeLegal(VT) || 5408 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5409 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5410 Opcode, VT, ScaleInt); 5411 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5412 EVT PromVT; 5413 if (VT.isScalarInteger()) 5414 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5415 else if (VT.isVector()) { 5416 PromVT = VT.getVectorElementType(); 5417 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5418 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5419 } else 5420 llvm_unreachable("Wrong VT for DIVFIX?"); 5421 if (Signed) { 5422 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5423 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5424 } else { 5425 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5426 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5427 } 5428 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5429 // For saturating operations, we need to shift up the LHS to get the 5430 // proper saturation width, and then shift down again afterwards. 5431 if (Saturating) 5432 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5433 DAG.getConstant(1, DL, ShiftTy)); 5434 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5435 if (Saturating) 5436 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5437 DAG.getConstant(1, DL, ShiftTy)); 5438 return DAG.getZExtOrTrunc(Res, DL, VT); 5439 } 5440 } 5441 5442 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5443 } 5444 5445 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5446 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5447 static void 5448 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5449 const SDValue &N) { 5450 switch (N.getOpcode()) { 5451 case ISD::CopyFromReg: { 5452 SDValue Op = N.getOperand(1); 5453 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5454 Op.getValueType().getSizeInBits()); 5455 return; 5456 } 5457 case ISD::BITCAST: 5458 case ISD::AssertZext: 5459 case ISD::AssertSext: 5460 case ISD::TRUNCATE: 5461 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5462 return; 5463 case ISD::BUILD_PAIR: 5464 case ISD::BUILD_VECTOR: 5465 case ISD::CONCAT_VECTORS: 5466 for (SDValue Op : N->op_values()) 5467 getUnderlyingArgRegs(Regs, Op); 5468 return; 5469 default: 5470 return; 5471 } 5472 } 5473 5474 /// If the DbgValueInst is a dbg_value of a function argument, create the 5475 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5476 /// instruction selection, they will be inserted to the entry BB. 5477 /// We don't currently support this for variadic dbg_values, as they shouldn't 5478 /// appear for function arguments or in the prologue. 5479 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5480 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5481 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5482 const Argument *Arg = dyn_cast<Argument>(V); 5483 if (!Arg) 5484 return false; 5485 5486 if (!IsDbgDeclare) { 5487 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5488 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5489 // the entry block. 5490 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5491 if (!IsInEntryBlock) 5492 return false; 5493 5494 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5495 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5496 // variable that also is a param. 5497 // 5498 // Although, if we are at the top of the entry block already, we can still 5499 // emit using ArgDbgValue. This might catch some situations when the 5500 // dbg.value refers to an argument that isn't used in the entry block, so 5501 // any CopyToReg node would be optimized out and the only way to express 5502 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5503 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5504 // we should only emit as ArgDbgValue if the Variable is an argument to the 5505 // current function, and the dbg.value intrinsic is found in the entry 5506 // block. 5507 bool VariableIsFunctionInputArg = Variable->isParameter() && 5508 !DL->getInlinedAt(); 5509 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5510 if (!IsInPrologue && !VariableIsFunctionInputArg) 5511 return false; 5512 5513 // Here we assume that a function argument on IR level only can be used to 5514 // describe one input parameter on source level. If we for example have 5515 // source code like this 5516 // 5517 // struct A { long x, y; }; 5518 // void foo(struct A a, long b) { 5519 // ... 5520 // b = a.x; 5521 // ... 5522 // } 5523 // 5524 // and IR like this 5525 // 5526 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5527 // entry: 5528 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5529 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5530 // call void @llvm.dbg.value(metadata i32 %b, "b", 5531 // ... 5532 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5533 // ... 5534 // 5535 // then the last dbg.value is describing a parameter "b" using a value that 5536 // is an argument. But since we already has used %a1 to describe a parameter 5537 // we should not handle that last dbg.value here (that would result in an 5538 // incorrect hoisting of the DBG_VALUE to the function entry). 5539 // Notice that we allow one dbg.value per IR level argument, to accommodate 5540 // for the situation with fragments above. 5541 if (VariableIsFunctionInputArg) { 5542 unsigned ArgNo = Arg->getArgNo(); 5543 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5544 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5545 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5546 return false; 5547 FuncInfo.DescribedArgs.set(ArgNo); 5548 } 5549 } 5550 5551 MachineFunction &MF = DAG.getMachineFunction(); 5552 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5553 5554 bool IsIndirect = false; 5555 Optional<MachineOperand> Op; 5556 // Some arguments' frame index is recorded during argument lowering. 5557 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5558 if (FI != std::numeric_limits<int>::max()) 5559 Op = MachineOperand::CreateFI(FI); 5560 5561 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5562 if (!Op && N.getNode()) { 5563 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5564 Register Reg; 5565 if (ArgRegsAndSizes.size() == 1) 5566 Reg = ArgRegsAndSizes.front().first; 5567 5568 if (Reg && Reg.isVirtual()) { 5569 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5570 Register PR = RegInfo.getLiveInPhysReg(Reg); 5571 if (PR) 5572 Reg = PR; 5573 } 5574 if (Reg) { 5575 Op = MachineOperand::CreateReg(Reg, false); 5576 IsIndirect = IsDbgDeclare; 5577 } 5578 } 5579 5580 if (!Op && N.getNode()) { 5581 // Check if frame index is available. 5582 SDValue LCandidate = peekThroughBitcasts(N); 5583 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5584 if (FrameIndexSDNode *FINode = 5585 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5586 Op = MachineOperand::CreateFI(FINode->getIndex()); 5587 } 5588 5589 if (!Op) { 5590 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5591 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5592 SplitRegs) { 5593 unsigned Offset = 0; 5594 for (auto RegAndSize : SplitRegs) { 5595 // If the expression is already a fragment, the current register 5596 // offset+size might extend beyond the fragment. In this case, only 5597 // the register bits that are inside the fragment are relevant. 5598 int RegFragmentSizeInBits = RegAndSize.second; 5599 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5600 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5601 // The register is entirely outside the expression fragment, 5602 // so is irrelevant for debug info. 5603 if (Offset >= ExprFragmentSizeInBits) 5604 break; 5605 // The register is partially outside the expression fragment, only 5606 // the low bits within the fragment are relevant for debug info. 5607 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5608 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5609 } 5610 } 5611 5612 auto FragmentExpr = DIExpression::createFragmentExpression( 5613 Expr, Offset, RegFragmentSizeInBits); 5614 Offset += RegAndSize.second; 5615 // If a valid fragment expression cannot be created, the variable's 5616 // correct value cannot be determined and so it is set as Undef. 5617 if (!FragmentExpr) { 5618 SDDbgValue *SDV = DAG.getConstantDbgValue( 5619 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5620 DAG.AddDbgValue(SDV, false); 5621 continue; 5622 } 5623 FuncInfo.ArgDbgValues.push_back( 5624 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5625 RegAndSize.first, Variable, *FragmentExpr)); 5626 } 5627 }; 5628 5629 // Check if ValueMap has reg number. 5630 DenseMap<const Value *, Register>::const_iterator 5631 VMI = FuncInfo.ValueMap.find(V); 5632 if (VMI != FuncInfo.ValueMap.end()) { 5633 const auto &TLI = DAG.getTargetLoweringInfo(); 5634 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5635 V->getType(), None); 5636 if (RFV.occupiesMultipleRegs()) { 5637 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5638 return true; 5639 } 5640 5641 Op = MachineOperand::CreateReg(VMI->second, false); 5642 IsIndirect = IsDbgDeclare; 5643 } else if (ArgRegsAndSizes.size() > 1) { 5644 // This was split due to the calling convention, and no virtual register 5645 // mapping exists for the value. 5646 splitMultiRegDbgValue(ArgRegsAndSizes); 5647 return true; 5648 } 5649 } 5650 5651 if (!Op) 5652 return false; 5653 5654 assert(Variable->isValidLocationForIntrinsic(DL) && 5655 "Expected inlined-at fields to agree"); 5656 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5657 FuncInfo.ArgDbgValues.push_back( 5658 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5659 *Op, Variable, Expr)); 5660 5661 return true; 5662 } 5663 5664 /// Return the appropriate SDDbgValue based on N. 5665 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5666 DILocalVariable *Variable, 5667 DIExpression *Expr, 5668 const DebugLoc &dl, 5669 unsigned DbgSDNodeOrder) { 5670 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5671 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5672 // stack slot locations. 5673 // 5674 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5675 // debug values here after optimization: 5676 // 5677 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5678 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5679 // 5680 // Both describe the direct values of their associated variables. 5681 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5682 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5683 } 5684 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5685 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5686 } 5687 5688 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5689 switch (Intrinsic) { 5690 case Intrinsic::smul_fix: 5691 return ISD::SMULFIX; 5692 case Intrinsic::umul_fix: 5693 return ISD::UMULFIX; 5694 case Intrinsic::smul_fix_sat: 5695 return ISD::SMULFIXSAT; 5696 case Intrinsic::umul_fix_sat: 5697 return ISD::UMULFIXSAT; 5698 case Intrinsic::sdiv_fix: 5699 return ISD::SDIVFIX; 5700 case Intrinsic::udiv_fix: 5701 return ISD::UDIVFIX; 5702 case Intrinsic::sdiv_fix_sat: 5703 return ISD::SDIVFIXSAT; 5704 case Intrinsic::udiv_fix_sat: 5705 return ISD::UDIVFIXSAT; 5706 default: 5707 llvm_unreachable("Unhandled fixed point intrinsic"); 5708 } 5709 } 5710 5711 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5712 const char *FunctionName) { 5713 assert(FunctionName && "FunctionName must not be nullptr"); 5714 SDValue Callee = DAG.getExternalSymbol( 5715 FunctionName, 5716 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5717 LowerCallTo(I, Callee, I.isTailCall()); 5718 } 5719 5720 /// Given a @llvm.call.preallocated.setup, return the corresponding 5721 /// preallocated call. 5722 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5723 assert(cast<CallBase>(PreallocatedSetup) 5724 ->getCalledFunction() 5725 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5726 "expected call_preallocated_setup Value"); 5727 for (auto *U : PreallocatedSetup->users()) { 5728 auto *UseCall = cast<CallBase>(U); 5729 const Function *Fn = UseCall->getCalledFunction(); 5730 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5731 return UseCall; 5732 } 5733 } 5734 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5735 } 5736 5737 /// Lower the call to the specified intrinsic function. 5738 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5739 unsigned Intrinsic) { 5740 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5741 SDLoc sdl = getCurSDLoc(); 5742 DebugLoc dl = getCurDebugLoc(); 5743 SDValue Res; 5744 5745 SDNodeFlags Flags; 5746 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5747 Flags.copyFMF(*FPOp); 5748 5749 switch (Intrinsic) { 5750 default: 5751 // By default, turn this into a target intrinsic node. 5752 visitTargetIntrinsic(I, Intrinsic); 5753 return; 5754 case Intrinsic::vscale: { 5755 match(&I, m_VScale(DAG.getDataLayout())); 5756 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5757 setValue(&I, 5758 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5759 return; 5760 } 5761 case Intrinsic::vastart: visitVAStart(I); return; 5762 case Intrinsic::vaend: visitVAEnd(I); return; 5763 case Intrinsic::vacopy: visitVACopy(I); return; 5764 case Intrinsic::returnaddress: 5765 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5766 TLI.getPointerTy(DAG.getDataLayout()), 5767 getValue(I.getArgOperand(0)))); 5768 return; 5769 case Intrinsic::addressofreturnaddress: 5770 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5771 TLI.getPointerTy(DAG.getDataLayout()))); 5772 return; 5773 case Intrinsic::sponentry: 5774 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5775 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5776 return; 5777 case Intrinsic::frameaddress: 5778 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5779 TLI.getFrameIndexTy(DAG.getDataLayout()), 5780 getValue(I.getArgOperand(0)))); 5781 return; 5782 case Intrinsic::read_volatile_register: 5783 case Intrinsic::read_register: { 5784 Value *Reg = I.getArgOperand(0); 5785 SDValue Chain = getRoot(); 5786 SDValue RegName = 5787 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5788 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5789 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5790 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5791 setValue(&I, Res); 5792 DAG.setRoot(Res.getValue(1)); 5793 return; 5794 } 5795 case Intrinsic::write_register: { 5796 Value *Reg = I.getArgOperand(0); 5797 Value *RegValue = I.getArgOperand(1); 5798 SDValue Chain = getRoot(); 5799 SDValue RegName = 5800 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5801 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5802 RegName, getValue(RegValue))); 5803 return; 5804 } 5805 case Intrinsic::memcpy: { 5806 const auto &MCI = cast<MemCpyInst>(I); 5807 SDValue Op1 = getValue(I.getArgOperand(0)); 5808 SDValue Op2 = getValue(I.getArgOperand(1)); 5809 SDValue Op3 = getValue(I.getArgOperand(2)); 5810 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5811 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5812 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5813 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5814 bool isVol = MCI.isVolatile(); 5815 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5816 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5817 // node. 5818 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5819 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5820 /* AlwaysInline */ false, isTC, 5821 MachinePointerInfo(I.getArgOperand(0)), 5822 MachinePointerInfo(I.getArgOperand(1))); 5823 updateDAGForMaybeTailCall(MC); 5824 return; 5825 } 5826 case Intrinsic::memcpy_inline: { 5827 const auto &MCI = cast<MemCpyInlineInst>(I); 5828 SDValue Dst = getValue(I.getArgOperand(0)); 5829 SDValue Src = getValue(I.getArgOperand(1)); 5830 SDValue Size = getValue(I.getArgOperand(2)); 5831 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5832 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5833 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5834 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5835 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5836 bool isVol = MCI.isVolatile(); 5837 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5838 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5839 // node. 5840 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5841 /* AlwaysInline */ true, isTC, 5842 MachinePointerInfo(I.getArgOperand(0)), 5843 MachinePointerInfo(I.getArgOperand(1))); 5844 updateDAGForMaybeTailCall(MC); 5845 return; 5846 } 5847 case Intrinsic::memset: { 5848 const auto &MSI = cast<MemSetInst>(I); 5849 SDValue Op1 = getValue(I.getArgOperand(0)); 5850 SDValue Op2 = getValue(I.getArgOperand(1)); 5851 SDValue Op3 = getValue(I.getArgOperand(2)); 5852 // @llvm.memset defines 0 and 1 to both mean no alignment. 5853 Align Alignment = MSI.getDestAlign().valueOrOne(); 5854 bool isVol = MSI.isVolatile(); 5855 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5856 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5857 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5858 MachinePointerInfo(I.getArgOperand(0))); 5859 updateDAGForMaybeTailCall(MS); 5860 return; 5861 } 5862 case Intrinsic::memmove: { 5863 const auto &MMI = cast<MemMoveInst>(I); 5864 SDValue Op1 = getValue(I.getArgOperand(0)); 5865 SDValue Op2 = getValue(I.getArgOperand(1)); 5866 SDValue Op3 = getValue(I.getArgOperand(2)); 5867 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5868 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5869 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5870 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5871 bool isVol = MMI.isVolatile(); 5872 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5873 // FIXME: Support passing different dest/src alignments to the memmove DAG 5874 // node. 5875 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5876 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5877 isTC, MachinePointerInfo(I.getArgOperand(0)), 5878 MachinePointerInfo(I.getArgOperand(1))); 5879 updateDAGForMaybeTailCall(MM); 5880 return; 5881 } 5882 case Intrinsic::memcpy_element_unordered_atomic: { 5883 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5884 SDValue Dst = getValue(MI.getRawDest()); 5885 SDValue Src = getValue(MI.getRawSource()); 5886 SDValue Length = getValue(MI.getLength()); 5887 5888 unsigned DstAlign = MI.getDestAlignment(); 5889 unsigned SrcAlign = MI.getSourceAlignment(); 5890 Type *LengthTy = MI.getLength()->getType(); 5891 unsigned ElemSz = MI.getElementSizeInBytes(); 5892 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5893 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5894 SrcAlign, Length, LengthTy, ElemSz, isTC, 5895 MachinePointerInfo(MI.getRawDest()), 5896 MachinePointerInfo(MI.getRawSource())); 5897 updateDAGForMaybeTailCall(MC); 5898 return; 5899 } 5900 case Intrinsic::memmove_element_unordered_atomic: { 5901 auto &MI = cast<AtomicMemMoveInst>(I); 5902 SDValue Dst = getValue(MI.getRawDest()); 5903 SDValue Src = getValue(MI.getRawSource()); 5904 SDValue Length = getValue(MI.getLength()); 5905 5906 unsigned DstAlign = MI.getDestAlignment(); 5907 unsigned SrcAlign = MI.getSourceAlignment(); 5908 Type *LengthTy = MI.getLength()->getType(); 5909 unsigned ElemSz = MI.getElementSizeInBytes(); 5910 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5911 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5912 SrcAlign, Length, LengthTy, ElemSz, isTC, 5913 MachinePointerInfo(MI.getRawDest()), 5914 MachinePointerInfo(MI.getRawSource())); 5915 updateDAGForMaybeTailCall(MC); 5916 return; 5917 } 5918 case Intrinsic::memset_element_unordered_atomic: { 5919 auto &MI = cast<AtomicMemSetInst>(I); 5920 SDValue Dst = getValue(MI.getRawDest()); 5921 SDValue Val = getValue(MI.getValue()); 5922 SDValue Length = getValue(MI.getLength()); 5923 5924 unsigned DstAlign = MI.getDestAlignment(); 5925 Type *LengthTy = MI.getLength()->getType(); 5926 unsigned ElemSz = MI.getElementSizeInBytes(); 5927 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5928 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5929 LengthTy, ElemSz, isTC, 5930 MachinePointerInfo(MI.getRawDest())); 5931 updateDAGForMaybeTailCall(MC); 5932 return; 5933 } 5934 case Intrinsic::call_preallocated_setup: { 5935 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5936 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5937 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5938 getRoot(), SrcValue); 5939 setValue(&I, Res); 5940 DAG.setRoot(Res); 5941 return; 5942 } 5943 case Intrinsic::call_preallocated_arg: { 5944 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5945 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5946 SDValue Ops[3]; 5947 Ops[0] = getRoot(); 5948 Ops[1] = SrcValue; 5949 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5950 MVT::i32); // arg index 5951 SDValue Res = DAG.getNode( 5952 ISD::PREALLOCATED_ARG, sdl, 5953 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5954 setValue(&I, Res); 5955 DAG.setRoot(Res.getValue(1)); 5956 return; 5957 } 5958 case Intrinsic::dbg_addr: 5959 case Intrinsic::dbg_declare: { 5960 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 5961 // they are non-variadic. 5962 const auto &DI = cast<DbgVariableIntrinsic>(I); 5963 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 5964 DILocalVariable *Variable = DI.getVariable(); 5965 DIExpression *Expression = DI.getExpression(); 5966 dropDanglingDebugInfo(Variable, Expression); 5967 assert(Variable && "Missing variable"); 5968 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5969 << "\n"); 5970 // Check if address has undef value. 5971 const Value *Address = DI.getVariableLocationOp(0); 5972 if (!Address || isa<UndefValue>(Address) || 5973 (Address->use_empty() && !isa<Argument>(Address))) { 5974 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5975 << " (bad/undef/unused-arg address)\n"); 5976 return; 5977 } 5978 5979 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5980 5981 // Check if this variable can be described by a frame index, typically 5982 // either as a static alloca or a byval parameter. 5983 int FI = std::numeric_limits<int>::max(); 5984 if (const auto *AI = 5985 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5986 if (AI->isStaticAlloca()) { 5987 auto I = FuncInfo.StaticAllocaMap.find(AI); 5988 if (I != FuncInfo.StaticAllocaMap.end()) 5989 FI = I->second; 5990 } 5991 } else if (const auto *Arg = dyn_cast<Argument>( 5992 Address->stripInBoundsConstantOffsets())) { 5993 FI = FuncInfo.getArgumentFrameIndex(Arg); 5994 } 5995 5996 // llvm.dbg.addr is control dependent and always generates indirect 5997 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5998 // the MachineFunction variable table. 5999 if (FI != std::numeric_limits<int>::max()) { 6000 if (Intrinsic == Intrinsic::dbg_addr) { 6001 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6002 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6003 dl, SDNodeOrder); 6004 DAG.AddDbgValue(SDV, isParameter); 6005 } else { 6006 LLVM_DEBUG(dbgs() << "Skipping " << DI 6007 << " (variable info stashed in MF side table)\n"); 6008 } 6009 return; 6010 } 6011 6012 SDValue &N = NodeMap[Address]; 6013 if (!N.getNode() && isa<Argument>(Address)) 6014 // Check unused arguments map. 6015 N = UnusedArgNodeMap[Address]; 6016 SDDbgValue *SDV; 6017 if (N.getNode()) { 6018 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6019 Address = BCI->getOperand(0); 6020 // Parameters are handled specially. 6021 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6022 if (isParameter && FINode) { 6023 // Byval parameter. We have a frame index at this point. 6024 SDV = 6025 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6026 /*IsIndirect*/ true, dl, SDNodeOrder); 6027 } else if (isa<Argument>(Address)) { 6028 // Address is an argument, so try to emit its dbg value using 6029 // virtual register info from the FuncInfo.ValueMap. 6030 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6031 return; 6032 } else { 6033 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6034 true, dl, SDNodeOrder); 6035 } 6036 DAG.AddDbgValue(SDV, isParameter); 6037 } else { 6038 // If Address is an argument then try to emit its dbg value using 6039 // virtual register info from the FuncInfo.ValueMap. 6040 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6041 N)) { 6042 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6043 << " (could not emit func-arg dbg_value)\n"); 6044 } 6045 } 6046 return; 6047 } 6048 case Intrinsic::dbg_label: { 6049 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6050 DILabel *Label = DI.getLabel(); 6051 assert(Label && "Missing label"); 6052 6053 SDDbgLabel *SDV; 6054 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6055 DAG.AddDbgLabel(SDV); 6056 return; 6057 } 6058 case Intrinsic::dbg_value: { 6059 const DbgValueInst &DI = cast<DbgValueInst>(I); 6060 assert(DI.getVariable() && "Missing variable"); 6061 6062 DILocalVariable *Variable = DI.getVariable(); 6063 DIExpression *Expression = DI.getExpression(); 6064 dropDanglingDebugInfo(Variable, Expression); 6065 SmallVector<Value *, 4> Values(DI.getValues()); 6066 if (Values.empty()) 6067 return; 6068 6069 if (std::count(Values.begin(), Values.end(), nullptr)) 6070 return; 6071 6072 bool IsVariadic = DI.hasArgList(); 6073 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6074 SDNodeOrder, IsVariadic)) 6075 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6076 return; 6077 } 6078 6079 case Intrinsic::eh_typeid_for: { 6080 // Find the type id for the given typeinfo. 6081 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6082 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6083 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6084 setValue(&I, Res); 6085 return; 6086 } 6087 6088 case Intrinsic::eh_return_i32: 6089 case Intrinsic::eh_return_i64: 6090 DAG.getMachineFunction().setCallsEHReturn(true); 6091 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6092 MVT::Other, 6093 getControlRoot(), 6094 getValue(I.getArgOperand(0)), 6095 getValue(I.getArgOperand(1)))); 6096 return; 6097 case Intrinsic::eh_unwind_init: 6098 DAG.getMachineFunction().setCallsUnwindInit(true); 6099 return; 6100 case Intrinsic::eh_dwarf_cfa: 6101 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6102 TLI.getPointerTy(DAG.getDataLayout()), 6103 getValue(I.getArgOperand(0)))); 6104 return; 6105 case Intrinsic::eh_sjlj_callsite: { 6106 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6107 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6108 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6109 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6110 6111 MMI.setCurrentCallSite(CI->getZExtValue()); 6112 return; 6113 } 6114 case Intrinsic::eh_sjlj_functioncontext: { 6115 // Get and store the index of the function context. 6116 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6117 AllocaInst *FnCtx = 6118 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6119 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6120 MFI.setFunctionContextIndex(FI); 6121 return; 6122 } 6123 case Intrinsic::eh_sjlj_setjmp: { 6124 SDValue Ops[2]; 6125 Ops[0] = getRoot(); 6126 Ops[1] = getValue(I.getArgOperand(0)); 6127 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6128 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6129 setValue(&I, Op.getValue(0)); 6130 DAG.setRoot(Op.getValue(1)); 6131 return; 6132 } 6133 case Intrinsic::eh_sjlj_longjmp: 6134 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6135 getRoot(), getValue(I.getArgOperand(0)))); 6136 return; 6137 case Intrinsic::eh_sjlj_setup_dispatch: 6138 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6139 getRoot())); 6140 return; 6141 case Intrinsic::masked_gather: 6142 visitMaskedGather(I); 6143 return; 6144 case Intrinsic::masked_load: 6145 visitMaskedLoad(I); 6146 return; 6147 case Intrinsic::masked_scatter: 6148 visitMaskedScatter(I); 6149 return; 6150 case Intrinsic::masked_store: 6151 visitMaskedStore(I); 6152 return; 6153 case Intrinsic::masked_expandload: 6154 visitMaskedLoad(I, true /* IsExpanding */); 6155 return; 6156 case Intrinsic::masked_compressstore: 6157 visitMaskedStore(I, true /* IsCompressing */); 6158 return; 6159 case Intrinsic::powi: 6160 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6161 getValue(I.getArgOperand(1)), DAG)); 6162 return; 6163 case Intrinsic::log: 6164 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6165 return; 6166 case Intrinsic::log2: 6167 setValue(&I, 6168 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6169 return; 6170 case Intrinsic::log10: 6171 setValue(&I, 6172 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6173 return; 6174 case Intrinsic::exp: 6175 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6176 return; 6177 case Intrinsic::exp2: 6178 setValue(&I, 6179 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6180 return; 6181 case Intrinsic::pow: 6182 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6183 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6184 return; 6185 case Intrinsic::sqrt: 6186 case Intrinsic::fabs: 6187 case Intrinsic::sin: 6188 case Intrinsic::cos: 6189 case Intrinsic::floor: 6190 case Intrinsic::ceil: 6191 case Intrinsic::trunc: 6192 case Intrinsic::rint: 6193 case Intrinsic::nearbyint: 6194 case Intrinsic::round: 6195 case Intrinsic::roundeven: 6196 case Intrinsic::canonicalize: { 6197 unsigned Opcode; 6198 switch (Intrinsic) { 6199 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6200 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6201 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6202 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6203 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6204 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6205 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6206 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6207 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6208 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6209 case Intrinsic::round: Opcode = ISD::FROUND; break; 6210 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6211 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6212 } 6213 6214 setValue(&I, DAG.getNode(Opcode, sdl, 6215 getValue(I.getArgOperand(0)).getValueType(), 6216 getValue(I.getArgOperand(0)), Flags)); 6217 return; 6218 } 6219 case Intrinsic::lround: 6220 case Intrinsic::llround: 6221 case Intrinsic::lrint: 6222 case Intrinsic::llrint: { 6223 unsigned Opcode; 6224 switch (Intrinsic) { 6225 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6226 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6227 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6228 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6229 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6230 } 6231 6232 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6233 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6234 getValue(I.getArgOperand(0)))); 6235 return; 6236 } 6237 case Intrinsic::minnum: 6238 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6239 getValue(I.getArgOperand(0)).getValueType(), 6240 getValue(I.getArgOperand(0)), 6241 getValue(I.getArgOperand(1)), Flags)); 6242 return; 6243 case Intrinsic::maxnum: 6244 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6245 getValue(I.getArgOperand(0)).getValueType(), 6246 getValue(I.getArgOperand(0)), 6247 getValue(I.getArgOperand(1)), Flags)); 6248 return; 6249 case Intrinsic::minimum: 6250 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6251 getValue(I.getArgOperand(0)).getValueType(), 6252 getValue(I.getArgOperand(0)), 6253 getValue(I.getArgOperand(1)), Flags)); 6254 return; 6255 case Intrinsic::maximum: 6256 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6257 getValue(I.getArgOperand(0)).getValueType(), 6258 getValue(I.getArgOperand(0)), 6259 getValue(I.getArgOperand(1)), Flags)); 6260 return; 6261 case Intrinsic::copysign: 6262 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6263 getValue(I.getArgOperand(0)).getValueType(), 6264 getValue(I.getArgOperand(0)), 6265 getValue(I.getArgOperand(1)), Flags)); 6266 return; 6267 case Intrinsic::fma: 6268 setValue(&I, DAG.getNode( 6269 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6270 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6271 getValue(I.getArgOperand(2)), Flags)); 6272 return; 6273 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6274 case Intrinsic::INTRINSIC: 6275 #include "llvm/IR/ConstrainedOps.def" 6276 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6277 return; 6278 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6279 #include "llvm/IR/VPIntrinsics.def" 6280 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6281 return; 6282 case Intrinsic::fmuladd: { 6283 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6284 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6285 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6286 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6287 getValue(I.getArgOperand(0)).getValueType(), 6288 getValue(I.getArgOperand(0)), 6289 getValue(I.getArgOperand(1)), 6290 getValue(I.getArgOperand(2)), Flags)); 6291 } else { 6292 // TODO: Intrinsic calls should have fast-math-flags. 6293 SDValue Mul = DAG.getNode( 6294 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6295 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6296 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6297 getValue(I.getArgOperand(0)).getValueType(), 6298 Mul, getValue(I.getArgOperand(2)), Flags); 6299 setValue(&I, Add); 6300 } 6301 return; 6302 } 6303 case Intrinsic::convert_to_fp16: 6304 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6305 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6306 getValue(I.getArgOperand(0)), 6307 DAG.getTargetConstant(0, sdl, 6308 MVT::i32)))); 6309 return; 6310 case Intrinsic::convert_from_fp16: 6311 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6312 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6313 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6314 getValue(I.getArgOperand(0))))); 6315 return; 6316 case Intrinsic::fptosi_sat: { 6317 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6318 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6319 getValue(I.getArgOperand(0)), 6320 DAG.getValueType(VT.getScalarType()))); 6321 return; 6322 } 6323 case Intrinsic::fptoui_sat: { 6324 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6325 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6326 getValue(I.getArgOperand(0)), 6327 DAG.getValueType(VT.getScalarType()))); 6328 return; 6329 } 6330 case Intrinsic::set_rounding: 6331 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6332 {getRoot(), getValue(I.getArgOperand(0))}); 6333 setValue(&I, Res); 6334 DAG.setRoot(Res.getValue(0)); 6335 return; 6336 case Intrinsic::pcmarker: { 6337 SDValue Tmp = getValue(I.getArgOperand(0)); 6338 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6339 return; 6340 } 6341 case Intrinsic::readcyclecounter: { 6342 SDValue Op = getRoot(); 6343 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6344 DAG.getVTList(MVT::i64, MVT::Other), Op); 6345 setValue(&I, Res); 6346 DAG.setRoot(Res.getValue(1)); 6347 return; 6348 } 6349 case Intrinsic::bitreverse: 6350 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6351 getValue(I.getArgOperand(0)).getValueType(), 6352 getValue(I.getArgOperand(0)))); 6353 return; 6354 case Intrinsic::bswap: 6355 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6356 getValue(I.getArgOperand(0)).getValueType(), 6357 getValue(I.getArgOperand(0)))); 6358 return; 6359 case Intrinsic::cttz: { 6360 SDValue Arg = getValue(I.getArgOperand(0)); 6361 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6362 EVT Ty = Arg.getValueType(); 6363 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6364 sdl, Ty, Arg)); 6365 return; 6366 } 6367 case Intrinsic::ctlz: { 6368 SDValue Arg = getValue(I.getArgOperand(0)); 6369 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6370 EVT Ty = Arg.getValueType(); 6371 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6372 sdl, Ty, Arg)); 6373 return; 6374 } 6375 case Intrinsic::ctpop: { 6376 SDValue Arg = getValue(I.getArgOperand(0)); 6377 EVT Ty = Arg.getValueType(); 6378 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6379 return; 6380 } 6381 case Intrinsic::fshl: 6382 case Intrinsic::fshr: { 6383 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6384 SDValue X = getValue(I.getArgOperand(0)); 6385 SDValue Y = getValue(I.getArgOperand(1)); 6386 SDValue Z = getValue(I.getArgOperand(2)); 6387 EVT VT = X.getValueType(); 6388 6389 if (X == Y) { 6390 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6391 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6392 } else { 6393 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6394 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6395 } 6396 return; 6397 } 6398 case Intrinsic::sadd_sat: { 6399 SDValue Op1 = getValue(I.getArgOperand(0)); 6400 SDValue Op2 = getValue(I.getArgOperand(1)); 6401 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6402 return; 6403 } 6404 case Intrinsic::uadd_sat: { 6405 SDValue Op1 = getValue(I.getArgOperand(0)); 6406 SDValue Op2 = getValue(I.getArgOperand(1)); 6407 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6408 return; 6409 } 6410 case Intrinsic::ssub_sat: { 6411 SDValue Op1 = getValue(I.getArgOperand(0)); 6412 SDValue Op2 = getValue(I.getArgOperand(1)); 6413 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6414 return; 6415 } 6416 case Intrinsic::usub_sat: { 6417 SDValue Op1 = getValue(I.getArgOperand(0)); 6418 SDValue Op2 = getValue(I.getArgOperand(1)); 6419 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6420 return; 6421 } 6422 case Intrinsic::sshl_sat: { 6423 SDValue Op1 = getValue(I.getArgOperand(0)); 6424 SDValue Op2 = getValue(I.getArgOperand(1)); 6425 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6426 return; 6427 } 6428 case Intrinsic::ushl_sat: { 6429 SDValue Op1 = getValue(I.getArgOperand(0)); 6430 SDValue Op2 = getValue(I.getArgOperand(1)); 6431 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6432 return; 6433 } 6434 case Intrinsic::smul_fix: 6435 case Intrinsic::umul_fix: 6436 case Intrinsic::smul_fix_sat: 6437 case Intrinsic::umul_fix_sat: { 6438 SDValue Op1 = getValue(I.getArgOperand(0)); 6439 SDValue Op2 = getValue(I.getArgOperand(1)); 6440 SDValue Op3 = getValue(I.getArgOperand(2)); 6441 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6442 Op1.getValueType(), Op1, Op2, Op3)); 6443 return; 6444 } 6445 case Intrinsic::sdiv_fix: 6446 case Intrinsic::udiv_fix: 6447 case Intrinsic::sdiv_fix_sat: 6448 case Intrinsic::udiv_fix_sat: { 6449 SDValue Op1 = getValue(I.getArgOperand(0)); 6450 SDValue Op2 = getValue(I.getArgOperand(1)); 6451 SDValue Op3 = getValue(I.getArgOperand(2)); 6452 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6453 Op1, Op2, Op3, DAG, TLI)); 6454 return; 6455 } 6456 case Intrinsic::smax: { 6457 SDValue Op1 = getValue(I.getArgOperand(0)); 6458 SDValue Op2 = getValue(I.getArgOperand(1)); 6459 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6460 return; 6461 } 6462 case Intrinsic::smin: { 6463 SDValue Op1 = getValue(I.getArgOperand(0)); 6464 SDValue Op2 = getValue(I.getArgOperand(1)); 6465 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6466 return; 6467 } 6468 case Intrinsic::umax: { 6469 SDValue Op1 = getValue(I.getArgOperand(0)); 6470 SDValue Op2 = getValue(I.getArgOperand(1)); 6471 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6472 return; 6473 } 6474 case Intrinsic::umin: { 6475 SDValue Op1 = getValue(I.getArgOperand(0)); 6476 SDValue Op2 = getValue(I.getArgOperand(1)); 6477 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6478 return; 6479 } 6480 case Intrinsic::abs: { 6481 // TODO: Preserve "int min is poison" arg in SDAG? 6482 SDValue Op1 = getValue(I.getArgOperand(0)); 6483 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6484 return; 6485 } 6486 case Intrinsic::stacksave: { 6487 SDValue Op = getRoot(); 6488 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6489 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6490 setValue(&I, Res); 6491 DAG.setRoot(Res.getValue(1)); 6492 return; 6493 } 6494 case Intrinsic::stackrestore: 6495 Res = getValue(I.getArgOperand(0)); 6496 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6497 return; 6498 case Intrinsic::get_dynamic_area_offset: { 6499 SDValue Op = getRoot(); 6500 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6501 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6502 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6503 // target. 6504 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6505 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6506 " intrinsic!"); 6507 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6508 Op); 6509 DAG.setRoot(Op); 6510 setValue(&I, Res); 6511 return; 6512 } 6513 case Intrinsic::stackguard: { 6514 MachineFunction &MF = DAG.getMachineFunction(); 6515 const Module &M = *MF.getFunction().getParent(); 6516 SDValue Chain = getRoot(); 6517 if (TLI.useLoadStackGuardNode()) { 6518 Res = getLoadStackGuard(DAG, sdl, Chain); 6519 } else { 6520 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6521 const Value *Global = TLI.getSDagStackGuard(M); 6522 Align Align = DL->getPrefTypeAlign(Global->getType()); 6523 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6524 MachinePointerInfo(Global, 0), Align, 6525 MachineMemOperand::MOVolatile); 6526 } 6527 if (TLI.useStackGuardXorFP()) 6528 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6529 DAG.setRoot(Chain); 6530 setValue(&I, Res); 6531 return; 6532 } 6533 case Intrinsic::stackprotector: { 6534 // Emit code into the DAG to store the stack guard onto the stack. 6535 MachineFunction &MF = DAG.getMachineFunction(); 6536 MachineFrameInfo &MFI = MF.getFrameInfo(); 6537 SDValue Src, Chain = getRoot(); 6538 6539 if (TLI.useLoadStackGuardNode()) 6540 Src = getLoadStackGuard(DAG, sdl, Chain); 6541 else 6542 Src = getValue(I.getArgOperand(0)); // The guard's value. 6543 6544 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6545 6546 int FI = FuncInfo.StaticAllocaMap[Slot]; 6547 MFI.setStackProtectorIndex(FI); 6548 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6549 6550 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6551 6552 // Store the stack protector onto the stack. 6553 Res = DAG.getStore( 6554 Chain, sdl, Src, FIN, 6555 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6556 MaybeAlign(), MachineMemOperand::MOVolatile); 6557 setValue(&I, Res); 6558 DAG.setRoot(Res); 6559 return; 6560 } 6561 case Intrinsic::objectsize: 6562 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6563 6564 case Intrinsic::is_constant: 6565 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6566 6567 case Intrinsic::annotation: 6568 case Intrinsic::ptr_annotation: 6569 case Intrinsic::launder_invariant_group: 6570 case Intrinsic::strip_invariant_group: 6571 // Drop the intrinsic, but forward the value 6572 setValue(&I, getValue(I.getOperand(0))); 6573 return; 6574 6575 case Intrinsic::assume: 6576 case Intrinsic::experimental_noalias_scope_decl: 6577 case Intrinsic::var_annotation: 6578 case Intrinsic::sideeffect: 6579 // Discard annotate attributes, noalias scope declarations, assumptions, and 6580 // artificial side-effects. 6581 return; 6582 6583 case Intrinsic::codeview_annotation: { 6584 // Emit a label associated with this metadata. 6585 MachineFunction &MF = DAG.getMachineFunction(); 6586 MCSymbol *Label = 6587 MF.getMMI().getContext().createTempSymbol("annotation", true); 6588 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6589 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6590 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6591 DAG.setRoot(Res); 6592 return; 6593 } 6594 6595 case Intrinsic::init_trampoline: { 6596 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6597 6598 SDValue Ops[6]; 6599 Ops[0] = getRoot(); 6600 Ops[1] = getValue(I.getArgOperand(0)); 6601 Ops[2] = getValue(I.getArgOperand(1)); 6602 Ops[3] = getValue(I.getArgOperand(2)); 6603 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6604 Ops[5] = DAG.getSrcValue(F); 6605 6606 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6607 6608 DAG.setRoot(Res); 6609 return; 6610 } 6611 case Intrinsic::adjust_trampoline: 6612 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6613 TLI.getPointerTy(DAG.getDataLayout()), 6614 getValue(I.getArgOperand(0)))); 6615 return; 6616 case Intrinsic::gcroot: { 6617 assert(DAG.getMachineFunction().getFunction().hasGC() && 6618 "only valid in functions with gc specified, enforced by Verifier"); 6619 assert(GFI && "implied by previous"); 6620 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6621 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6622 6623 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6624 GFI->addStackRoot(FI->getIndex(), TypeMap); 6625 return; 6626 } 6627 case Intrinsic::gcread: 6628 case Intrinsic::gcwrite: 6629 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6630 case Intrinsic::flt_rounds: 6631 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6632 setValue(&I, Res); 6633 DAG.setRoot(Res.getValue(1)); 6634 return; 6635 6636 case Intrinsic::expect: 6637 // Just replace __builtin_expect(exp, c) with EXP. 6638 setValue(&I, getValue(I.getArgOperand(0))); 6639 return; 6640 6641 case Intrinsic::ubsantrap: 6642 case Intrinsic::debugtrap: 6643 case Intrinsic::trap: { 6644 StringRef TrapFuncName = 6645 I.getAttributes() 6646 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6647 .getValueAsString(); 6648 if (TrapFuncName.empty()) { 6649 switch (Intrinsic) { 6650 case Intrinsic::trap: 6651 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6652 break; 6653 case Intrinsic::debugtrap: 6654 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6655 break; 6656 case Intrinsic::ubsantrap: 6657 DAG.setRoot(DAG.getNode( 6658 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6659 DAG.getTargetConstant( 6660 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6661 MVT::i32))); 6662 break; 6663 default: llvm_unreachable("unknown trap intrinsic"); 6664 } 6665 return; 6666 } 6667 TargetLowering::ArgListTy Args; 6668 if (Intrinsic == Intrinsic::ubsantrap) { 6669 Args.push_back(TargetLoweringBase::ArgListEntry()); 6670 Args[0].Val = I.getArgOperand(0); 6671 Args[0].Node = getValue(Args[0].Val); 6672 Args[0].Ty = Args[0].Val->getType(); 6673 } 6674 6675 TargetLowering::CallLoweringInfo CLI(DAG); 6676 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6677 CallingConv::C, I.getType(), 6678 DAG.getExternalSymbol(TrapFuncName.data(), 6679 TLI.getPointerTy(DAG.getDataLayout())), 6680 std::move(Args)); 6681 6682 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6683 DAG.setRoot(Result.second); 6684 return; 6685 } 6686 6687 case Intrinsic::uadd_with_overflow: 6688 case Intrinsic::sadd_with_overflow: 6689 case Intrinsic::usub_with_overflow: 6690 case Intrinsic::ssub_with_overflow: 6691 case Intrinsic::umul_with_overflow: 6692 case Intrinsic::smul_with_overflow: { 6693 ISD::NodeType Op; 6694 switch (Intrinsic) { 6695 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6696 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6697 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6698 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6699 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6700 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6701 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6702 } 6703 SDValue Op1 = getValue(I.getArgOperand(0)); 6704 SDValue Op2 = getValue(I.getArgOperand(1)); 6705 6706 EVT ResultVT = Op1.getValueType(); 6707 EVT OverflowVT = MVT::i1; 6708 if (ResultVT.isVector()) 6709 OverflowVT = EVT::getVectorVT( 6710 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6711 6712 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6713 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6714 return; 6715 } 6716 case Intrinsic::prefetch: { 6717 SDValue Ops[5]; 6718 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6719 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6720 Ops[0] = DAG.getRoot(); 6721 Ops[1] = getValue(I.getArgOperand(0)); 6722 Ops[2] = getValue(I.getArgOperand(1)); 6723 Ops[3] = getValue(I.getArgOperand(2)); 6724 Ops[4] = getValue(I.getArgOperand(3)); 6725 SDValue Result = DAG.getMemIntrinsicNode( 6726 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6727 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6728 /* align */ None, Flags); 6729 6730 // Chain the prefetch in parallell with any pending loads, to stay out of 6731 // the way of later optimizations. 6732 PendingLoads.push_back(Result); 6733 Result = getRoot(); 6734 DAG.setRoot(Result); 6735 return; 6736 } 6737 case Intrinsic::lifetime_start: 6738 case Intrinsic::lifetime_end: { 6739 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6740 // Stack coloring is not enabled in O0, discard region information. 6741 if (TM.getOptLevel() == CodeGenOpt::None) 6742 return; 6743 6744 const int64_t ObjectSize = 6745 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6746 Value *const ObjectPtr = I.getArgOperand(1); 6747 SmallVector<const Value *, 4> Allocas; 6748 getUnderlyingObjects(ObjectPtr, Allocas); 6749 6750 for (const Value *Alloca : Allocas) { 6751 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6752 6753 // Could not find an Alloca. 6754 if (!LifetimeObject) 6755 continue; 6756 6757 // First check that the Alloca is static, otherwise it won't have a 6758 // valid frame index. 6759 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6760 if (SI == FuncInfo.StaticAllocaMap.end()) 6761 return; 6762 6763 const int FrameIndex = SI->second; 6764 int64_t Offset; 6765 if (GetPointerBaseWithConstantOffset( 6766 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6767 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6768 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6769 Offset); 6770 DAG.setRoot(Res); 6771 } 6772 return; 6773 } 6774 case Intrinsic::pseudoprobe: { 6775 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6776 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6777 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6778 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6779 DAG.setRoot(Res); 6780 return; 6781 } 6782 case Intrinsic::invariant_start: 6783 // Discard region information. 6784 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6785 return; 6786 case Intrinsic::invariant_end: 6787 // Discard region information. 6788 return; 6789 case Intrinsic::clear_cache: 6790 /// FunctionName may be null. 6791 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6792 lowerCallToExternalSymbol(I, FunctionName); 6793 return; 6794 case Intrinsic::donothing: 6795 // ignore 6796 return; 6797 case Intrinsic::experimental_stackmap: 6798 visitStackmap(I); 6799 return; 6800 case Intrinsic::experimental_patchpoint_void: 6801 case Intrinsic::experimental_patchpoint_i64: 6802 visitPatchpoint(I); 6803 return; 6804 case Intrinsic::experimental_gc_statepoint: 6805 LowerStatepoint(cast<GCStatepointInst>(I)); 6806 return; 6807 case Intrinsic::experimental_gc_result: 6808 visitGCResult(cast<GCResultInst>(I)); 6809 return; 6810 case Intrinsic::experimental_gc_relocate: 6811 visitGCRelocate(cast<GCRelocateInst>(I)); 6812 return; 6813 case Intrinsic::instrprof_increment: 6814 llvm_unreachable("instrprof failed to lower an increment"); 6815 case Intrinsic::instrprof_value_profile: 6816 llvm_unreachable("instrprof failed to lower a value profiling call"); 6817 case Intrinsic::localescape: { 6818 MachineFunction &MF = DAG.getMachineFunction(); 6819 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6820 6821 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6822 // is the same on all targets. 6823 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6824 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6825 if (isa<ConstantPointerNull>(Arg)) 6826 continue; // Skip null pointers. They represent a hole in index space. 6827 AllocaInst *Slot = cast<AllocaInst>(Arg); 6828 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6829 "can only escape static allocas"); 6830 int FI = FuncInfo.StaticAllocaMap[Slot]; 6831 MCSymbol *FrameAllocSym = 6832 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6833 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6834 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6835 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6836 .addSym(FrameAllocSym) 6837 .addFrameIndex(FI); 6838 } 6839 6840 return; 6841 } 6842 6843 case Intrinsic::localrecover: { 6844 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6845 MachineFunction &MF = DAG.getMachineFunction(); 6846 6847 // Get the symbol that defines the frame offset. 6848 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6849 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6850 unsigned IdxVal = 6851 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6852 MCSymbol *FrameAllocSym = 6853 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6854 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6855 6856 Value *FP = I.getArgOperand(1); 6857 SDValue FPVal = getValue(FP); 6858 EVT PtrVT = FPVal.getValueType(); 6859 6860 // Create a MCSymbol for the label to avoid any target lowering 6861 // that would make this PC relative. 6862 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6863 SDValue OffsetVal = 6864 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6865 6866 // Add the offset to the FP. 6867 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6868 setValue(&I, Add); 6869 6870 return; 6871 } 6872 6873 case Intrinsic::eh_exceptionpointer: 6874 case Intrinsic::eh_exceptioncode: { 6875 // Get the exception pointer vreg, copy from it, and resize it to fit. 6876 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6877 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6878 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6879 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6880 SDValue N = 6881 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6882 if (Intrinsic == Intrinsic::eh_exceptioncode) 6883 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6884 setValue(&I, N); 6885 return; 6886 } 6887 case Intrinsic::xray_customevent: { 6888 // Here we want to make sure that the intrinsic behaves as if it has a 6889 // specific calling convention, and only for x86_64. 6890 // FIXME: Support other platforms later. 6891 const auto &Triple = DAG.getTarget().getTargetTriple(); 6892 if (Triple.getArch() != Triple::x86_64) 6893 return; 6894 6895 SDLoc DL = getCurSDLoc(); 6896 SmallVector<SDValue, 8> Ops; 6897 6898 // We want to say that we always want the arguments in registers. 6899 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6900 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6901 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6902 SDValue Chain = getRoot(); 6903 Ops.push_back(LogEntryVal); 6904 Ops.push_back(StrSizeVal); 6905 Ops.push_back(Chain); 6906 6907 // We need to enforce the calling convention for the callsite, so that 6908 // argument ordering is enforced correctly, and that register allocation can 6909 // see that some registers may be assumed clobbered and have to preserve 6910 // them across calls to the intrinsic. 6911 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6912 DL, NodeTys, Ops); 6913 SDValue patchableNode = SDValue(MN, 0); 6914 DAG.setRoot(patchableNode); 6915 setValue(&I, patchableNode); 6916 return; 6917 } 6918 case Intrinsic::xray_typedevent: { 6919 // Here we want to make sure that the intrinsic behaves as if it has a 6920 // specific calling convention, and only for x86_64. 6921 // FIXME: Support other platforms later. 6922 const auto &Triple = DAG.getTarget().getTargetTriple(); 6923 if (Triple.getArch() != Triple::x86_64) 6924 return; 6925 6926 SDLoc DL = getCurSDLoc(); 6927 SmallVector<SDValue, 8> Ops; 6928 6929 // We want to say that we always want the arguments in registers. 6930 // It's unclear to me how manipulating the selection DAG here forces callers 6931 // to provide arguments in registers instead of on the stack. 6932 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6933 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6934 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6935 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6936 SDValue Chain = getRoot(); 6937 Ops.push_back(LogTypeId); 6938 Ops.push_back(LogEntryVal); 6939 Ops.push_back(StrSizeVal); 6940 Ops.push_back(Chain); 6941 6942 // We need to enforce the calling convention for the callsite, so that 6943 // argument ordering is enforced correctly, and that register allocation can 6944 // see that some registers may be assumed clobbered and have to preserve 6945 // them across calls to the intrinsic. 6946 MachineSDNode *MN = DAG.getMachineNode( 6947 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6948 SDValue patchableNode = SDValue(MN, 0); 6949 DAG.setRoot(patchableNode); 6950 setValue(&I, patchableNode); 6951 return; 6952 } 6953 case Intrinsic::experimental_deoptimize: 6954 LowerDeoptimizeCall(&I); 6955 return; 6956 case Intrinsic::experimental_stepvector: 6957 visitStepVector(I); 6958 return; 6959 case Intrinsic::vector_reduce_fadd: 6960 case Intrinsic::vector_reduce_fmul: 6961 case Intrinsic::vector_reduce_add: 6962 case Intrinsic::vector_reduce_mul: 6963 case Intrinsic::vector_reduce_and: 6964 case Intrinsic::vector_reduce_or: 6965 case Intrinsic::vector_reduce_xor: 6966 case Intrinsic::vector_reduce_smax: 6967 case Intrinsic::vector_reduce_smin: 6968 case Intrinsic::vector_reduce_umax: 6969 case Intrinsic::vector_reduce_umin: 6970 case Intrinsic::vector_reduce_fmax: 6971 case Intrinsic::vector_reduce_fmin: 6972 visitVectorReduce(I, Intrinsic); 6973 return; 6974 6975 case Intrinsic::icall_branch_funnel: { 6976 SmallVector<SDValue, 16> Ops; 6977 Ops.push_back(getValue(I.getArgOperand(0))); 6978 6979 int64_t Offset; 6980 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6981 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6982 if (!Base) 6983 report_fatal_error( 6984 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6985 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6986 6987 struct BranchFunnelTarget { 6988 int64_t Offset; 6989 SDValue Target; 6990 }; 6991 SmallVector<BranchFunnelTarget, 8> Targets; 6992 6993 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6994 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6995 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6996 if (ElemBase != Base) 6997 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6998 "to the same GlobalValue"); 6999 7000 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7001 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7002 if (!GA) 7003 report_fatal_error( 7004 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7005 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7006 GA->getGlobal(), getCurSDLoc(), 7007 Val.getValueType(), GA->getOffset())}); 7008 } 7009 llvm::sort(Targets, 7010 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7011 return T1.Offset < T2.Offset; 7012 }); 7013 7014 for (auto &T : Targets) { 7015 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 7016 Ops.push_back(T.Target); 7017 } 7018 7019 Ops.push_back(DAG.getRoot()); // Chain 7020 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 7021 getCurSDLoc(), MVT::Other, Ops), 7022 0); 7023 DAG.setRoot(N); 7024 setValue(&I, N); 7025 HasTailCall = true; 7026 return; 7027 } 7028 7029 case Intrinsic::wasm_landingpad_index: 7030 // Information this intrinsic contained has been transferred to 7031 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7032 // delete it now. 7033 return; 7034 7035 case Intrinsic::aarch64_settag: 7036 case Intrinsic::aarch64_settag_zero: { 7037 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7038 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7039 SDValue Val = TSI.EmitTargetCodeForSetTag( 7040 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 7041 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7042 ZeroMemory); 7043 DAG.setRoot(Val); 7044 setValue(&I, Val); 7045 return; 7046 } 7047 case Intrinsic::ptrmask: { 7048 SDValue Ptr = getValue(I.getOperand(0)); 7049 SDValue Const = getValue(I.getOperand(1)); 7050 7051 EVT PtrVT = Ptr.getValueType(); 7052 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 7053 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 7054 return; 7055 } 7056 case Intrinsic::get_active_lane_mask: { 7057 auto DL = getCurSDLoc(); 7058 SDValue Index = getValue(I.getOperand(0)); 7059 SDValue TripCount = getValue(I.getOperand(1)); 7060 Type *ElementTy = I.getOperand(0)->getType(); 7061 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7062 unsigned VecWidth = VT.getVectorNumElements(); 7063 7064 SmallVector<SDValue, 16> OpsTripCount; 7065 SmallVector<SDValue, 16> OpsIndex; 7066 SmallVector<SDValue, 16> OpsStepConstants; 7067 for (unsigned i = 0; i < VecWidth; i++) { 7068 OpsTripCount.push_back(TripCount); 7069 OpsIndex.push_back(Index); 7070 OpsStepConstants.push_back( 7071 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 7072 } 7073 7074 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 7075 7076 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 7077 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 7078 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 7079 SDValue VectorInduction = DAG.getNode( 7080 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 7081 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 7082 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 7083 VectorTripCount, ISD::CondCode::SETULT); 7084 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 7085 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 7086 SetCC)); 7087 return; 7088 } 7089 case Intrinsic::experimental_vector_insert: { 7090 auto DL = getCurSDLoc(); 7091 7092 SDValue Vec = getValue(I.getOperand(0)); 7093 SDValue SubVec = getValue(I.getOperand(1)); 7094 SDValue Index = getValue(I.getOperand(2)); 7095 7096 // The intrinsic's index type is i64, but the SDNode requires an index type 7097 // suitable for the target. Convert the index as required. 7098 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7099 if (Index.getValueType() != VectorIdxTy) 7100 Index = DAG.getVectorIdxConstant( 7101 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7102 7103 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7104 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec, 7105 Index)); 7106 return; 7107 } 7108 case Intrinsic::experimental_vector_extract: { 7109 auto DL = getCurSDLoc(); 7110 7111 SDValue Vec = getValue(I.getOperand(0)); 7112 SDValue Index = getValue(I.getOperand(1)); 7113 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7114 7115 // The intrinsic's index type is i64, but the SDNode requires an index type 7116 // suitable for the target. Convert the index as required. 7117 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7118 if (Index.getValueType() != VectorIdxTy) 7119 Index = DAG.getVectorIdxConstant( 7120 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7121 7122 setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index)); 7123 return; 7124 } 7125 case Intrinsic::experimental_vector_reverse: 7126 visitVectorReverse(I); 7127 return; 7128 case Intrinsic::experimental_vector_splice: 7129 visitVectorSplice(I); 7130 return; 7131 } 7132 } 7133 7134 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7135 const ConstrainedFPIntrinsic &FPI) { 7136 SDLoc sdl = getCurSDLoc(); 7137 7138 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7139 SmallVector<EVT, 4> ValueVTs; 7140 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7141 ValueVTs.push_back(MVT::Other); // Out chain 7142 7143 // We do not need to serialize constrained FP intrinsics against 7144 // each other or against (nonvolatile) loads, so they can be 7145 // chained like loads. 7146 SDValue Chain = DAG.getRoot(); 7147 SmallVector<SDValue, 4> Opers; 7148 Opers.push_back(Chain); 7149 if (FPI.isUnaryOp()) { 7150 Opers.push_back(getValue(FPI.getArgOperand(0))); 7151 } else if (FPI.isTernaryOp()) { 7152 Opers.push_back(getValue(FPI.getArgOperand(0))); 7153 Opers.push_back(getValue(FPI.getArgOperand(1))); 7154 Opers.push_back(getValue(FPI.getArgOperand(2))); 7155 } else { 7156 Opers.push_back(getValue(FPI.getArgOperand(0))); 7157 Opers.push_back(getValue(FPI.getArgOperand(1))); 7158 } 7159 7160 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7161 assert(Result.getNode()->getNumValues() == 2); 7162 7163 // Push node to the appropriate list so that future instructions can be 7164 // chained up correctly. 7165 SDValue OutChain = Result.getValue(1); 7166 switch (EB) { 7167 case fp::ExceptionBehavior::ebIgnore: 7168 // The only reason why ebIgnore nodes still need to be chained is that 7169 // they might depend on the current rounding mode, and therefore must 7170 // not be moved across instruction that may change that mode. 7171 LLVM_FALLTHROUGH; 7172 case fp::ExceptionBehavior::ebMayTrap: 7173 // These must not be moved across calls or instructions that may change 7174 // floating-point exception masks. 7175 PendingConstrainedFP.push_back(OutChain); 7176 break; 7177 case fp::ExceptionBehavior::ebStrict: 7178 // These must not be moved across calls or instructions that may change 7179 // floating-point exception masks or read floating-point exception flags. 7180 // In addition, they cannot be optimized out even if unused. 7181 PendingConstrainedFPStrict.push_back(OutChain); 7182 break; 7183 } 7184 }; 7185 7186 SDVTList VTs = DAG.getVTList(ValueVTs); 7187 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7188 7189 SDNodeFlags Flags; 7190 if (EB == fp::ExceptionBehavior::ebIgnore) 7191 Flags.setNoFPExcept(true); 7192 7193 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7194 Flags.copyFMF(*FPOp); 7195 7196 unsigned Opcode; 7197 switch (FPI.getIntrinsicID()) { 7198 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7199 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7200 case Intrinsic::INTRINSIC: \ 7201 Opcode = ISD::STRICT_##DAGN; \ 7202 break; 7203 #include "llvm/IR/ConstrainedOps.def" 7204 case Intrinsic::experimental_constrained_fmuladd: { 7205 Opcode = ISD::STRICT_FMA; 7206 // Break fmuladd into fmul and fadd. 7207 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7208 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7209 ValueVTs[0])) { 7210 Opers.pop_back(); 7211 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7212 pushOutChain(Mul, EB); 7213 Opcode = ISD::STRICT_FADD; 7214 Opers.clear(); 7215 Opers.push_back(Mul.getValue(1)); 7216 Opers.push_back(Mul.getValue(0)); 7217 Opers.push_back(getValue(FPI.getArgOperand(2))); 7218 } 7219 break; 7220 } 7221 } 7222 7223 // A few strict DAG nodes carry additional operands that are not 7224 // set up by the default code above. 7225 switch (Opcode) { 7226 default: break; 7227 case ISD::STRICT_FP_ROUND: 7228 Opers.push_back( 7229 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7230 break; 7231 case ISD::STRICT_FSETCC: 7232 case ISD::STRICT_FSETCCS: { 7233 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7234 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7235 if (TM.Options.NoNaNsFPMath) 7236 Condition = getFCmpCodeWithoutNaN(Condition); 7237 Opers.push_back(DAG.getCondCode(Condition)); 7238 break; 7239 } 7240 } 7241 7242 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7243 pushOutChain(Result, EB); 7244 7245 SDValue FPResult = Result.getValue(0); 7246 setValue(&FPI, FPResult); 7247 } 7248 7249 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7250 Optional<unsigned> ResOPC; 7251 switch (VPIntrin.getIntrinsicID()) { 7252 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN: 7253 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID; 7254 #define END_REGISTER_VP_INTRINSIC(...) break; 7255 #include "llvm/IR/VPIntrinsics.def" 7256 } 7257 7258 if (!ResOPC.hasValue()) 7259 llvm_unreachable( 7260 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7261 7262 return ResOPC.getValue(); 7263 } 7264 7265 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7266 const VPIntrinsic &VPIntrin) { 7267 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7268 7269 SmallVector<EVT, 4> ValueVTs; 7270 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7271 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7272 SDVTList VTs = DAG.getVTList(ValueVTs); 7273 7274 // Request operands. 7275 SmallVector<SDValue, 7> OpValues; 7276 for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i) 7277 OpValues.push_back(getValue(VPIntrin.getArgOperand(i))); 7278 7279 SDLoc DL = getCurSDLoc(); 7280 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7281 setValue(&VPIntrin, Result); 7282 } 7283 7284 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7285 const BasicBlock *EHPadBB, 7286 MCSymbol *&BeginLabel) { 7287 MachineFunction &MF = DAG.getMachineFunction(); 7288 MachineModuleInfo &MMI = MF.getMMI(); 7289 7290 // Insert a label before the invoke call to mark the try range. This can be 7291 // used to detect deletion of the invoke via the MachineModuleInfo. 7292 BeginLabel = MMI.getContext().createTempSymbol(); 7293 7294 // For SjLj, keep track of which landing pads go with which invokes 7295 // so as to maintain the ordering of pads in the LSDA. 7296 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7297 if (CallSiteIndex) { 7298 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7299 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7300 7301 // Now that the call site is handled, stop tracking it. 7302 MMI.setCurrentCallSite(0); 7303 } 7304 7305 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7306 } 7307 7308 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7309 const BasicBlock *EHPadBB, 7310 MCSymbol *BeginLabel) { 7311 assert(BeginLabel && "BeginLabel should've been set"); 7312 7313 MachineFunction &MF = DAG.getMachineFunction(); 7314 MachineModuleInfo &MMI = MF.getMMI(); 7315 7316 // Insert a label at the end of the invoke call to mark the try range. This 7317 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7318 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7319 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7320 7321 // Inform MachineModuleInfo of range. 7322 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7323 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7324 // actually use outlined funclets and their LSDA info style. 7325 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7326 assert(II && "II should've been set"); 7327 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7328 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7329 } else if (!isScopedEHPersonality(Pers)) { 7330 assert(EHPadBB); 7331 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7332 } 7333 7334 return Chain; 7335 } 7336 7337 std::pair<SDValue, SDValue> 7338 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7339 const BasicBlock *EHPadBB) { 7340 MCSymbol *BeginLabel = nullptr; 7341 7342 if (EHPadBB) { 7343 // Both PendingLoads and PendingExports must be flushed here; 7344 // this call might not return. 7345 (void)getRoot(); 7346 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7347 CLI.setChain(getRoot()); 7348 } 7349 7350 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7351 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7352 7353 assert((CLI.IsTailCall || Result.second.getNode()) && 7354 "Non-null chain expected with non-tail call!"); 7355 assert((Result.second.getNode() || !Result.first.getNode()) && 7356 "Null value expected with tail call!"); 7357 7358 if (!Result.second.getNode()) { 7359 // As a special case, a null chain means that a tail call has been emitted 7360 // and the DAG root is already updated. 7361 HasTailCall = true; 7362 7363 // Since there's no actual continuation from this block, nothing can be 7364 // relying on us setting vregs for them. 7365 PendingExports.clear(); 7366 } else { 7367 DAG.setRoot(Result.second); 7368 } 7369 7370 if (EHPadBB) { 7371 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7372 BeginLabel)); 7373 } 7374 7375 return Result; 7376 } 7377 7378 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7379 bool isTailCall, 7380 const BasicBlock *EHPadBB) { 7381 auto &DL = DAG.getDataLayout(); 7382 FunctionType *FTy = CB.getFunctionType(); 7383 Type *RetTy = CB.getType(); 7384 7385 TargetLowering::ArgListTy Args; 7386 Args.reserve(CB.arg_size()); 7387 7388 const Value *SwiftErrorVal = nullptr; 7389 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7390 7391 if (isTailCall) { 7392 // Avoid emitting tail calls in functions with the disable-tail-calls 7393 // attribute. 7394 auto *Caller = CB.getParent()->getParent(); 7395 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7396 "true") 7397 isTailCall = false; 7398 7399 // We can't tail call inside a function with a swifterror argument. Lowering 7400 // does not support this yet. It would have to move into the swifterror 7401 // register before the call. 7402 if (TLI.supportSwiftError() && 7403 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7404 isTailCall = false; 7405 } 7406 7407 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7408 TargetLowering::ArgListEntry Entry; 7409 const Value *V = *I; 7410 7411 // Skip empty types 7412 if (V->getType()->isEmptyTy()) 7413 continue; 7414 7415 SDValue ArgNode = getValue(V); 7416 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7417 7418 Entry.setAttributes(&CB, I - CB.arg_begin()); 7419 7420 // Use swifterror virtual register as input to the call. 7421 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7422 SwiftErrorVal = V; 7423 // We find the virtual register for the actual swifterror argument. 7424 // Instead of using the Value, we use the virtual register instead. 7425 Entry.Node = 7426 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7427 EVT(TLI.getPointerTy(DL))); 7428 } 7429 7430 Args.push_back(Entry); 7431 7432 // If we have an explicit sret argument that is an Instruction, (i.e., it 7433 // might point to function-local memory), we can't meaningfully tail-call. 7434 if (Entry.IsSRet && isa<Instruction>(V)) 7435 isTailCall = false; 7436 } 7437 7438 // If call site has a cfguardtarget operand bundle, create and add an 7439 // additional ArgListEntry. 7440 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7441 TargetLowering::ArgListEntry Entry; 7442 Value *V = Bundle->Inputs[0]; 7443 SDValue ArgNode = getValue(V); 7444 Entry.Node = ArgNode; 7445 Entry.Ty = V->getType(); 7446 Entry.IsCFGuardTarget = true; 7447 Args.push_back(Entry); 7448 } 7449 7450 // Check if target-independent constraints permit a tail call here. 7451 // Target-dependent constraints are checked within TLI->LowerCallTo. 7452 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7453 isTailCall = false; 7454 7455 // Disable tail calls if there is an swifterror argument. Targets have not 7456 // been updated to support tail calls. 7457 if (TLI.supportSwiftError() && SwiftErrorVal) 7458 isTailCall = false; 7459 7460 TargetLowering::CallLoweringInfo CLI(DAG); 7461 CLI.setDebugLoc(getCurSDLoc()) 7462 .setChain(getRoot()) 7463 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7464 .setTailCall(isTailCall) 7465 .setConvergent(CB.isConvergent()) 7466 .setIsPreallocated( 7467 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7468 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7469 7470 if (Result.first.getNode()) { 7471 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7472 setValue(&CB, Result.first); 7473 } 7474 7475 // The last element of CLI.InVals has the SDValue for swifterror return. 7476 // Here we copy it to a virtual register and update SwiftErrorMap for 7477 // book-keeping. 7478 if (SwiftErrorVal && TLI.supportSwiftError()) { 7479 // Get the last element of InVals. 7480 SDValue Src = CLI.InVals.back(); 7481 Register VReg = 7482 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7483 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7484 DAG.setRoot(CopyNode); 7485 } 7486 } 7487 7488 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7489 SelectionDAGBuilder &Builder) { 7490 // Check to see if this load can be trivially constant folded, e.g. if the 7491 // input is from a string literal. 7492 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7493 // Cast pointer to the type we really want to load. 7494 Type *LoadTy = 7495 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7496 if (LoadVT.isVector()) 7497 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7498 7499 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7500 PointerType::getUnqual(LoadTy)); 7501 7502 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7503 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7504 return Builder.getValue(LoadCst); 7505 } 7506 7507 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7508 // still constant memory, the input chain can be the entry node. 7509 SDValue Root; 7510 bool ConstantMemory = false; 7511 7512 // Do not serialize (non-volatile) loads of constant memory with anything. 7513 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7514 Root = Builder.DAG.getEntryNode(); 7515 ConstantMemory = true; 7516 } else { 7517 // Do not serialize non-volatile loads against each other. 7518 Root = Builder.DAG.getRoot(); 7519 } 7520 7521 SDValue Ptr = Builder.getValue(PtrVal); 7522 SDValue LoadVal = 7523 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7524 MachinePointerInfo(PtrVal), Align(1)); 7525 7526 if (!ConstantMemory) 7527 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7528 return LoadVal; 7529 } 7530 7531 /// Record the value for an instruction that produces an integer result, 7532 /// converting the type where necessary. 7533 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7534 SDValue Value, 7535 bool IsSigned) { 7536 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7537 I.getType(), true); 7538 if (IsSigned) 7539 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7540 else 7541 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7542 setValue(&I, Value); 7543 } 7544 7545 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7546 /// true and lower it. Otherwise return false, and it will be lowered like a 7547 /// normal call. 7548 /// The caller already checked that \p I calls the appropriate LibFunc with a 7549 /// correct prototype. 7550 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7551 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7552 const Value *Size = I.getArgOperand(2); 7553 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7554 if (CSize && CSize->getZExtValue() == 0) { 7555 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7556 I.getType(), true); 7557 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7558 return true; 7559 } 7560 7561 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7562 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7563 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7564 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7565 if (Res.first.getNode()) { 7566 processIntegerCallValue(I, Res.first, true); 7567 PendingLoads.push_back(Res.second); 7568 return true; 7569 } 7570 7571 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7572 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7573 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7574 return false; 7575 7576 // If the target has a fast compare for the given size, it will return a 7577 // preferred load type for that size. Require that the load VT is legal and 7578 // that the target supports unaligned loads of that type. Otherwise, return 7579 // INVALID. 7580 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7581 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7582 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7583 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7584 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7585 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7586 // TODO: Check alignment of src and dest ptrs. 7587 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7588 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7589 if (!TLI.isTypeLegal(LVT) || 7590 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7591 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7592 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7593 } 7594 7595 return LVT; 7596 }; 7597 7598 // This turns into unaligned loads. We only do this if the target natively 7599 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7600 // we'll only produce a small number of byte loads. 7601 MVT LoadVT; 7602 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7603 switch (NumBitsToCompare) { 7604 default: 7605 return false; 7606 case 16: 7607 LoadVT = MVT::i16; 7608 break; 7609 case 32: 7610 LoadVT = MVT::i32; 7611 break; 7612 case 64: 7613 case 128: 7614 case 256: 7615 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7616 break; 7617 } 7618 7619 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7620 return false; 7621 7622 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7623 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7624 7625 // Bitcast to a wide integer type if the loads are vectors. 7626 if (LoadVT.isVector()) { 7627 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7628 LoadL = DAG.getBitcast(CmpVT, LoadL); 7629 LoadR = DAG.getBitcast(CmpVT, LoadR); 7630 } 7631 7632 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7633 processIntegerCallValue(I, Cmp, false); 7634 return true; 7635 } 7636 7637 /// See if we can lower a memchr call into an optimized form. If so, return 7638 /// true and lower it. Otherwise return false, and it will be lowered like a 7639 /// normal call. 7640 /// The caller already checked that \p I calls the appropriate LibFunc with a 7641 /// correct prototype. 7642 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7643 const Value *Src = I.getArgOperand(0); 7644 const Value *Char = I.getArgOperand(1); 7645 const Value *Length = I.getArgOperand(2); 7646 7647 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7648 std::pair<SDValue, SDValue> Res = 7649 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7650 getValue(Src), getValue(Char), getValue(Length), 7651 MachinePointerInfo(Src)); 7652 if (Res.first.getNode()) { 7653 setValue(&I, Res.first); 7654 PendingLoads.push_back(Res.second); 7655 return true; 7656 } 7657 7658 return false; 7659 } 7660 7661 /// See if we can lower a mempcpy call into an optimized form. If so, return 7662 /// true and lower it. Otherwise return false, and it will be lowered like a 7663 /// normal call. 7664 /// The caller already checked that \p I calls the appropriate LibFunc with a 7665 /// correct prototype. 7666 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7667 SDValue Dst = getValue(I.getArgOperand(0)); 7668 SDValue Src = getValue(I.getArgOperand(1)); 7669 SDValue Size = getValue(I.getArgOperand(2)); 7670 7671 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7672 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7673 // DAG::getMemcpy needs Alignment to be defined. 7674 Align Alignment = std::min(DstAlign, SrcAlign); 7675 7676 bool isVol = false; 7677 SDLoc sdl = getCurSDLoc(); 7678 7679 // In the mempcpy context we need to pass in a false value for isTailCall 7680 // because the return pointer needs to be adjusted by the size of 7681 // the copied memory. 7682 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7683 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7684 /*isTailCall=*/false, 7685 MachinePointerInfo(I.getArgOperand(0)), 7686 MachinePointerInfo(I.getArgOperand(1))); 7687 assert(MC.getNode() != nullptr && 7688 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7689 DAG.setRoot(MC); 7690 7691 // Check if Size needs to be truncated or extended. 7692 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7693 7694 // Adjust return pointer to point just past the last dst byte. 7695 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7696 Dst, Size); 7697 setValue(&I, DstPlusSize); 7698 return true; 7699 } 7700 7701 /// See if we can lower a strcpy call into an optimized form. If so, return 7702 /// true and lower it, otherwise return false and it will be lowered like a 7703 /// normal call. 7704 /// The caller already checked that \p I calls the appropriate LibFunc with a 7705 /// correct prototype. 7706 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7707 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7708 7709 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7710 std::pair<SDValue, SDValue> Res = 7711 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7712 getValue(Arg0), getValue(Arg1), 7713 MachinePointerInfo(Arg0), 7714 MachinePointerInfo(Arg1), isStpcpy); 7715 if (Res.first.getNode()) { 7716 setValue(&I, Res.first); 7717 DAG.setRoot(Res.second); 7718 return true; 7719 } 7720 7721 return false; 7722 } 7723 7724 /// See if we can lower a strcmp call into an optimized form. If so, return 7725 /// true and lower it, otherwise return false and it will be lowered like a 7726 /// normal call. 7727 /// The caller already checked that \p I calls the appropriate LibFunc with a 7728 /// correct prototype. 7729 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7730 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7731 7732 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7733 std::pair<SDValue, SDValue> Res = 7734 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7735 getValue(Arg0), getValue(Arg1), 7736 MachinePointerInfo(Arg0), 7737 MachinePointerInfo(Arg1)); 7738 if (Res.first.getNode()) { 7739 processIntegerCallValue(I, Res.first, true); 7740 PendingLoads.push_back(Res.second); 7741 return true; 7742 } 7743 7744 return false; 7745 } 7746 7747 /// See if we can lower a strlen call into an optimized form. If so, return 7748 /// true and lower it, otherwise return false and it will be lowered like a 7749 /// normal call. 7750 /// The caller already checked that \p I calls the appropriate LibFunc with a 7751 /// correct prototype. 7752 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7753 const Value *Arg0 = I.getArgOperand(0); 7754 7755 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7756 std::pair<SDValue, SDValue> Res = 7757 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7758 getValue(Arg0), MachinePointerInfo(Arg0)); 7759 if (Res.first.getNode()) { 7760 processIntegerCallValue(I, Res.first, false); 7761 PendingLoads.push_back(Res.second); 7762 return true; 7763 } 7764 7765 return false; 7766 } 7767 7768 /// See if we can lower a strnlen call into an optimized form. If so, return 7769 /// true and lower it, otherwise return false and it will be lowered like a 7770 /// normal call. 7771 /// The caller already checked that \p I calls the appropriate LibFunc with a 7772 /// correct prototype. 7773 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7774 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7775 7776 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7777 std::pair<SDValue, SDValue> Res = 7778 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7779 getValue(Arg0), getValue(Arg1), 7780 MachinePointerInfo(Arg0)); 7781 if (Res.first.getNode()) { 7782 processIntegerCallValue(I, Res.first, false); 7783 PendingLoads.push_back(Res.second); 7784 return true; 7785 } 7786 7787 return false; 7788 } 7789 7790 /// See if we can lower a unary floating-point operation into an SDNode with 7791 /// the specified Opcode. If so, return true and lower it, otherwise return 7792 /// false and it will be lowered like a normal call. 7793 /// The caller already checked that \p I calls the appropriate LibFunc with a 7794 /// correct prototype. 7795 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7796 unsigned Opcode) { 7797 // We already checked this call's prototype; verify it doesn't modify errno. 7798 if (!I.onlyReadsMemory()) 7799 return false; 7800 7801 SDNodeFlags Flags; 7802 Flags.copyFMF(cast<FPMathOperator>(I)); 7803 7804 SDValue Tmp = getValue(I.getArgOperand(0)); 7805 setValue(&I, 7806 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7807 return true; 7808 } 7809 7810 /// See if we can lower a binary floating-point operation into an SDNode with 7811 /// the specified Opcode. If so, return true and lower it. Otherwise return 7812 /// false, and it will be lowered like a normal call. 7813 /// The caller already checked that \p I calls the appropriate LibFunc with a 7814 /// correct prototype. 7815 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7816 unsigned Opcode) { 7817 // We already checked this call's prototype; verify it doesn't modify errno. 7818 if (!I.onlyReadsMemory()) 7819 return false; 7820 7821 SDNodeFlags Flags; 7822 Flags.copyFMF(cast<FPMathOperator>(I)); 7823 7824 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7825 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7826 EVT VT = Tmp0.getValueType(); 7827 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7828 return true; 7829 } 7830 7831 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7832 // Handle inline assembly differently. 7833 if (I.isInlineAsm()) { 7834 visitInlineAsm(I); 7835 return; 7836 } 7837 7838 if (Function *F = I.getCalledFunction()) { 7839 if (F->isDeclaration()) { 7840 // Is this an LLVM intrinsic or a target-specific intrinsic? 7841 unsigned IID = F->getIntrinsicID(); 7842 if (!IID) 7843 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7844 IID = II->getIntrinsicID(F); 7845 7846 if (IID) { 7847 visitIntrinsicCall(I, IID); 7848 return; 7849 } 7850 } 7851 7852 // Check for well-known libc/libm calls. If the function is internal, it 7853 // can't be a library call. Don't do the check if marked as nobuiltin for 7854 // some reason or the call site requires strict floating point semantics. 7855 LibFunc Func; 7856 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7857 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7858 LibInfo->hasOptimizedCodeGen(Func)) { 7859 switch (Func) { 7860 default: break; 7861 case LibFunc_bcmp: 7862 if (visitMemCmpBCmpCall(I)) 7863 return; 7864 break; 7865 case LibFunc_copysign: 7866 case LibFunc_copysignf: 7867 case LibFunc_copysignl: 7868 // We already checked this call's prototype; verify it doesn't modify 7869 // errno. 7870 if (I.onlyReadsMemory()) { 7871 SDValue LHS = getValue(I.getArgOperand(0)); 7872 SDValue RHS = getValue(I.getArgOperand(1)); 7873 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7874 LHS.getValueType(), LHS, RHS)); 7875 return; 7876 } 7877 break; 7878 case LibFunc_fabs: 7879 case LibFunc_fabsf: 7880 case LibFunc_fabsl: 7881 if (visitUnaryFloatCall(I, ISD::FABS)) 7882 return; 7883 break; 7884 case LibFunc_fmin: 7885 case LibFunc_fminf: 7886 case LibFunc_fminl: 7887 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7888 return; 7889 break; 7890 case LibFunc_fmax: 7891 case LibFunc_fmaxf: 7892 case LibFunc_fmaxl: 7893 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7894 return; 7895 break; 7896 case LibFunc_sin: 7897 case LibFunc_sinf: 7898 case LibFunc_sinl: 7899 if (visitUnaryFloatCall(I, ISD::FSIN)) 7900 return; 7901 break; 7902 case LibFunc_cos: 7903 case LibFunc_cosf: 7904 case LibFunc_cosl: 7905 if (visitUnaryFloatCall(I, ISD::FCOS)) 7906 return; 7907 break; 7908 case LibFunc_sqrt: 7909 case LibFunc_sqrtf: 7910 case LibFunc_sqrtl: 7911 case LibFunc_sqrt_finite: 7912 case LibFunc_sqrtf_finite: 7913 case LibFunc_sqrtl_finite: 7914 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7915 return; 7916 break; 7917 case LibFunc_floor: 7918 case LibFunc_floorf: 7919 case LibFunc_floorl: 7920 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7921 return; 7922 break; 7923 case LibFunc_nearbyint: 7924 case LibFunc_nearbyintf: 7925 case LibFunc_nearbyintl: 7926 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7927 return; 7928 break; 7929 case LibFunc_ceil: 7930 case LibFunc_ceilf: 7931 case LibFunc_ceill: 7932 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7933 return; 7934 break; 7935 case LibFunc_rint: 7936 case LibFunc_rintf: 7937 case LibFunc_rintl: 7938 if (visitUnaryFloatCall(I, ISD::FRINT)) 7939 return; 7940 break; 7941 case LibFunc_round: 7942 case LibFunc_roundf: 7943 case LibFunc_roundl: 7944 if (visitUnaryFloatCall(I, ISD::FROUND)) 7945 return; 7946 break; 7947 case LibFunc_trunc: 7948 case LibFunc_truncf: 7949 case LibFunc_truncl: 7950 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7951 return; 7952 break; 7953 case LibFunc_log2: 7954 case LibFunc_log2f: 7955 case LibFunc_log2l: 7956 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7957 return; 7958 break; 7959 case LibFunc_exp2: 7960 case LibFunc_exp2f: 7961 case LibFunc_exp2l: 7962 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7963 return; 7964 break; 7965 case LibFunc_memcmp: 7966 if (visitMemCmpBCmpCall(I)) 7967 return; 7968 break; 7969 case LibFunc_mempcpy: 7970 if (visitMemPCpyCall(I)) 7971 return; 7972 break; 7973 case LibFunc_memchr: 7974 if (visitMemChrCall(I)) 7975 return; 7976 break; 7977 case LibFunc_strcpy: 7978 if (visitStrCpyCall(I, false)) 7979 return; 7980 break; 7981 case LibFunc_stpcpy: 7982 if (visitStrCpyCall(I, true)) 7983 return; 7984 break; 7985 case LibFunc_strcmp: 7986 if (visitStrCmpCall(I)) 7987 return; 7988 break; 7989 case LibFunc_strlen: 7990 if (visitStrLenCall(I)) 7991 return; 7992 break; 7993 case LibFunc_strnlen: 7994 if (visitStrNLenCall(I)) 7995 return; 7996 break; 7997 } 7998 } 7999 } 8000 8001 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8002 // have to do anything here to lower funclet bundles. 8003 // CFGuardTarget bundles are lowered in LowerCallTo. 8004 assert(!I.hasOperandBundlesOtherThan( 8005 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8006 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8007 LLVMContext::OB_clang_arc_attachedcall}) && 8008 "Cannot lower calls with arbitrary operand bundles!"); 8009 8010 SDValue Callee = getValue(I.getCalledOperand()); 8011 8012 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8013 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8014 else 8015 // Check if we can potentially perform a tail call. More detailed checking 8016 // is be done within LowerCallTo, after more information about the call is 8017 // known. 8018 LowerCallTo(I, Callee, I.isTailCall()); 8019 } 8020 8021 namespace { 8022 8023 /// AsmOperandInfo - This contains information for each constraint that we are 8024 /// lowering. 8025 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8026 public: 8027 /// CallOperand - If this is the result output operand or a clobber 8028 /// this is null, otherwise it is the incoming operand to the CallInst. 8029 /// This gets modified as the asm is processed. 8030 SDValue CallOperand; 8031 8032 /// AssignedRegs - If this is a register or register class operand, this 8033 /// contains the set of register corresponding to the operand. 8034 RegsForValue AssignedRegs; 8035 8036 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8037 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8038 } 8039 8040 /// Whether or not this operand accesses memory 8041 bool hasMemory(const TargetLowering &TLI) const { 8042 // Indirect operand accesses access memory. 8043 if (isIndirect) 8044 return true; 8045 8046 for (const auto &Code : Codes) 8047 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8048 return true; 8049 8050 return false; 8051 } 8052 8053 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8054 /// corresponds to. If there is no Value* for this operand, it returns 8055 /// MVT::Other. 8056 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8057 const DataLayout &DL) const { 8058 if (!CallOperandVal) return MVT::Other; 8059 8060 if (isa<BasicBlock>(CallOperandVal)) 8061 return TLI.getProgramPointerTy(DL); 8062 8063 llvm::Type *OpTy = CallOperandVal->getType(); 8064 8065 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8066 // If this is an indirect operand, the operand is a pointer to the 8067 // accessed type. 8068 if (isIndirect) { 8069 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 8070 if (!PtrTy) 8071 report_fatal_error("Indirect operand for inline asm not a pointer!"); 8072 OpTy = PtrTy->getElementType(); 8073 } 8074 8075 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8076 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8077 if (STy->getNumElements() == 1) 8078 OpTy = STy->getElementType(0); 8079 8080 // If OpTy is not a single value, it may be a struct/union that we 8081 // can tile with integers. 8082 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8083 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8084 switch (BitSize) { 8085 default: break; 8086 case 1: 8087 case 8: 8088 case 16: 8089 case 32: 8090 case 64: 8091 case 128: 8092 OpTy = IntegerType::get(Context, BitSize); 8093 break; 8094 } 8095 } 8096 8097 return TLI.getValueType(DL, OpTy, true); 8098 } 8099 }; 8100 8101 8102 } // end anonymous namespace 8103 8104 /// Make sure that the output operand \p OpInfo and its corresponding input 8105 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8106 /// out). 8107 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8108 SDISelAsmOperandInfo &MatchingOpInfo, 8109 SelectionDAG &DAG) { 8110 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8111 return; 8112 8113 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8114 const auto &TLI = DAG.getTargetLoweringInfo(); 8115 8116 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8117 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8118 OpInfo.ConstraintVT); 8119 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8120 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8121 MatchingOpInfo.ConstraintVT); 8122 if ((OpInfo.ConstraintVT.isInteger() != 8123 MatchingOpInfo.ConstraintVT.isInteger()) || 8124 (MatchRC.second != InputRC.second)) { 8125 // FIXME: error out in a more elegant fashion 8126 report_fatal_error("Unsupported asm: input constraint" 8127 " with a matching output constraint of" 8128 " incompatible type!"); 8129 } 8130 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8131 } 8132 8133 /// Get a direct memory input to behave well as an indirect operand. 8134 /// This may introduce stores, hence the need for a \p Chain. 8135 /// \return The (possibly updated) chain. 8136 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8137 SDISelAsmOperandInfo &OpInfo, 8138 SelectionDAG &DAG) { 8139 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8140 8141 // If we don't have an indirect input, put it in the constpool if we can, 8142 // otherwise spill it to a stack slot. 8143 // TODO: This isn't quite right. We need to handle these according to 8144 // the addressing mode that the constraint wants. Also, this may take 8145 // an additional register for the computation and we don't want that 8146 // either. 8147 8148 // If the operand is a float, integer, or vector constant, spill to a 8149 // constant pool entry to get its address. 8150 const Value *OpVal = OpInfo.CallOperandVal; 8151 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8152 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8153 OpInfo.CallOperand = DAG.getConstantPool( 8154 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8155 return Chain; 8156 } 8157 8158 // Otherwise, create a stack slot and emit a store to it before the asm. 8159 Type *Ty = OpVal->getType(); 8160 auto &DL = DAG.getDataLayout(); 8161 uint64_t TySize = DL.getTypeAllocSize(Ty); 8162 MachineFunction &MF = DAG.getMachineFunction(); 8163 int SSFI = MF.getFrameInfo().CreateStackObject( 8164 TySize, DL.getPrefTypeAlign(Ty), false); 8165 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8166 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8167 MachinePointerInfo::getFixedStack(MF, SSFI), 8168 TLI.getMemValueType(DL, Ty)); 8169 OpInfo.CallOperand = StackSlot; 8170 8171 return Chain; 8172 } 8173 8174 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8175 /// specified operand. We prefer to assign virtual registers, to allow the 8176 /// register allocator to handle the assignment process. However, if the asm 8177 /// uses features that we can't model on machineinstrs, we have SDISel do the 8178 /// allocation. This produces generally horrible, but correct, code. 8179 /// 8180 /// OpInfo describes the operand 8181 /// RefOpInfo describes the matching operand if any, the operand otherwise 8182 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8183 SDISelAsmOperandInfo &OpInfo, 8184 SDISelAsmOperandInfo &RefOpInfo) { 8185 LLVMContext &Context = *DAG.getContext(); 8186 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8187 8188 MachineFunction &MF = DAG.getMachineFunction(); 8189 SmallVector<unsigned, 4> Regs; 8190 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8191 8192 // No work to do for memory operations. 8193 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8194 return; 8195 8196 // If this is a constraint for a single physreg, or a constraint for a 8197 // register class, find it. 8198 unsigned AssignedReg; 8199 const TargetRegisterClass *RC; 8200 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8201 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8202 // RC is unset only on failure. Return immediately. 8203 if (!RC) 8204 return; 8205 8206 // Get the actual register value type. This is important, because the user 8207 // may have asked for (e.g.) the AX register in i32 type. We need to 8208 // remember that AX is actually i16 to get the right extension. 8209 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8210 8211 if (OpInfo.ConstraintVT != MVT::Other) { 8212 // If this is an FP operand in an integer register (or visa versa), or more 8213 // generally if the operand value disagrees with the register class we plan 8214 // to stick it in, fix the operand type. 8215 // 8216 // If this is an input value, the bitcast to the new type is done now. 8217 // Bitcast for output value is done at the end of visitInlineAsm(). 8218 if ((OpInfo.Type == InlineAsm::isOutput || 8219 OpInfo.Type == InlineAsm::isInput) && 8220 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8221 // Try to convert to the first EVT that the reg class contains. If the 8222 // types are identical size, use a bitcast to convert (e.g. two differing 8223 // vector types). Note: output bitcast is done at the end of 8224 // visitInlineAsm(). 8225 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8226 // Exclude indirect inputs while they are unsupported because the code 8227 // to perform the load is missing and thus OpInfo.CallOperand still 8228 // refers to the input address rather than the pointed-to value. 8229 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8230 OpInfo.CallOperand = 8231 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8232 OpInfo.ConstraintVT = RegVT; 8233 // If the operand is an FP value and we want it in integer registers, 8234 // use the corresponding integer type. This turns an f64 value into 8235 // i64, which can be passed with two i32 values on a 32-bit machine. 8236 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8237 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8238 if (OpInfo.Type == InlineAsm::isInput) 8239 OpInfo.CallOperand = 8240 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8241 OpInfo.ConstraintVT = VT; 8242 } 8243 } 8244 } 8245 8246 // No need to allocate a matching input constraint since the constraint it's 8247 // matching to has already been allocated. 8248 if (OpInfo.isMatchingInputConstraint()) 8249 return; 8250 8251 EVT ValueVT = OpInfo.ConstraintVT; 8252 if (OpInfo.ConstraintVT == MVT::Other) 8253 ValueVT = RegVT; 8254 8255 // Initialize NumRegs. 8256 unsigned NumRegs = 1; 8257 if (OpInfo.ConstraintVT != MVT::Other) 8258 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8259 8260 // If this is a constraint for a specific physical register, like {r17}, 8261 // assign it now. 8262 8263 // If this associated to a specific register, initialize iterator to correct 8264 // place. If virtual, make sure we have enough registers 8265 8266 // Initialize iterator if necessary 8267 TargetRegisterClass::iterator I = RC->begin(); 8268 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8269 8270 // Do not check for single registers. 8271 if (AssignedReg) { 8272 for (; *I != AssignedReg; ++I) 8273 assert(I != RC->end() && "AssignedReg should be member of RC"); 8274 } 8275 8276 for (; NumRegs; --NumRegs, ++I) { 8277 assert(I != RC->end() && "Ran out of registers to allocate!"); 8278 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8279 Regs.push_back(R); 8280 } 8281 8282 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8283 } 8284 8285 static unsigned 8286 findMatchingInlineAsmOperand(unsigned OperandNo, 8287 const std::vector<SDValue> &AsmNodeOperands) { 8288 // Scan until we find the definition we already emitted of this operand. 8289 unsigned CurOp = InlineAsm::Op_FirstOperand; 8290 for (; OperandNo; --OperandNo) { 8291 // Advance to the next operand. 8292 unsigned OpFlag = 8293 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8294 assert((InlineAsm::isRegDefKind(OpFlag) || 8295 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8296 InlineAsm::isMemKind(OpFlag)) && 8297 "Skipped past definitions?"); 8298 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8299 } 8300 return CurOp; 8301 } 8302 8303 namespace { 8304 8305 class ExtraFlags { 8306 unsigned Flags = 0; 8307 8308 public: 8309 explicit ExtraFlags(const CallBase &Call) { 8310 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8311 if (IA->hasSideEffects()) 8312 Flags |= InlineAsm::Extra_HasSideEffects; 8313 if (IA->isAlignStack()) 8314 Flags |= InlineAsm::Extra_IsAlignStack; 8315 if (Call.isConvergent()) 8316 Flags |= InlineAsm::Extra_IsConvergent; 8317 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8318 } 8319 8320 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8321 // Ideally, we would only check against memory constraints. However, the 8322 // meaning of an Other constraint can be target-specific and we can't easily 8323 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8324 // for Other constraints as well. 8325 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8326 OpInfo.ConstraintType == TargetLowering::C_Other) { 8327 if (OpInfo.Type == InlineAsm::isInput) 8328 Flags |= InlineAsm::Extra_MayLoad; 8329 else if (OpInfo.Type == InlineAsm::isOutput) 8330 Flags |= InlineAsm::Extra_MayStore; 8331 else if (OpInfo.Type == InlineAsm::isClobber) 8332 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8333 } 8334 } 8335 8336 unsigned get() const { return Flags; } 8337 }; 8338 8339 } // end anonymous namespace 8340 8341 /// visitInlineAsm - Handle a call to an InlineAsm object. 8342 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8343 const BasicBlock *EHPadBB) { 8344 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8345 8346 /// ConstraintOperands - Information about all of the constraints. 8347 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8348 8349 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8350 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8351 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8352 8353 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8354 // AsmDialect, MayLoad, MayStore). 8355 bool HasSideEffect = IA->hasSideEffects(); 8356 ExtraFlags ExtraInfo(Call); 8357 8358 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8359 unsigned ResNo = 0; // ResNo - The result number of the next output. 8360 unsigned NumMatchingOps = 0; 8361 for (auto &T : TargetConstraints) { 8362 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8363 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8364 8365 // Compute the value type for each operand. 8366 if (OpInfo.Type == InlineAsm::isInput || 8367 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8368 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8369 8370 // Process the call argument. BasicBlocks are labels, currently appearing 8371 // only in asm's. 8372 if (isa<CallBrInst>(Call) && 8373 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8374 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8375 NumMatchingOps) && 8376 (NumMatchingOps == 0 || 8377 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8378 NumMatchingOps))) { 8379 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8380 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8381 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8382 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8383 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8384 } else { 8385 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8386 } 8387 8388 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8389 DAG.getDataLayout()); 8390 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8391 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8392 // The return value of the call is this value. As such, there is no 8393 // corresponding argument. 8394 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8395 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8396 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8397 DAG.getDataLayout(), STy->getElementType(ResNo)); 8398 } else { 8399 assert(ResNo == 0 && "Asm only has one result!"); 8400 OpInfo.ConstraintVT = 8401 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8402 } 8403 ++ResNo; 8404 } else { 8405 OpInfo.ConstraintVT = MVT::Other; 8406 } 8407 8408 if (OpInfo.hasMatchingInput()) 8409 ++NumMatchingOps; 8410 8411 if (!HasSideEffect) 8412 HasSideEffect = OpInfo.hasMemory(TLI); 8413 8414 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8415 // FIXME: Could we compute this on OpInfo rather than T? 8416 8417 // Compute the constraint code and ConstraintType to use. 8418 TLI.ComputeConstraintToUse(T, SDValue()); 8419 8420 if (T.ConstraintType == TargetLowering::C_Immediate && 8421 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8422 // We've delayed emitting a diagnostic like the "n" constraint because 8423 // inlining could cause an integer showing up. 8424 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8425 "' expects an integer constant " 8426 "expression"); 8427 8428 ExtraInfo.update(T); 8429 } 8430 8431 // We won't need to flush pending loads if this asm doesn't touch 8432 // memory and is nonvolatile. 8433 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8434 8435 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8436 if (EmitEHLabels) { 8437 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8438 } 8439 bool IsCallBr = isa<CallBrInst>(Call); 8440 8441 if (IsCallBr || EmitEHLabels) { 8442 // If this is a callbr or invoke we need to flush pending exports since 8443 // inlineasm_br and invoke are terminators. 8444 // We need to do this before nodes are glued to the inlineasm_br node. 8445 Chain = getControlRoot(); 8446 } 8447 8448 MCSymbol *BeginLabel = nullptr; 8449 if (EmitEHLabels) { 8450 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8451 } 8452 8453 // Second pass over the constraints: compute which constraint option to use. 8454 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8455 // If this is an output operand with a matching input operand, look up the 8456 // matching input. If their types mismatch, e.g. one is an integer, the 8457 // other is floating point, or their sizes are different, flag it as an 8458 // error. 8459 if (OpInfo.hasMatchingInput()) { 8460 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8461 patchMatchingInput(OpInfo, Input, DAG); 8462 } 8463 8464 // Compute the constraint code and ConstraintType to use. 8465 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8466 8467 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8468 OpInfo.Type == InlineAsm::isClobber) 8469 continue; 8470 8471 // If this is a memory input, and if the operand is not indirect, do what we 8472 // need to provide an address for the memory input. 8473 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8474 !OpInfo.isIndirect) { 8475 assert((OpInfo.isMultipleAlternative || 8476 (OpInfo.Type == InlineAsm::isInput)) && 8477 "Can only indirectify direct input operands!"); 8478 8479 // Memory operands really want the address of the value. 8480 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8481 8482 // There is no longer a Value* corresponding to this operand. 8483 OpInfo.CallOperandVal = nullptr; 8484 8485 // It is now an indirect operand. 8486 OpInfo.isIndirect = true; 8487 } 8488 8489 } 8490 8491 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8492 std::vector<SDValue> AsmNodeOperands; 8493 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8494 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8495 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8496 8497 // If we have a !srcloc metadata node associated with it, we want to attach 8498 // this to the ultimately generated inline asm machineinstr. To do this, we 8499 // pass in the third operand as this (potentially null) inline asm MDNode. 8500 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8501 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8502 8503 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8504 // bits as operand 3. 8505 AsmNodeOperands.push_back(DAG.getTargetConstant( 8506 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8507 8508 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8509 // this, assign virtual and physical registers for inputs and otput. 8510 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8511 // Assign Registers. 8512 SDISelAsmOperandInfo &RefOpInfo = 8513 OpInfo.isMatchingInputConstraint() 8514 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8515 : OpInfo; 8516 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8517 8518 auto DetectWriteToReservedRegister = [&]() { 8519 const MachineFunction &MF = DAG.getMachineFunction(); 8520 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8521 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8522 if (Register::isPhysicalRegister(Reg) && 8523 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8524 const char *RegName = TRI.getName(Reg); 8525 emitInlineAsmError(Call, "write to reserved register '" + 8526 Twine(RegName) + "'"); 8527 return true; 8528 } 8529 } 8530 return false; 8531 }; 8532 8533 switch (OpInfo.Type) { 8534 case InlineAsm::isOutput: 8535 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8536 unsigned ConstraintID = 8537 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8538 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8539 "Failed to convert memory constraint code to constraint id."); 8540 8541 // Add information to the INLINEASM node to know about this output. 8542 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8543 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8544 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8545 MVT::i32)); 8546 AsmNodeOperands.push_back(OpInfo.CallOperand); 8547 } else { 8548 // Otherwise, this outputs to a register (directly for C_Register / 8549 // C_RegisterClass, and a target-defined fashion for 8550 // C_Immediate/C_Other). Find a register that we can use. 8551 if (OpInfo.AssignedRegs.Regs.empty()) { 8552 emitInlineAsmError( 8553 Call, "couldn't allocate output register for constraint '" + 8554 Twine(OpInfo.ConstraintCode) + "'"); 8555 return; 8556 } 8557 8558 if (DetectWriteToReservedRegister()) 8559 return; 8560 8561 // Add information to the INLINEASM node to know that this register is 8562 // set. 8563 OpInfo.AssignedRegs.AddInlineAsmOperands( 8564 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8565 : InlineAsm::Kind_RegDef, 8566 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8567 } 8568 break; 8569 8570 case InlineAsm::isInput: { 8571 SDValue InOperandVal = OpInfo.CallOperand; 8572 8573 if (OpInfo.isMatchingInputConstraint()) { 8574 // If this is required to match an output register we have already set, 8575 // just use its register. 8576 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8577 AsmNodeOperands); 8578 unsigned OpFlag = 8579 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8580 if (InlineAsm::isRegDefKind(OpFlag) || 8581 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8582 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8583 if (OpInfo.isIndirect) { 8584 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8585 emitInlineAsmError(Call, "inline asm not supported yet: " 8586 "don't know how to handle tied " 8587 "indirect register inputs"); 8588 return; 8589 } 8590 8591 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8592 SmallVector<unsigned, 4> Regs; 8593 8594 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8595 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8596 MachineRegisterInfo &RegInfo = 8597 DAG.getMachineFunction().getRegInfo(); 8598 for (unsigned i = 0; i != NumRegs; ++i) 8599 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8600 } else { 8601 emitInlineAsmError(Call, 8602 "inline asm error: This value type register " 8603 "class is not natively supported!"); 8604 return; 8605 } 8606 8607 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8608 8609 SDLoc dl = getCurSDLoc(); 8610 // Use the produced MatchedRegs object to 8611 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8612 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8613 true, OpInfo.getMatchedOperand(), dl, 8614 DAG, AsmNodeOperands); 8615 break; 8616 } 8617 8618 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8619 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8620 "Unexpected number of operands"); 8621 // Add information to the INLINEASM node to know about this input. 8622 // See InlineAsm.h isUseOperandTiedToDef. 8623 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8624 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8625 OpInfo.getMatchedOperand()); 8626 AsmNodeOperands.push_back(DAG.getTargetConstant( 8627 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8628 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8629 break; 8630 } 8631 8632 // Treat indirect 'X' constraint as memory. 8633 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8634 OpInfo.isIndirect) 8635 OpInfo.ConstraintType = TargetLowering::C_Memory; 8636 8637 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8638 OpInfo.ConstraintType == TargetLowering::C_Other) { 8639 std::vector<SDValue> Ops; 8640 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8641 Ops, DAG); 8642 if (Ops.empty()) { 8643 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8644 if (isa<ConstantSDNode>(InOperandVal)) { 8645 emitInlineAsmError(Call, "value out of range for constraint '" + 8646 Twine(OpInfo.ConstraintCode) + "'"); 8647 return; 8648 } 8649 8650 emitInlineAsmError(Call, 8651 "invalid operand for inline asm constraint '" + 8652 Twine(OpInfo.ConstraintCode) + "'"); 8653 return; 8654 } 8655 8656 // Add information to the INLINEASM node to know about this input. 8657 unsigned ResOpType = 8658 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8659 AsmNodeOperands.push_back(DAG.getTargetConstant( 8660 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8661 llvm::append_range(AsmNodeOperands, Ops); 8662 break; 8663 } 8664 8665 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8666 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8667 assert(InOperandVal.getValueType() == 8668 TLI.getPointerTy(DAG.getDataLayout()) && 8669 "Memory operands expect pointer values"); 8670 8671 unsigned ConstraintID = 8672 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8673 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8674 "Failed to convert memory constraint code to constraint id."); 8675 8676 // Add information to the INLINEASM node to know about this input. 8677 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8678 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8679 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8680 getCurSDLoc(), 8681 MVT::i32)); 8682 AsmNodeOperands.push_back(InOperandVal); 8683 break; 8684 } 8685 8686 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8687 OpInfo.ConstraintType == TargetLowering::C_Register) && 8688 "Unknown constraint type!"); 8689 8690 // TODO: Support this. 8691 if (OpInfo.isIndirect) { 8692 emitInlineAsmError( 8693 Call, "Don't know how to handle indirect register inputs yet " 8694 "for constraint '" + 8695 Twine(OpInfo.ConstraintCode) + "'"); 8696 return; 8697 } 8698 8699 // Copy the input into the appropriate registers. 8700 if (OpInfo.AssignedRegs.Regs.empty()) { 8701 emitInlineAsmError(Call, 8702 "couldn't allocate input reg for constraint '" + 8703 Twine(OpInfo.ConstraintCode) + "'"); 8704 return; 8705 } 8706 8707 if (DetectWriteToReservedRegister()) 8708 return; 8709 8710 SDLoc dl = getCurSDLoc(); 8711 8712 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8713 &Call); 8714 8715 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8716 dl, DAG, AsmNodeOperands); 8717 break; 8718 } 8719 case InlineAsm::isClobber: 8720 // Add the clobbered value to the operand list, so that the register 8721 // allocator is aware that the physreg got clobbered. 8722 if (!OpInfo.AssignedRegs.Regs.empty()) 8723 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8724 false, 0, getCurSDLoc(), DAG, 8725 AsmNodeOperands); 8726 break; 8727 } 8728 } 8729 8730 // Finish up input operands. Set the input chain and add the flag last. 8731 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8732 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8733 8734 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8735 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8736 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8737 Flag = Chain.getValue(1); 8738 8739 // Do additional work to generate outputs. 8740 8741 SmallVector<EVT, 1> ResultVTs; 8742 SmallVector<SDValue, 1> ResultValues; 8743 SmallVector<SDValue, 8> OutChains; 8744 8745 llvm::Type *CallResultType = Call.getType(); 8746 ArrayRef<Type *> ResultTypes; 8747 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8748 ResultTypes = StructResult->elements(); 8749 else if (!CallResultType->isVoidTy()) 8750 ResultTypes = makeArrayRef(CallResultType); 8751 8752 auto CurResultType = ResultTypes.begin(); 8753 auto handleRegAssign = [&](SDValue V) { 8754 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8755 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8756 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8757 ++CurResultType; 8758 // If the type of the inline asm call site return value is different but has 8759 // same size as the type of the asm output bitcast it. One example of this 8760 // is for vectors with different width / number of elements. This can 8761 // happen for register classes that can contain multiple different value 8762 // types. The preg or vreg allocated may not have the same VT as was 8763 // expected. 8764 // 8765 // This can also happen for a return value that disagrees with the register 8766 // class it is put in, eg. a double in a general-purpose register on a 8767 // 32-bit machine. 8768 if (ResultVT != V.getValueType() && 8769 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8770 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8771 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8772 V.getValueType().isInteger()) { 8773 // If a result value was tied to an input value, the computed result 8774 // may have a wider width than the expected result. Extract the 8775 // relevant portion. 8776 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8777 } 8778 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8779 ResultVTs.push_back(ResultVT); 8780 ResultValues.push_back(V); 8781 }; 8782 8783 // Deal with output operands. 8784 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8785 if (OpInfo.Type == InlineAsm::isOutput) { 8786 SDValue Val; 8787 // Skip trivial output operands. 8788 if (OpInfo.AssignedRegs.Regs.empty()) 8789 continue; 8790 8791 switch (OpInfo.ConstraintType) { 8792 case TargetLowering::C_Register: 8793 case TargetLowering::C_RegisterClass: 8794 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8795 Chain, &Flag, &Call); 8796 break; 8797 case TargetLowering::C_Immediate: 8798 case TargetLowering::C_Other: 8799 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8800 OpInfo, DAG); 8801 break; 8802 case TargetLowering::C_Memory: 8803 break; // Already handled. 8804 case TargetLowering::C_Unknown: 8805 assert(false && "Unexpected unknown constraint"); 8806 } 8807 8808 // Indirect output manifest as stores. Record output chains. 8809 if (OpInfo.isIndirect) { 8810 const Value *Ptr = OpInfo.CallOperandVal; 8811 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8812 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8813 MachinePointerInfo(Ptr)); 8814 OutChains.push_back(Store); 8815 } else { 8816 // generate CopyFromRegs to associated registers. 8817 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8818 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8819 for (const SDValue &V : Val->op_values()) 8820 handleRegAssign(V); 8821 } else 8822 handleRegAssign(Val); 8823 } 8824 } 8825 } 8826 8827 // Set results. 8828 if (!ResultValues.empty()) { 8829 assert(CurResultType == ResultTypes.end() && 8830 "Mismatch in number of ResultTypes"); 8831 assert(ResultValues.size() == ResultTypes.size() && 8832 "Mismatch in number of output operands in asm result"); 8833 8834 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8835 DAG.getVTList(ResultVTs), ResultValues); 8836 setValue(&Call, V); 8837 } 8838 8839 // Collect store chains. 8840 if (!OutChains.empty()) 8841 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8842 8843 if (EmitEHLabels) { 8844 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 8845 } 8846 8847 // Only Update Root if inline assembly has a memory effect. 8848 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 8849 EmitEHLabels) 8850 DAG.setRoot(Chain); 8851 } 8852 8853 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8854 const Twine &Message) { 8855 LLVMContext &Ctx = *DAG.getContext(); 8856 Ctx.emitError(&Call, Message); 8857 8858 // Make sure we leave the DAG in a valid state 8859 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8860 SmallVector<EVT, 1> ValueVTs; 8861 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8862 8863 if (ValueVTs.empty()) 8864 return; 8865 8866 SmallVector<SDValue, 1> Ops; 8867 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8868 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8869 8870 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8871 } 8872 8873 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8874 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8875 MVT::Other, getRoot(), 8876 getValue(I.getArgOperand(0)), 8877 DAG.getSrcValue(I.getArgOperand(0)))); 8878 } 8879 8880 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8881 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8882 const DataLayout &DL = DAG.getDataLayout(); 8883 SDValue V = DAG.getVAArg( 8884 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8885 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8886 DL.getABITypeAlign(I.getType()).value()); 8887 DAG.setRoot(V.getValue(1)); 8888 8889 if (I.getType()->isPointerTy()) 8890 V = DAG.getPtrExtOrTrunc( 8891 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8892 setValue(&I, V); 8893 } 8894 8895 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8896 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8897 MVT::Other, getRoot(), 8898 getValue(I.getArgOperand(0)), 8899 DAG.getSrcValue(I.getArgOperand(0)))); 8900 } 8901 8902 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8903 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8904 MVT::Other, getRoot(), 8905 getValue(I.getArgOperand(0)), 8906 getValue(I.getArgOperand(1)), 8907 DAG.getSrcValue(I.getArgOperand(0)), 8908 DAG.getSrcValue(I.getArgOperand(1)))); 8909 } 8910 8911 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8912 const Instruction &I, 8913 SDValue Op) { 8914 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8915 if (!Range) 8916 return Op; 8917 8918 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8919 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8920 return Op; 8921 8922 APInt Lo = CR.getUnsignedMin(); 8923 if (!Lo.isMinValue()) 8924 return Op; 8925 8926 APInt Hi = CR.getUnsignedMax(); 8927 unsigned Bits = std::max(Hi.getActiveBits(), 8928 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8929 8930 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8931 8932 SDLoc SL = getCurSDLoc(); 8933 8934 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8935 DAG.getValueType(SmallVT)); 8936 unsigned NumVals = Op.getNode()->getNumValues(); 8937 if (NumVals == 1) 8938 return ZExt; 8939 8940 SmallVector<SDValue, 4> Ops; 8941 8942 Ops.push_back(ZExt); 8943 for (unsigned I = 1; I != NumVals; ++I) 8944 Ops.push_back(Op.getValue(I)); 8945 8946 return DAG.getMergeValues(Ops, SL); 8947 } 8948 8949 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8950 /// the call being lowered. 8951 /// 8952 /// This is a helper for lowering intrinsics that follow a target calling 8953 /// convention or require stack pointer adjustment. Only a subset of the 8954 /// intrinsic's operands need to participate in the calling convention. 8955 void SelectionDAGBuilder::populateCallLoweringInfo( 8956 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8957 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8958 bool IsPatchPoint) { 8959 TargetLowering::ArgListTy Args; 8960 Args.reserve(NumArgs); 8961 8962 // Populate the argument list. 8963 // Attributes for args start at offset 1, after the return attribute. 8964 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8965 ArgI != ArgE; ++ArgI) { 8966 const Value *V = Call->getOperand(ArgI); 8967 8968 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8969 8970 TargetLowering::ArgListEntry Entry; 8971 Entry.Node = getValue(V); 8972 Entry.Ty = V->getType(); 8973 Entry.setAttributes(Call, ArgI); 8974 Args.push_back(Entry); 8975 } 8976 8977 CLI.setDebugLoc(getCurSDLoc()) 8978 .setChain(getRoot()) 8979 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8980 .setDiscardResult(Call->use_empty()) 8981 .setIsPatchPoint(IsPatchPoint) 8982 .setIsPreallocated( 8983 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8984 } 8985 8986 /// Add a stack map intrinsic call's live variable operands to a stackmap 8987 /// or patchpoint target node's operand list. 8988 /// 8989 /// Constants are converted to TargetConstants purely as an optimization to 8990 /// avoid constant materialization and register allocation. 8991 /// 8992 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8993 /// generate addess computation nodes, and so FinalizeISel can convert the 8994 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8995 /// address materialization and register allocation, but may also be required 8996 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8997 /// alloca in the entry block, then the runtime may assume that the alloca's 8998 /// StackMap location can be read immediately after compilation and that the 8999 /// location is valid at any point during execution (this is similar to the 9000 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9001 /// only available in a register, then the runtime would need to trap when 9002 /// execution reaches the StackMap in order to read the alloca's location. 9003 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9004 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9005 SelectionDAGBuilder &Builder) { 9006 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 9007 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 9008 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 9009 Ops.push_back( 9010 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 9011 Ops.push_back( 9012 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 9013 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 9014 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 9015 Ops.push_back(Builder.DAG.getTargetFrameIndex( 9016 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 9017 } else 9018 Ops.push_back(OpVal); 9019 } 9020 } 9021 9022 /// Lower llvm.experimental.stackmap directly to its target opcode. 9023 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9024 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 9025 // [live variables...]) 9026 9027 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9028 9029 SDValue Chain, InFlag, Callee, NullPtr; 9030 SmallVector<SDValue, 32> Ops; 9031 9032 SDLoc DL = getCurSDLoc(); 9033 Callee = getValue(CI.getCalledOperand()); 9034 NullPtr = DAG.getIntPtrConstant(0, DL, true); 9035 9036 // The stackmap intrinsic only records the live variables (the arguments 9037 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9038 // intrinsic, this won't be lowered to a function call. This means we don't 9039 // have to worry about calling conventions and target specific lowering code. 9040 // Instead we perform the call lowering right here. 9041 // 9042 // chain, flag = CALLSEQ_START(chain, 0, 0) 9043 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9044 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9045 // 9046 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9047 InFlag = Chain.getValue(1); 9048 9049 // Add the <id> and <numBytes> constants. 9050 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 9051 Ops.push_back(DAG.getTargetConstant( 9052 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 9053 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 9054 Ops.push_back(DAG.getTargetConstant( 9055 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 9056 MVT::i32)); 9057 9058 // Push live variables for the stack map. 9059 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9060 9061 // We are not pushing any register mask info here on the operands list, 9062 // because the stackmap doesn't clobber anything. 9063 9064 // Push the chain and the glue flag. 9065 Ops.push_back(Chain); 9066 Ops.push_back(InFlag); 9067 9068 // Create the STACKMAP node. 9069 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9070 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9071 Chain = SDValue(SM, 0); 9072 InFlag = Chain.getValue(1); 9073 9074 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9075 9076 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9077 9078 // Set the root to the target-lowered call chain. 9079 DAG.setRoot(Chain); 9080 9081 // Inform the Frame Information that we have a stackmap in this function. 9082 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9083 } 9084 9085 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9086 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9087 const BasicBlock *EHPadBB) { 9088 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9089 // i32 <numBytes>, 9090 // i8* <target>, 9091 // i32 <numArgs>, 9092 // [Args...], 9093 // [live variables...]) 9094 9095 CallingConv::ID CC = CB.getCallingConv(); 9096 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9097 bool HasDef = !CB.getType()->isVoidTy(); 9098 SDLoc dl = getCurSDLoc(); 9099 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9100 9101 // Handle immediate and symbolic callees. 9102 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9103 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9104 /*isTarget=*/true); 9105 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9106 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9107 SDLoc(SymbolicCallee), 9108 SymbolicCallee->getValueType(0)); 9109 9110 // Get the real number of arguments participating in the call <numArgs> 9111 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9112 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9113 9114 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9115 // Intrinsics include all meta-operands up to but not including CC. 9116 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9117 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9118 "Not enough arguments provided to the patchpoint intrinsic"); 9119 9120 // For AnyRegCC the arguments are lowered later on manually. 9121 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9122 Type *ReturnTy = 9123 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9124 9125 TargetLowering::CallLoweringInfo CLI(DAG); 9126 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9127 ReturnTy, true); 9128 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9129 9130 SDNode *CallEnd = Result.second.getNode(); 9131 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9132 CallEnd = CallEnd->getOperand(0).getNode(); 9133 9134 /// Get a call instruction from the call sequence chain. 9135 /// Tail calls are not allowed. 9136 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9137 "Expected a callseq node."); 9138 SDNode *Call = CallEnd->getOperand(0).getNode(); 9139 bool HasGlue = Call->getGluedNode(); 9140 9141 // Replace the target specific call node with the patchable intrinsic. 9142 SmallVector<SDValue, 8> Ops; 9143 9144 // Add the <id> and <numBytes> constants. 9145 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9146 Ops.push_back(DAG.getTargetConstant( 9147 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9148 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9149 Ops.push_back(DAG.getTargetConstant( 9150 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9151 MVT::i32)); 9152 9153 // Add the callee. 9154 Ops.push_back(Callee); 9155 9156 // Adjust <numArgs> to account for any arguments that have been passed on the 9157 // stack instead. 9158 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9159 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9160 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9161 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9162 9163 // Add the calling convention 9164 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9165 9166 // Add the arguments we omitted previously. The register allocator should 9167 // place these in any free register. 9168 if (IsAnyRegCC) 9169 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9170 Ops.push_back(getValue(CB.getArgOperand(i))); 9171 9172 // Push the arguments from the call instruction up to the register mask. 9173 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9174 Ops.append(Call->op_begin() + 2, e); 9175 9176 // Push live variables for the stack map. 9177 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9178 9179 // Push the register mask info. 9180 if (HasGlue) 9181 Ops.push_back(*(Call->op_end()-2)); 9182 else 9183 Ops.push_back(*(Call->op_end()-1)); 9184 9185 // Push the chain (this is originally the first operand of the call, but 9186 // becomes now the last or second to last operand). 9187 Ops.push_back(*(Call->op_begin())); 9188 9189 // Push the glue flag (last operand). 9190 if (HasGlue) 9191 Ops.push_back(*(Call->op_end()-1)); 9192 9193 SDVTList NodeTys; 9194 if (IsAnyRegCC && HasDef) { 9195 // Create the return types based on the intrinsic definition 9196 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9197 SmallVector<EVT, 3> ValueVTs; 9198 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9199 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9200 9201 // There is always a chain and a glue type at the end 9202 ValueVTs.push_back(MVT::Other); 9203 ValueVTs.push_back(MVT::Glue); 9204 NodeTys = DAG.getVTList(ValueVTs); 9205 } else 9206 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9207 9208 // Replace the target specific call node with a PATCHPOINT node. 9209 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9210 dl, NodeTys, Ops); 9211 9212 // Update the NodeMap. 9213 if (HasDef) { 9214 if (IsAnyRegCC) 9215 setValue(&CB, SDValue(MN, 0)); 9216 else 9217 setValue(&CB, Result.first); 9218 } 9219 9220 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9221 // call sequence. Furthermore the location of the chain and glue can change 9222 // when the AnyReg calling convention is used and the intrinsic returns a 9223 // value. 9224 if (IsAnyRegCC && HasDef) { 9225 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9226 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9227 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9228 } else 9229 DAG.ReplaceAllUsesWith(Call, MN); 9230 DAG.DeleteNode(Call); 9231 9232 // Inform the Frame Information that we have a patchpoint in this function. 9233 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9234 } 9235 9236 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9237 unsigned Intrinsic) { 9238 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9239 SDValue Op1 = getValue(I.getArgOperand(0)); 9240 SDValue Op2; 9241 if (I.getNumArgOperands() > 1) 9242 Op2 = getValue(I.getArgOperand(1)); 9243 SDLoc dl = getCurSDLoc(); 9244 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9245 SDValue Res; 9246 SDNodeFlags SDFlags; 9247 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9248 SDFlags.copyFMF(*FPMO); 9249 9250 switch (Intrinsic) { 9251 case Intrinsic::vector_reduce_fadd: 9252 if (SDFlags.hasAllowReassociation()) 9253 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9254 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9255 SDFlags); 9256 else 9257 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9258 break; 9259 case Intrinsic::vector_reduce_fmul: 9260 if (SDFlags.hasAllowReassociation()) 9261 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9262 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9263 SDFlags); 9264 else 9265 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9266 break; 9267 case Intrinsic::vector_reduce_add: 9268 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9269 break; 9270 case Intrinsic::vector_reduce_mul: 9271 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9272 break; 9273 case Intrinsic::vector_reduce_and: 9274 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9275 break; 9276 case Intrinsic::vector_reduce_or: 9277 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9278 break; 9279 case Intrinsic::vector_reduce_xor: 9280 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9281 break; 9282 case Intrinsic::vector_reduce_smax: 9283 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9284 break; 9285 case Intrinsic::vector_reduce_smin: 9286 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9287 break; 9288 case Intrinsic::vector_reduce_umax: 9289 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9290 break; 9291 case Intrinsic::vector_reduce_umin: 9292 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9293 break; 9294 case Intrinsic::vector_reduce_fmax: 9295 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9296 break; 9297 case Intrinsic::vector_reduce_fmin: 9298 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9299 break; 9300 default: 9301 llvm_unreachable("Unhandled vector reduce intrinsic"); 9302 } 9303 setValue(&I, Res); 9304 } 9305 9306 /// Returns an AttributeList representing the attributes applied to the return 9307 /// value of the given call. 9308 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9309 SmallVector<Attribute::AttrKind, 2> Attrs; 9310 if (CLI.RetSExt) 9311 Attrs.push_back(Attribute::SExt); 9312 if (CLI.RetZExt) 9313 Attrs.push_back(Attribute::ZExt); 9314 if (CLI.IsInReg) 9315 Attrs.push_back(Attribute::InReg); 9316 9317 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9318 Attrs); 9319 } 9320 9321 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9322 /// implementation, which just calls LowerCall. 9323 /// FIXME: When all targets are 9324 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9325 std::pair<SDValue, SDValue> 9326 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9327 // Handle the incoming return values from the call. 9328 CLI.Ins.clear(); 9329 Type *OrigRetTy = CLI.RetTy; 9330 SmallVector<EVT, 4> RetTys; 9331 SmallVector<uint64_t, 4> Offsets; 9332 auto &DL = CLI.DAG.getDataLayout(); 9333 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9334 9335 if (CLI.IsPostTypeLegalization) { 9336 // If we are lowering a libcall after legalization, split the return type. 9337 SmallVector<EVT, 4> OldRetTys; 9338 SmallVector<uint64_t, 4> OldOffsets; 9339 RetTys.swap(OldRetTys); 9340 Offsets.swap(OldOffsets); 9341 9342 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9343 EVT RetVT = OldRetTys[i]; 9344 uint64_t Offset = OldOffsets[i]; 9345 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9346 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9347 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9348 RetTys.append(NumRegs, RegisterVT); 9349 for (unsigned j = 0; j != NumRegs; ++j) 9350 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9351 } 9352 } 9353 9354 SmallVector<ISD::OutputArg, 4> Outs; 9355 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9356 9357 bool CanLowerReturn = 9358 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9359 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9360 9361 SDValue DemoteStackSlot; 9362 int DemoteStackIdx = -100; 9363 if (!CanLowerReturn) { 9364 // FIXME: equivalent assert? 9365 // assert(!CS.hasInAllocaArgument() && 9366 // "sret demotion is incompatible with inalloca"); 9367 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9368 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9369 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9370 DemoteStackIdx = 9371 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9372 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9373 DL.getAllocaAddrSpace()); 9374 9375 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9376 ArgListEntry Entry; 9377 Entry.Node = DemoteStackSlot; 9378 Entry.Ty = StackSlotPtrType; 9379 Entry.IsSExt = false; 9380 Entry.IsZExt = false; 9381 Entry.IsInReg = false; 9382 Entry.IsSRet = true; 9383 Entry.IsNest = false; 9384 Entry.IsByVal = false; 9385 Entry.IsByRef = false; 9386 Entry.IsReturned = false; 9387 Entry.IsSwiftSelf = false; 9388 Entry.IsSwiftAsync = false; 9389 Entry.IsSwiftError = false; 9390 Entry.IsCFGuardTarget = false; 9391 Entry.Alignment = Alignment; 9392 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9393 CLI.NumFixedArgs += 1; 9394 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9395 9396 // sret demotion isn't compatible with tail-calls, since the sret argument 9397 // points into the callers stack frame. 9398 CLI.IsTailCall = false; 9399 } else { 9400 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9401 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9402 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9403 ISD::ArgFlagsTy Flags; 9404 if (NeedsRegBlock) { 9405 Flags.setInConsecutiveRegs(); 9406 if (I == RetTys.size() - 1) 9407 Flags.setInConsecutiveRegsLast(); 9408 } 9409 EVT VT = RetTys[I]; 9410 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9411 CLI.CallConv, VT); 9412 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9413 CLI.CallConv, VT); 9414 for (unsigned i = 0; i != NumRegs; ++i) { 9415 ISD::InputArg MyFlags; 9416 MyFlags.Flags = Flags; 9417 MyFlags.VT = RegisterVT; 9418 MyFlags.ArgVT = VT; 9419 MyFlags.Used = CLI.IsReturnValueUsed; 9420 if (CLI.RetTy->isPointerTy()) { 9421 MyFlags.Flags.setPointer(); 9422 MyFlags.Flags.setPointerAddrSpace( 9423 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9424 } 9425 if (CLI.RetSExt) 9426 MyFlags.Flags.setSExt(); 9427 if (CLI.RetZExt) 9428 MyFlags.Flags.setZExt(); 9429 if (CLI.IsInReg) 9430 MyFlags.Flags.setInReg(); 9431 CLI.Ins.push_back(MyFlags); 9432 } 9433 } 9434 } 9435 9436 // We push in swifterror return as the last element of CLI.Ins. 9437 ArgListTy &Args = CLI.getArgs(); 9438 if (supportSwiftError()) { 9439 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9440 if (Args[i].IsSwiftError) { 9441 ISD::InputArg MyFlags; 9442 MyFlags.VT = getPointerTy(DL); 9443 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9444 MyFlags.Flags.setSwiftError(); 9445 CLI.Ins.push_back(MyFlags); 9446 } 9447 } 9448 } 9449 9450 // Handle all of the outgoing arguments. 9451 CLI.Outs.clear(); 9452 CLI.OutVals.clear(); 9453 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9454 SmallVector<EVT, 4> ValueVTs; 9455 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9456 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9457 Type *FinalType = Args[i].Ty; 9458 if (Args[i].IsByVal) 9459 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9460 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9461 FinalType, CLI.CallConv, CLI.IsVarArg); 9462 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9463 ++Value) { 9464 EVT VT = ValueVTs[Value]; 9465 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9466 SDValue Op = SDValue(Args[i].Node.getNode(), 9467 Args[i].Node.getResNo() + Value); 9468 ISD::ArgFlagsTy Flags; 9469 9470 // Certain targets (such as MIPS), may have a different ABI alignment 9471 // for a type depending on the context. Give the target a chance to 9472 // specify the alignment it wants. 9473 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9474 Flags.setOrigAlign(OriginalAlignment); 9475 9476 if (Args[i].Ty->isPointerTy()) { 9477 Flags.setPointer(); 9478 Flags.setPointerAddrSpace( 9479 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9480 } 9481 if (Args[i].IsZExt) 9482 Flags.setZExt(); 9483 if (Args[i].IsSExt) 9484 Flags.setSExt(); 9485 if (Args[i].IsInReg) { 9486 // If we are using vectorcall calling convention, a structure that is 9487 // passed InReg - is surely an HVA 9488 if (CLI.CallConv == CallingConv::X86_VectorCall && 9489 isa<StructType>(FinalType)) { 9490 // The first value of a structure is marked 9491 if (0 == Value) 9492 Flags.setHvaStart(); 9493 Flags.setHva(); 9494 } 9495 // Set InReg Flag 9496 Flags.setInReg(); 9497 } 9498 if (Args[i].IsSRet) 9499 Flags.setSRet(); 9500 if (Args[i].IsSwiftSelf) 9501 Flags.setSwiftSelf(); 9502 if (Args[i].IsSwiftAsync) 9503 Flags.setSwiftAsync(); 9504 if (Args[i].IsSwiftError) 9505 Flags.setSwiftError(); 9506 if (Args[i].IsCFGuardTarget) 9507 Flags.setCFGuardTarget(); 9508 if (Args[i].IsByVal) 9509 Flags.setByVal(); 9510 if (Args[i].IsByRef) 9511 Flags.setByRef(); 9512 if (Args[i].IsPreallocated) { 9513 Flags.setPreallocated(); 9514 // Set the byval flag for CCAssignFn callbacks that don't know about 9515 // preallocated. This way we can know how many bytes we should've 9516 // allocated and how many bytes a callee cleanup function will pop. If 9517 // we port preallocated to more targets, we'll have to add custom 9518 // preallocated handling in the various CC lowering callbacks. 9519 Flags.setByVal(); 9520 } 9521 if (Args[i].IsInAlloca) { 9522 Flags.setInAlloca(); 9523 // Set the byval flag for CCAssignFn callbacks that don't know about 9524 // inalloca. This way we can know how many bytes we should've allocated 9525 // and how many bytes a callee cleanup function will pop. If we port 9526 // inalloca to more targets, we'll have to add custom inalloca handling 9527 // in the various CC lowering callbacks. 9528 Flags.setByVal(); 9529 } 9530 Align MemAlign; 9531 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9532 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9533 Type *ElementTy = Ty->getElementType(); 9534 9535 unsigned FrameSize = DL.getTypeAllocSize( 9536 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9537 Flags.setByValSize(FrameSize); 9538 9539 // info is not there but there are cases it cannot get right. 9540 if (auto MA = Args[i].Alignment) 9541 MemAlign = *MA; 9542 else 9543 MemAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9544 } else if (auto MA = Args[i].Alignment) { 9545 MemAlign = *MA; 9546 } else { 9547 MemAlign = OriginalAlignment; 9548 } 9549 Flags.setMemAlign(MemAlign); 9550 if (Args[i].IsNest) 9551 Flags.setNest(); 9552 if (NeedsRegBlock) 9553 Flags.setInConsecutiveRegs(); 9554 9555 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9556 CLI.CallConv, VT); 9557 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9558 CLI.CallConv, VT); 9559 SmallVector<SDValue, 4> Parts(NumParts); 9560 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9561 9562 if (Args[i].IsSExt) 9563 ExtendKind = ISD::SIGN_EXTEND; 9564 else if (Args[i].IsZExt) 9565 ExtendKind = ISD::ZERO_EXTEND; 9566 9567 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9568 // for now. 9569 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9570 CanLowerReturn) { 9571 assert((CLI.RetTy == Args[i].Ty || 9572 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9573 CLI.RetTy->getPointerAddressSpace() == 9574 Args[i].Ty->getPointerAddressSpace())) && 9575 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9576 // Before passing 'returned' to the target lowering code, ensure that 9577 // either the register MVT and the actual EVT are the same size or that 9578 // the return value and argument are extended in the same way; in these 9579 // cases it's safe to pass the argument register value unchanged as the 9580 // return register value (although it's at the target's option whether 9581 // to do so) 9582 // TODO: allow code generation to take advantage of partially preserved 9583 // registers rather than clobbering the entire register when the 9584 // parameter extension method is not compatible with the return 9585 // extension method 9586 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9587 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9588 CLI.RetZExt == Args[i].IsZExt)) 9589 Flags.setReturned(); 9590 } 9591 9592 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9593 CLI.CallConv, ExtendKind); 9594 9595 for (unsigned j = 0; j != NumParts; ++j) { 9596 // if it isn't first piece, alignment must be 1 9597 // For scalable vectors the scalable part is currently handled 9598 // by individual targets, so we just use the known minimum size here. 9599 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9600 i < CLI.NumFixedArgs, i, 9601 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9602 if (NumParts > 1 && j == 0) 9603 MyFlags.Flags.setSplit(); 9604 else if (j != 0) { 9605 MyFlags.Flags.setOrigAlign(Align(1)); 9606 if (j == NumParts - 1) 9607 MyFlags.Flags.setSplitEnd(); 9608 } 9609 9610 CLI.Outs.push_back(MyFlags); 9611 CLI.OutVals.push_back(Parts[j]); 9612 } 9613 9614 if (NeedsRegBlock && Value == NumValues - 1) 9615 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9616 } 9617 } 9618 9619 SmallVector<SDValue, 4> InVals; 9620 CLI.Chain = LowerCall(CLI, InVals); 9621 9622 // Update CLI.InVals to use outside of this function. 9623 CLI.InVals = InVals; 9624 9625 // Verify that the target's LowerCall behaved as expected. 9626 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9627 "LowerCall didn't return a valid chain!"); 9628 assert((!CLI.IsTailCall || InVals.empty()) && 9629 "LowerCall emitted a return value for a tail call!"); 9630 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9631 "LowerCall didn't emit the correct number of values!"); 9632 9633 // For a tail call, the return value is merely live-out and there aren't 9634 // any nodes in the DAG representing it. Return a special value to 9635 // indicate that a tail call has been emitted and no more Instructions 9636 // should be processed in the current block. 9637 if (CLI.IsTailCall) { 9638 CLI.DAG.setRoot(CLI.Chain); 9639 return std::make_pair(SDValue(), SDValue()); 9640 } 9641 9642 #ifndef NDEBUG 9643 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9644 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9645 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9646 "LowerCall emitted a value with the wrong type!"); 9647 } 9648 #endif 9649 9650 SmallVector<SDValue, 4> ReturnValues; 9651 if (!CanLowerReturn) { 9652 // The instruction result is the result of loading from the 9653 // hidden sret parameter. 9654 SmallVector<EVT, 1> PVTs; 9655 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9656 9657 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9658 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9659 EVT PtrVT = PVTs[0]; 9660 9661 unsigned NumValues = RetTys.size(); 9662 ReturnValues.resize(NumValues); 9663 SmallVector<SDValue, 4> Chains(NumValues); 9664 9665 // An aggregate return value cannot wrap around the address space, so 9666 // offsets to its parts don't wrap either. 9667 SDNodeFlags Flags; 9668 Flags.setNoUnsignedWrap(true); 9669 9670 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9671 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9672 for (unsigned i = 0; i < NumValues; ++i) { 9673 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9674 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9675 PtrVT), Flags); 9676 SDValue L = CLI.DAG.getLoad( 9677 RetTys[i], CLI.DL, CLI.Chain, Add, 9678 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9679 DemoteStackIdx, Offsets[i]), 9680 HiddenSRetAlign); 9681 ReturnValues[i] = L; 9682 Chains[i] = L.getValue(1); 9683 } 9684 9685 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9686 } else { 9687 // Collect the legal value parts into potentially illegal values 9688 // that correspond to the original function's return values. 9689 Optional<ISD::NodeType> AssertOp; 9690 if (CLI.RetSExt) 9691 AssertOp = ISD::AssertSext; 9692 else if (CLI.RetZExt) 9693 AssertOp = ISD::AssertZext; 9694 unsigned CurReg = 0; 9695 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9696 EVT VT = RetTys[I]; 9697 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9698 CLI.CallConv, VT); 9699 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9700 CLI.CallConv, VT); 9701 9702 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9703 NumRegs, RegisterVT, VT, nullptr, 9704 CLI.CallConv, AssertOp)); 9705 CurReg += NumRegs; 9706 } 9707 9708 // For a function returning void, there is no return value. We can't create 9709 // such a node, so we just return a null return value in that case. In 9710 // that case, nothing will actually look at the value. 9711 if (ReturnValues.empty()) 9712 return std::make_pair(SDValue(), CLI.Chain); 9713 } 9714 9715 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9716 CLI.DAG.getVTList(RetTys), ReturnValues); 9717 return std::make_pair(Res, CLI.Chain); 9718 } 9719 9720 /// Places new result values for the node in Results (their number 9721 /// and types must exactly match those of the original return values of 9722 /// the node), or leaves Results empty, which indicates that the node is not 9723 /// to be custom lowered after all. 9724 void TargetLowering::LowerOperationWrapper(SDNode *N, 9725 SmallVectorImpl<SDValue> &Results, 9726 SelectionDAG &DAG) const { 9727 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9728 9729 if (!Res.getNode()) 9730 return; 9731 9732 // If the original node has one result, take the return value from 9733 // LowerOperation as is. It might not be result number 0. 9734 if (N->getNumValues() == 1) { 9735 Results.push_back(Res); 9736 return; 9737 } 9738 9739 // If the original node has multiple results, then the return node should 9740 // have the same number of results. 9741 assert((N->getNumValues() == Res->getNumValues()) && 9742 "Lowering returned the wrong number of results!"); 9743 9744 // Places new result values base on N result number. 9745 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9746 Results.push_back(Res.getValue(I)); 9747 } 9748 9749 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9750 llvm_unreachable("LowerOperation not implemented for this target!"); 9751 } 9752 9753 void 9754 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9755 SDValue Op = getNonRegisterValue(V); 9756 assert((Op.getOpcode() != ISD::CopyFromReg || 9757 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9758 "Copy from a reg to the same reg!"); 9759 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9760 9761 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9762 // If this is an InlineAsm we have to match the registers required, not the 9763 // notional registers required by the type. 9764 9765 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9766 None); // This is not an ABI copy. 9767 SDValue Chain = DAG.getEntryNode(); 9768 9769 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9770 FuncInfo.PreferredExtendType.end()) 9771 ? ISD::ANY_EXTEND 9772 : FuncInfo.PreferredExtendType[V]; 9773 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9774 PendingExports.push_back(Chain); 9775 } 9776 9777 #include "llvm/CodeGen/SelectionDAGISel.h" 9778 9779 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9780 /// entry block, return true. This includes arguments used by switches, since 9781 /// the switch may expand into multiple basic blocks. 9782 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9783 // With FastISel active, we may be splitting blocks, so force creation 9784 // of virtual registers for all non-dead arguments. 9785 if (FastISel) 9786 return A->use_empty(); 9787 9788 const BasicBlock &Entry = A->getParent()->front(); 9789 for (const User *U : A->users()) 9790 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9791 return false; // Use not in entry block. 9792 9793 return true; 9794 } 9795 9796 using ArgCopyElisionMapTy = 9797 DenseMap<const Argument *, 9798 std::pair<const AllocaInst *, const StoreInst *>>; 9799 9800 /// Scan the entry block of the function in FuncInfo for arguments that look 9801 /// like copies into a local alloca. Record any copied arguments in 9802 /// ArgCopyElisionCandidates. 9803 static void 9804 findArgumentCopyElisionCandidates(const DataLayout &DL, 9805 FunctionLoweringInfo *FuncInfo, 9806 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9807 // Record the state of every static alloca used in the entry block. Argument 9808 // allocas are all used in the entry block, so we need approximately as many 9809 // entries as we have arguments. 9810 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9811 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9812 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9813 StaticAllocas.reserve(NumArgs * 2); 9814 9815 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9816 if (!V) 9817 return nullptr; 9818 V = V->stripPointerCasts(); 9819 const auto *AI = dyn_cast<AllocaInst>(V); 9820 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9821 return nullptr; 9822 auto Iter = StaticAllocas.insert({AI, Unknown}); 9823 return &Iter.first->second; 9824 }; 9825 9826 // Look for stores of arguments to static allocas. Look through bitcasts and 9827 // GEPs to handle type coercions, as long as the alloca is fully initialized 9828 // by the store. Any non-store use of an alloca escapes it and any subsequent 9829 // unanalyzed store might write it. 9830 // FIXME: Handle structs initialized with multiple stores. 9831 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9832 // Look for stores, and handle non-store uses conservatively. 9833 const auto *SI = dyn_cast<StoreInst>(&I); 9834 if (!SI) { 9835 // We will look through cast uses, so ignore them completely. 9836 if (I.isCast()) 9837 continue; 9838 // Ignore debug info and pseudo op intrinsics, they don't escape or store 9839 // to allocas. 9840 if (I.isDebugOrPseudoInst()) 9841 continue; 9842 // This is an unknown instruction. Assume it escapes or writes to all 9843 // static alloca operands. 9844 for (const Use &U : I.operands()) { 9845 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9846 *Info = StaticAllocaInfo::Clobbered; 9847 } 9848 continue; 9849 } 9850 9851 // If the stored value is a static alloca, mark it as escaped. 9852 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9853 *Info = StaticAllocaInfo::Clobbered; 9854 9855 // Check if the destination is a static alloca. 9856 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9857 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9858 if (!Info) 9859 continue; 9860 const AllocaInst *AI = cast<AllocaInst>(Dst); 9861 9862 // Skip allocas that have been initialized or clobbered. 9863 if (*Info != StaticAllocaInfo::Unknown) 9864 continue; 9865 9866 // Check if the stored value is an argument, and that this store fully 9867 // initializes the alloca. Don't elide copies from the same argument twice. 9868 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9869 const auto *Arg = dyn_cast<Argument>(Val); 9870 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9871 Arg->getType()->isEmptyTy() || 9872 DL.getTypeStoreSize(Arg->getType()) != 9873 DL.getTypeAllocSize(AI->getAllocatedType()) || 9874 ArgCopyElisionCandidates.count(Arg)) { 9875 *Info = StaticAllocaInfo::Clobbered; 9876 continue; 9877 } 9878 9879 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9880 << '\n'); 9881 9882 // Mark this alloca and store for argument copy elision. 9883 *Info = StaticAllocaInfo::Elidable; 9884 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9885 9886 // Stop scanning if we've seen all arguments. This will happen early in -O0 9887 // builds, which is useful, because -O0 builds have large entry blocks and 9888 // many allocas. 9889 if (ArgCopyElisionCandidates.size() == NumArgs) 9890 break; 9891 } 9892 } 9893 9894 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9895 /// ArgVal is a load from a suitable fixed stack object. 9896 static void tryToElideArgumentCopy( 9897 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9898 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9899 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9900 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9901 SDValue ArgVal, bool &ArgHasUses) { 9902 // Check if this is a load from a fixed stack object. 9903 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9904 if (!LNode) 9905 return; 9906 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9907 if (!FINode) 9908 return; 9909 9910 // Check that the fixed stack object is the right size and alignment. 9911 // Look at the alignment that the user wrote on the alloca instead of looking 9912 // at the stack object. 9913 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9914 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9915 const AllocaInst *AI = ArgCopyIter->second.first; 9916 int FixedIndex = FINode->getIndex(); 9917 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9918 int OldIndex = AllocaIndex; 9919 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9920 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9921 LLVM_DEBUG( 9922 dbgs() << " argument copy elision failed due to bad fixed stack " 9923 "object size\n"); 9924 return; 9925 } 9926 Align RequiredAlignment = AI->getAlign(); 9927 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9928 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9929 "greater than stack argument alignment (" 9930 << DebugStr(RequiredAlignment) << " vs " 9931 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9932 return; 9933 } 9934 9935 // Perform the elision. Delete the old stack object and replace its only use 9936 // in the variable info map. Mark the stack object as mutable. 9937 LLVM_DEBUG({ 9938 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9939 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9940 << '\n'; 9941 }); 9942 MFI.RemoveStackObject(OldIndex); 9943 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9944 AllocaIndex = FixedIndex; 9945 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9946 Chains.push_back(ArgVal.getValue(1)); 9947 9948 // Avoid emitting code for the store implementing the copy. 9949 const StoreInst *SI = ArgCopyIter->second.second; 9950 ElidedArgCopyInstrs.insert(SI); 9951 9952 // Check for uses of the argument again so that we can avoid exporting ArgVal 9953 // if it is't used by anything other than the store. 9954 for (const Value *U : Arg.users()) { 9955 if (U != SI) { 9956 ArgHasUses = true; 9957 break; 9958 } 9959 } 9960 } 9961 9962 void SelectionDAGISel::LowerArguments(const Function &F) { 9963 SelectionDAG &DAG = SDB->DAG; 9964 SDLoc dl = SDB->getCurSDLoc(); 9965 const DataLayout &DL = DAG.getDataLayout(); 9966 SmallVector<ISD::InputArg, 16> Ins; 9967 9968 // In Naked functions we aren't going to save any registers. 9969 if (F.hasFnAttribute(Attribute::Naked)) 9970 return; 9971 9972 if (!FuncInfo->CanLowerReturn) { 9973 // Put in an sret pointer parameter before all the other parameters. 9974 SmallVector<EVT, 1> ValueVTs; 9975 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9976 F.getReturnType()->getPointerTo( 9977 DAG.getDataLayout().getAllocaAddrSpace()), 9978 ValueVTs); 9979 9980 // NOTE: Assuming that a pointer will never break down to more than one VT 9981 // or one register. 9982 ISD::ArgFlagsTy Flags; 9983 Flags.setSRet(); 9984 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9985 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9986 ISD::InputArg::NoArgIndex, 0); 9987 Ins.push_back(RetArg); 9988 } 9989 9990 // Look for stores of arguments to static allocas. Mark such arguments with a 9991 // flag to ask the target to give us the memory location of that argument if 9992 // available. 9993 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9994 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9995 ArgCopyElisionCandidates); 9996 9997 // Set up the incoming argument description vector. 9998 for (const Argument &Arg : F.args()) { 9999 unsigned ArgNo = Arg.getArgNo(); 10000 SmallVector<EVT, 4> ValueVTs; 10001 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10002 bool isArgValueUsed = !Arg.use_empty(); 10003 unsigned PartBase = 0; 10004 Type *FinalType = Arg.getType(); 10005 if (Arg.hasAttribute(Attribute::ByVal)) 10006 FinalType = Arg.getParamByValType(); 10007 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10008 FinalType, F.getCallingConv(), F.isVarArg()); 10009 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10010 Value != NumValues; ++Value) { 10011 EVT VT = ValueVTs[Value]; 10012 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10013 ISD::ArgFlagsTy Flags; 10014 10015 10016 if (Arg.getType()->isPointerTy()) { 10017 Flags.setPointer(); 10018 Flags.setPointerAddrSpace( 10019 cast<PointerType>(Arg.getType())->getAddressSpace()); 10020 } 10021 if (Arg.hasAttribute(Attribute::ZExt)) 10022 Flags.setZExt(); 10023 if (Arg.hasAttribute(Attribute::SExt)) 10024 Flags.setSExt(); 10025 if (Arg.hasAttribute(Attribute::InReg)) { 10026 // If we are using vectorcall calling convention, a structure that is 10027 // passed InReg - is surely an HVA 10028 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10029 isa<StructType>(Arg.getType())) { 10030 // The first value of a structure is marked 10031 if (0 == Value) 10032 Flags.setHvaStart(); 10033 Flags.setHva(); 10034 } 10035 // Set InReg Flag 10036 Flags.setInReg(); 10037 } 10038 if (Arg.hasAttribute(Attribute::StructRet)) 10039 Flags.setSRet(); 10040 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10041 Flags.setSwiftSelf(); 10042 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10043 Flags.setSwiftAsync(); 10044 if (Arg.hasAttribute(Attribute::SwiftError)) 10045 Flags.setSwiftError(); 10046 if (Arg.hasAttribute(Attribute::ByVal)) 10047 Flags.setByVal(); 10048 if (Arg.hasAttribute(Attribute::ByRef)) 10049 Flags.setByRef(); 10050 if (Arg.hasAttribute(Attribute::InAlloca)) { 10051 Flags.setInAlloca(); 10052 // Set the byval flag for CCAssignFn callbacks that don't know about 10053 // inalloca. This way we can know how many bytes we should've allocated 10054 // and how many bytes a callee cleanup function will pop. If we port 10055 // inalloca to more targets, we'll have to add custom inalloca handling 10056 // in the various CC lowering callbacks. 10057 Flags.setByVal(); 10058 } 10059 if (Arg.hasAttribute(Attribute::Preallocated)) { 10060 Flags.setPreallocated(); 10061 // Set the byval flag for CCAssignFn callbacks that don't know about 10062 // preallocated. This way we can know how many bytes we should've 10063 // allocated and how many bytes a callee cleanup function will pop. If 10064 // we port preallocated to more targets, we'll have to add custom 10065 // preallocated handling in the various CC lowering callbacks. 10066 Flags.setByVal(); 10067 } 10068 10069 // Certain targets (such as MIPS), may have a different ABI alignment 10070 // for a type depending on the context. Give the target a chance to 10071 // specify the alignment it wants. 10072 const Align OriginalAlignment( 10073 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10074 Flags.setOrigAlign(OriginalAlignment); 10075 10076 Align MemAlign; 10077 Type *ArgMemTy = nullptr; 10078 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10079 Flags.isByRef()) { 10080 if (!ArgMemTy) 10081 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10082 10083 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10084 10085 // For in-memory arguments, size and alignment should be passed from FE. 10086 // BE will guess if this info is not there but there are cases it cannot 10087 // get right. 10088 if (auto ParamAlign = Arg.getParamStackAlign()) 10089 MemAlign = *ParamAlign; 10090 else if ((ParamAlign = Arg.getParamAlign())) 10091 MemAlign = *ParamAlign; 10092 else 10093 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10094 if (Flags.isByRef()) 10095 Flags.setByRefSize(MemSize); 10096 else 10097 Flags.setByValSize(MemSize); 10098 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10099 MemAlign = *ParamAlign; 10100 } else { 10101 MemAlign = OriginalAlignment; 10102 } 10103 Flags.setMemAlign(MemAlign); 10104 10105 if (Arg.hasAttribute(Attribute::Nest)) 10106 Flags.setNest(); 10107 if (NeedsRegBlock) 10108 Flags.setInConsecutiveRegs(); 10109 if (ArgCopyElisionCandidates.count(&Arg)) 10110 Flags.setCopyElisionCandidate(); 10111 if (Arg.hasAttribute(Attribute::Returned)) 10112 Flags.setReturned(); 10113 10114 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10115 *CurDAG->getContext(), F.getCallingConv(), VT); 10116 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10117 *CurDAG->getContext(), F.getCallingConv(), VT); 10118 for (unsigned i = 0; i != NumRegs; ++i) { 10119 // For scalable vectors, use the minimum size; individual targets 10120 // are responsible for handling scalable vector arguments and 10121 // return values. 10122 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10123 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10124 if (NumRegs > 1 && i == 0) 10125 MyFlags.Flags.setSplit(); 10126 // if it isn't first piece, alignment must be 1 10127 else if (i > 0) { 10128 MyFlags.Flags.setOrigAlign(Align(1)); 10129 if (i == NumRegs - 1) 10130 MyFlags.Flags.setSplitEnd(); 10131 } 10132 Ins.push_back(MyFlags); 10133 } 10134 if (NeedsRegBlock && Value == NumValues - 1) 10135 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10136 PartBase += VT.getStoreSize().getKnownMinSize(); 10137 } 10138 } 10139 10140 // Call the target to set up the argument values. 10141 SmallVector<SDValue, 8> InVals; 10142 SDValue NewRoot = TLI->LowerFormalArguments( 10143 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10144 10145 // Verify that the target's LowerFormalArguments behaved as expected. 10146 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10147 "LowerFormalArguments didn't return a valid chain!"); 10148 assert(InVals.size() == Ins.size() && 10149 "LowerFormalArguments didn't emit the correct number of values!"); 10150 LLVM_DEBUG({ 10151 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10152 assert(InVals[i].getNode() && 10153 "LowerFormalArguments emitted a null value!"); 10154 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10155 "LowerFormalArguments emitted a value with the wrong type!"); 10156 } 10157 }); 10158 10159 // Update the DAG with the new chain value resulting from argument lowering. 10160 DAG.setRoot(NewRoot); 10161 10162 // Set up the argument values. 10163 unsigned i = 0; 10164 if (!FuncInfo->CanLowerReturn) { 10165 // Create a virtual register for the sret pointer, and put in a copy 10166 // from the sret argument into it. 10167 SmallVector<EVT, 1> ValueVTs; 10168 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10169 F.getReturnType()->getPointerTo( 10170 DAG.getDataLayout().getAllocaAddrSpace()), 10171 ValueVTs); 10172 MVT VT = ValueVTs[0].getSimpleVT(); 10173 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10174 Optional<ISD::NodeType> AssertOp = None; 10175 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10176 nullptr, F.getCallingConv(), AssertOp); 10177 10178 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10179 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10180 Register SRetReg = 10181 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10182 FuncInfo->DemoteRegister = SRetReg; 10183 NewRoot = 10184 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10185 DAG.setRoot(NewRoot); 10186 10187 // i indexes lowered arguments. Bump it past the hidden sret argument. 10188 ++i; 10189 } 10190 10191 SmallVector<SDValue, 4> Chains; 10192 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10193 for (const Argument &Arg : F.args()) { 10194 SmallVector<SDValue, 4> ArgValues; 10195 SmallVector<EVT, 4> ValueVTs; 10196 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10197 unsigned NumValues = ValueVTs.size(); 10198 if (NumValues == 0) 10199 continue; 10200 10201 bool ArgHasUses = !Arg.use_empty(); 10202 10203 // Elide the copying store if the target loaded this argument from a 10204 // suitable fixed stack object. 10205 if (Ins[i].Flags.isCopyElisionCandidate()) { 10206 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10207 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10208 InVals[i], ArgHasUses); 10209 } 10210 10211 // If this argument is unused then remember its value. It is used to generate 10212 // debugging information. 10213 bool isSwiftErrorArg = 10214 TLI->supportSwiftError() && 10215 Arg.hasAttribute(Attribute::SwiftError); 10216 if (!ArgHasUses && !isSwiftErrorArg) { 10217 SDB->setUnusedArgValue(&Arg, InVals[i]); 10218 10219 // Also remember any frame index for use in FastISel. 10220 if (FrameIndexSDNode *FI = 10221 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10222 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10223 } 10224 10225 for (unsigned Val = 0; Val != NumValues; ++Val) { 10226 EVT VT = ValueVTs[Val]; 10227 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10228 F.getCallingConv(), VT); 10229 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10230 *CurDAG->getContext(), F.getCallingConv(), VT); 10231 10232 // Even an apparent 'unused' swifterror argument needs to be returned. So 10233 // we do generate a copy for it that can be used on return from the 10234 // function. 10235 if (ArgHasUses || isSwiftErrorArg) { 10236 Optional<ISD::NodeType> AssertOp; 10237 if (Arg.hasAttribute(Attribute::SExt)) 10238 AssertOp = ISD::AssertSext; 10239 else if (Arg.hasAttribute(Attribute::ZExt)) 10240 AssertOp = ISD::AssertZext; 10241 10242 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10243 PartVT, VT, nullptr, 10244 F.getCallingConv(), AssertOp)); 10245 } 10246 10247 i += NumParts; 10248 } 10249 10250 // We don't need to do anything else for unused arguments. 10251 if (ArgValues.empty()) 10252 continue; 10253 10254 // Note down frame index. 10255 if (FrameIndexSDNode *FI = 10256 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10257 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10258 10259 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10260 SDB->getCurSDLoc()); 10261 10262 SDB->setValue(&Arg, Res); 10263 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10264 // We want to associate the argument with the frame index, among 10265 // involved operands, that correspond to the lowest address. The 10266 // getCopyFromParts function, called earlier, is swapping the order of 10267 // the operands to BUILD_PAIR depending on endianness. The result of 10268 // that swapping is that the least significant bits of the argument will 10269 // be in the first operand of the BUILD_PAIR node, and the most 10270 // significant bits will be in the second operand. 10271 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10272 if (LoadSDNode *LNode = 10273 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10274 if (FrameIndexSDNode *FI = 10275 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10276 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10277 } 10278 10279 // Analyses past this point are naive and don't expect an assertion. 10280 if (Res.getOpcode() == ISD::AssertZext) 10281 Res = Res.getOperand(0); 10282 10283 // Update the SwiftErrorVRegDefMap. 10284 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10285 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10286 if (Register::isVirtualRegister(Reg)) 10287 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10288 Reg); 10289 } 10290 10291 // If this argument is live outside of the entry block, insert a copy from 10292 // wherever we got it to the vreg that other BB's will reference it as. 10293 if (Res.getOpcode() == ISD::CopyFromReg) { 10294 // If we can, though, try to skip creating an unnecessary vreg. 10295 // FIXME: This isn't very clean... it would be nice to make this more 10296 // general. 10297 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10298 if (Register::isVirtualRegister(Reg)) { 10299 FuncInfo->ValueMap[&Arg] = Reg; 10300 continue; 10301 } 10302 } 10303 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10304 FuncInfo->InitializeRegForValue(&Arg); 10305 SDB->CopyToExportRegsIfNeeded(&Arg); 10306 } 10307 } 10308 10309 if (!Chains.empty()) { 10310 Chains.push_back(NewRoot); 10311 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10312 } 10313 10314 DAG.setRoot(NewRoot); 10315 10316 assert(i == InVals.size() && "Argument register count mismatch!"); 10317 10318 // If any argument copy elisions occurred and we have debug info, update the 10319 // stale frame indices used in the dbg.declare variable info table. 10320 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10321 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10322 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10323 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10324 if (I != ArgCopyElisionFrameIndexMap.end()) 10325 VI.Slot = I->second; 10326 } 10327 } 10328 10329 // Finally, if the target has anything special to do, allow it to do so. 10330 emitFunctionEntryCode(); 10331 } 10332 10333 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10334 /// ensure constants are generated when needed. Remember the virtual registers 10335 /// that need to be added to the Machine PHI nodes as input. We cannot just 10336 /// directly add them, because expansion might result in multiple MBB's for one 10337 /// BB. As such, the start of the BB might correspond to a different MBB than 10338 /// the end. 10339 void 10340 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10341 const Instruction *TI = LLVMBB->getTerminator(); 10342 10343 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10344 10345 // Check PHI nodes in successors that expect a value to be available from this 10346 // block. 10347 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10348 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10349 if (!isa<PHINode>(SuccBB->begin())) continue; 10350 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10351 10352 // If this terminator has multiple identical successors (common for 10353 // switches), only handle each succ once. 10354 if (!SuccsHandled.insert(SuccMBB).second) 10355 continue; 10356 10357 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10358 10359 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10360 // nodes and Machine PHI nodes, but the incoming operands have not been 10361 // emitted yet. 10362 for (const PHINode &PN : SuccBB->phis()) { 10363 // Ignore dead phi's. 10364 if (PN.use_empty()) 10365 continue; 10366 10367 // Skip empty types 10368 if (PN.getType()->isEmptyTy()) 10369 continue; 10370 10371 unsigned Reg; 10372 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10373 10374 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10375 unsigned &RegOut = ConstantsOut[C]; 10376 if (RegOut == 0) { 10377 RegOut = FuncInfo.CreateRegs(C); 10378 CopyValueToVirtualRegister(C, RegOut); 10379 } 10380 Reg = RegOut; 10381 } else { 10382 DenseMap<const Value *, Register>::iterator I = 10383 FuncInfo.ValueMap.find(PHIOp); 10384 if (I != FuncInfo.ValueMap.end()) 10385 Reg = I->second; 10386 else { 10387 assert(isa<AllocaInst>(PHIOp) && 10388 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10389 "Didn't codegen value into a register!??"); 10390 Reg = FuncInfo.CreateRegs(PHIOp); 10391 CopyValueToVirtualRegister(PHIOp, Reg); 10392 } 10393 } 10394 10395 // Remember that this register needs to added to the machine PHI node as 10396 // the input for this MBB. 10397 SmallVector<EVT, 4> ValueVTs; 10398 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10399 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10400 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10401 EVT VT = ValueVTs[vti]; 10402 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10403 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10404 FuncInfo.PHINodesToUpdate.push_back( 10405 std::make_pair(&*MBBI++, Reg + i)); 10406 Reg += NumRegisters; 10407 } 10408 } 10409 } 10410 10411 ConstantsOut.clear(); 10412 } 10413 10414 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10415 /// is 0. 10416 MachineBasicBlock * 10417 SelectionDAGBuilder::StackProtectorDescriptor:: 10418 AddSuccessorMBB(const BasicBlock *BB, 10419 MachineBasicBlock *ParentMBB, 10420 bool IsLikely, 10421 MachineBasicBlock *SuccMBB) { 10422 // If SuccBB has not been created yet, create it. 10423 if (!SuccMBB) { 10424 MachineFunction *MF = ParentMBB->getParent(); 10425 MachineFunction::iterator BBI(ParentMBB); 10426 SuccMBB = MF->CreateMachineBasicBlock(BB); 10427 MF->insert(++BBI, SuccMBB); 10428 } 10429 // Add it as a successor of ParentMBB. 10430 ParentMBB->addSuccessor( 10431 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10432 return SuccMBB; 10433 } 10434 10435 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10436 MachineFunction::iterator I(MBB); 10437 if (++I == FuncInfo.MF->end()) 10438 return nullptr; 10439 return &*I; 10440 } 10441 10442 /// During lowering new call nodes can be created (such as memset, etc.). 10443 /// Those will become new roots of the current DAG, but complications arise 10444 /// when they are tail calls. In such cases, the call lowering will update 10445 /// the root, but the builder still needs to know that a tail call has been 10446 /// lowered in order to avoid generating an additional return. 10447 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10448 // If the node is null, we do have a tail call. 10449 if (MaybeTC.getNode() != nullptr) 10450 DAG.setRoot(MaybeTC); 10451 else 10452 HasTailCall = true; 10453 } 10454 10455 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10456 MachineBasicBlock *SwitchMBB, 10457 MachineBasicBlock *DefaultMBB) { 10458 MachineFunction *CurMF = FuncInfo.MF; 10459 MachineBasicBlock *NextMBB = nullptr; 10460 MachineFunction::iterator BBI(W.MBB); 10461 if (++BBI != FuncInfo.MF->end()) 10462 NextMBB = &*BBI; 10463 10464 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10465 10466 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10467 10468 if (Size == 2 && W.MBB == SwitchMBB) { 10469 // If any two of the cases has the same destination, and if one value 10470 // is the same as the other, but has one bit unset that the other has set, 10471 // use bit manipulation to do two compares at once. For example: 10472 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10473 // TODO: This could be extended to merge any 2 cases in switches with 3 10474 // cases. 10475 // TODO: Handle cases where W.CaseBB != SwitchBB. 10476 CaseCluster &Small = *W.FirstCluster; 10477 CaseCluster &Big = *W.LastCluster; 10478 10479 if (Small.Low == Small.High && Big.Low == Big.High && 10480 Small.MBB == Big.MBB) { 10481 const APInt &SmallValue = Small.Low->getValue(); 10482 const APInt &BigValue = Big.Low->getValue(); 10483 10484 // Check that there is only one bit different. 10485 APInt CommonBit = BigValue ^ SmallValue; 10486 if (CommonBit.isPowerOf2()) { 10487 SDValue CondLHS = getValue(Cond); 10488 EVT VT = CondLHS.getValueType(); 10489 SDLoc DL = getCurSDLoc(); 10490 10491 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10492 DAG.getConstant(CommonBit, DL, VT)); 10493 SDValue Cond = DAG.getSetCC( 10494 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10495 ISD::SETEQ); 10496 10497 // Update successor info. 10498 // Both Small and Big will jump to Small.BB, so we sum up the 10499 // probabilities. 10500 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10501 if (BPI) 10502 addSuccessorWithProb( 10503 SwitchMBB, DefaultMBB, 10504 // The default destination is the first successor in IR. 10505 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10506 else 10507 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10508 10509 // Insert the true branch. 10510 SDValue BrCond = 10511 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10512 DAG.getBasicBlock(Small.MBB)); 10513 // Insert the false branch. 10514 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10515 DAG.getBasicBlock(DefaultMBB)); 10516 10517 DAG.setRoot(BrCond); 10518 return; 10519 } 10520 } 10521 } 10522 10523 if (TM.getOptLevel() != CodeGenOpt::None) { 10524 // Here, we order cases by probability so the most likely case will be 10525 // checked first. However, two clusters can have the same probability in 10526 // which case their relative ordering is non-deterministic. So we use Low 10527 // as a tie-breaker as clusters are guaranteed to never overlap. 10528 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10529 [](const CaseCluster &a, const CaseCluster &b) { 10530 return a.Prob != b.Prob ? 10531 a.Prob > b.Prob : 10532 a.Low->getValue().slt(b.Low->getValue()); 10533 }); 10534 10535 // Rearrange the case blocks so that the last one falls through if possible 10536 // without changing the order of probabilities. 10537 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10538 --I; 10539 if (I->Prob > W.LastCluster->Prob) 10540 break; 10541 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10542 std::swap(*I, *W.LastCluster); 10543 break; 10544 } 10545 } 10546 } 10547 10548 // Compute total probability. 10549 BranchProbability DefaultProb = W.DefaultProb; 10550 BranchProbability UnhandledProbs = DefaultProb; 10551 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10552 UnhandledProbs += I->Prob; 10553 10554 MachineBasicBlock *CurMBB = W.MBB; 10555 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10556 bool FallthroughUnreachable = false; 10557 MachineBasicBlock *Fallthrough; 10558 if (I == W.LastCluster) { 10559 // For the last cluster, fall through to the default destination. 10560 Fallthrough = DefaultMBB; 10561 FallthroughUnreachable = isa<UnreachableInst>( 10562 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10563 } else { 10564 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10565 CurMF->insert(BBI, Fallthrough); 10566 // Put Cond in a virtual register to make it available from the new blocks. 10567 ExportFromCurrentBlock(Cond); 10568 } 10569 UnhandledProbs -= I->Prob; 10570 10571 switch (I->Kind) { 10572 case CC_JumpTable: { 10573 // FIXME: Optimize away range check based on pivot comparisons. 10574 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10575 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10576 10577 // The jump block hasn't been inserted yet; insert it here. 10578 MachineBasicBlock *JumpMBB = JT->MBB; 10579 CurMF->insert(BBI, JumpMBB); 10580 10581 auto JumpProb = I->Prob; 10582 auto FallthroughProb = UnhandledProbs; 10583 10584 // If the default statement is a target of the jump table, we evenly 10585 // distribute the default probability to successors of CurMBB. Also 10586 // update the probability on the edge from JumpMBB to Fallthrough. 10587 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10588 SE = JumpMBB->succ_end(); 10589 SI != SE; ++SI) { 10590 if (*SI == DefaultMBB) { 10591 JumpProb += DefaultProb / 2; 10592 FallthroughProb -= DefaultProb / 2; 10593 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10594 JumpMBB->normalizeSuccProbs(); 10595 break; 10596 } 10597 } 10598 10599 if (FallthroughUnreachable) { 10600 // Skip the range check if the fallthrough block is unreachable. 10601 JTH->OmitRangeCheck = true; 10602 } 10603 10604 if (!JTH->OmitRangeCheck) 10605 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10606 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10607 CurMBB->normalizeSuccProbs(); 10608 10609 // The jump table header will be inserted in our current block, do the 10610 // range check, and fall through to our fallthrough block. 10611 JTH->HeaderBB = CurMBB; 10612 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10613 10614 // If we're in the right place, emit the jump table header right now. 10615 if (CurMBB == SwitchMBB) { 10616 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10617 JTH->Emitted = true; 10618 } 10619 break; 10620 } 10621 case CC_BitTests: { 10622 // FIXME: Optimize away range check based on pivot comparisons. 10623 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10624 10625 // The bit test blocks haven't been inserted yet; insert them here. 10626 for (BitTestCase &BTC : BTB->Cases) 10627 CurMF->insert(BBI, BTC.ThisBB); 10628 10629 // Fill in fields of the BitTestBlock. 10630 BTB->Parent = CurMBB; 10631 BTB->Default = Fallthrough; 10632 10633 BTB->DefaultProb = UnhandledProbs; 10634 // If the cases in bit test don't form a contiguous range, we evenly 10635 // distribute the probability on the edge to Fallthrough to two 10636 // successors of CurMBB. 10637 if (!BTB->ContiguousRange) { 10638 BTB->Prob += DefaultProb / 2; 10639 BTB->DefaultProb -= DefaultProb / 2; 10640 } 10641 10642 if (FallthroughUnreachable) { 10643 // Skip the range check if the fallthrough block is unreachable. 10644 BTB->OmitRangeCheck = true; 10645 } 10646 10647 // If we're in the right place, emit the bit test header right now. 10648 if (CurMBB == SwitchMBB) { 10649 visitBitTestHeader(*BTB, SwitchMBB); 10650 BTB->Emitted = true; 10651 } 10652 break; 10653 } 10654 case CC_Range: { 10655 const Value *RHS, *LHS, *MHS; 10656 ISD::CondCode CC; 10657 if (I->Low == I->High) { 10658 // Check Cond == I->Low. 10659 CC = ISD::SETEQ; 10660 LHS = Cond; 10661 RHS=I->Low; 10662 MHS = nullptr; 10663 } else { 10664 // Check I->Low <= Cond <= I->High. 10665 CC = ISD::SETLE; 10666 LHS = I->Low; 10667 MHS = Cond; 10668 RHS = I->High; 10669 } 10670 10671 // If Fallthrough is unreachable, fold away the comparison. 10672 if (FallthroughUnreachable) 10673 CC = ISD::SETTRUE; 10674 10675 // The false probability is the sum of all unhandled cases. 10676 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10677 getCurSDLoc(), I->Prob, UnhandledProbs); 10678 10679 if (CurMBB == SwitchMBB) 10680 visitSwitchCase(CB, SwitchMBB); 10681 else 10682 SL->SwitchCases.push_back(CB); 10683 10684 break; 10685 } 10686 } 10687 CurMBB = Fallthrough; 10688 } 10689 } 10690 10691 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10692 CaseClusterIt First, 10693 CaseClusterIt Last) { 10694 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10695 if (X.Prob != CC.Prob) 10696 return X.Prob > CC.Prob; 10697 10698 // Ties are broken by comparing the case value. 10699 return X.Low->getValue().slt(CC.Low->getValue()); 10700 }); 10701 } 10702 10703 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10704 const SwitchWorkListItem &W, 10705 Value *Cond, 10706 MachineBasicBlock *SwitchMBB) { 10707 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10708 "Clusters not sorted?"); 10709 10710 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10711 10712 // Balance the tree based on branch probabilities to create a near-optimal (in 10713 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10714 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10715 CaseClusterIt LastLeft = W.FirstCluster; 10716 CaseClusterIt FirstRight = W.LastCluster; 10717 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10718 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10719 10720 // Move LastLeft and FirstRight towards each other from opposite directions to 10721 // find a partitioning of the clusters which balances the probability on both 10722 // sides. If LeftProb and RightProb are equal, alternate which side is 10723 // taken to ensure 0-probability nodes are distributed evenly. 10724 unsigned I = 0; 10725 while (LastLeft + 1 < FirstRight) { 10726 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10727 LeftProb += (++LastLeft)->Prob; 10728 else 10729 RightProb += (--FirstRight)->Prob; 10730 I++; 10731 } 10732 10733 while (true) { 10734 // Our binary search tree differs from a typical BST in that ours can have up 10735 // to three values in each leaf. The pivot selection above doesn't take that 10736 // into account, which means the tree might require more nodes and be less 10737 // efficient. We compensate for this here. 10738 10739 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10740 unsigned NumRight = W.LastCluster - FirstRight + 1; 10741 10742 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10743 // If one side has less than 3 clusters, and the other has more than 3, 10744 // consider taking a cluster from the other side. 10745 10746 if (NumLeft < NumRight) { 10747 // Consider moving the first cluster on the right to the left side. 10748 CaseCluster &CC = *FirstRight; 10749 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10750 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10751 if (LeftSideRank <= RightSideRank) { 10752 // Moving the cluster to the left does not demote it. 10753 ++LastLeft; 10754 ++FirstRight; 10755 continue; 10756 } 10757 } else { 10758 assert(NumRight < NumLeft); 10759 // Consider moving the last element on the left to the right side. 10760 CaseCluster &CC = *LastLeft; 10761 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10762 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10763 if (RightSideRank <= LeftSideRank) { 10764 // Moving the cluster to the right does not demot it. 10765 --LastLeft; 10766 --FirstRight; 10767 continue; 10768 } 10769 } 10770 } 10771 break; 10772 } 10773 10774 assert(LastLeft + 1 == FirstRight); 10775 assert(LastLeft >= W.FirstCluster); 10776 assert(FirstRight <= W.LastCluster); 10777 10778 // Use the first element on the right as pivot since we will make less-than 10779 // comparisons against it. 10780 CaseClusterIt PivotCluster = FirstRight; 10781 assert(PivotCluster > W.FirstCluster); 10782 assert(PivotCluster <= W.LastCluster); 10783 10784 CaseClusterIt FirstLeft = W.FirstCluster; 10785 CaseClusterIt LastRight = W.LastCluster; 10786 10787 const ConstantInt *Pivot = PivotCluster->Low; 10788 10789 // New blocks will be inserted immediately after the current one. 10790 MachineFunction::iterator BBI(W.MBB); 10791 ++BBI; 10792 10793 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10794 // we can branch to its destination directly if it's squeezed exactly in 10795 // between the known lower bound and Pivot - 1. 10796 MachineBasicBlock *LeftMBB; 10797 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10798 FirstLeft->Low == W.GE && 10799 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10800 LeftMBB = FirstLeft->MBB; 10801 } else { 10802 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10803 FuncInfo.MF->insert(BBI, LeftMBB); 10804 WorkList.push_back( 10805 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10806 // Put Cond in a virtual register to make it available from the new blocks. 10807 ExportFromCurrentBlock(Cond); 10808 } 10809 10810 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10811 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10812 // directly if RHS.High equals the current upper bound. 10813 MachineBasicBlock *RightMBB; 10814 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10815 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10816 RightMBB = FirstRight->MBB; 10817 } else { 10818 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10819 FuncInfo.MF->insert(BBI, RightMBB); 10820 WorkList.push_back( 10821 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10822 // Put Cond in a virtual register to make it available from the new blocks. 10823 ExportFromCurrentBlock(Cond); 10824 } 10825 10826 // Create the CaseBlock record that will be used to lower the branch. 10827 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10828 getCurSDLoc(), LeftProb, RightProb); 10829 10830 if (W.MBB == SwitchMBB) 10831 visitSwitchCase(CB, SwitchMBB); 10832 else 10833 SL->SwitchCases.push_back(CB); 10834 } 10835 10836 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10837 // from the swith statement. 10838 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10839 BranchProbability PeeledCaseProb) { 10840 if (PeeledCaseProb == BranchProbability::getOne()) 10841 return BranchProbability::getZero(); 10842 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10843 10844 uint32_t Numerator = CaseProb.getNumerator(); 10845 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10846 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10847 } 10848 10849 // Try to peel the top probability case if it exceeds the threshold. 10850 // Return current MachineBasicBlock for the switch statement if the peeling 10851 // does not occur. 10852 // If the peeling is performed, return the newly created MachineBasicBlock 10853 // for the peeled switch statement. Also update Clusters to remove the peeled 10854 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10855 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10856 const SwitchInst &SI, CaseClusterVector &Clusters, 10857 BranchProbability &PeeledCaseProb) { 10858 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10859 // Don't perform if there is only one cluster or optimizing for size. 10860 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10861 TM.getOptLevel() == CodeGenOpt::None || 10862 SwitchMBB->getParent()->getFunction().hasMinSize()) 10863 return SwitchMBB; 10864 10865 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10866 unsigned PeeledCaseIndex = 0; 10867 bool SwitchPeeled = false; 10868 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10869 CaseCluster &CC = Clusters[Index]; 10870 if (CC.Prob < TopCaseProb) 10871 continue; 10872 TopCaseProb = CC.Prob; 10873 PeeledCaseIndex = Index; 10874 SwitchPeeled = true; 10875 } 10876 if (!SwitchPeeled) 10877 return SwitchMBB; 10878 10879 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10880 << TopCaseProb << "\n"); 10881 10882 // Record the MBB for the peeled switch statement. 10883 MachineFunction::iterator BBI(SwitchMBB); 10884 ++BBI; 10885 MachineBasicBlock *PeeledSwitchMBB = 10886 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10887 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10888 10889 ExportFromCurrentBlock(SI.getCondition()); 10890 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10891 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10892 nullptr, nullptr, TopCaseProb.getCompl()}; 10893 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10894 10895 Clusters.erase(PeeledCaseIt); 10896 for (CaseCluster &CC : Clusters) { 10897 LLVM_DEBUG( 10898 dbgs() << "Scale the probablity for one cluster, before scaling: " 10899 << CC.Prob << "\n"); 10900 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10901 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10902 } 10903 PeeledCaseProb = TopCaseProb; 10904 return PeeledSwitchMBB; 10905 } 10906 10907 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10908 // Extract cases from the switch. 10909 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10910 CaseClusterVector Clusters; 10911 Clusters.reserve(SI.getNumCases()); 10912 for (auto I : SI.cases()) { 10913 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10914 const ConstantInt *CaseVal = I.getCaseValue(); 10915 BranchProbability Prob = 10916 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10917 : BranchProbability(1, SI.getNumCases() + 1); 10918 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10919 } 10920 10921 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10922 10923 // Cluster adjacent cases with the same destination. We do this at all 10924 // optimization levels because it's cheap to do and will make codegen faster 10925 // if there are many clusters. 10926 sortAndRangeify(Clusters); 10927 10928 // The branch probablity of the peeled case. 10929 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10930 MachineBasicBlock *PeeledSwitchMBB = 10931 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10932 10933 // If there is only the default destination, jump there directly. 10934 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10935 if (Clusters.empty()) { 10936 assert(PeeledSwitchMBB == SwitchMBB); 10937 SwitchMBB->addSuccessor(DefaultMBB); 10938 if (DefaultMBB != NextBlock(SwitchMBB)) { 10939 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10940 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10941 } 10942 return; 10943 } 10944 10945 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10946 SL->findBitTestClusters(Clusters, &SI); 10947 10948 LLVM_DEBUG({ 10949 dbgs() << "Case clusters: "; 10950 for (const CaseCluster &C : Clusters) { 10951 if (C.Kind == CC_JumpTable) 10952 dbgs() << "JT:"; 10953 if (C.Kind == CC_BitTests) 10954 dbgs() << "BT:"; 10955 10956 C.Low->getValue().print(dbgs(), true); 10957 if (C.Low != C.High) { 10958 dbgs() << '-'; 10959 C.High->getValue().print(dbgs(), true); 10960 } 10961 dbgs() << ' '; 10962 } 10963 dbgs() << '\n'; 10964 }); 10965 10966 assert(!Clusters.empty()); 10967 SwitchWorkList WorkList; 10968 CaseClusterIt First = Clusters.begin(); 10969 CaseClusterIt Last = Clusters.end() - 1; 10970 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10971 // Scale the branchprobability for DefaultMBB if the peel occurs and 10972 // DefaultMBB is not replaced. 10973 if (PeeledCaseProb != BranchProbability::getZero() && 10974 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10975 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10976 WorkList.push_back( 10977 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10978 10979 while (!WorkList.empty()) { 10980 SwitchWorkListItem W = WorkList.pop_back_val(); 10981 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10982 10983 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10984 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10985 // For optimized builds, lower large range as a balanced binary tree. 10986 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10987 continue; 10988 } 10989 10990 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10991 } 10992 } 10993 10994 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 10995 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10996 auto DL = getCurSDLoc(); 10997 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10998 EVT OpVT = 10999 TLI.getTypeToTransformTo(*DAG.getContext(), ResultVT.getScalarType()); 11000 SDValue Step = DAG.getConstant(1, DL, OpVT); 11001 setValue(&I, DAG.getStepVector(DL, ResultVT, Step)); 11002 } 11003 11004 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11005 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11006 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11007 11008 SDLoc DL = getCurSDLoc(); 11009 SDValue V = getValue(I.getOperand(0)); 11010 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11011 11012 if (VT.isScalableVector()) { 11013 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11014 return; 11015 } 11016 11017 // Use VECTOR_SHUFFLE for the fixed-length vector 11018 // to maintain existing behavior. 11019 SmallVector<int, 8> Mask; 11020 unsigned NumElts = VT.getVectorMinNumElements(); 11021 for (unsigned i = 0; i != NumElts; ++i) 11022 Mask.push_back(NumElts - 1 - i); 11023 11024 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11025 } 11026 11027 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11028 SmallVector<EVT, 4> ValueVTs; 11029 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11030 ValueVTs); 11031 unsigned NumValues = ValueVTs.size(); 11032 if (NumValues == 0) return; 11033 11034 SmallVector<SDValue, 4> Values(NumValues); 11035 SDValue Op = getValue(I.getOperand(0)); 11036 11037 for (unsigned i = 0; i != NumValues; ++i) 11038 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11039 SDValue(Op.getNode(), Op.getResNo() + i)); 11040 11041 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11042 DAG.getVTList(ValueVTs), Values)); 11043 } 11044 11045 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11046 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11047 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11048 11049 SDLoc DL = getCurSDLoc(); 11050 SDValue V1 = getValue(I.getOperand(0)); 11051 SDValue V2 = getValue(I.getOperand(1)); 11052 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11053 11054 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11055 if (VT.isScalableVector()) { 11056 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11057 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11058 DAG.getConstant(Imm, DL, IdxVT))); 11059 return; 11060 } 11061 11062 unsigned NumElts = VT.getVectorNumElements(); 11063 11064 if ((-Imm > NumElts) || (Imm >= NumElts)) { 11065 // Result is undefined if immediate is out-of-bounds. 11066 setValue(&I, DAG.getUNDEF(VT)); 11067 return; 11068 } 11069 11070 uint64_t Idx = (NumElts + Imm) % NumElts; 11071 11072 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11073 SmallVector<int, 8> Mask; 11074 for (unsigned i = 0; i < NumElts; ++i) 11075 Mask.push_back(Idx + i); 11076 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11077 } 11078