1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/BlockFrequencyInfo.h" 28 #include "llvm/Analysis/BranchProbabilityInfo.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/Analysis/EHPersonalities.h" 31 #include "llvm/Analysis/Loads.h" 32 #include "llvm/Analysis/MemoryLocation.h" 33 #include "llvm/Analysis/ProfileSummaryInfo.h" 34 #include "llvm/Analysis/TargetLibraryInfo.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/Analysis/VectorUtils.h" 37 #include "llvm/CodeGen/Analysis.h" 38 #include "llvm/CodeGen/FunctionLoweringInfo.h" 39 #include "llvm/CodeGen/GCMetadata.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 53 #include "llvm/CodeGen/StackMaps.h" 54 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 55 #include "llvm/CodeGen/TargetFrameLowering.h" 56 #include "llvm/CodeGen/TargetInstrInfo.h" 57 #include "llvm/CodeGen/TargetOpcodes.h" 58 #include "llvm/CodeGen/TargetRegisterInfo.h" 59 #include "llvm/CodeGen/TargetSubtargetInfo.h" 60 #include "llvm/CodeGen/WinEHFuncInfo.h" 61 #include "llvm/IR/Argument.h" 62 #include "llvm/IR/Attributes.h" 63 #include "llvm/IR/BasicBlock.h" 64 #include "llvm/IR/CFG.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/ConstantRange.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugInfoMetadata.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GetElementPtrTypeIterator.h" 74 #include "llvm/IR/InlineAsm.h" 75 #include "llvm/IR/InstrTypes.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/IntrinsicsAArch64.h" 80 #include "llvm/IR/IntrinsicsWebAssembly.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Operator.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Statepoint.h" 87 #include "llvm/IR/Type.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/MC/MCContext.h" 91 #include "llvm/MC/MCSymbol.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/MathExtras.h" 98 #include "llvm/Support/raw_ostream.h" 99 #include "llvm/Target/TargetIntrinsicInfo.h" 100 #include "llvm/Target/TargetMachine.h" 101 #include "llvm/Target/TargetOptions.h" 102 #include "llvm/Transforms/Utils/Local.h" 103 #include <cstddef> 104 #include <cstring> 105 #include <iterator> 106 #include <limits> 107 #include <numeric> 108 #include <tuple> 109 110 using namespace llvm; 111 using namespace PatternMatch; 112 using namespace SwitchCG; 113 114 #define DEBUG_TYPE "isel" 115 116 /// LimitFloatPrecision - Generate low-precision inline sequences for 117 /// some float libcalls (6, 8 or 12 bits). 118 static unsigned LimitFloatPrecision; 119 120 static cl::opt<bool> 121 InsertAssertAlign("insert-assert-align", cl::init(true), 122 cl::desc("Insert the experimental `assertalign` node."), 123 cl::ReallyHidden); 124 125 static cl::opt<unsigned, true> 126 LimitFPPrecision("limit-float-precision", 127 cl::desc("Generate low-precision inline sequences " 128 "for some float libcalls"), 129 cl::location(LimitFloatPrecision), cl::Hidden, 130 cl::init(0)); 131 132 static cl::opt<unsigned> SwitchPeelThreshold( 133 "switch-peel-threshold", cl::Hidden, cl::init(66), 134 cl::desc("Set the case probability threshold for peeling the case from a " 135 "switch statement. A value greater than 100 will void this " 136 "optimization")); 137 138 // Limit the width of DAG chains. This is important in general to prevent 139 // DAG-based analysis from blowing up. For example, alias analysis and 140 // load clustering may not complete in reasonable time. It is difficult to 141 // recognize and avoid this situation within each individual analysis, and 142 // future analyses are likely to have the same behavior. Limiting DAG width is 143 // the safe approach and will be especially important with global DAGs. 144 // 145 // MaxParallelChains default is arbitrarily high to avoid affecting 146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 147 // sequence over this should have been converted to llvm.memcpy by the 148 // frontend. It is easy to induce this behavior with .ll code such as: 149 // %buffer = alloca [4096 x i8] 150 // %data = load [4096 x i8]* %argPtr 151 // store [4096 x i8] %data, [4096 x i8]* %buffer 152 static const unsigned MaxParallelChains = 64; 153 154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 155 const SDValue *Parts, unsigned NumParts, 156 MVT PartVT, EVT ValueVT, const Value *V, 157 Optional<CallingConv::ID> CC); 158 159 /// getCopyFromParts - Create a value that contains the specified legal parts 160 /// combined into the value they represent. If the parts combine to a type 161 /// larger than ValueVT then AssertOp can be used to specify whether the extra 162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 163 /// (ISD::AssertSext). 164 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 165 const SDValue *Parts, unsigned NumParts, 166 MVT PartVT, EVT ValueVT, const Value *V, 167 Optional<CallingConv::ID> CC = None, 168 Optional<ISD::NodeType> AssertOp = None) { 169 // Let the target assemble the parts if it wants to 170 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 171 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 172 PartVT, ValueVT, CC)) 173 return Val; 174 175 if (ValueVT.isVector()) 176 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 177 CC); 178 179 assert(NumParts > 0 && "No parts to assemble!"); 180 SDValue Val = Parts[0]; 181 182 if (NumParts > 1) { 183 // Assemble the value from multiple parts. 184 if (ValueVT.isInteger()) { 185 unsigned PartBits = PartVT.getSizeInBits(); 186 unsigned ValueBits = ValueVT.getSizeInBits(); 187 188 // Assemble the power of 2 part. 189 unsigned RoundParts = 190 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 191 unsigned RoundBits = PartBits * RoundParts; 192 EVT RoundVT = RoundBits == ValueBits ? 193 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 194 SDValue Lo, Hi; 195 196 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 197 198 if (RoundParts > 2) { 199 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 200 PartVT, HalfVT, V); 201 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 202 RoundParts / 2, PartVT, HalfVT, V); 203 } else { 204 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 205 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 206 } 207 208 if (DAG.getDataLayout().isBigEndian()) 209 std::swap(Lo, Hi); 210 211 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 212 213 if (RoundParts < NumParts) { 214 // Assemble the trailing non-power-of-2 part. 215 unsigned OddParts = NumParts - RoundParts; 216 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 217 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 218 OddVT, V, CC); 219 220 // Combine the round and odd parts. 221 Lo = Val; 222 if (DAG.getDataLayout().isBigEndian()) 223 std::swap(Lo, Hi); 224 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 225 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 226 Hi = 227 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 228 DAG.getConstant(Lo.getValueSizeInBits(), DL, 229 TLI.getPointerTy(DAG.getDataLayout()))); 230 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 231 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 232 } 233 } else if (PartVT.isFloatingPoint()) { 234 // FP split into multiple FP parts (for ppcf128) 235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 236 "Unexpected split"); 237 SDValue Lo, Hi; 238 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 239 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 240 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 241 std::swap(Lo, Hi); 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 243 } else { 244 // FP split into integer parts (soft fp) 245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 246 !PartVT.isVector() && "Unexpected split"); 247 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 249 } 250 } 251 252 // There is now one part, held in Val. Correct it to match ValueVT. 253 // PartEVT is the type of the register class that holds the value. 254 // ValueVT is the type of the inline asm operation. 255 EVT PartEVT = Val.getValueType(); 256 257 if (PartEVT == ValueVT) 258 return Val; 259 260 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 261 ValueVT.bitsLT(PartEVT)) { 262 // For an FP value in an integer part, we need to truncate to the right 263 // width first. 264 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 265 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 266 } 267 268 // Handle types that have the same size. 269 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 270 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 271 272 // Handle types with different sizes. 273 if (PartEVT.isInteger() && ValueVT.isInteger()) { 274 if (ValueVT.bitsLT(PartEVT)) { 275 // For a truncate, see if we have any information to 276 // indicate whether the truncated bits will always be 277 // zero or sign-extension. 278 if (AssertOp.hasValue()) 279 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 280 DAG.getValueType(ValueVT)); 281 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 282 } 283 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 284 } 285 286 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 287 // FP_ROUND's are always exact here. 288 if (ValueVT.bitsLT(Val.getValueType())) 289 return DAG.getNode( 290 ISD::FP_ROUND, DL, ValueVT, Val, 291 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 292 293 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 294 } 295 296 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 297 // then truncating. 298 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 299 ValueVT.bitsLT(PartEVT)) { 300 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 301 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 302 } 303 304 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 305 } 306 307 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 308 const Twine &ErrMsg) { 309 const Instruction *I = dyn_cast_or_null<Instruction>(V); 310 if (!V) 311 return Ctx.emitError(ErrMsg); 312 313 const char *AsmError = ", possible invalid constraint for vector type"; 314 if (const CallInst *CI = dyn_cast<CallInst>(I)) 315 if (CI->isInlineAsm()) 316 return Ctx.emitError(I, ErrMsg + AsmError); 317 318 return Ctx.emitError(I, ErrMsg); 319 } 320 321 /// getCopyFromPartsVector - Create a value that contains the specified legal 322 /// parts combined into the value they represent. If the parts combine to a 323 /// type larger than ValueVT then AssertOp can be used to specify whether the 324 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 325 /// ValueVT (ISD::AssertSext). 326 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 327 const SDValue *Parts, unsigned NumParts, 328 MVT PartVT, EVT ValueVT, const Value *V, 329 Optional<CallingConv::ID> CallConv) { 330 assert(ValueVT.isVector() && "Not a vector value"); 331 assert(NumParts > 0 && "No parts to assemble!"); 332 const bool IsABIRegCopy = CallConv.hasValue(); 333 334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 335 SDValue Val = Parts[0]; 336 337 // Handle a multi-element vector. 338 if (NumParts > 1) { 339 EVT IntermediateVT; 340 MVT RegisterVT; 341 unsigned NumIntermediates; 342 unsigned NumRegs; 343 344 if (IsABIRegCopy) { 345 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 346 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } else { 349 NumRegs = 350 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 351 NumIntermediates, RegisterVT); 352 } 353 354 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 355 NumParts = NumRegs; // Silence a compiler warning. 356 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 357 assert(RegisterVT.getSizeInBits() == 358 Parts[0].getSimpleValueType().getSizeInBits() && 359 "Part type sizes don't match!"); 360 361 // Assemble the parts into intermediate operands. 362 SmallVector<SDValue, 8> Ops(NumIntermediates); 363 if (NumIntermediates == NumParts) { 364 // If the register was not expanded, truncate or copy the value, 365 // as appropriate. 366 for (unsigned i = 0; i != NumParts; ++i) 367 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 368 PartVT, IntermediateVT, V, CallConv); 369 } else if (NumParts > 0) { 370 // If the intermediate type was expanded, build the intermediate 371 // operands from the parts. 372 assert(NumParts % NumIntermediates == 0 && 373 "Must expand into a divisible number of parts!"); 374 unsigned Factor = NumParts / NumIntermediates; 375 for (unsigned i = 0; i != NumIntermediates; ++i) 376 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 377 PartVT, IntermediateVT, V, CallConv); 378 } 379 380 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 381 // intermediate operands. 382 EVT BuiltVectorTy = 383 IntermediateVT.isVector() 384 ? EVT::getVectorVT( 385 *DAG.getContext(), IntermediateVT.getScalarType(), 386 IntermediateVT.getVectorElementCount() * NumParts) 387 : EVT::getVectorVT(*DAG.getContext(), 388 IntermediateVT.getScalarType(), 389 NumIntermediates); 390 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 391 : ISD::BUILD_VECTOR, 392 DL, BuiltVectorTy, Ops); 393 } 394 395 // There is now one part, held in Val. Correct it to match ValueVT. 396 EVT PartEVT = Val.getValueType(); 397 398 if (PartEVT == ValueVT) 399 return Val; 400 401 if (PartEVT.isVector()) { 402 // If the element type of the source/dest vectors are the same, but the 403 // parts vector has more elements than the value vector, then we have a 404 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 405 // elements we want. 406 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 407 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 408 ValueVT.getVectorElementCount().getKnownMinValue()) && 409 (PartEVT.getVectorElementCount().isScalable() == 410 ValueVT.getVectorElementCount().isScalable()) && 411 "Cannot narrow, it would be a lossy transformation"); 412 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 413 DAG.getVectorIdxConstant(0, DL)); 414 } 415 416 // Vector/Vector bitcast. 417 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 418 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 419 420 assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() && 421 "Cannot handle this kind of promotion"); 422 // Promoted vector extract 423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 424 425 } 426 427 // Trivial bitcast if the types are the same size and the destination 428 // vector type is legal. 429 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 430 TLI.isTypeLegal(ValueVT)) 431 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 432 433 if (ValueVT.getVectorNumElements() != 1) { 434 // Certain ABIs require that vectors are passed as integers. For vectors 435 // are the same size, this is an obvious bitcast. 436 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 437 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 438 } else if (ValueVT.bitsLT(PartEVT)) { 439 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 440 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 441 // Drop the extra bits. 442 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 443 return DAG.getBitcast(ValueVT, Val); 444 } 445 446 diagnosePossiblyInvalidConstraint( 447 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 448 return DAG.getUNDEF(ValueVT); 449 } 450 451 // Handle cases such as i8 -> <1 x i1> 452 EVT ValueSVT = ValueVT.getVectorElementType(); 453 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 454 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 455 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 456 else 457 Val = ValueVT.isFloatingPoint() 458 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 459 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 460 } 461 462 return DAG.getBuildVector(ValueVT, DL, Val); 463 } 464 465 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 466 SDValue Val, SDValue *Parts, unsigned NumParts, 467 MVT PartVT, const Value *V, 468 Optional<CallingConv::ID> CallConv); 469 470 /// getCopyToParts - Create a series of nodes that contain the specified value 471 /// split into legal parts. If the parts contain more bits than Val, then, for 472 /// integers, ExtendKind can be used to specify how to generate the extra bits. 473 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 474 SDValue *Parts, unsigned NumParts, MVT PartVT, 475 const Value *V, 476 Optional<CallingConv::ID> CallConv = None, 477 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 478 // Let the target split the parts if it wants to 479 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 480 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 481 CallConv)) 482 return; 483 EVT ValueVT = Val.getValueType(); 484 485 // Handle the vector case separately. 486 if (ValueVT.isVector()) 487 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 488 CallConv); 489 490 unsigned PartBits = PartVT.getSizeInBits(); 491 unsigned OrigNumParts = NumParts; 492 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 493 "Copying to an illegal type!"); 494 495 if (NumParts == 0) 496 return; 497 498 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 499 EVT PartEVT = PartVT; 500 if (PartEVT == ValueVT) { 501 assert(NumParts == 1 && "No-op copy with multiple parts!"); 502 Parts[0] = Val; 503 return; 504 } 505 506 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 507 // If the parts cover more bits than the value has, promote the value. 508 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 509 assert(NumParts == 1 && "Do not know what to promote to!"); 510 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 511 } else { 512 if (ValueVT.isFloatingPoint()) { 513 // FP values need to be bitcast, then extended if they are being put 514 // into a larger container. 515 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 516 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 517 } 518 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 519 ValueVT.isInteger() && 520 "Unknown mismatch!"); 521 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 522 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 523 if (PartVT == MVT::x86mmx) 524 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 525 } 526 } else if (PartBits == ValueVT.getSizeInBits()) { 527 // Different types of the same size. 528 assert(NumParts == 1 && PartEVT != ValueVT); 529 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 530 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 531 // If the parts cover less bits than value has, truncate the value. 532 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 533 ValueVT.isInteger() && 534 "Unknown mismatch!"); 535 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 536 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 537 if (PartVT == MVT::x86mmx) 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } 540 541 // The value may have changed - recompute ValueVT. 542 ValueVT = Val.getValueType(); 543 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 544 "Failed to tile the value with PartVT!"); 545 546 if (NumParts == 1) { 547 if (PartEVT != ValueVT) { 548 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 549 "scalar-to-vector conversion failed"); 550 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 551 } 552 553 Parts[0] = Val; 554 return; 555 } 556 557 // Expand the value into multiple parts. 558 if (NumParts & (NumParts - 1)) { 559 // The number of parts is not a power of 2. Split off and copy the tail. 560 assert(PartVT.isInteger() && ValueVT.isInteger() && 561 "Do not know what to expand to!"); 562 unsigned RoundParts = 1 << Log2_32(NumParts); 563 unsigned RoundBits = RoundParts * PartBits; 564 unsigned OddParts = NumParts - RoundParts; 565 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 566 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 567 568 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 569 CallConv); 570 571 if (DAG.getDataLayout().isBigEndian()) 572 // The odd parts were reversed by getCopyToParts - unreverse them. 573 std::reverse(Parts + RoundParts, Parts + NumParts); 574 575 NumParts = RoundParts; 576 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 577 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 578 } 579 580 // The number of parts is a power of 2. Repeatedly bisect the value using 581 // EXTRACT_ELEMENT. 582 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 583 EVT::getIntegerVT(*DAG.getContext(), 584 ValueVT.getSizeInBits()), 585 Val); 586 587 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 588 for (unsigned i = 0; i < NumParts; i += StepSize) { 589 unsigned ThisBits = StepSize * PartBits / 2; 590 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 591 SDValue &Part0 = Parts[i]; 592 SDValue &Part1 = Parts[i+StepSize/2]; 593 594 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 595 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 596 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 597 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 598 599 if (ThisBits == PartBits && ThisVT != PartVT) { 600 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 601 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 602 } 603 } 604 } 605 606 if (DAG.getDataLayout().isBigEndian()) 607 std::reverse(Parts, Parts + OrigNumParts); 608 } 609 610 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 611 const SDLoc &DL, EVT PartVT) { 612 if (!PartVT.isVector()) 613 return SDValue(); 614 615 EVT ValueVT = Val.getValueType(); 616 ElementCount PartNumElts = PartVT.getVectorElementCount(); 617 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 618 619 // We only support widening vectors with equivalent element types and 620 // fixed/scalable properties. If a target needs to widen a fixed-length type 621 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 622 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 623 PartNumElts.isScalable() != ValueNumElts.isScalable() || 624 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 625 return SDValue(); 626 627 // Widening a scalable vector to another scalable vector is done by inserting 628 // the vector into a larger undef one. 629 if (PartNumElts.isScalable()) 630 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 631 Val, DAG.getVectorIdxConstant(0, DL)); 632 633 EVT ElementVT = PartVT.getVectorElementType(); 634 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 635 // undef elements. 636 SmallVector<SDValue, 16> Ops; 637 DAG.ExtractVectorElements(Val, Ops); 638 SDValue EltUndef = DAG.getUNDEF(ElementVT); 639 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 640 641 // FIXME: Use CONCAT for 2x -> 4x. 642 return DAG.getBuildVector(PartVT, DL, Ops); 643 } 644 645 /// getCopyToPartsVector - Create a series of nodes that contain the specified 646 /// value split into legal parts. 647 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 648 SDValue Val, SDValue *Parts, unsigned NumParts, 649 MVT PartVT, const Value *V, 650 Optional<CallingConv::ID> CallConv) { 651 EVT ValueVT = Val.getValueType(); 652 assert(ValueVT.isVector() && "Not a vector"); 653 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 654 const bool IsABIRegCopy = CallConv.hasValue(); 655 656 if (NumParts == 1) { 657 EVT PartEVT = PartVT; 658 if (PartEVT == ValueVT) { 659 // Nothing to do. 660 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 661 // Bitconvert vector->vector case. 662 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 663 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 664 Val = Widened; 665 } else if (PartVT.isVector() && 666 PartEVT.getVectorElementType().bitsGE( 667 ValueVT.getVectorElementType()) && 668 PartEVT.getVectorElementCount() == 669 ValueVT.getVectorElementCount()) { 670 671 // Promoted vector extract 672 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 673 } else { 674 if (ValueVT.getVectorElementCount().isScalar()) { 675 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 676 DAG.getVectorIdxConstant(0, DL)); 677 } else { 678 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 679 assert(PartVT.getFixedSizeInBits() > ValueSize && 680 "lossy conversion of vector to scalar type"); 681 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 682 Val = DAG.getBitcast(IntermediateType, Val); 683 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 684 } 685 } 686 687 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 688 Parts[0] = Val; 689 return; 690 } 691 692 // Handle a multi-element vector. 693 EVT IntermediateVT; 694 MVT RegisterVT; 695 unsigned NumIntermediates; 696 unsigned NumRegs; 697 if (IsABIRegCopy) { 698 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 699 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 700 NumIntermediates, RegisterVT); 701 } else { 702 NumRegs = 703 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 704 NumIntermediates, RegisterVT); 705 } 706 707 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 708 NumParts = NumRegs; // Silence a compiler warning. 709 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 710 711 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 712 "Mixing scalable and fixed vectors when copying in parts"); 713 714 Optional<ElementCount> DestEltCnt; 715 716 if (IntermediateVT.isVector()) 717 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 718 else 719 DestEltCnt = ElementCount::getFixed(NumIntermediates); 720 721 EVT BuiltVectorTy = EVT::getVectorVT( 722 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 723 724 if (ValueVT == BuiltVectorTy) { 725 // Nothing to do. 726 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 727 // Bitconvert vector->vector case. 728 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 729 } else if (SDValue Widened = 730 widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 731 Val = Widened; 732 } else if (BuiltVectorTy.getVectorElementType().bitsGE( 733 ValueVT.getVectorElementType()) && 734 BuiltVectorTy.getVectorElementCount() == 735 ValueVT.getVectorElementCount()) { 736 // Promoted vector extract 737 Val = DAG.getAnyExtOrTrunc(Val, DL, BuiltVectorTy); 738 } 739 740 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 741 742 // Split the vector into intermediate operands. 743 SmallVector<SDValue, 8> Ops(NumIntermediates); 744 for (unsigned i = 0; i != NumIntermediates; ++i) { 745 if (IntermediateVT.isVector()) { 746 // This does something sensible for scalable vectors - see the 747 // definition of EXTRACT_SUBVECTOR for further details. 748 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 749 Ops[i] = 750 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 751 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 752 } else { 753 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 754 DAG.getVectorIdxConstant(i, DL)); 755 } 756 } 757 758 // Split the intermediate operands into legal parts. 759 if (NumParts == NumIntermediates) { 760 // If the register was not expanded, promote or copy the value, 761 // as appropriate. 762 for (unsigned i = 0; i != NumParts; ++i) 763 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 764 } else if (NumParts > 0) { 765 // If the intermediate type was expanded, split each the value into 766 // legal parts. 767 assert(NumIntermediates != 0 && "division by zero"); 768 assert(NumParts % NumIntermediates == 0 && 769 "Must expand into a divisible number of parts!"); 770 unsigned Factor = NumParts / NumIntermediates; 771 for (unsigned i = 0; i != NumIntermediates; ++i) 772 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 773 CallConv); 774 } 775 } 776 777 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 778 EVT valuevt, Optional<CallingConv::ID> CC) 779 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 780 RegCount(1, regs.size()), CallConv(CC) {} 781 782 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 783 const DataLayout &DL, unsigned Reg, Type *Ty, 784 Optional<CallingConv::ID> CC) { 785 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 786 787 CallConv = CC; 788 789 for (EVT ValueVT : ValueVTs) { 790 unsigned NumRegs = 791 isABIMangled() 792 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 793 : TLI.getNumRegisters(Context, ValueVT); 794 MVT RegisterVT = 795 isABIMangled() 796 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 797 : TLI.getRegisterType(Context, ValueVT); 798 for (unsigned i = 0; i != NumRegs; ++i) 799 Regs.push_back(Reg + i); 800 RegVTs.push_back(RegisterVT); 801 RegCount.push_back(NumRegs); 802 Reg += NumRegs; 803 } 804 } 805 806 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 807 FunctionLoweringInfo &FuncInfo, 808 const SDLoc &dl, SDValue &Chain, 809 SDValue *Flag, const Value *V) const { 810 // A Value with type {} or [0 x %t] needs no registers. 811 if (ValueVTs.empty()) 812 return SDValue(); 813 814 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 815 816 // Assemble the legal parts into the final values. 817 SmallVector<SDValue, 4> Values(ValueVTs.size()); 818 SmallVector<SDValue, 8> Parts; 819 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 820 // Copy the legal parts from the registers. 821 EVT ValueVT = ValueVTs[Value]; 822 unsigned NumRegs = RegCount[Value]; 823 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 824 *DAG.getContext(), 825 CallConv.getValue(), RegVTs[Value]) 826 : RegVTs[Value]; 827 828 Parts.resize(NumRegs); 829 for (unsigned i = 0; i != NumRegs; ++i) { 830 SDValue P; 831 if (!Flag) { 832 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 833 } else { 834 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 835 *Flag = P.getValue(2); 836 } 837 838 Chain = P.getValue(1); 839 Parts[i] = P; 840 841 // If the source register was virtual and if we know something about it, 842 // add an assert node. 843 if (!Register::isVirtualRegister(Regs[Part + i]) || 844 !RegisterVT.isInteger()) 845 continue; 846 847 const FunctionLoweringInfo::LiveOutInfo *LOI = 848 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 849 if (!LOI) 850 continue; 851 852 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 853 unsigned NumSignBits = LOI->NumSignBits; 854 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 855 856 if (NumZeroBits == RegSize) { 857 // The current value is a zero. 858 // Explicitly express that as it would be easier for 859 // optimizations to kick in. 860 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 861 continue; 862 } 863 864 // FIXME: We capture more information than the dag can represent. For 865 // now, just use the tightest assertzext/assertsext possible. 866 bool isSExt; 867 EVT FromVT(MVT::Other); 868 if (NumZeroBits) { 869 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 870 isSExt = false; 871 } else if (NumSignBits > 1) { 872 FromVT = 873 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 874 isSExt = true; 875 } else { 876 continue; 877 } 878 // Add an assertion node. 879 assert(FromVT != MVT::Other); 880 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 881 RegisterVT, P, DAG.getValueType(FromVT)); 882 } 883 884 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 885 RegisterVT, ValueVT, V, CallConv); 886 Part += NumRegs; 887 Parts.clear(); 888 } 889 890 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 891 } 892 893 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 894 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 895 const Value *V, 896 ISD::NodeType PreferredExtendType) const { 897 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 898 ISD::NodeType ExtendKind = PreferredExtendType; 899 900 // Get the list of the values's legal parts. 901 unsigned NumRegs = Regs.size(); 902 SmallVector<SDValue, 8> Parts(NumRegs); 903 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 904 unsigned NumParts = RegCount[Value]; 905 906 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 907 *DAG.getContext(), 908 CallConv.getValue(), RegVTs[Value]) 909 : RegVTs[Value]; 910 911 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 912 ExtendKind = ISD::ZERO_EXTEND; 913 914 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 915 NumParts, RegisterVT, V, CallConv, ExtendKind); 916 Part += NumParts; 917 } 918 919 // Copy the parts into the registers. 920 SmallVector<SDValue, 8> Chains(NumRegs); 921 for (unsigned i = 0; i != NumRegs; ++i) { 922 SDValue Part; 923 if (!Flag) { 924 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 925 } else { 926 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 927 *Flag = Part.getValue(1); 928 } 929 930 Chains[i] = Part.getValue(0); 931 } 932 933 if (NumRegs == 1 || Flag) 934 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 935 // flagged to it. That is the CopyToReg nodes and the user are considered 936 // a single scheduling unit. If we create a TokenFactor and return it as 937 // chain, then the TokenFactor is both a predecessor (operand) of the 938 // user as well as a successor (the TF operands are flagged to the user). 939 // c1, f1 = CopyToReg 940 // c2, f2 = CopyToReg 941 // c3 = TokenFactor c1, c2 942 // ... 943 // = op c3, ..., f2 944 Chain = Chains[NumRegs-1]; 945 else 946 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 947 } 948 949 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 950 unsigned MatchingIdx, const SDLoc &dl, 951 SelectionDAG &DAG, 952 std::vector<SDValue> &Ops) const { 953 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 954 955 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 956 if (HasMatching) 957 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 958 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 959 // Put the register class of the virtual registers in the flag word. That 960 // way, later passes can recompute register class constraints for inline 961 // assembly as well as normal instructions. 962 // Don't do this for tied operands that can use the regclass information 963 // from the def. 964 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 965 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 966 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 967 } 968 969 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 970 Ops.push_back(Res); 971 972 if (Code == InlineAsm::Kind_Clobber) { 973 // Clobbers should always have a 1:1 mapping with registers, and may 974 // reference registers that have illegal (e.g. vector) types. Hence, we 975 // shouldn't try to apply any sort of splitting logic to them. 976 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 977 "No 1:1 mapping from clobbers to regs?"); 978 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 979 (void)SP; 980 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 981 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 982 assert( 983 (Regs[I] != SP || 984 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 985 "If we clobbered the stack pointer, MFI should know about it."); 986 } 987 return; 988 } 989 990 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 991 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 992 MVT RegisterVT = RegVTs[Value]; 993 for (unsigned i = 0; i != NumRegs; ++i) { 994 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 995 unsigned TheReg = Regs[Reg++]; 996 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 997 } 998 } 999 } 1000 1001 SmallVector<std::pair<unsigned, TypeSize>, 4> 1002 RegsForValue::getRegsAndSizes() const { 1003 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1004 unsigned I = 0; 1005 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1006 unsigned RegCount = std::get<0>(CountAndVT); 1007 MVT RegisterVT = std::get<1>(CountAndVT); 1008 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1009 for (unsigned E = I + RegCount; I != E; ++I) 1010 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1011 } 1012 return OutVec; 1013 } 1014 1015 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1016 const TargetLibraryInfo *li) { 1017 AA = aa; 1018 GFI = gfi; 1019 LibInfo = li; 1020 DL = &DAG.getDataLayout(); 1021 Context = DAG.getContext(); 1022 LPadToCallSiteMap.clear(); 1023 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1024 } 1025 1026 void SelectionDAGBuilder::clear() { 1027 NodeMap.clear(); 1028 UnusedArgNodeMap.clear(); 1029 PendingLoads.clear(); 1030 PendingExports.clear(); 1031 PendingConstrainedFP.clear(); 1032 PendingConstrainedFPStrict.clear(); 1033 CurInst = nullptr; 1034 HasTailCall = false; 1035 SDNodeOrder = LowestSDNodeOrder; 1036 StatepointLowering.clear(); 1037 } 1038 1039 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1040 DanglingDebugInfoMap.clear(); 1041 } 1042 1043 // Update DAG root to include dependencies on Pending chains. 1044 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1045 SDValue Root = DAG.getRoot(); 1046 1047 if (Pending.empty()) 1048 return Root; 1049 1050 // Add current root to PendingChains, unless we already indirectly 1051 // depend on it. 1052 if (Root.getOpcode() != ISD::EntryToken) { 1053 unsigned i = 0, e = Pending.size(); 1054 for (; i != e; ++i) { 1055 assert(Pending[i].getNode()->getNumOperands() > 1); 1056 if (Pending[i].getNode()->getOperand(0) == Root) 1057 break; // Don't add the root if we already indirectly depend on it. 1058 } 1059 1060 if (i == e) 1061 Pending.push_back(Root); 1062 } 1063 1064 if (Pending.size() == 1) 1065 Root = Pending[0]; 1066 else 1067 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1068 1069 DAG.setRoot(Root); 1070 Pending.clear(); 1071 return Root; 1072 } 1073 1074 SDValue SelectionDAGBuilder::getMemoryRoot() { 1075 return updateRoot(PendingLoads); 1076 } 1077 1078 SDValue SelectionDAGBuilder::getRoot() { 1079 // Chain up all pending constrained intrinsics together with all 1080 // pending loads, by simply appending them to PendingLoads and 1081 // then calling getMemoryRoot(). 1082 PendingLoads.reserve(PendingLoads.size() + 1083 PendingConstrainedFP.size() + 1084 PendingConstrainedFPStrict.size()); 1085 PendingLoads.append(PendingConstrainedFP.begin(), 1086 PendingConstrainedFP.end()); 1087 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1088 PendingConstrainedFPStrict.end()); 1089 PendingConstrainedFP.clear(); 1090 PendingConstrainedFPStrict.clear(); 1091 return getMemoryRoot(); 1092 } 1093 1094 SDValue SelectionDAGBuilder::getControlRoot() { 1095 // We need to emit pending fpexcept.strict constrained intrinsics, 1096 // so append them to the PendingExports list. 1097 PendingExports.append(PendingConstrainedFPStrict.begin(), 1098 PendingConstrainedFPStrict.end()); 1099 PendingConstrainedFPStrict.clear(); 1100 return updateRoot(PendingExports); 1101 } 1102 1103 void SelectionDAGBuilder::visit(const Instruction &I) { 1104 // Set up outgoing PHI node register values before emitting the terminator. 1105 if (I.isTerminator()) { 1106 HandlePHINodesInSuccessorBlocks(I.getParent()); 1107 } 1108 1109 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1110 if (!isa<DbgInfoIntrinsic>(I)) 1111 ++SDNodeOrder; 1112 1113 CurInst = &I; 1114 1115 visit(I.getOpcode(), I); 1116 1117 if (!I.isTerminator() && !HasTailCall && 1118 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1119 CopyToExportRegsIfNeeded(&I); 1120 1121 CurInst = nullptr; 1122 } 1123 1124 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1125 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1126 } 1127 1128 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1129 // Note: this doesn't use InstVisitor, because it has to work with 1130 // ConstantExpr's in addition to instructions. 1131 switch (Opcode) { 1132 default: llvm_unreachable("Unknown instruction type encountered!"); 1133 // Build the switch statement using the Instruction.def file. 1134 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1135 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1136 #include "llvm/IR/Instruction.def" 1137 } 1138 } 1139 1140 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1141 DebugLoc DL, unsigned Order) { 1142 // We treat variadic dbg_values differently at this stage. 1143 if (DI->hasArgList()) { 1144 // For variadic dbg_values we will now insert an undef. 1145 // FIXME: We can potentially recover these! 1146 SmallVector<SDDbgOperand, 2> Locs; 1147 for (const Value *V : DI->getValues()) { 1148 auto Undef = UndefValue::get(V->getType()); 1149 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1150 } 1151 SDDbgValue *SDV = DAG.getDbgValueList( 1152 DI->getVariable(), DI->getExpression(), Locs, {}, 1153 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1154 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1155 } else { 1156 // TODO: Dangling debug info will eventually either be resolved or produce 1157 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1158 // between the original dbg.value location and its resolved DBG_VALUE, 1159 // which we should ideally fill with an extra Undef DBG_VALUE. 1160 assert(DI->getNumVariableLocationOps() == 1 && 1161 "DbgValueInst without an ArgList should have a single location " 1162 "operand."); 1163 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1164 } 1165 } 1166 1167 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1168 const DIExpression *Expr) { 1169 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1170 const DbgValueInst *DI = DDI.getDI(); 1171 DIVariable *DanglingVariable = DI->getVariable(); 1172 DIExpression *DanglingExpr = DI->getExpression(); 1173 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1174 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1175 return true; 1176 } 1177 return false; 1178 }; 1179 1180 for (auto &DDIMI : DanglingDebugInfoMap) { 1181 DanglingDebugInfoVector &DDIV = DDIMI.second; 1182 1183 // If debug info is to be dropped, run it through final checks to see 1184 // whether it can be salvaged. 1185 for (auto &DDI : DDIV) 1186 if (isMatchingDbgValue(DDI)) 1187 salvageUnresolvedDbgValue(DDI); 1188 1189 erase_if(DDIV, isMatchingDbgValue); 1190 } 1191 } 1192 1193 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1194 // generate the debug data structures now that we've seen its definition. 1195 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1196 SDValue Val) { 1197 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1198 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1199 return; 1200 1201 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1202 for (auto &DDI : DDIV) { 1203 const DbgValueInst *DI = DDI.getDI(); 1204 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1205 assert(DI && "Ill-formed DanglingDebugInfo"); 1206 DebugLoc dl = DDI.getdl(); 1207 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1208 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1209 DILocalVariable *Variable = DI->getVariable(); 1210 DIExpression *Expr = DI->getExpression(); 1211 assert(Variable->isValidLocationForIntrinsic(dl) && 1212 "Expected inlined-at fields to agree"); 1213 SDDbgValue *SDV; 1214 if (Val.getNode()) { 1215 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1216 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1217 // we couldn't resolve it directly when examining the DbgValue intrinsic 1218 // in the first place we should not be more successful here). Unless we 1219 // have some test case that prove this to be correct we should avoid 1220 // calling EmitFuncArgumentDbgValue here. 1221 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1222 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1223 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1224 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1225 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1226 // inserted after the definition of Val when emitting the instructions 1227 // after ISel. An alternative could be to teach 1228 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1229 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1230 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1231 << ValSDNodeOrder << "\n"); 1232 SDV = getDbgValue(Val, Variable, Expr, dl, 1233 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1234 DAG.AddDbgValue(SDV, false); 1235 } else 1236 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1237 << "in EmitFuncArgumentDbgValue\n"); 1238 } else { 1239 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1240 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1241 auto SDV = 1242 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1243 DAG.AddDbgValue(SDV, false); 1244 } 1245 } 1246 DDIV.clear(); 1247 } 1248 1249 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1250 assert(!DDI.getDI()->hasArgList() && 1251 "Not implemented for variadic dbg_values"); 1252 Value *V = DDI.getDI()->getValue(0); 1253 DILocalVariable *Var = DDI.getDI()->getVariable(); 1254 DIExpression *Expr = DDI.getDI()->getExpression(); 1255 DebugLoc DL = DDI.getdl(); 1256 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1257 unsigned SDOrder = DDI.getSDNodeOrder(); 1258 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1259 // that DW_OP_stack_value is desired. 1260 assert(isa<DbgValueInst>(DDI.getDI())); 1261 bool StackValue = true; 1262 1263 // Can this Value can be encoded without any further work? 1264 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1265 return; 1266 1267 // Attempt to salvage back through as many instructions as possible. Bail if 1268 // a non-instruction is seen, such as a constant expression or global 1269 // variable. FIXME: Further work could recover those too. 1270 while (isa<Instruction>(V)) { 1271 Instruction &VAsInst = *cast<Instruction>(V); 1272 // Temporary "0", awaiting real implementation. 1273 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue, 0); 1274 1275 // If we cannot salvage any further, and haven't yet found a suitable debug 1276 // expression, bail out. 1277 if (!NewExpr) 1278 break; 1279 1280 // New value and expr now represent this debuginfo. 1281 V = VAsInst.getOperand(0); 1282 Expr = NewExpr; 1283 1284 // Some kind of simplification occurred: check whether the operand of the 1285 // salvaged debug expression can be encoded in this DAG. 1286 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1287 /*IsVariadic=*/false)) { 1288 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1289 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1290 return; 1291 } 1292 } 1293 1294 // This was the final opportunity to salvage this debug information, and it 1295 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1296 // any earlier variable location. 1297 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1298 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1299 DAG.AddDbgValue(SDV, false); 1300 1301 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1302 << "\n"); 1303 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1304 << "\n"); 1305 } 1306 1307 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1308 DILocalVariable *Var, 1309 DIExpression *Expr, DebugLoc dl, 1310 DebugLoc InstDL, unsigned Order, 1311 bool IsVariadic) { 1312 if (Values.empty()) 1313 return true; 1314 SmallVector<SDDbgOperand> LocationOps; 1315 SmallVector<SDNode *> Dependencies; 1316 for (const Value *V : Values) { 1317 // Constant value. 1318 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1319 isa<ConstantPointerNull>(V)) { 1320 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1321 continue; 1322 } 1323 1324 // If the Value is a frame index, we can create a FrameIndex debug value 1325 // without relying on the DAG at all. 1326 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1327 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1328 if (SI != FuncInfo.StaticAllocaMap.end()) { 1329 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1330 continue; 1331 } 1332 } 1333 1334 // Do not use getValue() in here; we don't want to generate code at 1335 // this point if it hasn't been done yet. 1336 SDValue N = NodeMap[V]; 1337 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1338 N = UnusedArgNodeMap[V]; 1339 if (N.getNode()) { 1340 // Only emit func arg dbg value for non-variadic dbg.values for now. 1341 if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1342 return true; 1343 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1344 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1345 // describe stack slot locations. 1346 // 1347 // Consider "int x = 0; int *px = &x;". There are two kinds of 1348 // interesting debug values here after optimization: 1349 // 1350 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1351 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1352 // 1353 // Both describe the direct values of their associated variables. 1354 Dependencies.push_back(N.getNode()); 1355 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1356 continue; 1357 } 1358 LocationOps.emplace_back( 1359 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1360 continue; 1361 } 1362 1363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1364 // Special rules apply for the first dbg.values of parameter variables in a 1365 // function. Identify them by the fact they reference Argument Values, that 1366 // they're parameters, and they are parameters of the current function. We 1367 // need to let them dangle until they get an SDNode. 1368 bool IsParamOfFunc = 1369 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1370 if (IsParamOfFunc) 1371 return false; 1372 1373 // The value is not used in this block yet (or it would have an SDNode). 1374 // We still want the value to appear for the user if possible -- if it has 1375 // an associated VReg, we can refer to that instead. 1376 auto VMI = FuncInfo.ValueMap.find(V); 1377 if (VMI != FuncInfo.ValueMap.end()) { 1378 unsigned Reg = VMI->second; 1379 // If this is a PHI node, it may be split up into several MI PHI nodes 1380 // (in FunctionLoweringInfo::set). 1381 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1382 V->getType(), None); 1383 if (RFV.occupiesMultipleRegs()) { 1384 // FIXME: We could potentially support variadic dbg_values here. 1385 if (IsVariadic) 1386 return false; 1387 unsigned Offset = 0; 1388 unsigned BitsToDescribe = 0; 1389 if (auto VarSize = Var->getSizeInBits()) 1390 BitsToDescribe = *VarSize; 1391 if (auto Fragment = Expr->getFragmentInfo()) 1392 BitsToDescribe = Fragment->SizeInBits; 1393 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1394 // Bail out if all bits are described already. 1395 if (Offset >= BitsToDescribe) 1396 break; 1397 // TODO: handle scalable vectors. 1398 unsigned RegisterSize = RegAndSize.second; 1399 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1400 ? BitsToDescribe - Offset 1401 : RegisterSize; 1402 auto FragmentExpr = DIExpression::createFragmentExpression( 1403 Expr, Offset, FragmentSize); 1404 if (!FragmentExpr) 1405 continue; 1406 SDDbgValue *SDV = DAG.getVRegDbgValue( 1407 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1408 DAG.AddDbgValue(SDV, false); 1409 Offset += RegisterSize; 1410 } 1411 return true; 1412 } 1413 // We can use simple vreg locations for variadic dbg_values as well. 1414 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1415 continue; 1416 } 1417 // We failed to create a SDDbgOperand for V. 1418 return false; 1419 } 1420 1421 // We have created a SDDbgOperand for each Value in Values. 1422 // Should use Order instead of SDNodeOrder? 1423 assert(!LocationOps.empty()); 1424 SDDbgValue *SDV = 1425 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1426 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1427 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1428 return true; 1429 } 1430 1431 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1432 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1433 for (auto &Pair : DanglingDebugInfoMap) 1434 for (auto &DDI : Pair.second) 1435 salvageUnresolvedDbgValue(DDI); 1436 clearDanglingDebugInfo(); 1437 } 1438 1439 /// getCopyFromRegs - If there was virtual register allocated for the value V 1440 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1441 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1442 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1443 SDValue Result; 1444 1445 if (It != FuncInfo.ValueMap.end()) { 1446 Register InReg = It->second; 1447 1448 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1449 DAG.getDataLayout(), InReg, Ty, 1450 None); // This is not an ABI copy. 1451 SDValue Chain = DAG.getEntryNode(); 1452 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1453 V); 1454 resolveDanglingDebugInfo(V, Result); 1455 } 1456 1457 return Result; 1458 } 1459 1460 /// getValue - Return an SDValue for the given Value. 1461 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1462 // If we already have an SDValue for this value, use it. It's important 1463 // to do this first, so that we don't create a CopyFromReg if we already 1464 // have a regular SDValue. 1465 SDValue &N = NodeMap[V]; 1466 if (N.getNode()) return N; 1467 1468 // If there's a virtual register allocated and initialized for this 1469 // value, use it. 1470 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1471 return copyFromReg; 1472 1473 // Otherwise create a new SDValue and remember it. 1474 SDValue Val = getValueImpl(V); 1475 NodeMap[V] = Val; 1476 resolveDanglingDebugInfo(V, Val); 1477 return Val; 1478 } 1479 1480 /// getNonRegisterValue - Return an SDValue for the given Value, but 1481 /// don't look in FuncInfo.ValueMap for a virtual register. 1482 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1483 // If we already have an SDValue for this value, use it. 1484 SDValue &N = NodeMap[V]; 1485 if (N.getNode()) { 1486 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1487 // Remove the debug location from the node as the node is about to be used 1488 // in a location which may differ from the original debug location. This 1489 // is relevant to Constant and ConstantFP nodes because they can appear 1490 // as constant expressions inside PHI nodes. 1491 N->setDebugLoc(DebugLoc()); 1492 } 1493 return N; 1494 } 1495 1496 // Otherwise create a new SDValue and remember it. 1497 SDValue Val = getValueImpl(V); 1498 NodeMap[V] = Val; 1499 resolveDanglingDebugInfo(V, Val); 1500 return Val; 1501 } 1502 1503 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1504 /// Create an SDValue for the given value. 1505 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1506 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1507 1508 if (const Constant *C = dyn_cast<Constant>(V)) { 1509 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1510 1511 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1512 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1513 1514 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1515 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1516 1517 if (isa<ConstantPointerNull>(C)) { 1518 unsigned AS = V->getType()->getPointerAddressSpace(); 1519 return DAG.getConstant(0, getCurSDLoc(), 1520 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1521 } 1522 1523 if (match(C, m_VScale(DAG.getDataLayout()))) 1524 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1525 1526 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1527 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1528 1529 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1530 return DAG.getUNDEF(VT); 1531 1532 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1533 visit(CE->getOpcode(), *CE); 1534 SDValue N1 = NodeMap[V]; 1535 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1536 return N1; 1537 } 1538 1539 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1540 SmallVector<SDValue, 4> Constants; 1541 for (const Use &U : C->operands()) { 1542 SDNode *Val = getValue(U).getNode(); 1543 // If the operand is an empty aggregate, there are no values. 1544 if (!Val) continue; 1545 // Add each leaf value from the operand to the Constants list 1546 // to form a flattened list of all the values. 1547 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1548 Constants.push_back(SDValue(Val, i)); 1549 } 1550 1551 return DAG.getMergeValues(Constants, getCurSDLoc()); 1552 } 1553 1554 if (const ConstantDataSequential *CDS = 1555 dyn_cast<ConstantDataSequential>(C)) { 1556 SmallVector<SDValue, 4> Ops; 1557 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1558 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1559 // Add each leaf value from the operand to the Constants list 1560 // to form a flattened list of all the values. 1561 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1562 Ops.push_back(SDValue(Val, i)); 1563 } 1564 1565 if (isa<ArrayType>(CDS->getType())) 1566 return DAG.getMergeValues(Ops, getCurSDLoc()); 1567 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1568 } 1569 1570 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1571 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1572 "Unknown struct or array constant!"); 1573 1574 SmallVector<EVT, 4> ValueVTs; 1575 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1576 unsigned NumElts = ValueVTs.size(); 1577 if (NumElts == 0) 1578 return SDValue(); // empty struct 1579 SmallVector<SDValue, 4> Constants(NumElts); 1580 for (unsigned i = 0; i != NumElts; ++i) { 1581 EVT EltVT = ValueVTs[i]; 1582 if (isa<UndefValue>(C)) 1583 Constants[i] = DAG.getUNDEF(EltVT); 1584 else if (EltVT.isFloatingPoint()) 1585 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1586 else 1587 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1588 } 1589 1590 return DAG.getMergeValues(Constants, getCurSDLoc()); 1591 } 1592 1593 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1594 return DAG.getBlockAddress(BA, VT); 1595 1596 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1597 return getValue(Equiv->getGlobalValue()); 1598 1599 VectorType *VecTy = cast<VectorType>(V->getType()); 1600 1601 // Now that we know the number and type of the elements, get that number of 1602 // elements into the Ops array based on what kind of constant it is. 1603 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1604 SmallVector<SDValue, 16> Ops; 1605 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1606 for (unsigned i = 0; i != NumElements; ++i) 1607 Ops.push_back(getValue(CV->getOperand(i))); 1608 1609 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1610 } else if (isa<ConstantAggregateZero>(C)) { 1611 EVT EltVT = 1612 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1613 1614 SDValue Op; 1615 if (EltVT.isFloatingPoint()) 1616 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1617 else 1618 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1619 1620 if (isa<ScalableVectorType>(VecTy)) 1621 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1622 else { 1623 SmallVector<SDValue, 16> Ops; 1624 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1625 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1626 } 1627 } 1628 llvm_unreachable("Unknown vector constant"); 1629 } 1630 1631 // If this is a static alloca, generate it as the frameindex instead of 1632 // computation. 1633 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1634 DenseMap<const AllocaInst*, int>::iterator SI = 1635 FuncInfo.StaticAllocaMap.find(AI); 1636 if (SI != FuncInfo.StaticAllocaMap.end()) 1637 return DAG.getFrameIndex(SI->second, 1638 TLI.getFrameIndexTy(DAG.getDataLayout())); 1639 } 1640 1641 // If this is an instruction which fast-isel has deferred, select it now. 1642 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1643 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1644 1645 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1646 Inst->getType(), None); 1647 SDValue Chain = DAG.getEntryNode(); 1648 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1649 } 1650 1651 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1652 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1653 } 1654 llvm_unreachable("Can't get register for value!"); 1655 } 1656 1657 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1658 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1659 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1660 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1661 bool IsSEH = isAsynchronousEHPersonality(Pers); 1662 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1663 if (!IsSEH) 1664 CatchPadMBB->setIsEHScopeEntry(); 1665 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1666 if (IsMSVCCXX || IsCoreCLR) 1667 CatchPadMBB->setIsEHFuncletEntry(); 1668 } 1669 1670 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1671 // Update machine-CFG edge. 1672 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1673 FuncInfo.MBB->addSuccessor(TargetMBB); 1674 TargetMBB->setIsEHCatchretTarget(true); 1675 DAG.getMachineFunction().setHasEHCatchret(true); 1676 1677 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1678 bool IsSEH = isAsynchronousEHPersonality(Pers); 1679 if (IsSEH) { 1680 // If this is not a fall-through branch or optimizations are switched off, 1681 // emit the branch. 1682 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1683 TM.getOptLevel() == CodeGenOpt::None) 1684 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1685 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1686 return; 1687 } 1688 1689 // Figure out the funclet membership for the catchret's successor. 1690 // This will be used by the FuncletLayout pass to determine how to order the 1691 // BB's. 1692 // A 'catchret' returns to the outer scope's color. 1693 Value *ParentPad = I.getCatchSwitchParentPad(); 1694 const BasicBlock *SuccessorColor; 1695 if (isa<ConstantTokenNone>(ParentPad)) 1696 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1697 else 1698 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1699 assert(SuccessorColor && "No parent funclet for catchret!"); 1700 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1701 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1702 1703 // Create the terminator node. 1704 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1705 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1706 DAG.getBasicBlock(SuccessorColorMBB)); 1707 DAG.setRoot(Ret); 1708 } 1709 1710 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1711 // Don't emit any special code for the cleanuppad instruction. It just marks 1712 // the start of an EH scope/funclet. 1713 FuncInfo.MBB->setIsEHScopeEntry(); 1714 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1715 if (Pers != EHPersonality::Wasm_CXX) { 1716 FuncInfo.MBB->setIsEHFuncletEntry(); 1717 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1718 } 1719 } 1720 1721 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1722 // not match, it is OK to add only the first unwind destination catchpad to the 1723 // successors, because there will be at least one invoke instruction within the 1724 // catch scope that points to the next unwind destination, if one exists, so 1725 // CFGSort cannot mess up with BB sorting order. 1726 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1727 // call within them, and catchpads only consisting of 'catch (...)' have a 1728 // '__cxa_end_catch' call within them, both of which generate invokes in case 1729 // the next unwind destination exists, i.e., the next unwind destination is not 1730 // the caller.) 1731 // 1732 // Having at most one EH pad successor is also simpler and helps later 1733 // transformations. 1734 // 1735 // For example, 1736 // current: 1737 // invoke void @foo to ... unwind label %catch.dispatch 1738 // catch.dispatch: 1739 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1740 // catch.start: 1741 // ... 1742 // ... in this BB or some other child BB dominated by this BB there will be an 1743 // invoke that points to 'next' BB as an unwind destination 1744 // 1745 // next: ; We don't need to add this to 'current' BB's successor 1746 // ... 1747 static void findWasmUnwindDestinations( 1748 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1749 BranchProbability Prob, 1750 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1751 &UnwindDests) { 1752 while (EHPadBB) { 1753 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1754 if (isa<CleanupPadInst>(Pad)) { 1755 // Stop on cleanup pads. 1756 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1757 UnwindDests.back().first->setIsEHScopeEntry(); 1758 break; 1759 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1760 // Add the catchpad handlers to the possible destinations. We don't 1761 // continue to the unwind destination of the catchswitch for wasm. 1762 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1763 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1764 UnwindDests.back().first->setIsEHScopeEntry(); 1765 } 1766 break; 1767 } else { 1768 continue; 1769 } 1770 } 1771 } 1772 1773 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1774 /// many places it could ultimately go. In the IR, we have a single unwind 1775 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1776 /// This function skips over imaginary basic blocks that hold catchswitch 1777 /// instructions, and finds all the "real" machine 1778 /// basic block destinations. As those destinations may not be successors of 1779 /// EHPadBB, here we also calculate the edge probability to those destinations. 1780 /// The passed-in Prob is the edge probability to EHPadBB. 1781 static void findUnwindDestinations( 1782 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1783 BranchProbability Prob, 1784 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1785 &UnwindDests) { 1786 EHPersonality Personality = 1787 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1788 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1789 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1790 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1791 bool IsSEH = isAsynchronousEHPersonality(Personality); 1792 1793 if (IsWasmCXX) { 1794 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1795 assert(UnwindDests.size() <= 1 && 1796 "There should be at most one unwind destination for wasm"); 1797 return; 1798 } 1799 1800 while (EHPadBB) { 1801 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1802 BasicBlock *NewEHPadBB = nullptr; 1803 if (isa<LandingPadInst>(Pad)) { 1804 // Stop on landingpads. They are not funclets. 1805 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1806 break; 1807 } else if (isa<CleanupPadInst>(Pad)) { 1808 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1809 // personalities. 1810 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1811 UnwindDests.back().first->setIsEHScopeEntry(); 1812 UnwindDests.back().first->setIsEHFuncletEntry(); 1813 break; 1814 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1815 // Add the catchpad handlers to the possible destinations. 1816 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1817 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1818 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1819 if (IsMSVCCXX || IsCoreCLR) 1820 UnwindDests.back().first->setIsEHFuncletEntry(); 1821 if (!IsSEH) 1822 UnwindDests.back().first->setIsEHScopeEntry(); 1823 } 1824 NewEHPadBB = CatchSwitch->getUnwindDest(); 1825 } else { 1826 continue; 1827 } 1828 1829 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1830 if (BPI && NewEHPadBB) 1831 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1832 EHPadBB = NewEHPadBB; 1833 } 1834 } 1835 1836 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1837 // Update successor info. 1838 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1839 auto UnwindDest = I.getUnwindDest(); 1840 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1841 BranchProbability UnwindDestProb = 1842 (BPI && UnwindDest) 1843 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1844 : BranchProbability::getZero(); 1845 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1846 for (auto &UnwindDest : UnwindDests) { 1847 UnwindDest.first->setIsEHPad(); 1848 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1849 } 1850 FuncInfo.MBB->normalizeSuccProbs(); 1851 1852 // Create the terminator node. 1853 SDValue Ret = 1854 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1855 DAG.setRoot(Ret); 1856 } 1857 1858 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1859 report_fatal_error("visitCatchSwitch not yet implemented!"); 1860 } 1861 1862 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1863 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1864 auto &DL = DAG.getDataLayout(); 1865 SDValue Chain = getControlRoot(); 1866 SmallVector<ISD::OutputArg, 8> Outs; 1867 SmallVector<SDValue, 8> OutVals; 1868 1869 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1870 // lower 1871 // 1872 // %val = call <ty> @llvm.experimental.deoptimize() 1873 // ret <ty> %val 1874 // 1875 // differently. 1876 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1877 LowerDeoptimizingReturn(); 1878 return; 1879 } 1880 1881 if (!FuncInfo.CanLowerReturn) { 1882 unsigned DemoteReg = FuncInfo.DemoteRegister; 1883 const Function *F = I.getParent()->getParent(); 1884 1885 // Emit a store of the return value through the virtual register. 1886 // Leave Outs empty so that LowerReturn won't try to load return 1887 // registers the usual way. 1888 SmallVector<EVT, 1> PtrValueVTs; 1889 ComputeValueVTs(TLI, DL, 1890 F->getReturnType()->getPointerTo( 1891 DAG.getDataLayout().getAllocaAddrSpace()), 1892 PtrValueVTs); 1893 1894 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1895 DemoteReg, PtrValueVTs[0]); 1896 SDValue RetOp = getValue(I.getOperand(0)); 1897 1898 SmallVector<EVT, 4> ValueVTs, MemVTs; 1899 SmallVector<uint64_t, 4> Offsets; 1900 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1901 &Offsets); 1902 unsigned NumValues = ValueVTs.size(); 1903 1904 SmallVector<SDValue, 4> Chains(NumValues); 1905 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1906 for (unsigned i = 0; i != NumValues; ++i) { 1907 // An aggregate return value cannot wrap around the address space, so 1908 // offsets to its parts don't wrap either. 1909 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1910 TypeSize::Fixed(Offsets[i])); 1911 1912 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1913 if (MemVTs[i] != ValueVTs[i]) 1914 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1915 Chains[i] = DAG.getStore( 1916 Chain, getCurSDLoc(), Val, 1917 // FIXME: better loc info would be nice. 1918 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1919 commonAlignment(BaseAlign, Offsets[i])); 1920 } 1921 1922 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1923 MVT::Other, Chains); 1924 } else if (I.getNumOperands() != 0) { 1925 SmallVector<EVT, 4> ValueVTs; 1926 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1927 unsigned NumValues = ValueVTs.size(); 1928 if (NumValues) { 1929 SDValue RetOp = getValue(I.getOperand(0)); 1930 1931 const Function *F = I.getParent()->getParent(); 1932 1933 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1934 I.getOperand(0)->getType(), F->getCallingConv(), 1935 /*IsVarArg*/ false); 1936 1937 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1938 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1939 Attribute::SExt)) 1940 ExtendKind = ISD::SIGN_EXTEND; 1941 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1942 Attribute::ZExt)) 1943 ExtendKind = ISD::ZERO_EXTEND; 1944 1945 LLVMContext &Context = F->getContext(); 1946 bool RetInReg = F->getAttributes().hasAttribute( 1947 AttributeList::ReturnIndex, Attribute::InReg); 1948 1949 for (unsigned j = 0; j != NumValues; ++j) { 1950 EVT VT = ValueVTs[j]; 1951 1952 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1953 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1954 1955 CallingConv::ID CC = F->getCallingConv(); 1956 1957 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1958 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1959 SmallVector<SDValue, 4> Parts(NumParts); 1960 getCopyToParts(DAG, getCurSDLoc(), 1961 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1962 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1963 1964 // 'inreg' on function refers to return value 1965 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1966 if (RetInReg) 1967 Flags.setInReg(); 1968 1969 if (I.getOperand(0)->getType()->isPointerTy()) { 1970 Flags.setPointer(); 1971 Flags.setPointerAddrSpace( 1972 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1973 } 1974 1975 if (NeedsRegBlock) { 1976 Flags.setInConsecutiveRegs(); 1977 if (j == NumValues - 1) 1978 Flags.setInConsecutiveRegsLast(); 1979 } 1980 1981 // Propagate extension type if any 1982 if (ExtendKind == ISD::SIGN_EXTEND) 1983 Flags.setSExt(); 1984 else if (ExtendKind == ISD::ZERO_EXTEND) 1985 Flags.setZExt(); 1986 1987 for (unsigned i = 0; i < NumParts; ++i) { 1988 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1989 VT, /*isfixed=*/true, 0, 0)); 1990 OutVals.push_back(Parts[i]); 1991 } 1992 } 1993 } 1994 } 1995 1996 // Push in swifterror virtual register as the last element of Outs. This makes 1997 // sure swifterror virtual register will be returned in the swifterror 1998 // physical register. 1999 const Function *F = I.getParent()->getParent(); 2000 if (TLI.supportSwiftError() && 2001 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2002 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2003 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2004 Flags.setSwiftError(); 2005 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 2006 EVT(TLI.getPointerTy(DL)) /*argvt*/, 2007 true /*isfixed*/, 1 /*origidx*/, 2008 0 /*partOffs*/)); 2009 // Create SDNode for the swifterror virtual register. 2010 OutVals.push_back( 2011 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2012 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2013 EVT(TLI.getPointerTy(DL)))); 2014 } 2015 2016 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2017 CallingConv::ID CallConv = 2018 DAG.getMachineFunction().getFunction().getCallingConv(); 2019 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2020 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2021 2022 // Verify that the target's LowerReturn behaved as expected. 2023 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2024 "LowerReturn didn't return a valid chain!"); 2025 2026 // Update the DAG with the new chain value resulting from return lowering. 2027 DAG.setRoot(Chain); 2028 } 2029 2030 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2031 /// created for it, emit nodes to copy the value into the virtual 2032 /// registers. 2033 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2034 // Skip empty types 2035 if (V->getType()->isEmptyTy()) 2036 return; 2037 2038 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2039 if (VMI != FuncInfo.ValueMap.end()) { 2040 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2041 CopyValueToVirtualRegister(V, VMI->second); 2042 } 2043 } 2044 2045 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2046 /// the current basic block, add it to ValueMap now so that we'll get a 2047 /// CopyTo/FromReg. 2048 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2049 // No need to export constants. 2050 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2051 2052 // Already exported? 2053 if (FuncInfo.isExportedInst(V)) return; 2054 2055 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2056 CopyValueToVirtualRegister(V, Reg); 2057 } 2058 2059 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2060 const BasicBlock *FromBB) { 2061 // The operands of the setcc have to be in this block. We don't know 2062 // how to export them from some other block. 2063 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2064 // Can export from current BB. 2065 if (VI->getParent() == FromBB) 2066 return true; 2067 2068 // Is already exported, noop. 2069 return FuncInfo.isExportedInst(V); 2070 } 2071 2072 // If this is an argument, we can export it if the BB is the entry block or 2073 // if it is already exported. 2074 if (isa<Argument>(V)) { 2075 if (FromBB->isEntryBlock()) 2076 return true; 2077 2078 // Otherwise, can only export this if it is already exported. 2079 return FuncInfo.isExportedInst(V); 2080 } 2081 2082 // Otherwise, constants can always be exported. 2083 return true; 2084 } 2085 2086 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2087 BranchProbability 2088 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2089 const MachineBasicBlock *Dst) const { 2090 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2091 const BasicBlock *SrcBB = Src->getBasicBlock(); 2092 const BasicBlock *DstBB = Dst->getBasicBlock(); 2093 if (!BPI) { 2094 // If BPI is not available, set the default probability as 1 / N, where N is 2095 // the number of successors. 2096 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2097 return BranchProbability(1, SuccSize); 2098 } 2099 return BPI->getEdgeProbability(SrcBB, DstBB); 2100 } 2101 2102 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2103 MachineBasicBlock *Dst, 2104 BranchProbability Prob) { 2105 if (!FuncInfo.BPI) 2106 Src->addSuccessorWithoutProb(Dst); 2107 else { 2108 if (Prob.isUnknown()) 2109 Prob = getEdgeProbability(Src, Dst); 2110 Src->addSuccessor(Dst, Prob); 2111 } 2112 } 2113 2114 static bool InBlock(const Value *V, const BasicBlock *BB) { 2115 if (const Instruction *I = dyn_cast<Instruction>(V)) 2116 return I->getParent() == BB; 2117 return true; 2118 } 2119 2120 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2121 /// This function emits a branch and is used at the leaves of an OR or an 2122 /// AND operator tree. 2123 void 2124 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2125 MachineBasicBlock *TBB, 2126 MachineBasicBlock *FBB, 2127 MachineBasicBlock *CurBB, 2128 MachineBasicBlock *SwitchBB, 2129 BranchProbability TProb, 2130 BranchProbability FProb, 2131 bool InvertCond) { 2132 const BasicBlock *BB = CurBB->getBasicBlock(); 2133 2134 // If the leaf of the tree is a comparison, merge the condition into 2135 // the caseblock. 2136 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2137 // The operands of the cmp have to be in this block. We don't know 2138 // how to export them from some other block. If this is the first block 2139 // of the sequence, no exporting is needed. 2140 if (CurBB == SwitchBB || 2141 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2142 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2143 ISD::CondCode Condition; 2144 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2145 ICmpInst::Predicate Pred = 2146 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2147 Condition = getICmpCondCode(Pred); 2148 } else { 2149 const FCmpInst *FC = cast<FCmpInst>(Cond); 2150 FCmpInst::Predicate Pred = 2151 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2152 Condition = getFCmpCondCode(Pred); 2153 if (TM.Options.NoNaNsFPMath) 2154 Condition = getFCmpCodeWithoutNaN(Condition); 2155 } 2156 2157 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2158 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2159 SL->SwitchCases.push_back(CB); 2160 return; 2161 } 2162 } 2163 2164 // Create a CaseBlock record representing this branch. 2165 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2166 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2167 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2168 SL->SwitchCases.push_back(CB); 2169 } 2170 2171 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2172 MachineBasicBlock *TBB, 2173 MachineBasicBlock *FBB, 2174 MachineBasicBlock *CurBB, 2175 MachineBasicBlock *SwitchBB, 2176 Instruction::BinaryOps Opc, 2177 BranchProbability TProb, 2178 BranchProbability FProb, 2179 bool InvertCond) { 2180 // Skip over not part of the tree and remember to invert op and operands at 2181 // next level. 2182 Value *NotCond; 2183 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2184 InBlock(NotCond, CurBB->getBasicBlock())) { 2185 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2186 !InvertCond); 2187 return; 2188 } 2189 2190 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2191 const Value *BOpOp0, *BOpOp1; 2192 // Compute the effective opcode for Cond, taking into account whether it needs 2193 // to be inverted, e.g. 2194 // and (not (or A, B)), C 2195 // gets lowered as 2196 // and (and (not A, not B), C) 2197 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2198 if (BOp) { 2199 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2200 ? Instruction::And 2201 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2202 ? Instruction::Or 2203 : (Instruction::BinaryOps)0); 2204 if (InvertCond) { 2205 if (BOpc == Instruction::And) 2206 BOpc = Instruction::Or; 2207 else if (BOpc == Instruction::Or) 2208 BOpc = Instruction::And; 2209 } 2210 } 2211 2212 // If this node is not part of the or/and tree, emit it as a branch. 2213 // Note that all nodes in the tree should have same opcode. 2214 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2215 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2216 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2217 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2218 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2219 TProb, FProb, InvertCond); 2220 return; 2221 } 2222 2223 // Create TmpBB after CurBB. 2224 MachineFunction::iterator BBI(CurBB); 2225 MachineFunction &MF = DAG.getMachineFunction(); 2226 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2227 CurBB->getParent()->insert(++BBI, TmpBB); 2228 2229 if (Opc == Instruction::Or) { 2230 // Codegen X | Y as: 2231 // BB1: 2232 // jmp_if_X TBB 2233 // jmp TmpBB 2234 // TmpBB: 2235 // jmp_if_Y TBB 2236 // jmp FBB 2237 // 2238 2239 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2240 // The requirement is that 2241 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2242 // = TrueProb for original BB. 2243 // Assuming the original probabilities are A and B, one choice is to set 2244 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2245 // A/(1+B) and 2B/(1+B). This choice assumes that 2246 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2247 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2248 // TmpBB, but the math is more complicated. 2249 2250 auto NewTrueProb = TProb / 2; 2251 auto NewFalseProb = TProb / 2 + FProb; 2252 // Emit the LHS condition. 2253 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2254 NewFalseProb, InvertCond); 2255 2256 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2257 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2258 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2259 // Emit the RHS condition into TmpBB. 2260 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2261 Probs[1], InvertCond); 2262 } else { 2263 assert(Opc == Instruction::And && "Unknown merge op!"); 2264 // Codegen X & Y as: 2265 // BB1: 2266 // jmp_if_X TmpBB 2267 // jmp FBB 2268 // TmpBB: 2269 // jmp_if_Y TBB 2270 // jmp FBB 2271 // 2272 // This requires creation of TmpBB after CurBB. 2273 2274 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2275 // The requirement is that 2276 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2277 // = FalseProb for original BB. 2278 // Assuming the original probabilities are A and B, one choice is to set 2279 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2280 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2281 // TrueProb for BB1 * FalseProb for TmpBB. 2282 2283 auto NewTrueProb = TProb + FProb / 2; 2284 auto NewFalseProb = FProb / 2; 2285 // Emit the LHS condition. 2286 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2287 NewFalseProb, InvertCond); 2288 2289 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2290 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2291 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2292 // Emit the RHS condition into TmpBB. 2293 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2294 Probs[1], InvertCond); 2295 } 2296 } 2297 2298 /// If the set of cases should be emitted as a series of branches, return true. 2299 /// If we should emit this as a bunch of and/or'd together conditions, return 2300 /// false. 2301 bool 2302 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2303 if (Cases.size() != 2) return true; 2304 2305 // If this is two comparisons of the same values or'd or and'd together, they 2306 // will get folded into a single comparison, so don't emit two blocks. 2307 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2308 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2309 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2310 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2311 return false; 2312 } 2313 2314 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2315 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2316 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2317 Cases[0].CC == Cases[1].CC && 2318 isa<Constant>(Cases[0].CmpRHS) && 2319 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2320 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2321 return false; 2322 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2323 return false; 2324 } 2325 2326 return true; 2327 } 2328 2329 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2330 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2331 2332 // Update machine-CFG edges. 2333 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2334 2335 if (I.isUnconditional()) { 2336 // Update machine-CFG edges. 2337 BrMBB->addSuccessor(Succ0MBB); 2338 2339 // If this is not a fall-through branch or optimizations are switched off, 2340 // emit the branch. 2341 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2342 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2343 MVT::Other, getControlRoot(), 2344 DAG.getBasicBlock(Succ0MBB))); 2345 2346 return; 2347 } 2348 2349 // If this condition is one of the special cases we handle, do special stuff 2350 // now. 2351 const Value *CondVal = I.getCondition(); 2352 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2353 2354 // If this is a series of conditions that are or'd or and'd together, emit 2355 // this as a sequence of branches instead of setcc's with and/or operations. 2356 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2357 // unpredictable branches, and vector extracts because those jumps are likely 2358 // expensive for any target), this should improve performance. 2359 // For example, instead of something like: 2360 // cmp A, B 2361 // C = seteq 2362 // cmp D, E 2363 // F = setle 2364 // or C, F 2365 // jnz foo 2366 // Emit: 2367 // cmp A, B 2368 // je foo 2369 // cmp D, E 2370 // jle foo 2371 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2372 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2373 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2374 Value *Vec; 2375 const Value *BOp0, *BOp1; 2376 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2377 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2378 Opcode = Instruction::And; 2379 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2380 Opcode = Instruction::Or; 2381 2382 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2383 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2384 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2385 getEdgeProbability(BrMBB, Succ0MBB), 2386 getEdgeProbability(BrMBB, Succ1MBB), 2387 /*InvertCond=*/false); 2388 // If the compares in later blocks need to use values not currently 2389 // exported from this block, export them now. This block should always 2390 // be the first entry. 2391 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2392 2393 // Allow some cases to be rejected. 2394 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2395 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2396 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2397 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2398 } 2399 2400 // Emit the branch for this block. 2401 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2402 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2403 return; 2404 } 2405 2406 // Okay, we decided not to do this, remove any inserted MBB's and clear 2407 // SwitchCases. 2408 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2409 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2410 2411 SL->SwitchCases.clear(); 2412 } 2413 } 2414 2415 // Create a CaseBlock record representing this branch. 2416 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2417 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2418 2419 // Use visitSwitchCase to actually insert the fast branch sequence for this 2420 // cond branch. 2421 visitSwitchCase(CB, BrMBB); 2422 } 2423 2424 /// visitSwitchCase - Emits the necessary code to represent a single node in 2425 /// the binary search tree resulting from lowering a switch instruction. 2426 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2427 MachineBasicBlock *SwitchBB) { 2428 SDValue Cond; 2429 SDValue CondLHS = getValue(CB.CmpLHS); 2430 SDLoc dl = CB.DL; 2431 2432 if (CB.CC == ISD::SETTRUE) { 2433 // Branch or fall through to TrueBB. 2434 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2435 SwitchBB->normalizeSuccProbs(); 2436 if (CB.TrueBB != NextBlock(SwitchBB)) { 2437 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2438 DAG.getBasicBlock(CB.TrueBB))); 2439 } 2440 return; 2441 } 2442 2443 auto &TLI = DAG.getTargetLoweringInfo(); 2444 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2445 2446 // Build the setcc now. 2447 if (!CB.CmpMHS) { 2448 // Fold "(X == true)" to X and "(X == false)" to !X to 2449 // handle common cases produced by branch lowering. 2450 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2451 CB.CC == ISD::SETEQ) 2452 Cond = CondLHS; 2453 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2454 CB.CC == ISD::SETEQ) { 2455 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2456 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2457 } else { 2458 SDValue CondRHS = getValue(CB.CmpRHS); 2459 2460 // If a pointer's DAG type is larger than its memory type then the DAG 2461 // values are zero-extended. This breaks signed comparisons so truncate 2462 // back to the underlying type before doing the compare. 2463 if (CondLHS.getValueType() != MemVT) { 2464 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2465 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2466 } 2467 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2468 } 2469 } else { 2470 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2471 2472 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2473 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2474 2475 SDValue CmpOp = getValue(CB.CmpMHS); 2476 EVT VT = CmpOp.getValueType(); 2477 2478 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2479 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2480 ISD::SETLE); 2481 } else { 2482 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2483 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2484 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2485 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2486 } 2487 } 2488 2489 // Update successor info 2490 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2491 // TrueBB and FalseBB are always different unless the incoming IR is 2492 // degenerate. This only happens when running llc on weird IR. 2493 if (CB.TrueBB != CB.FalseBB) 2494 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2495 SwitchBB->normalizeSuccProbs(); 2496 2497 // If the lhs block is the next block, invert the condition so that we can 2498 // fall through to the lhs instead of the rhs block. 2499 if (CB.TrueBB == NextBlock(SwitchBB)) { 2500 std::swap(CB.TrueBB, CB.FalseBB); 2501 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2502 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2503 } 2504 2505 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2506 MVT::Other, getControlRoot(), Cond, 2507 DAG.getBasicBlock(CB.TrueBB)); 2508 2509 // Insert the false branch. Do this even if it's a fall through branch, 2510 // this makes it easier to do DAG optimizations which require inverting 2511 // the branch condition. 2512 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2513 DAG.getBasicBlock(CB.FalseBB)); 2514 2515 DAG.setRoot(BrCond); 2516 } 2517 2518 /// visitJumpTable - Emit JumpTable node in the current MBB 2519 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2520 // Emit the code for the jump table 2521 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2522 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2523 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2524 JT.Reg, PTy); 2525 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2526 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2527 MVT::Other, Index.getValue(1), 2528 Table, Index); 2529 DAG.setRoot(BrJumpTable); 2530 } 2531 2532 /// visitJumpTableHeader - This function emits necessary code to produce index 2533 /// in the JumpTable from switch case. 2534 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2535 JumpTableHeader &JTH, 2536 MachineBasicBlock *SwitchBB) { 2537 SDLoc dl = getCurSDLoc(); 2538 2539 // Subtract the lowest switch case value from the value being switched on. 2540 SDValue SwitchOp = getValue(JTH.SValue); 2541 EVT VT = SwitchOp.getValueType(); 2542 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2543 DAG.getConstant(JTH.First, dl, VT)); 2544 2545 // The SDNode we just created, which holds the value being switched on minus 2546 // the smallest case value, needs to be copied to a virtual register so it 2547 // can be used as an index into the jump table in a subsequent basic block. 2548 // This value may be smaller or larger than the target's pointer type, and 2549 // therefore require extension or truncating. 2550 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2551 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2552 2553 unsigned JumpTableReg = 2554 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2555 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2556 JumpTableReg, SwitchOp); 2557 JT.Reg = JumpTableReg; 2558 2559 if (!JTH.OmitRangeCheck) { 2560 // Emit the range check for the jump table, and branch to the default block 2561 // for the switch statement if the value being switched on exceeds the 2562 // largest case in the switch. 2563 SDValue CMP = DAG.getSetCC( 2564 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2565 Sub.getValueType()), 2566 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2567 2568 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2569 MVT::Other, CopyTo, CMP, 2570 DAG.getBasicBlock(JT.Default)); 2571 2572 // Avoid emitting unnecessary branches to the next block. 2573 if (JT.MBB != NextBlock(SwitchBB)) 2574 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2575 DAG.getBasicBlock(JT.MBB)); 2576 2577 DAG.setRoot(BrCond); 2578 } else { 2579 // Avoid emitting unnecessary branches to the next block. 2580 if (JT.MBB != NextBlock(SwitchBB)) 2581 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2582 DAG.getBasicBlock(JT.MBB))); 2583 else 2584 DAG.setRoot(CopyTo); 2585 } 2586 } 2587 2588 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2589 /// variable if there exists one. 2590 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2591 SDValue &Chain) { 2592 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2593 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2594 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2595 MachineFunction &MF = DAG.getMachineFunction(); 2596 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2597 MachineSDNode *Node = 2598 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2599 if (Global) { 2600 MachinePointerInfo MPInfo(Global); 2601 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2602 MachineMemOperand::MODereferenceable; 2603 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2604 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2605 DAG.setNodeMemRefs(Node, {MemRef}); 2606 } 2607 if (PtrTy != PtrMemTy) 2608 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2609 return SDValue(Node, 0); 2610 } 2611 2612 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2613 /// tail spliced into a stack protector check success bb. 2614 /// 2615 /// For a high level explanation of how this fits into the stack protector 2616 /// generation see the comment on the declaration of class 2617 /// StackProtectorDescriptor. 2618 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2619 MachineBasicBlock *ParentBB) { 2620 2621 // First create the loads to the guard/stack slot for the comparison. 2622 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2623 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2624 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2625 2626 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2627 int FI = MFI.getStackProtectorIndex(); 2628 2629 SDValue Guard; 2630 SDLoc dl = getCurSDLoc(); 2631 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2632 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2633 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2634 2635 // Generate code to load the content of the guard slot. 2636 SDValue GuardVal = DAG.getLoad( 2637 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2638 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2639 MachineMemOperand::MOVolatile); 2640 2641 if (TLI.useStackGuardXorFP()) 2642 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2643 2644 // Retrieve guard check function, nullptr if instrumentation is inlined. 2645 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2646 // The target provides a guard check function to validate the guard value. 2647 // Generate a call to that function with the content of the guard slot as 2648 // argument. 2649 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2650 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2651 2652 TargetLowering::ArgListTy Args; 2653 TargetLowering::ArgListEntry Entry; 2654 Entry.Node = GuardVal; 2655 Entry.Ty = FnTy->getParamType(0); 2656 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2657 Entry.IsInReg = true; 2658 Args.push_back(Entry); 2659 2660 TargetLowering::CallLoweringInfo CLI(DAG); 2661 CLI.setDebugLoc(getCurSDLoc()) 2662 .setChain(DAG.getEntryNode()) 2663 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2664 getValue(GuardCheckFn), std::move(Args)); 2665 2666 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2667 DAG.setRoot(Result.second); 2668 return; 2669 } 2670 2671 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2672 // Otherwise, emit a volatile load to retrieve the stack guard value. 2673 SDValue Chain = DAG.getEntryNode(); 2674 if (TLI.useLoadStackGuardNode()) { 2675 Guard = getLoadStackGuard(DAG, dl, Chain); 2676 } else { 2677 const Value *IRGuard = TLI.getSDagStackGuard(M); 2678 SDValue GuardPtr = getValue(IRGuard); 2679 2680 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2681 MachinePointerInfo(IRGuard, 0), Align, 2682 MachineMemOperand::MOVolatile); 2683 } 2684 2685 // Perform the comparison via a getsetcc. 2686 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2687 *DAG.getContext(), 2688 Guard.getValueType()), 2689 Guard, GuardVal, ISD::SETNE); 2690 2691 // If the guard/stackslot do not equal, branch to failure MBB. 2692 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2693 MVT::Other, GuardVal.getOperand(0), 2694 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2695 // Otherwise branch to success MBB. 2696 SDValue Br = DAG.getNode(ISD::BR, dl, 2697 MVT::Other, BrCond, 2698 DAG.getBasicBlock(SPD.getSuccessMBB())); 2699 2700 DAG.setRoot(Br); 2701 } 2702 2703 /// Codegen the failure basic block for a stack protector check. 2704 /// 2705 /// A failure stack protector machine basic block consists simply of a call to 2706 /// __stack_chk_fail(). 2707 /// 2708 /// For a high level explanation of how this fits into the stack protector 2709 /// generation see the comment on the declaration of class 2710 /// StackProtectorDescriptor. 2711 void 2712 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2713 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2714 TargetLowering::MakeLibCallOptions CallOptions; 2715 CallOptions.setDiscardResult(true); 2716 SDValue Chain = 2717 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2718 None, CallOptions, getCurSDLoc()).second; 2719 // On PS4, the "return address" must still be within the calling function, 2720 // even if it's at the very end, so emit an explicit TRAP here. 2721 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2722 if (TM.getTargetTriple().isPS4CPU()) 2723 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2724 // WebAssembly needs an unreachable instruction after a non-returning call, 2725 // because the function return type can be different from __stack_chk_fail's 2726 // return type (void). 2727 if (TM.getTargetTriple().isWasm()) 2728 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2729 2730 DAG.setRoot(Chain); 2731 } 2732 2733 /// visitBitTestHeader - This function emits necessary code to produce value 2734 /// suitable for "bit tests" 2735 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2736 MachineBasicBlock *SwitchBB) { 2737 SDLoc dl = getCurSDLoc(); 2738 2739 // Subtract the minimum value. 2740 SDValue SwitchOp = getValue(B.SValue); 2741 EVT VT = SwitchOp.getValueType(); 2742 SDValue RangeSub = 2743 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2744 2745 // Determine the type of the test operands. 2746 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2747 bool UsePtrType = false; 2748 if (!TLI.isTypeLegal(VT)) { 2749 UsePtrType = true; 2750 } else { 2751 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2752 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2753 // Switch table case range are encoded into series of masks. 2754 // Just use pointer type, it's guaranteed to fit. 2755 UsePtrType = true; 2756 break; 2757 } 2758 } 2759 SDValue Sub = RangeSub; 2760 if (UsePtrType) { 2761 VT = TLI.getPointerTy(DAG.getDataLayout()); 2762 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2763 } 2764 2765 B.RegVT = VT.getSimpleVT(); 2766 B.Reg = FuncInfo.CreateReg(B.RegVT); 2767 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2768 2769 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2770 2771 if (!B.OmitRangeCheck) 2772 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2773 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2774 SwitchBB->normalizeSuccProbs(); 2775 2776 SDValue Root = CopyTo; 2777 if (!B.OmitRangeCheck) { 2778 // Conditional branch to the default block. 2779 SDValue RangeCmp = DAG.getSetCC(dl, 2780 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2781 RangeSub.getValueType()), 2782 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2783 ISD::SETUGT); 2784 2785 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2786 DAG.getBasicBlock(B.Default)); 2787 } 2788 2789 // Avoid emitting unnecessary branches to the next block. 2790 if (MBB != NextBlock(SwitchBB)) 2791 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2792 2793 DAG.setRoot(Root); 2794 } 2795 2796 /// visitBitTestCase - this function produces one "bit test" 2797 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2798 MachineBasicBlock* NextMBB, 2799 BranchProbability BranchProbToNext, 2800 unsigned Reg, 2801 BitTestCase &B, 2802 MachineBasicBlock *SwitchBB) { 2803 SDLoc dl = getCurSDLoc(); 2804 MVT VT = BB.RegVT; 2805 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2806 SDValue Cmp; 2807 unsigned PopCount = countPopulation(B.Mask); 2808 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2809 if (PopCount == 1) { 2810 // Testing for a single bit; just compare the shift count with what it 2811 // would need to be to shift a 1 bit in that position. 2812 Cmp = DAG.getSetCC( 2813 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2814 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2815 ISD::SETEQ); 2816 } else if (PopCount == BB.Range) { 2817 // There is only one zero bit in the range, test for it directly. 2818 Cmp = DAG.getSetCC( 2819 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2820 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2821 ISD::SETNE); 2822 } else { 2823 // Make desired shift 2824 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2825 DAG.getConstant(1, dl, VT), ShiftOp); 2826 2827 // Emit bit tests and jumps 2828 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2829 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2830 Cmp = DAG.getSetCC( 2831 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2832 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2833 } 2834 2835 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2836 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2837 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2838 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2839 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2840 // one as they are relative probabilities (and thus work more like weights), 2841 // and hence we need to normalize them to let the sum of them become one. 2842 SwitchBB->normalizeSuccProbs(); 2843 2844 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2845 MVT::Other, getControlRoot(), 2846 Cmp, DAG.getBasicBlock(B.TargetBB)); 2847 2848 // Avoid emitting unnecessary branches to the next block. 2849 if (NextMBB != NextBlock(SwitchBB)) 2850 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2851 DAG.getBasicBlock(NextMBB)); 2852 2853 DAG.setRoot(BrAnd); 2854 } 2855 2856 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2857 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2858 2859 // Retrieve successors. Look through artificial IR level blocks like 2860 // catchswitch for successors. 2861 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2862 const BasicBlock *EHPadBB = I.getSuccessor(1); 2863 2864 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2865 // have to do anything here to lower funclet bundles. 2866 assert(!I.hasOperandBundlesOtherThan( 2867 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2868 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2869 LLVMContext::OB_cfguardtarget, 2870 LLVMContext::OB_clang_arc_attachedcall}) && 2871 "Cannot lower invokes with arbitrary operand bundles yet!"); 2872 2873 const Value *Callee(I.getCalledOperand()); 2874 const Function *Fn = dyn_cast<Function>(Callee); 2875 if (isa<InlineAsm>(Callee)) 2876 visitInlineAsm(I, EHPadBB); 2877 else if (Fn && Fn->isIntrinsic()) { 2878 switch (Fn->getIntrinsicID()) { 2879 default: 2880 llvm_unreachable("Cannot invoke this intrinsic"); 2881 case Intrinsic::donothing: 2882 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2883 case Intrinsic::seh_try_begin: 2884 case Intrinsic::seh_scope_begin: 2885 case Intrinsic::seh_try_end: 2886 case Intrinsic::seh_scope_end: 2887 break; 2888 case Intrinsic::experimental_patchpoint_void: 2889 case Intrinsic::experimental_patchpoint_i64: 2890 visitPatchpoint(I, EHPadBB); 2891 break; 2892 case Intrinsic::experimental_gc_statepoint: 2893 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2894 break; 2895 case Intrinsic::wasm_rethrow: { 2896 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2897 // special because it can be invoked, so we manually lower it to a DAG 2898 // node here. 2899 SmallVector<SDValue, 8> Ops; 2900 Ops.push_back(getRoot()); // inchain 2901 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2902 Ops.push_back( 2903 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2904 TLI.getPointerTy(DAG.getDataLayout()))); 2905 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2906 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2907 break; 2908 } 2909 } 2910 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2911 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2912 // Eventually we will support lowering the @llvm.experimental.deoptimize 2913 // intrinsic, and right now there are no plans to support other intrinsics 2914 // with deopt state. 2915 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2916 } else { 2917 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2918 } 2919 2920 // If the value of the invoke is used outside of its defining block, make it 2921 // available as a virtual register. 2922 // We already took care of the exported value for the statepoint instruction 2923 // during call to the LowerStatepoint. 2924 if (!isa<GCStatepointInst>(I)) { 2925 CopyToExportRegsIfNeeded(&I); 2926 } 2927 2928 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2929 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2930 BranchProbability EHPadBBProb = 2931 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2932 : BranchProbability::getZero(); 2933 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2934 2935 // Update successor info. 2936 addSuccessorWithProb(InvokeMBB, Return); 2937 for (auto &UnwindDest : UnwindDests) { 2938 UnwindDest.first->setIsEHPad(); 2939 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2940 } 2941 InvokeMBB->normalizeSuccProbs(); 2942 2943 // Drop into normal successor. 2944 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2945 DAG.getBasicBlock(Return))); 2946 } 2947 2948 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2949 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2950 2951 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2952 // have to do anything here to lower funclet bundles. 2953 assert(!I.hasOperandBundlesOtherThan( 2954 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2955 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2956 2957 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2958 visitInlineAsm(I); 2959 CopyToExportRegsIfNeeded(&I); 2960 2961 // Retrieve successors. 2962 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2963 2964 // Update successor info. 2965 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2966 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2967 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2968 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2969 Target->setIsInlineAsmBrIndirectTarget(); 2970 } 2971 CallBrMBB->normalizeSuccProbs(); 2972 2973 // Drop into default successor. 2974 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2975 MVT::Other, getControlRoot(), 2976 DAG.getBasicBlock(Return))); 2977 } 2978 2979 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2980 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2981 } 2982 2983 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2984 assert(FuncInfo.MBB->isEHPad() && 2985 "Call to landingpad not in landing pad!"); 2986 2987 // If there aren't registers to copy the values into (e.g., during SjLj 2988 // exceptions), then don't bother to create these DAG nodes. 2989 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2990 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2991 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2992 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2993 return; 2994 2995 // If landingpad's return type is token type, we don't create DAG nodes 2996 // for its exception pointer and selector value. The extraction of exception 2997 // pointer or selector value from token type landingpads is not currently 2998 // supported. 2999 if (LP.getType()->isTokenTy()) 3000 return; 3001 3002 SmallVector<EVT, 2> ValueVTs; 3003 SDLoc dl = getCurSDLoc(); 3004 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3005 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3006 3007 // Get the two live-in registers as SDValues. The physregs have already been 3008 // copied into virtual registers. 3009 SDValue Ops[2]; 3010 if (FuncInfo.ExceptionPointerVirtReg) { 3011 Ops[0] = DAG.getZExtOrTrunc( 3012 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3013 FuncInfo.ExceptionPointerVirtReg, 3014 TLI.getPointerTy(DAG.getDataLayout())), 3015 dl, ValueVTs[0]); 3016 } else { 3017 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3018 } 3019 Ops[1] = DAG.getZExtOrTrunc( 3020 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3021 FuncInfo.ExceptionSelectorVirtReg, 3022 TLI.getPointerTy(DAG.getDataLayout())), 3023 dl, ValueVTs[1]); 3024 3025 // Merge into one. 3026 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3027 DAG.getVTList(ValueVTs), Ops); 3028 setValue(&LP, Res); 3029 } 3030 3031 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3032 MachineBasicBlock *Last) { 3033 // Update JTCases. 3034 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 3035 if (SL->JTCases[i].first.HeaderBB == First) 3036 SL->JTCases[i].first.HeaderBB = Last; 3037 3038 // Update BitTestCases. 3039 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 3040 if (SL->BitTestCases[i].Parent == First) 3041 SL->BitTestCases[i].Parent = Last; 3042 } 3043 3044 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3045 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3046 3047 // Update machine-CFG edges with unique successors. 3048 SmallSet<BasicBlock*, 32> Done; 3049 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3050 BasicBlock *BB = I.getSuccessor(i); 3051 bool Inserted = Done.insert(BB).second; 3052 if (!Inserted) 3053 continue; 3054 3055 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3056 addSuccessorWithProb(IndirectBrMBB, Succ); 3057 } 3058 IndirectBrMBB->normalizeSuccProbs(); 3059 3060 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3061 MVT::Other, getControlRoot(), 3062 getValue(I.getAddress()))); 3063 } 3064 3065 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3066 if (!DAG.getTarget().Options.TrapUnreachable) 3067 return; 3068 3069 // We may be able to ignore unreachable behind a noreturn call. 3070 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3071 const BasicBlock &BB = *I.getParent(); 3072 if (&I != &BB.front()) { 3073 BasicBlock::const_iterator PredI = 3074 std::prev(BasicBlock::const_iterator(&I)); 3075 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3076 if (Call->doesNotReturn()) 3077 return; 3078 } 3079 } 3080 } 3081 3082 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3083 } 3084 3085 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3086 SDNodeFlags Flags; 3087 3088 SDValue Op = getValue(I.getOperand(0)); 3089 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3090 Op, Flags); 3091 setValue(&I, UnNodeValue); 3092 } 3093 3094 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3095 SDNodeFlags Flags; 3096 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3097 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3098 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3099 } 3100 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3101 Flags.setExact(ExactOp->isExact()); 3102 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3103 Flags.copyFMF(*FPOp); 3104 3105 SDValue Op1 = getValue(I.getOperand(0)); 3106 SDValue Op2 = getValue(I.getOperand(1)); 3107 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3108 Op1, Op2, Flags); 3109 setValue(&I, BinNodeValue); 3110 } 3111 3112 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3113 SDValue Op1 = getValue(I.getOperand(0)); 3114 SDValue Op2 = getValue(I.getOperand(1)); 3115 3116 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3117 Op1.getValueType(), DAG.getDataLayout()); 3118 3119 // Coerce the shift amount to the right type if we can. 3120 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3121 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3122 unsigned Op2Size = Op2.getValueSizeInBits(); 3123 SDLoc DL = getCurSDLoc(); 3124 3125 // If the operand is smaller than the shift count type, promote it. 3126 if (ShiftSize > Op2Size) 3127 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3128 3129 // If the operand is larger than the shift count type but the shift 3130 // count type has enough bits to represent any shift value, truncate 3131 // it now. This is a common case and it exposes the truncate to 3132 // optimization early. 3133 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3134 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3135 // Otherwise we'll need to temporarily settle for some other convenient 3136 // type. Type legalization will make adjustments once the shiftee is split. 3137 else 3138 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3139 } 3140 3141 bool nuw = false; 3142 bool nsw = false; 3143 bool exact = false; 3144 3145 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3146 3147 if (const OverflowingBinaryOperator *OFBinOp = 3148 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3149 nuw = OFBinOp->hasNoUnsignedWrap(); 3150 nsw = OFBinOp->hasNoSignedWrap(); 3151 } 3152 if (const PossiblyExactOperator *ExactOp = 3153 dyn_cast<const PossiblyExactOperator>(&I)) 3154 exact = ExactOp->isExact(); 3155 } 3156 SDNodeFlags Flags; 3157 Flags.setExact(exact); 3158 Flags.setNoSignedWrap(nsw); 3159 Flags.setNoUnsignedWrap(nuw); 3160 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3161 Flags); 3162 setValue(&I, Res); 3163 } 3164 3165 void SelectionDAGBuilder::visitSDiv(const User &I) { 3166 SDValue Op1 = getValue(I.getOperand(0)); 3167 SDValue Op2 = getValue(I.getOperand(1)); 3168 3169 SDNodeFlags Flags; 3170 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3171 cast<PossiblyExactOperator>(&I)->isExact()); 3172 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3173 Op2, Flags)); 3174 } 3175 3176 void SelectionDAGBuilder::visitICmp(const User &I) { 3177 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3178 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3179 predicate = IC->getPredicate(); 3180 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3181 predicate = ICmpInst::Predicate(IC->getPredicate()); 3182 SDValue Op1 = getValue(I.getOperand(0)); 3183 SDValue Op2 = getValue(I.getOperand(1)); 3184 ISD::CondCode Opcode = getICmpCondCode(predicate); 3185 3186 auto &TLI = DAG.getTargetLoweringInfo(); 3187 EVT MemVT = 3188 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3189 3190 // If a pointer's DAG type is larger than its memory type then the DAG values 3191 // are zero-extended. This breaks signed comparisons so truncate back to the 3192 // underlying type before doing the compare. 3193 if (Op1.getValueType() != MemVT) { 3194 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3195 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3196 } 3197 3198 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3199 I.getType()); 3200 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3201 } 3202 3203 void SelectionDAGBuilder::visitFCmp(const User &I) { 3204 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3205 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3206 predicate = FC->getPredicate(); 3207 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3208 predicate = FCmpInst::Predicate(FC->getPredicate()); 3209 SDValue Op1 = getValue(I.getOperand(0)); 3210 SDValue Op2 = getValue(I.getOperand(1)); 3211 3212 ISD::CondCode Condition = getFCmpCondCode(predicate); 3213 auto *FPMO = cast<FPMathOperator>(&I); 3214 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3215 Condition = getFCmpCodeWithoutNaN(Condition); 3216 3217 SDNodeFlags Flags; 3218 Flags.copyFMF(*FPMO); 3219 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3220 3221 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3222 I.getType()); 3223 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3224 } 3225 3226 // Check if the condition of the select has one use or two users that are both 3227 // selects with the same condition. 3228 static bool hasOnlySelectUsers(const Value *Cond) { 3229 return llvm::all_of(Cond->users(), [](const Value *V) { 3230 return isa<SelectInst>(V); 3231 }); 3232 } 3233 3234 void SelectionDAGBuilder::visitSelect(const User &I) { 3235 SmallVector<EVT, 4> ValueVTs; 3236 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3237 ValueVTs); 3238 unsigned NumValues = ValueVTs.size(); 3239 if (NumValues == 0) return; 3240 3241 SmallVector<SDValue, 4> Values(NumValues); 3242 SDValue Cond = getValue(I.getOperand(0)); 3243 SDValue LHSVal = getValue(I.getOperand(1)); 3244 SDValue RHSVal = getValue(I.getOperand(2)); 3245 SmallVector<SDValue, 1> BaseOps(1, Cond); 3246 ISD::NodeType OpCode = 3247 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3248 3249 bool IsUnaryAbs = false; 3250 bool Negate = false; 3251 3252 SDNodeFlags Flags; 3253 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3254 Flags.copyFMF(*FPOp); 3255 3256 // Min/max matching is only viable if all output VTs are the same. 3257 if (is_splat(ValueVTs)) { 3258 EVT VT = ValueVTs[0]; 3259 LLVMContext &Ctx = *DAG.getContext(); 3260 auto &TLI = DAG.getTargetLoweringInfo(); 3261 3262 // We care about the legality of the operation after it has been type 3263 // legalized. 3264 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3265 VT = TLI.getTypeToTransformTo(Ctx, VT); 3266 3267 // If the vselect is legal, assume we want to leave this as a vector setcc + 3268 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3269 // min/max is legal on the scalar type. 3270 bool UseScalarMinMax = VT.isVector() && 3271 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3272 3273 Value *LHS, *RHS; 3274 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3275 ISD::NodeType Opc = ISD::DELETED_NODE; 3276 switch (SPR.Flavor) { 3277 case SPF_UMAX: Opc = ISD::UMAX; break; 3278 case SPF_UMIN: Opc = ISD::UMIN; break; 3279 case SPF_SMAX: Opc = ISD::SMAX; break; 3280 case SPF_SMIN: Opc = ISD::SMIN; break; 3281 case SPF_FMINNUM: 3282 switch (SPR.NaNBehavior) { 3283 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3284 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3285 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3286 case SPNB_RETURNS_ANY: { 3287 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3288 Opc = ISD::FMINNUM; 3289 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3290 Opc = ISD::FMINIMUM; 3291 else if (UseScalarMinMax) 3292 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3293 ISD::FMINNUM : ISD::FMINIMUM; 3294 break; 3295 } 3296 } 3297 break; 3298 case SPF_FMAXNUM: 3299 switch (SPR.NaNBehavior) { 3300 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3301 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3302 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3303 case SPNB_RETURNS_ANY: 3304 3305 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3306 Opc = ISD::FMAXNUM; 3307 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3308 Opc = ISD::FMAXIMUM; 3309 else if (UseScalarMinMax) 3310 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3311 ISD::FMAXNUM : ISD::FMAXIMUM; 3312 break; 3313 } 3314 break; 3315 case SPF_NABS: 3316 Negate = true; 3317 LLVM_FALLTHROUGH; 3318 case SPF_ABS: 3319 IsUnaryAbs = true; 3320 Opc = ISD::ABS; 3321 break; 3322 default: break; 3323 } 3324 3325 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3326 (TLI.isOperationLegalOrCustom(Opc, VT) || 3327 (UseScalarMinMax && 3328 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3329 // If the underlying comparison instruction is used by any other 3330 // instruction, the consumed instructions won't be destroyed, so it is 3331 // not profitable to convert to a min/max. 3332 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3333 OpCode = Opc; 3334 LHSVal = getValue(LHS); 3335 RHSVal = getValue(RHS); 3336 BaseOps.clear(); 3337 } 3338 3339 if (IsUnaryAbs) { 3340 OpCode = Opc; 3341 LHSVal = getValue(LHS); 3342 BaseOps.clear(); 3343 } 3344 } 3345 3346 if (IsUnaryAbs) { 3347 for (unsigned i = 0; i != NumValues; ++i) { 3348 SDLoc dl = getCurSDLoc(); 3349 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3350 Values[i] = 3351 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3352 if (Negate) 3353 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3354 Values[i]); 3355 } 3356 } else { 3357 for (unsigned i = 0; i != NumValues; ++i) { 3358 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3359 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3360 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3361 Values[i] = DAG.getNode( 3362 OpCode, getCurSDLoc(), 3363 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3364 } 3365 } 3366 3367 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3368 DAG.getVTList(ValueVTs), Values)); 3369 } 3370 3371 void SelectionDAGBuilder::visitTrunc(const User &I) { 3372 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3373 SDValue N = getValue(I.getOperand(0)); 3374 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3375 I.getType()); 3376 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3377 } 3378 3379 void SelectionDAGBuilder::visitZExt(const User &I) { 3380 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3381 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3382 SDValue N = getValue(I.getOperand(0)); 3383 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3384 I.getType()); 3385 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3386 } 3387 3388 void SelectionDAGBuilder::visitSExt(const User &I) { 3389 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3390 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3391 SDValue N = getValue(I.getOperand(0)); 3392 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3393 I.getType()); 3394 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3395 } 3396 3397 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3398 // FPTrunc is never a no-op cast, no need to check 3399 SDValue N = getValue(I.getOperand(0)); 3400 SDLoc dl = getCurSDLoc(); 3401 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3402 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3403 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3404 DAG.getTargetConstant( 3405 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3406 } 3407 3408 void SelectionDAGBuilder::visitFPExt(const User &I) { 3409 // FPExt is never a no-op cast, no need to check 3410 SDValue N = getValue(I.getOperand(0)); 3411 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3412 I.getType()); 3413 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3414 } 3415 3416 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3417 // FPToUI is never a no-op cast, no need to check 3418 SDValue N = getValue(I.getOperand(0)); 3419 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3420 I.getType()); 3421 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3422 } 3423 3424 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3425 // FPToSI is never a no-op cast, no need to check 3426 SDValue N = getValue(I.getOperand(0)); 3427 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3428 I.getType()); 3429 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3430 } 3431 3432 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3433 // UIToFP is never a no-op cast, no need to check 3434 SDValue N = getValue(I.getOperand(0)); 3435 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3436 I.getType()); 3437 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3438 } 3439 3440 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3441 // SIToFP is never a no-op cast, no need to check 3442 SDValue N = getValue(I.getOperand(0)); 3443 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3444 I.getType()); 3445 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3446 } 3447 3448 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3449 // What to do depends on the size of the integer and the size of the pointer. 3450 // We can either truncate, zero extend, or no-op, accordingly. 3451 SDValue N = getValue(I.getOperand(0)); 3452 auto &TLI = DAG.getTargetLoweringInfo(); 3453 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3454 I.getType()); 3455 EVT PtrMemVT = 3456 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3457 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3458 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3459 setValue(&I, N); 3460 } 3461 3462 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3463 // What to do depends on the size of the integer and the size of the pointer. 3464 // We can either truncate, zero extend, or no-op, accordingly. 3465 SDValue N = getValue(I.getOperand(0)); 3466 auto &TLI = DAG.getTargetLoweringInfo(); 3467 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3468 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3469 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3470 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3471 setValue(&I, N); 3472 } 3473 3474 void SelectionDAGBuilder::visitBitCast(const User &I) { 3475 SDValue N = getValue(I.getOperand(0)); 3476 SDLoc dl = getCurSDLoc(); 3477 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3478 I.getType()); 3479 3480 // BitCast assures us that source and destination are the same size so this is 3481 // either a BITCAST or a no-op. 3482 if (DestVT != N.getValueType()) 3483 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3484 DestVT, N)); // convert types. 3485 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3486 // might fold any kind of constant expression to an integer constant and that 3487 // is not what we are looking for. Only recognize a bitcast of a genuine 3488 // constant integer as an opaque constant. 3489 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3490 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3491 /*isOpaque*/true)); 3492 else 3493 setValue(&I, N); // noop cast. 3494 } 3495 3496 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3497 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3498 const Value *SV = I.getOperand(0); 3499 SDValue N = getValue(SV); 3500 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3501 3502 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3503 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3504 3505 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3506 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3507 3508 setValue(&I, N); 3509 } 3510 3511 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3512 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3513 SDValue InVec = getValue(I.getOperand(0)); 3514 SDValue InVal = getValue(I.getOperand(1)); 3515 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3516 TLI.getVectorIdxTy(DAG.getDataLayout())); 3517 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3518 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3519 InVec, InVal, InIdx)); 3520 } 3521 3522 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3523 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3524 SDValue InVec = getValue(I.getOperand(0)); 3525 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3526 TLI.getVectorIdxTy(DAG.getDataLayout())); 3527 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3528 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3529 InVec, InIdx)); 3530 } 3531 3532 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3533 SDValue Src1 = getValue(I.getOperand(0)); 3534 SDValue Src2 = getValue(I.getOperand(1)); 3535 ArrayRef<int> Mask; 3536 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3537 Mask = SVI->getShuffleMask(); 3538 else 3539 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3540 SDLoc DL = getCurSDLoc(); 3541 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3542 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3543 EVT SrcVT = Src1.getValueType(); 3544 3545 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3546 VT.isScalableVector()) { 3547 // Canonical splat form of first element of first input vector. 3548 SDValue FirstElt = 3549 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3550 DAG.getVectorIdxConstant(0, DL)); 3551 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3552 return; 3553 } 3554 3555 // For now, we only handle splats for scalable vectors. 3556 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3557 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3558 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3559 3560 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3561 unsigned MaskNumElts = Mask.size(); 3562 3563 if (SrcNumElts == MaskNumElts) { 3564 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3565 return; 3566 } 3567 3568 // Normalize the shuffle vector since mask and vector length don't match. 3569 if (SrcNumElts < MaskNumElts) { 3570 // Mask is longer than the source vectors. We can use concatenate vector to 3571 // make the mask and vectors lengths match. 3572 3573 if (MaskNumElts % SrcNumElts == 0) { 3574 // Mask length is a multiple of the source vector length. 3575 // Check if the shuffle is some kind of concatenation of the input 3576 // vectors. 3577 unsigned NumConcat = MaskNumElts / SrcNumElts; 3578 bool IsConcat = true; 3579 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3580 for (unsigned i = 0; i != MaskNumElts; ++i) { 3581 int Idx = Mask[i]; 3582 if (Idx < 0) 3583 continue; 3584 // Ensure the indices in each SrcVT sized piece are sequential and that 3585 // the same source is used for the whole piece. 3586 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3587 (ConcatSrcs[i / SrcNumElts] >= 0 && 3588 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3589 IsConcat = false; 3590 break; 3591 } 3592 // Remember which source this index came from. 3593 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3594 } 3595 3596 // The shuffle is concatenating multiple vectors together. Just emit 3597 // a CONCAT_VECTORS operation. 3598 if (IsConcat) { 3599 SmallVector<SDValue, 8> ConcatOps; 3600 for (auto Src : ConcatSrcs) { 3601 if (Src < 0) 3602 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3603 else if (Src == 0) 3604 ConcatOps.push_back(Src1); 3605 else 3606 ConcatOps.push_back(Src2); 3607 } 3608 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3609 return; 3610 } 3611 } 3612 3613 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3614 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3615 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3616 PaddedMaskNumElts); 3617 3618 // Pad both vectors with undefs to make them the same length as the mask. 3619 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3620 3621 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3622 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3623 MOps1[0] = Src1; 3624 MOps2[0] = Src2; 3625 3626 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3627 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3628 3629 // Readjust mask for new input vector length. 3630 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3631 for (unsigned i = 0; i != MaskNumElts; ++i) { 3632 int Idx = Mask[i]; 3633 if (Idx >= (int)SrcNumElts) 3634 Idx -= SrcNumElts - PaddedMaskNumElts; 3635 MappedOps[i] = Idx; 3636 } 3637 3638 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3639 3640 // If the concatenated vector was padded, extract a subvector with the 3641 // correct number of elements. 3642 if (MaskNumElts != PaddedMaskNumElts) 3643 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3644 DAG.getVectorIdxConstant(0, DL)); 3645 3646 setValue(&I, Result); 3647 return; 3648 } 3649 3650 if (SrcNumElts > MaskNumElts) { 3651 // Analyze the access pattern of the vector to see if we can extract 3652 // two subvectors and do the shuffle. 3653 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3654 bool CanExtract = true; 3655 for (int Idx : Mask) { 3656 unsigned Input = 0; 3657 if (Idx < 0) 3658 continue; 3659 3660 if (Idx >= (int)SrcNumElts) { 3661 Input = 1; 3662 Idx -= SrcNumElts; 3663 } 3664 3665 // If all the indices come from the same MaskNumElts sized portion of 3666 // the sources we can use extract. Also make sure the extract wouldn't 3667 // extract past the end of the source. 3668 int NewStartIdx = alignDown(Idx, MaskNumElts); 3669 if (NewStartIdx + MaskNumElts > SrcNumElts || 3670 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3671 CanExtract = false; 3672 // Make sure we always update StartIdx as we use it to track if all 3673 // elements are undef. 3674 StartIdx[Input] = NewStartIdx; 3675 } 3676 3677 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3678 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3679 return; 3680 } 3681 if (CanExtract) { 3682 // Extract appropriate subvector and generate a vector shuffle 3683 for (unsigned Input = 0; Input < 2; ++Input) { 3684 SDValue &Src = Input == 0 ? Src1 : Src2; 3685 if (StartIdx[Input] < 0) 3686 Src = DAG.getUNDEF(VT); 3687 else { 3688 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3689 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3690 } 3691 } 3692 3693 // Calculate new mask. 3694 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3695 for (int &Idx : MappedOps) { 3696 if (Idx >= (int)SrcNumElts) 3697 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3698 else if (Idx >= 0) 3699 Idx -= StartIdx[0]; 3700 } 3701 3702 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3703 return; 3704 } 3705 } 3706 3707 // We can't use either concat vectors or extract subvectors so fall back to 3708 // replacing the shuffle with extract and build vector. 3709 // to insert and build vector. 3710 EVT EltVT = VT.getVectorElementType(); 3711 SmallVector<SDValue,8> Ops; 3712 for (int Idx : Mask) { 3713 SDValue Res; 3714 3715 if (Idx < 0) { 3716 Res = DAG.getUNDEF(EltVT); 3717 } else { 3718 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3719 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3720 3721 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3722 DAG.getVectorIdxConstant(Idx, DL)); 3723 } 3724 3725 Ops.push_back(Res); 3726 } 3727 3728 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3729 } 3730 3731 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3732 ArrayRef<unsigned> Indices; 3733 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3734 Indices = IV->getIndices(); 3735 else 3736 Indices = cast<ConstantExpr>(&I)->getIndices(); 3737 3738 const Value *Op0 = I.getOperand(0); 3739 const Value *Op1 = I.getOperand(1); 3740 Type *AggTy = I.getType(); 3741 Type *ValTy = Op1->getType(); 3742 bool IntoUndef = isa<UndefValue>(Op0); 3743 bool FromUndef = isa<UndefValue>(Op1); 3744 3745 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3746 3747 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3748 SmallVector<EVT, 4> AggValueVTs; 3749 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3750 SmallVector<EVT, 4> ValValueVTs; 3751 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3752 3753 unsigned NumAggValues = AggValueVTs.size(); 3754 unsigned NumValValues = ValValueVTs.size(); 3755 SmallVector<SDValue, 4> Values(NumAggValues); 3756 3757 // Ignore an insertvalue that produces an empty object 3758 if (!NumAggValues) { 3759 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3760 return; 3761 } 3762 3763 SDValue Agg = getValue(Op0); 3764 unsigned i = 0; 3765 // Copy the beginning value(s) from the original aggregate. 3766 for (; i != LinearIndex; ++i) 3767 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3768 SDValue(Agg.getNode(), Agg.getResNo() + i); 3769 // Copy values from the inserted value(s). 3770 if (NumValValues) { 3771 SDValue Val = getValue(Op1); 3772 for (; i != LinearIndex + NumValValues; ++i) 3773 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3774 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3775 } 3776 // Copy remaining value(s) from the original aggregate. 3777 for (; i != NumAggValues; ++i) 3778 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3779 SDValue(Agg.getNode(), Agg.getResNo() + i); 3780 3781 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3782 DAG.getVTList(AggValueVTs), Values)); 3783 } 3784 3785 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3786 ArrayRef<unsigned> Indices; 3787 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3788 Indices = EV->getIndices(); 3789 else 3790 Indices = cast<ConstantExpr>(&I)->getIndices(); 3791 3792 const Value *Op0 = I.getOperand(0); 3793 Type *AggTy = Op0->getType(); 3794 Type *ValTy = I.getType(); 3795 bool OutOfUndef = isa<UndefValue>(Op0); 3796 3797 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3798 3799 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3800 SmallVector<EVT, 4> ValValueVTs; 3801 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3802 3803 unsigned NumValValues = ValValueVTs.size(); 3804 3805 // Ignore a extractvalue that produces an empty object 3806 if (!NumValValues) { 3807 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3808 return; 3809 } 3810 3811 SmallVector<SDValue, 4> Values(NumValValues); 3812 3813 SDValue Agg = getValue(Op0); 3814 // Copy out the selected value(s). 3815 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3816 Values[i - LinearIndex] = 3817 OutOfUndef ? 3818 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3819 SDValue(Agg.getNode(), Agg.getResNo() + i); 3820 3821 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3822 DAG.getVTList(ValValueVTs), Values)); 3823 } 3824 3825 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3826 Value *Op0 = I.getOperand(0); 3827 // Note that the pointer operand may be a vector of pointers. Take the scalar 3828 // element which holds a pointer. 3829 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3830 SDValue N = getValue(Op0); 3831 SDLoc dl = getCurSDLoc(); 3832 auto &TLI = DAG.getTargetLoweringInfo(); 3833 3834 // Normalize Vector GEP - all scalar operands should be converted to the 3835 // splat vector. 3836 bool IsVectorGEP = I.getType()->isVectorTy(); 3837 ElementCount VectorElementCount = 3838 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3839 : ElementCount::getFixed(0); 3840 3841 if (IsVectorGEP && !N.getValueType().isVector()) { 3842 LLVMContext &Context = *DAG.getContext(); 3843 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3844 if (VectorElementCount.isScalable()) 3845 N = DAG.getSplatVector(VT, dl, N); 3846 else 3847 N = DAG.getSplatBuildVector(VT, dl, N); 3848 } 3849 3850 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3851 GTI != E; ++GTI) { 3852 const Value *Idx = GTI.getOperand(); 3853 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3854 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3855 if (Field) { 3856 // N = N + Offset 3857 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3858 3859 // In an inbounds GEP with an offset that is nonnegative even when 3860 // interpreted as signed, assume there is no unsigned overflow. 3861 SDNodeFlags Flags; 3862 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3863 Flags.setNoUnsignedWrap(true); 3864 3865 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3866 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3867 } 3868 } else { 3869 // IdxSize is the width of the arithmetic according to IR semantics. 3870 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3871 // (and fix up the result later). 3872 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3873 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3874 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3875 // We intentionally mask away the high bits here; ElementSize may not 3876 // fit in IdxTy. 3877 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3878 bool ElementScalable = ElementSize.isScalable(); 3879 3880 // If this is a scalar constant or a splat vector of constants, 3881 // handle it quickly. 3882 const auto *C = dyn_cast<Constant>(Idx); 3883 if (C && isa<VectorType>(C->getType())) 3884 C = C->getSplatValue(); 3885 3886 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3887 if (CI && CI->isZero()) 3888 continue; 3889 if (CI && !ElementScalable) { 3890 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3891 LLVMContext &Context = *DAG.getContext(); 3892 SDValue OffsVal; 3893 if (IsVectorGEP) 3894 OffsVal = DAG.getConstant( 3895 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3896 else 3897 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3898 3899 // In an inbounds GEP with an offset that is nonnegative even when 3900 // interpreted as signed, assume there is no unsigned overflow. 3901 SDNodeFlags Flags; 3902 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3903 Flags.setNoUnsignedWrap(true); 3904 3905 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3906 3907 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3908 continue; 3909 } 3910 3911 // N = N + Idx * ElementMul; 3912 SDValue IdxN = getValue(Idx); 3913 3914 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3915 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3916 VectorElementCount); 3917 if (VectorElementCount.isScalable()) 3918 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3919 else 3920 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3921 } 3922 3923 // If the index is smaller or larger than intptr_t, truncate or extend 3924 // it. 3925 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3926 3927 if (ElementScalable) { 3928 EVT VScaleTy = N.getValueType().getScalarType(); 3929 SDValue VScale = DAG.getNode( 3930 ISD::VSCALE, dl, VScaleTy, 3931 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3932 if (IsVectorGEP) 3933 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3934 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3935 } else { 3936 // If this is a multiply by a power of two, turn it into a shl 3937 // immediately. This is a very common case. 3938 if (ElementMul != 1) { 3939 if (ElementMul.isPowerOf2()) { 3940 unsigned Amt = ElementMul.logBase2(); 3941 IdxN = DAG.getNode(ISD::SHL, dl, 3942 N.getValueType(), IdxN, 3943 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3944 } else { 3945 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3946 IdxN.getValueType()); 3947 IdxN = DAG.getNode(ISD::MUL, dl, 3948 N.getValueType(), IdxN, Scale); 3949 } 3950 } 3951 } 3952 3953 N = DAG.getNode(ISD::ADD, dl, 3954 N.getValueType(), N, IdxN); 3955 } 3956 } 3957 3958 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3959 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3960 if (IsVectorGEP) { 3961 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3962 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3963 } 3964 3965 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3966 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3967 3968 setValue(&I, N); 3969 } 3970 3971 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3972 // If this is a fixed sized alloca in the entry block of the function, 3973 // allocate it statically on the stack. 3974 if (FuncInfo.StaticAllocaMap.count(&I)) 3975 return; // getValue will auto-populate this. 3976 3977 SDLoc dl = getCurSDLoc(); 3978 Type *Ty = I.getAllocatedType(); 3979 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3980 auto &DL = DAG.getDataLayout(); 3981 uint64_t TySize = DL.getTypeAllocSize(Ty); 3982 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3983 3984 SDValue AllocSize = getValue(I.getArraySize()); 3985 3986 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3987 if (AllocSize.getValueType() != IntPtr) 3988 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3989 3990 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3991 AllocSize, 3992 DAG.getConstant(TySize, dl, IntPtr)); 3993 3994 // Handle alignment. If the requested alignment is less than or equal to 3995 // the stack alignment, ignore it. If the size is greater than or equal to 3996 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3997 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3998 if (*Alignment <= StackAlign) 3999 Alignment = None; 4000 4001 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4002 // Round the size of the allocation up to the stack alignment size 4003 // by add SA-1 to the size. This doesn't overflow because we're computing 4004 // an address inside an alloca. 4005 SDNodeFlags Flags; 4006 Flags.setNoUnsignedWrap(true); 4007 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4008 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4009 4010 // Mask out the low bits for alignment purposes. 4011 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4012 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4013 4014 SDValue Ops[] = { 4015 getRoot(), AllocSize, 4016 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4017 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4018 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4019 setValue(&I, DSA); 4020 DAG.setRoot(DSA.getValue(1)); 4021 4022 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4023 } 4024 4025 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4026 if (I.isAtomic()) 4027 return visitAtomicLoad(I); 4028 4029 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4030 const Value *SV = I.getOperand(0); 4031 if (TLI.supportSwiftError()) { 4032 // Swifterror values can come from either a function parameter with 4033 // swifterror attribute or an alloca with swifterror attribute. 4034 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4035 if (Arg->hasSwiftErrorAttr()) 4036 return visitLoadFromSwiftError(I); 4037 } 4038 4039 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4040 if (Alloca->isSwiftError()) 4041 return visitLoadFromSwiftError(I); 4042 } 4043 } 4044 4045 SDValue Ptr = getValue(SV); 4046 4047 Type *Ty = I.getType(); 4048 Align Alignment = I.getAlign(); 4049 4050 AAMDNodes AAInfo; 4051 I.getAAMetadata(AAInfo); 4052 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4053 4054 SmallVector<EVT, 4> ValueVTs, MemVTs; 4055 SmallVector<uint64_t, 4> Offsets; 4056 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4057 unsigned NumValues = ValueVTs.size(); 4058 if (NumValues == 0) 4059 return; 4060 4061 bool isVolatile = I.isVolatile(); 4062 4063 SDValue Root; 4064 bool ConstantMemory = false; 4065 if (isVolatile) 4066 // Serialize volatile loads with other side effects. 4067 Root = getRoot(); 4068 else if (NumValues > MaxParallelChains) 4069 Root = getMemoryRoot(); 4070 else if (AA && 4071 AA->pointsToConstantMemory(MemoryLocation( 4072 SV, 4073 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4074 AAInfo))) { 4075 // Do not serialize (non-volatile) loads of constant memory with anything. 4076 Root = DAG.getEntryNode(); 4077 ConstantMemory = true; 4078 } else { 4079 // Do not serialize non-volatile loads against each other. 4080 Root = DAG.getRoot(); 4081 } 4082 4083 SDLoc dl = getCurSDLoc(); 4084 4085 if (isVolatile) 4086 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4087 4088 // An aggregate load cannot wrap around the address space, so offsets to its 4089 // parts don't wrap either. 4090 SDNodeFlags Flags; 4091 Flags.setNoUnsignedWrap(true); 4092 4093 SmallVector<SDValue, 4> Values(NumValues); 4094 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4095 EVT PtrVT = Ptr.getValueType(); 4096 4097 MachineMemOperand::Flags MMOFlags 4098 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4099 4100 unsigned ChainI = 0; 4101 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4102 // Serializing loads here may result in excessive register pressure, and 4103 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4104 // could recover a bit by hoisting nodes upward in the chain by recognizing 4105 // they are side-effect free or do not alias. The optimizer should really 4106 // avoid this case by converting large object/array copies to llvm.memcpy 4107 // (MaxParallelChains should always remain as failsafe). 4108 if (ChainI == MaxParallelChains) { 4109 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4110 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4111 makeArrayRef(Chains.data(), ChainI)); 4112 Root = Chain; 4113 ChainI = 0; 4114 } 4115 SDValue A = DAG.getNode(ISD::ADD, dl, 4116 PtrVT, Ptr, 4117 DAG.getConstant(Offsets[i], dl, PtrVT), 4118 Flags); 4119 4120 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4121 MachinePointerInfo(SV, Offsets[i]), Alignment, 4122 MMOFlags, AAInfo, Ranges); 4123 Chains[ChainI] = L.getValue(1); 4124 4125 if (MemVTs[i] != ValueVTs[i]) 4126 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4127 4128 Values[i] = L; 4129 } 4130 4131 if (!ConstantMemory) { 4132 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4133 makeArrayRef(Chains.data(), ChainI)); 4134 if (isVolatile) 4135 DAG.setRoot(Chain); 4136 else 4137 PendingLoads.push_back(Chain); 4138 } 4139 4140 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4141 DAG.getVTList(ValueVTs), Values)); 4142 } 4143 4144 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4145 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4146 "call visitStoreToSwiftError when backend supports swifterror"); 4147 4148 SmallVector<EVT, 4> ValueVTs; 4149 SmallVector<uint64_t, 4> Offsets; 4150 const Value *SrcV = I.getOperand(0); 4151 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4152 SrcV->getType(), ValueVTs, &Offsets); 4153 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4154 "expect a single EVT for swifterror"); 4155 4156 SDValue Src = getValue(SrcV); 4157 // Create a virtual register, then update the virtual register. 4158 Register VReg = 4159 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4160 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4161 // Chain can be getRoot or getControlRoot. 4162 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4163 SDValue(Src.getNode(), Src.getResNo())); 4164 DAG.setRoot(CopyNode); 4165 } 4166 4167 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4168 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4169 "call visitLoadFromSwiftError when backend supports swifterror"); 4170 4171 assert(!I.isVolatile() && 4172 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4173 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4174 "Support volatile, non temporal, invariant for load_from_swift_error"); 4175 4176 const Value *SV = I.getOperand(0); 4177 Type *Ty = I.getType(); 4178 AAMDNodes AAInfo; 4179 I.getAAMetadata(AAInfo); 4180 assert( 4181 (!AA || 4182 !AA->pointsToConstantMemory(MemoryLocation( 4183 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4184 AAInfo))) && 4185 "load_from_swift_error should not be constant memory"); 4186 4187 SmallVector<EVT, 4> ValueVTs; 4188 SmallVector<uint64_t, 4> Offsets; 4189 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4190 ValueVTs, &Offsets); 4191 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4192 "expect a single EVT for swifterror"); 4193 4194 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4195 SDValue L = DAG.getCopyFromReg( 4196 getRoot(), getCurSDLoc(), 4197 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4198 4199 setValue(&I, L); 4200 } 4201 4202 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4203 if (I.isAtomic()) 4204 return visitAtomicStore(I); 4205 4206 const Value *SrcV = I.getOperand(0); 4207 const Value *PtrV = I.getOperand(1); 4208 4209 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4210 if (TLI.supportSwiftError()) { 4211 // Swifterror values can come from either a function parameter with 4212 // swifterror attribute or an alloca with swifterror attribute. 4213 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4214 if (Arg->hasSwiftErrorAttr()) 4215 return visitStoreToSwiftError(I); 4216 } 4217 4218 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4219 if (Alloca->isSwiftError()) 4220 return visitStoreToSwiftError(I); 4221 } 4222 } 4223 4224 SmallVector<EVT, 4> ValueVTs, MemVTs; 4225 SmallVector<uint64_t, 4> Offsets; 4226 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4227 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4228 unsigned NumValues = ValueVTs.size(); 4229 if (NumValues == 0) 4230 return; 4231 4232 // Get the lowered operands. Note that we do this after 4233 // checking if NumResults is zero, because with zero results 4234 // the operands won't have values in the map. 4235 SDValue Src = getValue(SrcV); 4236 SDValue Ptr = getValue(PtrV); 4237 4238 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4239 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4240 SDLoc dl = getCurSDLoc(); 4241 Align Alignment = I.getAlign(); 4242 AAMDNodes AAInfo; 4243 I.getAAMetadata(AAInfo); 4244 4245 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4246 4247 // An aggregate load cannot wrap around the address space, so offsets to its 4248 // parts don't wrap either. 4249 SDNodeFlags Flags; 4250 Flags.setNoUnsignedWrap(true); 4251 4252 unsigned ChainI = 0; 4253 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4254 // See visitLoad comments. 4255 if (ChainI == MaxParallelChains) { 4256 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4257 makeArrayRef(Chains.data(), ChainI)); 4258 Root = Chain; 4259 ChainI = 0; 4260 } 4261 SDValue Add = 4262 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4263 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4264 if (MemVTs[i] != ValueVTs[i]) 4265 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4266 SDValue St = 4267 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4268 Alignment, MMOFlags, AAInfo); 4269 Chains[ChainI] = St; 4270 } 4271 4272 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4273 makeArrayRef(Chains.data(), ChainI)); 4274 DAG.setRoot(StoreNode); 4275 } 4276 4277 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4278 bool IsCompressing) { 4279 SDLoc sdl = getCurSDLoc(); 4280 4281 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4282 MaybeAlign &Alignment) { 4283 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4284 Src0 = I.getArgOperand(0); 4285 Ptr = I.getArgOperand(1); 4286 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4287 Mask = I.getArgOperand(3); 4288 }; 4289 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4290 MaybeAlign &Alignment) { 4291 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4292 Src0 = I.getArgOperand(0); 4293 Ptr = I.getArgOperand(1); 4294 Mask = I.getArgOperand(2); 4295 Alignment = None; 4296 }; 4297 4298 Value *PtrOperand, *MaskOperand, *Src0Operand; 4299 MaybeAlign Alignment; 4300 if (IsCompressing) 4301 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4302 else 4303 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4304 4305 SDValue Ptr = getValue(PtrOperand); 4306 SDValue Src0 = getValue(Src0Operand); 4307 SDValue Mask = getValue(MaskOperand); 4308 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4309 4310 EVT VT = Src0.getValueType(); 4311 if (!Alignment) 4312 Alignment = DAG.getEVTAlign(VT); 4313 4314 AAMDNodes AAInfo; 4315 I.getAAMetadata(AAInfo); 4316 4317 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4318 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4319 // TODO: Make MachineMemOperands aware of scalable 4320 // vectors. 4321 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4322 SDValue StoreNode = 4323 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4324 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4325 DAG.setRoot(StoreNode); 4326 setValue(&I, StoreNode); 4327 } 4328 4329 // Get a uniform base for the Gather/Scatter intrinsic. 4330 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4331 // We try to represent it as a base pointer + vector of indices. 4332 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4333 // The first operand of the GEP may be a single pointer or a vector of pointers 4334 // Example: 4335 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4336 // or 4337 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4338 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4339 // 4340 // When the first GEP operand is a single pointer - it is the uniform base we 4341 // are looking for. If first operand of the GEP is a splat vector - we 4342 // extract the splat value and use it as a uniform base. 4343 // In all other cases the function returns 'false'. 4344 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4345 ISD::MemIndexType &IndexType, SDValue &Scale, 4346 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4347 SelectionDAG& DAG = SDB->DAG; 4348 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4349 const DataLayout &DL = DAG.getDataLayout(); 4350 4351 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4352 4353 // Handle splat constant pointer. 4354 if (auto *C = dyn_cast<Constant>(Ptr)) { 4355 C = C->getSplatValue(); 4356 if (!C) 4357 return false; 4358 4359 Base = SDB->getValue(C); 4360 4361 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4362 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4363 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4364 IndexType = ISD::SIGNED_SCALED; 4365 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4366 return true; 4367 } 4368 4369 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4370 if (!GEP || GEP->getParent() != CurBB) 4371 return false; 4372 4373 if (GEP->getNumOperands() != 2) 4374 return false; 4375 4376 const Value *BasePtr = GEP->getPointerOperand(); 4377 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4378 4379 // Make sure the base is scalar and the index is a vector. 4380 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4381 return false; 4382 4383 Base = SDB->getValue(BasePtr); 4384 Index = SDB->getValue(IndexVal); 4385 IndexType = ISD::SIGNED_SCALED; 4386 Scale = DAG.getTargetConstant( 4387 DL.getTypeAllocSize(GEP->getResultElementType()), 4388 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4389 return true; 4390 } 4391 4392 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4393 SDLoc sdl = getCurSDLoc(); 4394 4395 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4396 const Value *Ptr = I.getArgOperand(1); 4397 SDValue Src0 = getValue(I.getArgOperand(0)); 4398 SDValue Mask = getValue(I.getArgOperand(3)); 4399 EVT VT = Src0.getValueType(); 4400 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4401 ->getMaybeAlignValue() 4402 .getValueOr(DAG.getEVTAlign(VT)); 4403 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4404 4405 AAMDNodes AAInfo; 4406 I.getAAMetadata(AAInfo); 4407 4408 SDValue Base; 4409 SDValue Index; 4410 ISD::MemIndexType IndexType; 4411 SDValue Scale; 4412 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4413 I.getParent()); 4414 4415 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4416 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4417 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4418 // TODO: Make MachineMemOperands aware of scalable 4419 // vectors. 4420 MemoryLocation::UnknownSize, Alignment, AAInfo); 4421 if (!UniformBase) { 4422 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4423 Index = getValue(Ptr); 4424 IndexType = ISD::SIGNED_UNSCALED; 4425 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4426 } 4427 4428 EVT IdxVT = Index.getValueType(); 4429 EVT EltTy = IdxVT.getVectorElementType(); 4430 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4431 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4432 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4433 } 4434 4435 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4436 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4437 Ops, MMO, IndexType, false); 4438 DAG.setRoot(Scatter); 4439 setValue(&I, Scatter); 4440 } 4441 4442 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4443 SDLoc sdl = getCurSDLoc(); 4444 4445 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4446 MaybeAlign &Alignment) { 4447 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4448 Ptr = I.getArgOperand(0); 4449 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4450 Mask = I.getArgOperand(2); 4451 Src0 = I.getArgOperand(3); 4452 }; 4453 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4454 MaybeAlign &Alignment) { 4455 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4456 Ptr = I.getArgOperand(0); 4457 Alignment = None; 4458 Mask = I.getArgOperand(1); 4459 Src0 = I.getArgOperand(2); 4460 }; 4461 4462 Value *PtrOperand, *MaskOperand, *Src0Operand; 4463 MaybeAlign Alignment; 4464 if (IsExpanding) 4465 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4466 else 4467 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4468 4469 SDValue Ptr = getValue(PtrOperand); 4470 SDValue Src0 = getValue(Src0Operand); 4471 SDValue Mask = getValue(MaskOperand); 4472 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4473 4474 EVT VT = Src0.getValueType(); 4475 if (!Alignment) 4476 Alignment = DAG.getEVTAlign(VT); 4477 4478 AAMDNodes AAInfo; 4479 I.getAAMetadata(AAInfo); 4480 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4481 4482 // Do not serialize masked loads of constant memory with anything. 4483 MemoryLocation ML; 4484 if (VT.isScalableVector()) 4485 ML = MemoryLocation::getAfter(PtrOperand); 4486 else 4487 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4488 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4489 AAInfo); 4490 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4491 4492 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4493 4494 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4495 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4496 // TODO: Make MachineMemOperands aware of scalable 4497 // vectors. 4498 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4499 4500 SDValue Load = 4501 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4502 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4503 if (AddToChain) 4504 PendingLoads.push_back(Load.getValue(1)); 4505 setValue(&I, Load); 4506 } 4507 4508 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4509 SDLoc sdl = getCurSDLoc(); 4510 4511 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4512 const Value *Ptr = I.getArgOperand(0); 4513 SDValue Src0 = getValue(I.getArgOperand(3)); 4514 SDValue Mask = getValue(I.getArgOperand(2)); 4515 4516 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4517 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4518 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4519 ->getMaybeAlignValue() 4520 .getValueOr(DAG.getEVTAlign(VT)); 4521 4522 AAMDNodes AAInfo; 4523 I.getAAMetadata(AAInfo); 4524 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4525 4526 SDValue Root = DAG.getRoot(); 4527 SDValue Base; 4528 SDValue Index; 4529 ISD::MemIndexType IndexType; 4530 SDValue Scale; 4531 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4532 I.getParent()); 4533 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4534 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4535 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4536 // TODO: Make MachineMemOperands aware of scalable 4537 // vectors. 4538 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4539 4540 if (!UniformBase) { 4541 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4542 Index = getValue(Ptr); 4543 IndexType = ISD::SIGNED_UNSCALED; 4544 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4545 } 4546 4547 EVT IdxVT = Index.getValueType(); 4548 EVT EltTy = IdxVT.getVectorElementType(); 4549 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4550 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4551 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4552 } 4553 4554 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4555 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4556 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4557 4558 PendingLoads.push_back(Gather.getValue(1)); 4559 setValue(&I, Gather); 4560 } 4561 4562 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4563 SDLoc dl = getCurSDLoc(); 4564 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4565 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4566 SyncScope::ID SSID = I.getSyncScopeID(); 4567 4568 SDValue InChain = getRoot(); 4569 4570 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4571 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4572 4573 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4574 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4575 4576 MachineFunction &MF = DAG.getMachineFunction(); 4577 MachineMemOperand *MMO = MF.getMachineMemOperand( 4578 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4579 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4580 FailureOrdering); 4581 4582 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4583 dl, MemVT, VTs, InChain, 4584 getValue(I.getPointerOperand()), 4585 getValue(I.getCompareOperand()), 4586 getValue(I.getNewValOperand()), MMO); 4587 4588 SDValue OutChain = L.getValue(2); 4589 4590 setValue(&I, L); 4591 DAG.setRoot(OutChain); 4592 } 4593 4594 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4595 SDLoc dl = getCurSDLoc(); 4596 ISD::NodeType NT; 4597 switch (I.getOperation()) { 4598 default: llvm_unreachable("Unknown atomicrmw operation"); 4599 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4600 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4601 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4602 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4603 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4604 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4605 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4606 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4607 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4608 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4609 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4610 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4611 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4612 } 4613 AtomicOrdering Ordering = I.getOrdering(); 4614 SyncScope::ID SSID = I.getSyncScopeID(); 4615 4616 SDValue InChain = getRoot(); 4617 4618 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4619 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4620 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4621 4622 MachineFunction &MF = DAG.getMachineFunction(); 4623 MachineMemOperand *MMO = MF.getMachineMemOperand( 4624 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4625 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4626 4627 SDValue L = 4628 DAG.getAtomic(NT, dl, MemVT, InChain, 4629 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4630 MMO); 4631 4632 SDValue OutChain = L.getValue(1); 4633 4634 setValue(&I, L); 4635 DAG.setRoot(OutChain); 4636 } 4637 4638 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4639 SDLoc dl = getCurSDLoc(); 4640 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4641 SDValue Ops[3]; 4642 Ops[0] = getRoot(); 4643 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4644 TLI.getFenceOperandTy(DAG.getDataLayout())); 4645 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4646 TLI.getFenceOperandTy(DAG.getDataLayout())); 4647 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4648 } 4649 4650 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4651 SDLoc dl = getCurSDLoc(); 4652 AtomicOrdering Order = I.getOrdering(); 4653 SyncScope::ID SSID = I.getSyncScopeID(); 4654 4655 SDValue InChain = getRoot(); 4656 4657 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4658 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4659 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4660 4661 if (!TLI.supportsUnalignedAtomics() && 4662 I.getAlignment() < MemVT.getSizeInBits() / 8) 4663 report_fatal_error("Cannot generate unaligned atomic load"); 4664 4665 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4666 4667 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4668 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4669 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4670 4671 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4672 4673 SDValue Ptr = getValue(I.getPointerOperand()); 4674 4675 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4676 // TODO: Once this is better exercised by tests, it should be merged with 4677 // the normal path for loads to prevent future divergence. 4678 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4679 if (MemVT != VT) 4680 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4681 4682 setValue(&I, L); 4683 SDValue OutChain = L.getValue(1); 4684 if (!I.isUnordered()) 4685 DAG.setRoot(OutChain); 4686 else 4687 PendingLoads.push_back(OutChain); 4688 return; 4689 } 4690 4691 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4692 Ptr, MMO); 4693 4694 SDValue OutChain = L.getValue(1); 4695 if (MemVT != VT) 4696 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4697 4698 setValue(&I, L); 4699 DAG.setRoot(OutChain); 4700 } 4701 4702 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4703 SDLoc dl = getCurSDLoc(); 4704 4705 AtomicOrdering Ordering = I.getOrdering(); 4706 SyncScope::ID SSID = I.getSyncScopeID(); 4707 4708 SDValue InChain = getRoot(); 4709 4710 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4711 EVT MemVT = 4712 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4713 4714 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4715 report_fatal_error("Cannot generate unaligned atomic store"); 4716 4717 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4718 4719 MachineFunction &MF = DAG.getMachineFunction(); 4720 MachineMemOperand *MMO = MF.getMachineMemOperand( 4721 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4722 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4723 4724 SDValue Val = getValue(I.getValueOperand()); 4725 if (Val.getValueType() != MemVT) 4726 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4727 SDValue Ptr = getValue(I.getPointerOperand()); 4728 4729 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4730 // TODO: Once this is better exercised by tests, it should be merged with 4731 // the normal path for stores to prevent future divergence. 4732 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4733 DAG.setRoot(S); 4734 return; 4735 } 4736 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4737 Ptr, Val, MMO); 4738 4739 4740 DAG.setRoot(OutChain); 4741 } 4742 4743 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4744 /// node. 4745 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4746 unsigned Intrinsic) { 4747 // Ignore the callsite's attributes. A specific call site may be marked with 4748 // readnone, but the lowering code will expect the chain based on the 4749 // definition. 4750 const Function *F = I.getCalledFunction(); 4751 bool HasChain = !F->doesNotAccessMemory(); 4752 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4753 4754 // Build the operand list. 4755 SmallVector<SDValue, 8> Ops; 4756 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4757 if (OnlyLoad) { 4758 // We don't need to serialize loads against other loads. 4759 Ops.push_back(DAG.getRoot()); 4760 } else { 4761 Ops.push_back(getRoot()); 4762 } 4763 } 4764 4765 // Info is set by getTgtMemInstrinsic 4766 TargetLowering::IntrinsicInfo Info; 4767 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4768 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4769 DAG.getMachineFunction(), 4770 Intrinsic); 4771 4772 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4773 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4774 Info.opc == ISD::INTRINSIC_W_CHAIN) 4775 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4776 TLI.getPointerTy(DAG.getDataLayout()))); 4777 4778 // Add all operands of the call to the operand list. 4779 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4780 const Value *Arg = I.getArgOperand(i); 4781 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4782 Ops.push_back(getValue(Arg)); 4783 continue; 4784 } 4785 4786 // Use TargetConstant instead of a regular constant for immarg. 4787 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4788 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4789 assert(CI->getBitWidth() <= 64 && 4790 "large intrinsic immediates not handled"); 4791 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4792 } else { 4793 Ops.push_back( 4794 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4795 } 4796 } 4797 4798 SmallVector<EVT, 4> ValueVTs; 4799 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4800 4801 if (HasChain) 4802 ValueVTs.push_back(MVT::Other); 4803 4804 SDVTList VTs = DAG.getVTList(ValueVTs); 4805 4806 // Create the node. 4807 SDValue Result; 4808 if (IsTgtIntrinsic) { 4809 // This is target intrinsic that touches memory 4810 AAMDNodes AAInfo; 4811 I.getAAMetadata(AAInfo); 4812 Result = 4813 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4814 MachinePointerInfo(Info.ptrVal, Info.offset), 4815 Info.align, Info.flags, Info.size, AAInfo); 4816 } else if (!HasChain) { 4817 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4818 } else if (!I.getType()->isVoidTy()) { 4819 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4820 } else { 4821 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4822 } 4823 4824 if (HasChain) { 4825 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4826 if (OnlyLoad) 4827 PendingLoads.push_back(Chain); 4828 else 4829 DAG.setRoot(Chain); 4830 } 4831 4832 if (!I.getType()->isVoidTy()) { 4833 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4834 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4835 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4836 } else 4837 Result = lowerRangeToAssertZExt(DAG, I, Result); 4838 4839 MaybeAlign Alignment = I.getRetAlign(); 4840 if (!Alignment) 4841 Alignment = F->getAttributes().getRetAlignment(); 4842 // Insert `assertalign` node if there's an alignment. 4843 if (InsertAssertAlign && Alignment) { 4844 Result = 4845 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4846 } 4847 4848 setValue(&I, Result); 4849 } 4850 } 4851 4852 /// GetSignificand - Get the significand and build it into a floating-point 4853 /// number with exponent of 1: 4854 /// 4855 /// Op = (Op & 0x007fffff) | 0x3f800000; 4856 /// 4857 /// where Op is the hexadecimal representation of floating point value. 4858 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4859 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4860 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4861 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4862 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4863 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4864 } 4865 4866 /// GetExponent - Get the exponent: 4867 /// 4868 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4869 /// 4870 /// where Op is the hexadecimal representation of floating point value. 4871 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4872 const TargetLowering &TLI, const SDLoc &dl) { 4873 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4874 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4875 SDValue t1 = DAG.getNode( 4876 ISD::SRL, dl, MVT::i32, t0, 4877 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4878 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4879 DAG.getConstant(127, dl, MVT::i32)); 4880 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4881 } 4882 4883 /// getF32Constant - Get 32-bit floating point constant. 4884 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4885 const SDLoc &dl) { 4886 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4887 MVT::f32); 4888 } 4889 4890 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4891 SelectionDAG &DAG) { 4892 // TODO: What fast-math-flags should be set on the floating-point nodes? 4893 4894 // IntegerPartOfX = ((int32_t)(t0); 4895 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4896 4897 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4898 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4899 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4900 4901 // IntegerPartOfX <<= 23; 4902 IntegerPartOfX = DAG.getNode( 4903 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4904 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4905 DAG.getDataLayout()))); 4906 4907 SDValue TwoToFractionalPartOfX; 4908 if (LimitFloatPrecision <= 6) { 4909 // For floating-point precision of 6: 4910 // 4911 // TwoToFractionalPartOfX = 4912 // 0.997535578f + 4913 // (0.735607626f + 0.252464424f * x) * x; 4914 // 4915 // error 0.0144103317, which is 6 bits 4916 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4917 getF32Constant(DAG, 0x3e814304, dl)); 4918 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4919 getF32Constant(DAG, 0x3f3c50c8, dl)); 4920 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4921 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4922 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4923 } else if (LimitFloatPrecision <= 12) { 4924 // For floating-point precision of 12: 4925 // 4926 // TwoToFractionalPartOfX = 4927 // 0.999892986f + 4928 // (0.696457318f + 4929 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4930 // 4931 // error 0.000107046256, which is 13 to 14 bits 4932 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4933 getF32Constant(DAG, 0x3da235e3, dl)); 4934 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4935 getF32Constant(DAG, 0x3e65b8f3, dl)); 4936 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4937 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4938 getF32Constant(DAG, 0x3f324b07, dl)); 4939 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4940 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4941 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4942 } else { // LimitFloatPrecision <= 18 4943 // For floating-point precision of 18: 4944 // 4945 // TwoToFractionalPartOfX = 4946 // 0.999999982f + 4947 // (0.693148872f + 4948 // (0.240227044f + 4949 // (0.554906021e-1f + 4950 // (0.961591928e-2f + 4951 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4952 // error 2.47208000*10^(-7), which is better than 18 bits 4953 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4954 getF32Constant(DAG, 0x3924b03e, dl)); 4955 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4956 getF32Constant(DAG, 0x3ab24b87, dl)); 4957 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4958 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4959 getF32Constant(DAG, 0x3c1d8c17, dl)); 4960 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4961 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4962 getF32Constant(DAG, 0x3d634a1d, dl)); 4963 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4964 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4965 getF32Constant(DAG, 0x3e75fe14, dl)); 4966 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4967 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4968 getF32Constant(DAG, 0x3f317234, dl)); 4969 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4970 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4971 getF32Constant(DAG, 0x3f800000, dl)); 4972 } 4973 4974 // Add the exponent into the result in integer domain. 4975 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4976 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4977 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4978 } 4979 4980 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4981 /// limited-precision mode. 4982 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4983 const TargetLowering &TLI, SDNodeFlags Flags) { 4984 if (Op.getValueType() == MVT::f32 && 4985 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4986 4987 // Put the exponent in the right bit position for later addition to the 4988 // final result: 4989 // 4990 // t0 = Op * log2(e) 4991 4992 // TODO: What fast-math-flags should be set here? 4993 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4994 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4995 return getLimitedPrecisionExp2(t0, dl, DAG); 4996 } 4997 4998 // No special expansion. 4999 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5000 } 5001 5002 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5003 /// limited-precision mode. 5004 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5005 const TargetLowering &TLI, SDNodeFlags Flags) { 5006 // TODO: What fast-math-flags should be set on the floating-point nodes? 5007 5008 if (Op.getValueType() == MVT::f32 && 5009 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5010 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5011 5012 // Scale the exponent by log(2). 5013 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5014 SDValue LogOfExponent = 5015 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5016 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5017 5018 // Get the significand and build it into a floating-point number with 5019 // exponent of 1. 5020 SDValue X = GetSignificand(DAG, Op1, dl); 5021 5022 SDValue LogOfMantissa; 5023 if (LimitFloatPrecision <= 6) { 5024 // For floating-point precision of 6: 5025 // 5026 // LogofMantissa = 5027 // -1.1609546f + 5028 // (1.4034025f - 0.23903021f * x) * x; 5029 // 5030 // error 0.0034276066, which is better than 8 bits 5031 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5032 getF32Constant(DAG, 0xbe74c456, dl)); 5033 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5034 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5035 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5036 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5037 getF32Constant(DAG, 0x3f949a29, dl)); 5038 } else if (LimitFloatPrecision <= 12) { 5039 // For floating-point precision of 12: 5040 // 5041 // LogOfMantissa = 5042 // -1.7417939f + 5043 // (2.8212026f + 5044 // (-1.4699568f + 5045 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5046 // 5047 // error 0.000061011436, which is 14 bits 5048 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5049 getF32Constant(DAG, 0xbd67b6d6, dl)); 5050 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5051 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5052 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5053 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5054 getF32Constant(DAG, 0x3fbc278b, dl)); 5055 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5056 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5057 getF32Constant(DAG, 0x40348e95, dl)); 5058 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5059 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5060 getF32Constant(DAG, 0x3fdef31a, dl)); 5061 } else { // LimitFloatPrecision <= 18 5062 // For floating-point precision of 18: 5063 // 5064 // LogOfMantissa = 5065 // -2.1072184f + 5066 // (4.2372794f + 5067 // (-3.7029485f + 5068 // (2.2781945f + 5069 // (-0.87823314f + 5070 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5071 // 5072 // error 0.0000023660568, which is better than 18 bits 5073 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5074 getF32Constant(DAG, 0xbc91e5ac, dl)); 5075 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5076 getF32Constant(DAG, 0x3e4350aa, dl)); 5077 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5078 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5079 getF32Constant(DAG, 0x3f60d3e3, dl)); 5080 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5081 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5082 getF32Constant(DAG, 0x4011cdf0, dl)); 5083 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5084 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5085 getF32Constant(DAG, 0x406cfd1c, dl)); 5086 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5087 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5088 getF32Constant(DAG, 0x408797cb, dl)); 5089 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5090 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5091 getF32Constant(DAG, 0x4006dcab, dl)); 5092 } 5093 5094 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5095 } 5096 5097 // No special expansion. 5098 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5099 } 5100 5101 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5102 /// limited-precision mode. 5103 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5104 const TargetLowering &TLI, SDNodeFlags Flags) { 5105 // TODO: What fast-math-flags should be set on the floating-point nodes? 5106 5107 if (Op.getValueType() == MVT::f32 && 5108 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5109 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5110 5111 // Get the exponent. 5112 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5113 5114 // Get the significand and build it into a floating-point number with 5115 // exponent of 1. 5116 SDValue X = GetSignificand(DAG, Op1, dl); 5117 5118 // Different possible minimax approximations of significand in 5119 // floating-point for various degrees of accuracy over [1,2]. 5120 SDValue Log2ofMantissa; 5121 if (LimitFloatPrecision <= 6) { 5122 // For floating-point precision of 6: 5123 // 5124 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5125 // 5126 // error 0.0049451742, which is more than 7 bits 5127 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5128 getF32Constant(DAG, 0xbeb08fe0, dl)); 5129 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5130 getF32Constant(DAG, 0x40019463, dl)); 5131 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5132 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5133 getF32Constant(DAG, 0x3fd6633d, dl)); 5134 } else if (LimitFloatPrecision <= 12) { 5135 // For floating-point precision of 12: 5136 // 5137 // Log2ofMantissa = 5138 // -2.51285454f + 5139 // (4.07009056f + 5140 // (-2.12067489f + 5141 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5142 // 5143 // error 0.0000876136000, which is better than 13 bits 5144 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5145 getF32Constant(DAG, 0xbda7262e, dl)); 5146 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5147 getF32Constant(DAG, 0x3f25280b, dl)); 5148 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5149 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5150 getF32Constant(DAG, 0x4007b923, dl)); 5151 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5152 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5153 getF32Constant(DAG, 0x40823e2f, dl)); 5154 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5155 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5156 getF32Constant(DAG, 0x4020d29c, dl)); 5157 } else { // LimitFloatPrecision <= 18 5158 // For floating-point precision of 18: 5159 // 5160 // Log2ofMantissa = 5161 // -3.0400495f + 5162 // (6.1129976f + 5163 // (-5.3420409f + 5164 // (3.2865683f + 5165 // (-1.2669343f + 5166 // (0.27515199f - 5167 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5168 // 5169 // error 0.0000018516, which is better than 18 bits 5170 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5171 getF32Constant(DAG, 0xbcd2769e, dl)); 5172 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5173 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5174 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5175 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5176 getF32Constant(DAG, 0x3fa22ae7, dl)); 5177 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5178 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5179 getF32Constant(DAG, 0x40525723, dl)); 5180 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5181 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5182 getF32Constant(DAG, 0x40aaf200, dl)); 5183 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5184 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5185 getF32Constant(DAG, 0x40c39dad, dl)); 5186 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5187 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5188 getF32Constant(DAG, 0x4042902c, dl)); 5189 } 5190 5191 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5192 } 5193 5194 // No special expansion. 5195 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5196 } 5197 5198 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5199 /// limited-precision mode. 5200 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5201 const TargetLowering &TLI, SDNodeFlags Flags) { 5202 // TODO: What fast-math-flags should be set on the floating-point nodes? 5203 5204 if (Op.getValueType() == MVT::f32 && 5205 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5206 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5207 5208 // Scale the exponent by log10(2) [0.30102999f]. 5209 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5210 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5211 getF32Constant(DAG, 0x3e9a209a, dl)); 5212 5213 // Get the significand and build it into a floating-point number with 5214 // exponent of 1. 5215 SDValue X = GetSignificand(DAG, Op1, dl); 5216 5217 SDValue Log10ofMantissa; 5218 if (LimitFloatPrecision <= 6) { 5219 // For floating-point precision of 6: 5220 // 5221 // Log10ofMantissa = 5222 // -0.50419619f + 5223 // (0.60948995f - 0.10380950f * x) * x; 5224 // 5225 // error 0.0014886165, which is 6 bits 5226 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5227 getF32Constant(DAG, 0xbdd49a13, dl)); 5228 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5229 getF32Constant(DAG, 0x3f1c0789, dl)); 5230 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5231 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5232 getF32Constant(DAG, 0x3f011300, dl)); 5233 } else if (LimitFloatPrecision <= 12) { 5234 // For floating-point precision of 12: 5235 // 5236 // Log10ofMantissa = 5237 // -0.64831180f + 5238 // (0.91751397f + 5239 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5240 // 5241 // error 0.00019228036, which is better than 12 bits 5242 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5243 getF32Constant(DAG, 0x3d431f31, dl)); 5244 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5245 getF32Constant(DAG, 0x3ea21fb2, dl)); 5246 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5247 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5248 getF32Constant(DAG, 0x3f6ae232, dl)); 5249 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5250 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5251 getF32Constant(DAG, 0x3f25f7c3, dl)); 5252 } else { // LimitFloatPrecision <= 18 5253 // For floating-point precision of 18: 5254 // 5255 // Log10ofMantissa = 5256 // -0.84299375f + 5257 // (1.5327582f + 5258 // (-1.0688956f + 5259 // (0.49102474f + 5260 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5261 // 5262 // error 0.0000037995730, which is better than 18 bits 5263 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5264 getF32Constant(DAG, 0x3c5d51ce, dl)); 5265 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5266 getF32Constant(DAG, 0x3e00685a, dl)); 5267 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5268 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5269 getF32Constant(DAG, 0x3efb6798, dl)); 5270 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5271 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5272 getF32Constant(DAG, 0x3f88d192, dl)); 5273 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5274 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5275 getF32Constant(DAG, 0x3fc4316c, dl)); 5276 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5277 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5278 getF32Constant(DAG, 0x3f57ce70, dl)); 5279 } 5280 5281 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5282 } 5283 5284 // No special expansion. 5285 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5286 } 5287 5288 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5289 /// limited-precision mode. 5290 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5291 const TargetLowering &TLI, SDNodeFlags Flags) { 5292 if (Op.getValueType() == MVT::f32 && 5293 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5294 return getLimitedPrecisionExp2(Op, dl, DAG); 5295 5296 // No special expansion. 5297 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5298 } 5299 5300 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5301 /// limited-precision mode with x == 10.0f. 5302 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5303 SelectionDAG &DAG, const TargetLowering &TLI, 5304 SDNodeFlags Flags) { 5305 bool IsExp10 = false; 5306 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5307 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5308 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5309 APFloat Ten(10.0f); 5310 IsExp10 = LHSC->isExactlyValue(Ten); 5311 } 5312 } 5313 5314 // TODO: What fast-math-flags should be set on the FMUL node? 5315 if (IsExp10) { 5316 // Put the exponent in the right bit position for later addition to the 5317 // final result: 5318 // 5319 // #define LOG2OF10 3.3219281f 5320 // t0 = Op * LOG2OF10; 5321 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5322 getF32Constant(DAG, 0x40549a78, dl)); 5323 return getLimitedPrecisionExp2(t0, dl, DAG); 5324 } 5325 5326 // No special expansion. 5327 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5328 } 5329 5330 /// ExpandPowI - Expand a llvm.powi intrinsic. 5331 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5332 SelectionDAG &DAG) { 5333 // If RHS is a constant, we can expand this out to a multiplication tree, 5334 // otherwise we end up lowering to a call to __powidf2 (for example). When 5335 // optimizing for size, we only want to do this if the expansion would produce 5336 // a small number of multiplies, otherwise we do the full expansion. 5337 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5338 // Get the exponent as a positive value. 5339 unsigned Val = RHSC->getSExtValue(); 5340 if ((int)Val < 0) Val = -Val; 5341 5342 // powi(x, 0) -> 1.0 5343 if (Val == 0) 5344 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5345 5346 bool OptForSize = DAG.shouldOptForSize(); 5347 if (!OptForSize || 5348 // If optimizing for size, don't insert too many multiplies. 5349 // This inserts up to 5 multiplies. 5350 countPopulation(Val) + Log2_32(Val) < 7) { 5351 // We use the simple binary decomposition method to generate the multiply 5352 // sequence. There are more optimal ways to do this (for example, 5353 // powi(x,15) generates one more multiply than it should), but this has 5354 // the benefit of being both really simple and much better than a libcall. 5355 SDValue Res; // Logically starts equal to 1.0 5356 SDValue CurSquare = LHS; 5357 // TODO: Intrinsics should have fast-math-flags that propagate to these 5358 // nodes. 5359 while (Val) { 5360 if (Val & 1) { 5361 if (Res.getNode()) 5362 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5363 else 5364 Res = CurSquare; // 1.0*CurSquare. 5365 } 5366 5367 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5368 CurSquare, CurSquare); 5369 Val >>= 1; 5370 } 5371 5372 // If the original was negative, invert the result, producing 1/(x*x*x). 5373 if (RHSC->getSExtValue() < 0) 5374 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5375 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5376 return Res; 5377 } 5378 } 5379 5380 // Otherwise, expand to a libcall. 5381 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5382 } 5383 5384 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5385 SDValue LHS, SDValue RHS, SDValue Scale, 5386 SelectionDAG &DAG, const TargetLowering &TLI) { 5387 EVT VT = LHS.getValueType(); 5388 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5389 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5390 LLVMContext &Ctx = *DAG.getContext(); 5391 5392 // If the type is legal but the operation isn't, this node might survive all 5393 // the way to operation legalization. If we end up there and we do not have 5394 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5395 // node. 5396 5397 // Coax the legalizer into expanding the node during type legalization instead 5398 // by bumping the size by one bit. This will force it to Promote, enabling the 5399 // early expansion and avoiding the need to expand later. 5400 5401 // We don't have to do this if Scale is 0; that can always be expanded, unless 5402 // it's a saturating signed operation. Those can experience true integer 5403 // division overflow, a case which we must avoid. 5404 5405 // FIXME: We wouldn't have to do this (or any of the early 5406 // expansion/promotion) if it was possible to expand a libcall of an 5407 // illegal type during operation legalization. But it's not, so things 5408 // get a bit hacky. 5409 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5410 if ((ScaleInt > 0 || (Saturating && Signed)) && 5411 (TLI.isTypeLegal(VT) || 5412 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5413 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5414 Opcode, VT, ScaleInt); 5415 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5416 EVT PromVT; 5417 if (VT.isScalarInteger()) 5418 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5419 else if (VT.isVector()) { 5420 PromVT = VT.getVectorElementType(); 5421 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5422 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5423 } else 5424 llvm_unreachable("Wrong VT for DIVFIX?"); 5425 if (Signed) { 5426 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5427 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5428 } else { 5429 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5430 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5431 } 5432 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5433 // For saturating operations, we need to shift up the LHS to get the 5434 // proper saturation width, and then shift down again afterwards. 5435 if (Saturating) 5436 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5437 DAG.getConstant(1, DL, ShiftTy)); 5438 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5439 if (Saturating) 5440 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5441 DAG.getConstant(1, DL, ShiftTy)); 5442 return DAG.getZExtOrTrunc(Res, DL, VT); 5443 } 5444 } 5445 5446 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5447 } 5448 5449 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5450 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5451 static void 5452 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5453 const SDValue &N) { 5454 switch (N.getOpcode()) { 5455 case ISD::CopyFromReg: { 5456 SDValue Op = N.getOperand(1); 5457 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5458 Op.getValueType().getSizeInBits()); 5459 return; 5460 } 5461 case ISD::BITCAST: 5462 case ISD::AssertZext: 5463 case ISD::AssertSext: 5464 case ISD::TRUNCATE: 5465 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5466 return; 5467 case ISD::BUILD_PAIR: 5468 case ISD::BUILD_VECTOR: 5469 case ISD::CONCAT_VECTORS: 5470 for (SDValue Op : N->op_values()) 5471 getUnderlyingArgRegs(Regs, Op); 5472 return; 5473 default: 5474 return; 5475 } 5476 } 5477 5478 /// If the DbgValueInst is a dbg_value of a function argument, create the 5479 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5480 /// instruction selection, they will be inserted to the entry BB. 5481 /// We don't currently support this for variadic dbg_values, as they shouldn't 5482 /// appear for function arguments or in the prologue. 5483 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5484 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5485 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5486 const Argument *Arg = dyn_cast<Argument>(V); 5487 if (!Arg) 5488 return false; 5489 5490 if (!IsDbgDeclare) { 5491 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5492 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5493 // the entry block. 5494 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5495 if (!IsInEntryBlock) 5496 return false; 5497 5498 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5499 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5500 // variable that also is a param. 5501 // 5502 // Although, if we are at the top of the entry block already, we can still 5503 // emit using ArgDbgValue. This might catch some situations when the 5504 // dbg.value refers to an argument that isn't used in the entry block, so 5505 // any CopyToReg node would be optimized out and the only way to express 5506 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5507 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5508 // we should only emit as ArgDbgValue if the Variable is an argument to the 5509 // current function, and the dbg.value intrinsic is found in the entry 5510 // block. 5511 bool VariableIsFunctionInputArg = Variable->isParameter() && 5512 !DL->getInlinedAt(); 5513 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5514 if (!IsInPrologue && !VariableIsFunctionInputArg) 5515 return false; 5516 5517 // Here we assume that a function argument on IR level only can be used to 5518 // describe one input parameter on source level. If we for example have 5519 // source code like this 5520 // 5521 // struct A { long x, y; }; 5522 // void foo(struct A a, long b) { 5523 // ... 5524 // b = a.x; 5525 // ... 5526 // } 5527 // 5528 // and IR like this 5529 // 5530 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5531 // entry: 5532 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5533 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5534 // call void @llvm.dbg.value(metadata i32 %b, "b", 5535 // ... 5536 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5537 // ... 5538 // 5539 // then the last dbg.value is describing a parameter "b" using a value that 5540 // is an argument. But since we already has used %a1 to describe a parameter 5541 // we should not handle that last dbg.value here (that would result in an 5542 // incorrect hoisting of the DBG_VALUE to the function entry). 5543 // Notice that we allow one dbg.value per IR level argument, to accommodate 5544 // for the situation with fragments above. 5545 if (VariableIsFunctionInputArg) { 5546 unsigned ArgNo = Arg->getArgNo(); 5547 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5548 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5549 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5550 return false; 5551 FuncInfo.DescribedArgs.set(ArgNo); 5552 } 5553 } 5554 5555 MachineFunction &MF = DAG.getMachineFunction(); 5556 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5557 5558 bool IsIndirect = false; 5559 Optional<MachineOperand> Op; 5560 // Some arguments' frame index is recorded during argument lowering. 5561 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5562 if (FI != std::numeric_limits<int>::max()) 5563 Op = MachineOperand::CreateFI(FI); 5564 5565 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5566 if (!Op && N.getNode()) { 5567 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5568 Register Reg; 5569 if (ArgRegsAndSizes.size() == 1) 5570 Reg = ArgRegsAndSizes.front().first; 5571 5572 if (Reg && Reg.isVirtual()) { 5573 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5574 Register PR = RegInfo.getLiveInPhysReg(Reg); 5575 if (PR) 5576 Reg = PR; 5577 } 5578 if (Reg) { 5579 Op = MachineOperand::CreateReg(Reg, false); 5580 IsIndirect = IsDbgDeclare; 5581 } 5582 } 5583 5584 if (!Op && N.getNode()) { 5585 // Check if frame index is available. 5586 SDValue LCandidate = peekThroughBitcasts(N); 5587 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5588 if (FrameIndexSDNode *FINode = 5589 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5590 Op = MachineOperand::CreateFI(FINode->getIndex()); 5591 } 5592 5593 if (!Op) { 5594 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5595 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5596 SplitRegs) { 5597 unsigned Offset = 0; 5598 for (auto RegAndSize : SplitRegs) { 5599 // If the expression is already a fragment, the current register 5600 // offset+size might extend beyond the fragment. In this case, only 5601 // the register bits that are inside the fragment are relevant. 5602 int RegFragmentSizeInBits = RegAndSize.second; 5603 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5604 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5605 // The register is entirely outside the expression fragment, 5606 // so is irrelevant for debug info. 5607 if (Offset >= ExprFragmentSizeInBits) 5608 break; 5609 // The register is partially outside the expression fragment, only 5610 // the low bits within the fragment are relevant for debug info. 5611 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5612 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5613 } 5614 } 5615 5616 auto FragmentExpr = DIExpression::createFragmentExpression( 5617 Expr, Offset, RegFragmentSizeInBits); 5618 Offset += RegAndSize.second; 5619 // If a valid fragment expression cannot be created, the variable's 5620 // correct value cannot be determined and so it is set as Undef. 5621 if (!FragmentExpr) { 5622 SDDbgValue *SDV = DAG.getConstantDbgValue( 5623 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5624 DAG.AddDbgValue(SDV, false); 5625 continue; 5626 } 5627 FuncInfo.ArgDbgValues.push_back( 5628 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5629 RegAndSize.first, Variable, *FragmentExpr)); 5630 } 5631 }; 5632 5633 // Check if ValueMap has reg number. 5634 DenseMap<const Value *, Register>::const_iterator 5635 VMI = FuncInfo.ValueMap.find(V); 5636 if (VMI != FuncInfo.ValueMap.end()) { 5637 const auto &TLI = DAG.getTargetLoweringInfo(); 5638 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5639 V->getType(), None); 5640 if (RFV.occupiesMultipleRegs()) { 5641 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5642 return true; 5643 } 5644 5645 Op = MachineOperand::CreateReg(VMI->second, false); 5646 IsIndirect = IsDbgDeclare; 5647 } else if (ArgRegsAndSizes.size() > 1) { 5648 // This was split due to the calling convention, and no virtual register 5649 // mapping exists for the value. 5650 splitMultiRegDbgValue(ArgRegsAndSizes); 5651 return true; 5652 } 5653 } 5654 5655 if (!Op) 5656 return false; 5657 5658 assert(Variable->isValidLocationForIntrinsic(DL) && 5659 "Expected inlined-at fields to agree"); 5660 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5661 FuncInfo.ArgDbgValues.push_back( 5662 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5663 *Op, Variable, Expr)); 5664 5665 return true; 5666 } 5667 5668 /// Return the appropriate SDDbgValue based on N. 5669 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5670 DILocalVariable *Variable, 5671 DIExpression *Expr, 5672 const DebugLoc &dl, 5673 unsigned DbgSDNodeOrder) { 5674 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5675 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5676 // stack slot locations. 5677 // 5678 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5679 // debug values here after optimization: 5680 // 5681 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5682 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5683 // 5684 // Both describe the direct values of their associated variables. 5685 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5686 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5687 } 5688 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5689 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5690 } 5691 5692 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5693 switch (Intrinsic) { 5694 case Intrinsic::smul_fix: 5695 return ISD::SMULFIX; 5696 case Intrinsic::umul_fix: 5697 return ISD::UMULFIX; 5698 case Intrinsic::smul_fix_sat: 5699 return ISD::SMULFIXSAT; 5700 case Intrinsic::umul_fix_sat: 5701 return ISD::UMULFIXSAT; 5702 case Intrinsic::sdiv_fix: 5703 return ISD::SDIVFIX; 5704 case Intrinsic::udiv_fix: 5705 return ISD::UDIVFIX; 5706 case Intrinsic::sdiv_fix_sat: 5707 return ISD::SDIVFIXSAT; 5708 case Intrinsic::udiv_fix_sat: 5709 return ISD::UDIVFIXSAT; 5710 default: 5711 llvm_unreachable("Unhandled fixed point intrinsic"); 5712 } 5713 } 5714 5715 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5716 const char *FunctionName) { 5717 assert(FunctionName && "FunctionName must not be nullptr"); 5718 SDValue Callee = DAG.getExternalSymbol( 5719 FunctionName, 5720 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5721 LowerCallTo(I, Callee, I.isTailCall()); 5722 } 5723 5724 /// Given a @llvm.call.preallocated.setup, return the corresponding 5725 /// preallocated call. 5726 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5727 assert(cast<CallBase>(PreallocatedSetup) 5728 ->getCalledFunction() 5729 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5730 "expected call_preallocated_setup Value"); 5731 for (auto *U : PreallocatedSetup->users()) { 5732 auto *UseCall = cast<CallBase>(U); 5733 const Function *Fn = UseCall->getCalledFunction(); 5734 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5735 return UseCall; 5736 } 5737 } 5738 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5739 } 5740 5741 /// Lower the call to the specified intrinsic function. 5742 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5743 unsigned Intrinsic) { 5744 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5745 SDLoc sdl = getCurSDLoc(); 5746 DebugLoc dl = getCurDebugLoc(); 5747 SDValue Res; 5748 5749 SDNodeFlags Flags; 5750 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5751 Flags.copyFMF(*FPOp); 5752 5753 switch (Intrinsic) { 5754 default: 5755 // By default, turn this into a target intrinsic node. 5756 visitTargetIntrinsic(I, Intrinsic); 5757 return; 5758 case Intrinsic::vscale: { 5759 match(&I, m_VScale(DAG.getDataLayout())); 5760 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5761 setValue(&I, 5762 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5763 return; 5764 } 5765 case Intrinsic::vastart: visitVAStart(I); return; 5766 case Intrinsic::vaend: visitVAEnd(I); return; 5767 case Intrinsic::vacopy: visitVACopy(I); return; 5768 case Intrinsic::returnaddress: 5769 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5770 TLI.getPointerTy(DAG.getDataLayout()), 5771 getValue(I.getArgOperand(0)))); 5772 return; 5773 case Intrinsic::addressofreturnaddress: 5774 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5775 TLI.getPointerTy(DAG.getDataLayout()))); 5776 return; 5777 case Intrinsic::sponentry: 5778 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5779 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5780 return; 5781 case Intrinsic::frameaddress: 5782 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5783 TLI.getFrameIndexTy(DAG.getDataLayout()), 5784 getValue(I.getArgOperand(0)))); 5785 return; 5786 case Intrinsic::read_volatile_register: 5787 case Intrinsic::read_register: { 5788 Value *Reg = I.getArgOperand(0); 5789 SDValue Chain = getRoot(); 5790 SDValue RegName = 5791 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5792 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5793 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5794 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5795 setValue(&I, Res); 5796 DAG.setRoot(Res.getValue(1)); 5797 return; 5798 } 5799 case Intrinsic::write_register: { 5800 Value *Reg = I.getArgOperand(0); 5801 Value *RegValue = I.getArgOperand(1); 5802 SDValue Chain = getRoot(); 5803 SDValue RegName = 5804 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5805 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5806 RegName, getValue(RegValue))); 5807 return; 5808 } 5809 case Intrinsic::memcpy: { 5810 const auto &MCI = cast<MemCpyInst>(I); 5811 SDValue Op1 = getValue(I.getArgOperand(0)); 5812 SDValue Op2 = getValue(I.getArgOperand(1)); 5813 SDValue Op3 = getValue(I.getArgOperand(2)); 5814 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5815 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5816 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5817 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5818 bool isVol = MCI.isVolatile(); 5819 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5820 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5821 // node. 5822 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5823 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5824 /* AlwaysInline */ false, isTC, 5825 MachinePointerInfo(I.getArgOperand(0)), 5826 MachinePointerInfo(I.getArgOperand(1))); 5827 updateDAGForMaybeTailCall(MC); 5828 return; 5829 } 5830 case Intrinsic::memcpy_inline: { 5831 const auto &MCI = cast<MemCpyInlineInst>(I); 5832 SDValue Dst = getValue(I.getArgOperand(0)); 5833 SDValue Src = getValue(I.getArgOperand(1)); 5834 SDValue Size = getValue(I.getArgOperand(2)); 5835 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5836 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5837 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5838 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5839 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5840 bool isVol = MCI.isVolatile(); 5841 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5842 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5843 // node. 5844 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5845 /* AlwaysInline */ true, isTC, 5846 MachinePointerInfo(I.getArgOperand(0)), 5847 MachinePointerInfo(I.getArgOperand(1))); 5848 updateDAGForMaybeTailCall(MC); 5849 return; 5850 } 5851 case Intrinsic::memset: { 5852 const auto &MSI = cast<MemSetInst>(I); 5853 SDValue Op1 = getValue(I.getArgOperand(0)); 5854 SDValue Op2 = getValue(I.getArgOperand(1)); 5855 SDValue Op3 = getValue(I.getArgOperand(2)); 5856 // @llvm.memset defines 0 and 1 to both mean no alignment. 5857 Align Alignment = MSI.getDestAlign().valueOrOne(); 5858 bool isVol = MSI.isVolatile(); 5859 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5860 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5861 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5862 MachinePointerInfo(I.getArgOperand(0))); 5863 updateDAGForMaybeTailCall(MS); 5864 return; 5865 } 5866 case Intrinsic::memmove: { 5867 const auto &MMI = cast<MemMoveInst>(I); 5868 SDValue Op1 = getValue(I.getArgOperand(0)); 5869 SDValue Op2 = getValue(I.getArgOperand(1)); 5870 SDValue Op3 = getValue(I.getArgOperand(2)); 5871 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5872 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5873 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5874 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5875 bool isVol = MMI.isVolatile(); 5876 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5877 // FIXME: Support passing different dest/src alignments to the memmove DAG 5878 // node. 5879 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5880 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5881 isTC, MachinePointerInfo(I.getArgOperand(0)), 5882 MachinePointerInfo(I.getArgOperand(1))); 5883 updateDAGForMaybeTailCall(MM); 5884 return; 5885 } 5886 case Intrinsic::memcpy_element_unordered_atomic: { 5887 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5888 SDValue Dst = getValue(MI.getRawDest()); 5889 SDValue Src = getValue(MI.getRawSource()); 5890 SDValue Length = getValue(MI.getLength()); 5891 5892 unsigned DstAlign = MI.getDestAlignment(); 5893 unsigned SrcAlign = MI.getSourceAlignment(); 5894 Type *LengthTy = MI.getLength()->getType(); 5895 unsigned ElemSz = MI.getElementSizeInBytes(); 5896 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5897 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5898 SrcAlign, Length, LengthTy, ElemSz, isTC, 5899 MachinePointerInfo(MI.getRawDest()), 5900 MachinePointerInfo(MI.getRawSource())); 5901 updateDAGForMaybeTailCall(MC); 5902 return; 5903 } 5904 case Intrinsic::memmove_element_unordered_atomic: { 5905 auto &MI = cast<AtomicMemMoveInst>(I); 5906 SDValue Dst = getValue(MI.getRawDest()); 5907 SDValue Src = getValue(MI.getRawSource()); 5908 SDValue Length = getValue(MI.getLength()); 5909 5910 unsigned DstAlign = MI.getDestAlignment(); 5911 unsigned SrcAlign = MI.getSourceAlignment(); 5912 Type *LengthTy = MI.getLength()->getType(); 5913 unsigned ElemSz = MI.getElementSizeInBytes(); 5914 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5915 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5916 SrcAlign, Length, LengthTy, ElemSz, isTC, 5917 MachinePointerInfo(MI.getRawDest()), 5918 MachinePointerInfo(MI.getRawSource())); 5919 updateDAGForMaybeTailCall(MC); 5920 return; 5921 } 5922 case Intrinsic::memset_element_unordered_atomic: { 5923 auto &MI = cast<AtomicMemSetInst>(I); 5924 SDValue Dst = getValue(MI.getRawDest()); 5925 SDValue Val = getValue(MI.getValue()); 5926 SDValue Length = getValue(MI.getLength()); 5927 5928 unsigned DstAlign = MI.getDestAlignment(); 5929 Type *LengthTy = MI.getLength()->getType(); 5930 unsigned ElemSz = MI.getElementSizeInBytes(); 5931 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5932 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5933 LengthTy, ElemSz, isTC, 5934 MachinePointerInfo(MI.getRawDest())); 5935 updateDAGForMaybeTailCall(MC); 5936 return; 5937 } 5938 case Intrinsic::call_preallocated_setup: { 5939 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5940 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5941 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5942 getRoot(), SrcValue); 5943 setValue(&I, Res); 5944 DAG.setRoot(Res); 5945 return; 5946 } 5947 case Intrinsic::call_preallocated_arg: { 5948 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5949 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5950 SDValue Ops[3]; 5951 Ops[0] = getRoot(); 5952 Ops[1] = SrcValue; 5953 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5954 MVT::i32); // arg index 5955 SDValue Res = DAG.getNode( 5956 ISD::PREALLOCATED_ARG, sdl, 5957 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5958 setValue(&I, Res); 5959 DAG.setRoot(Res.getValue(1)); 5960 return; 5961 } 5962 case Intrinsic::dbg_addr: 5963 case Intrinsic::dbg_declare: { 5964 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 5965 // they are non-variadic. 5966 const auto &DI = cast<DbgVariableIntrinsic>(I); 5967 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 5968 DILocalVariable *Variable = DI.getVariable(); 5969 DIExpression *Expression = DI.getExpression(); 5970 dropDanglingDebugInfo(Variable, Expression); 5971 assert(Variable && "Missing variable"); 5972 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5973 << "\n"); 5974 // Check if address has undef value. 5975 const Value *Address = DI.getVariableLocationOp(0); 5976 if (!Address || isa<UndefValue>(Address) || 5977 (Address->use_empty() && !isa<Argument>(Address))) { 5978 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5979 << " (bad/undef/unused-arg address)\n"); 5980 return; 5981 } 5982 5983 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5984 5985 // Check if this variable can be described by a frame index, typically 5986 // either as a static alloca or a byval parameter. 5987 int FI = std::numeric_limits<int>::max(); 5988 if (const auto *AI = 5989 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5990 if (AI->isStaticAlloca()) { 5991 auto I = FuncInfo.StaticAllocaMap.find(AI); 5992 if (I != FuncInfo.StaticAllocaMap.end()) 5993 FI = I->second; 5994 } 5995 } else if (const auto *Arg = dyn_cast<Argument>( 5996 Address->stripInBoundsConstantOffsets())) { 5997 FI = FuncInfo.getArgumentFrameIndex(Arg); 5998 } 5999 6000 // llvm.dbg.addr is control dependent and always generates indirect 6001 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6002 // the MachineFunction variable table. 6003 if (FI != std::numeric_limits<int>::max()) { 6004 if (Intrinsic == Intrinsic::dbg_addr) { 6005 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6006 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6007 dl, SDNodeOrder); 6008 DAG.AddDbgValue(SDV, isParameter); 6009 } else { 6010 LLVM_DEBUG(dbgs() << "Skipping " << DI 6011 << " (variable info stashed in MF side table)\n"); 6012 } 6013 return; 6014 } 6015 6016 SDValue &N = NodeMap[Address]; 6017 if (!N.getNode() && isa<Argument>(Address)) 6018 // Check unused arguments map. 6019 N = UnusedArgNodeMap[Address]; 6020 SDDbgValue *SDV; 6021 if (N.getNode()) { 6022 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6023 Address = BCI->getOperand(0); 6024 // Parameters are handled specially. 6025 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6026 if (isParameter && FINode) { 6027 // Byval parameter. We have a frame index at this point. 6028 SDV = 6029 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6030 /*IsIndirect*/ true, dl, SDNodeOrder); 6031 } else if (isa<Argument>(Address)) { 6032 // Address is an argument, so try to emit its dbg value using 6033 // virtual register info from the FuncInfo.ValueMap. 6034 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6035 return; 6036 } else { 6037 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6038 true, dl, SDNodeOrder); 6039 } 6040 DAG.AddDbgValue(SDV, isParameter); 6041 } else { 6042 // If Address is an argument then try to emit its dbg value using 6043 // virtual register info from the FuncInfo.ValueMap. 6044 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6045 N)) { 6046 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6047 << " (could not emit func-arg dbg_value)\n"); 6048 } 6049 } 6050 return; 6051 } 6052 case Intrinsic::dbg_label: { 6053 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6054 DILabel *Label = DI.getLabel(); 6055 assert(Label && "Missing label"); 6056 6057 SDDbgLabel *SDV; 6058 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6059 DAG.AddDbgLabel(SDV); 6060 return; 6061 } 6062 case Intrinsic::dbg_value: { 6063 const DbgValueInst &DI = cast<DbgValueInst>(I); 6064 assert(DI.getVariable() && "Missing variable"); 6065 6066 DILocalVariable *Variable = DI.getVariable(); 6067 DIExpression *Expression = DI.getExpression(); 6068 dropDanglingDebugInfo(Variable, Expression); 6069 SmallVector<Value *, 4> Values(DI.getValues()); 6070 if (Values.empty()) 6071 return; 6072 6073 if (std::count(Values.begin(), Values.end(), nullptr)) 6074 return; 6075 6076 bool IsVariadic = DI.hasArgList(); 6077 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6078 SDNodeOrder, IsVariadic)) 6079 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6080 return; 6081 } 6082 6083 case Intrinsic::eh_typeid_for: { 6084 // Find the type id for the given typeinfo. 6085 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6086 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6087 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6088 setValue(&I, Res); 6089 return; 6090 } 6091 6092 case Intrinsic::eh_return_i32: 6093 case Intrinsic::eh_return_i64: 6094 DAG.getMachineFunction().setCallsEHReturn(true); 6095 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6096 MVT::Other, 6097 getControlRoot(), 6098 getValue(I.getArgOperand(0)), 6099 getValue(I.getArgOperand(1)))); 6100 return; 6101 case Intrinsic::eh_unwind_init: 6102 DAG.getMachineFunction().setCallsUnwindInit(true); 6103 return; 6104 case Intrinsic::eh_dwarf_cfa: 6105 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6106 TLI.getPointerTy(DAG.getDataLayout()), 6107 getValue(I.getArgOperand(0)))); 6108 return; 6109 case Intrinsic::eh_sjlj_callsite: { 6110 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6111 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6112 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6113 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6114 6115 MMI.setCurrentCallSite(CI->getZExtValue()); 6116 return; 6117 } 6118 case Intrinsic::eh_sjlj_functioncontext: { 6119 // Get and store the index of the function context. 6120 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6121 AllocaInst *FnCtx = 6122 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6123 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6124 MFI.setFunctionContextIndex(FI); 6125 return; 6126 } 6127 case Intrinsic::eh_sjlj_setjmp: { 6128 SDValue Ops[2]; 6129 Ops[0] = getRoot(); 6130 Ops[1] = getValue(I.getArgOperand(0)); 6131 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6132 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6133 setValue(&I, Op.getValue(0)); 6134 DAG.setRoot(Op.getValue(1)); 6135 return; 6136 } 6137 case Intrinsic::eh_sjlj_longjmp: 6138 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6139 getRoot(), getValue(I.getArgOperand(0)))); 6140 return; 6141 case Intrinsic::eh_sjlj_setup_dispatch: 6142 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6143 getRoot())); 6144 return; 6145 case Intrinsic::masked_gather: 6146 visitMaskedGather(I); 6147 return; 6148 case Intrinsic::masked_load: 6149 visitMaskedLoad(I); 6150 return; 6151 case Intrinsic::masked_scatter: 6152 visitMaskedScatter(I); 6153 return; 6154 case Intrinsic::masked_store: 6155 visitMaskedStore(I); 6156 return; 6157 case Intrinsic::masked_expandload: 6158 visitMaskedLoad(I, true /* IsExpanding */); 6159 return; 6160 case Intrinsic::masked_compressstore: 6161 visitMaskedStore(I, true /* IsCompressing */); 6162 return; 6163 case Intrinsic::powi: 6164 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6165 getValue(I.getArgOperand(1)), DAG)); 6166 return; 6167 case Intrinsic::log: 6168 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6169 return; 6170 case Intrinsic::log2: 6171 setValue(&I, 6172 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6173 return; 6174 case Intrinsic::log10: 6175 setValue(&I, 6176 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6177 return; 6178 case Intrinsic::exp: 6179 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6180 return; 6181 case Intrinsic::exp2: 6182 setValue(&I, 6183 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6184 return; 6185 case Intrinsic::pow: 6186 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6187 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6188 return; 6189 case Intrinsic::sqrt: 6190 case Intrinsic::fabs: 6191 case Intrinsic::sin: 6192 case Intrinsic::cos: 6193 case Intrinsic::floor: 6194 case Intrinsic::ceil: 6195 case Intrinsic::trunc: 6196 case Intrinsic::rint: 6197 case Intrinsic::nearbyint: 6198 case Intrinsic::round: 6199 case Intrinsic::roundeven: 6200 case Intrinsic::canonicalize: { 6201 unsigned Opcode; 6202 switch (Intrinsic) { 6203 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6204 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6205 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6206 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6207 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6208 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6209 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6210 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6211 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6212 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6213 case Intrinsic::round: Opcode = ISD::FROUND; break; 6214 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6215 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6216 } 6217 6218 setValue(&I, DAG.getNode(Opcode, sdl, 6219 getValue(I.getArgOperand(0)).getValueType(), 6220 getValue(I.getArgOperand(0)), Flags)); 6221 return; 6222 } 6223 case Intrinsic::lround: 6224 case Intrinsic::llround: 6225 case Intrinsic::lrint: 6226 case Intrinsic::llrint: { 6227 unsigned Opcode; 6228 switch (Intrinsic) { 6229 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6230 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6231 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6232 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6233 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6234 } 6235 6236 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6237 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6238 getValue(I.getArgOperand(0)))); 6239 return; 6240 } 6241 case Intrinsic::minnum: 6242 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6243 getValue(I.getArgOperand(0)).getValueType(), 6244 getValue(I.getArgOperand(0)), 6245 getValue(I.getArgOperand(1)), Flags)); 6246 return; 6247 case Intrinsic::maxnum: 6248 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6249 getValue(I.getArgOperand(0)).getValueType(), 6250 getValue(I.getArgOperand(0)), 6251 getValue(I.getArgOperand(1)), Flags)); 6252 return; 6253 case Intrinsic::minimum: 6254 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6255 getValue(I.getArgOperand(0)).getValueType(), 6256 getValue(I.getArgOperand(0)), 6257 getValue(I.getArgOperand(1)), Flags)); 6258 return; 6259 case Intrinsic::maximum: 6260 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6261 getValue(I.getArgOperand(0)).getValueType(), 6262 getValue(I.getArgOperand(0)), 6263 getValue(I.getArgOperand(1)), Flags)); 6264 return; 6265 case Intrinsic::copysign: 6266 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6267 getValue(I.getArgOperand(0)).getValueType(), 6268 getValue(I.getArgOperand(0)), 6269 getValue(I.getArgOperand(1)), Flags)); 6270 return; 6271 case Intrinsic::fma: 6272 setValue(&I, DAG.getNode( 6273 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6274 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6275 getValue(I.getArgOperand(2)), Flags)); 6276 return; 6277 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6278 case Intrinsic::INTRINSIC: 6279 #include "llvm/IR/ConstrainedOps.def" 6280 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6281 return; 6282 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6283 #include "llvm/IR/VPIntrinsics.def" 6284 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6285 return; 6286 case Intrinsic::fmuladd: { 6287 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6288 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6289 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6290 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6291 getValue(I.getArgOperand(0)).getValueType(), 6292 getValue(I.getArgOperand(0)), 6293 getValue(I.getArgOperand(1)), 6294 getValue(I.getArgOperand(2)), Flags)); 6295 } else { 6296 // TODO: Intrinsic calls should have fast-math-flags. 6297 SDValue Mul = DAG.getNode( 6298 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6299 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6300 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6301 getValue(I.getArgOperand(0)).getValueType(), 6302 Mul, getValue(I.getArgOperand(2)), Flags); 6303 setValue(&I, Add); 6304 } 6305 return; 6306 } 6307 case Intrinsic::convert_to_fp16: 6308 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6309 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6310 getValue(I.getArgOperand(0)), 6311 DAG.getTargetConstant(0, sdl, 6312 MVT::i32)))); 6313 return; 6314 case Intrinsic::convert_from_fp16: 6315 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6316 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6317 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6318 getValue(I.getArgOperand(0))))); 6319 return; 6320 case Intrinsic::fptosi_sat: { 6321 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6322 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6323 getValue(I.getArgOperand(0)), 6324 DAG.getValueType(VT.getScalarType()))); 6325 return; 6326 } 6327 case Intrinsic::fptoui_sat: { 6328 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6329 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6330 getValue(I.getArgOperand(0)), 6331 DAG.getValueType(VT.getScalarType()))); 6332 return; 6333 } 6334 case Intrinsic::set_rounding: 6335 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6336 {getRoot(), getValue(I.getArgOperand(0))}); 6337 setValue(&I, Res); 6338 DAG.setRoot(Res.getValue(0)); 6339 return; 6340 case Intrinsic::pcmarker: { 6341 SDValue Tmp = getValue(I.getArgOperand(0)); 6342 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6343 return; 6344 } 6345 case Intrinsic::readcyclecounter: { 6346 SDValue Op = getRoot(); 6347 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6348 DAG.getVTList(MVT::i64, MVT::Other), Op); 6349 setValue(&I, Res); 6350 DAG.setRoot(Res.getValue(1)); 6351 return; 6352 } 6353 case Intrinsic::bitreverse: 6354 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6355 getValue(I.getArgOperand(0)).getValueType(), 6356 getValue(I.getArgOperand(0)))); 6357 return; 6358 case Intrinsic::bswap: 6359 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6360 getValue(I.getArgOperand(0)).getValueType(), 6361 getValue(I.getArgOperand(0)))); 6362 return; 6363 case Intrinsic::cttz: { 6364 SDValue Arg = getValue(I.getArgOperand(0)); 6365 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6366 EVT Ty = Arg.getValueType(); 6367 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6368 sdl, Ty, Arg)); 6369 return; 6370 } 6371 case Intrinsic::ctlz: { 6372 SDValue Arg = getValue(I.getArgOperand(0)); 6373 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6374 EVT Ty = Arg.getValueType(); 6375 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6376 sdl, Ty, Arg)); 6377 return; 6378 } 6379 case Intrinsic::ctpop: { 6380 SDValue Arg = getValue(I.getArgOperand(0)); 6381 EVT Ty = Arg.getValueType(); 6382 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6383 return; 6384 } 6385 case Intrinsic::fshl: 6386 case Intrinsic::fshr: { 6387 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6388 SDValue X = getValue(I.getArgOperand(0)); 6389 SDValue Y = getValue(I.getArgOperand(1)); 6390 SDValue Z = getValue(I.getArgOperand(2)); 6391 EVT VT = X.getValueType(); 6392 6393 if (X == Y) { 6394 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6395 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6396 } else { 6397 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6398 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6399 } 6400 return; 6401 } 6402 case Intrinsic::sadd_sat: { 6403 SDValue Op1 = getValue(I.getArgOperand(0)); 6404 SDValue Op2 = getValue(I.getArgOperand(1)); 6405 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6406 return; 6407 } 6408 case Intrinsic::uadd_sat: { 6409 SDValue Op1 = getValue(I.getArgOperand(0)); 6410 SDValue Op2 = getValue(I.getArgOperand(1)); 6411 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6412 return; 6413 } 6414 case Intrinsic::ssub_sat: { 6415 SDValue Op1 = getValue(I.getArgOperand(0)); 6416 SDValue Op2 = getValue(I.getArgOperand(1)); 6417 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6418 return; 6419 } 6420 case Intrinsic::usub_sat: { 6421 SDValue Op1 = getValue(I.getArgOperand(0)); 6422 SDValue Op2 = getValue(I.getArgOperand(1)); 6423 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6424 return; 6425 } 6426 case Intrinsic::sshl_sat: { 6427 SDValue Op1 = getValue(I.getArgOperand(0)); 6428 SDValue Op2 = getValue(I.getArgOperand(1)); 6429 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6430 return; 6431 } 6432 case Intrinsic::ushl_sat: { 6433 SDValue Op1 = getValue(I.getArgOperand(0)); 6434 SDValue Op2 = getValue(I.getArgOperand(1)); 6435 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6436 return; 6437 } 6438 case Intrinsic::smul_fix: 6439 case Intrinsic::umul_fix: 6440 case Intrinsic::smul_fix_sat: 6441 case Intrinsic::umul_fix_sat: { 6442 SDValue Op1 = getValue(I.getArgOperand(0)); 6443 SDValue Op2 = getValue(I.getArgOperand(1)); 6444 SDValue Op3 = getValue(I.getArgOperand(2)); 6445 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6446 Op1.getValueType(), Op1, Op2, Op3)); 6447 return; 6448 } 6449 case Intrinsic::sdiv_fix: 6450 case Intrinsic::udiv_fix: 6451 case Intrinsic::sdiv_fix_sat: 6452 case Intrinsic::udiv_fix_sat: { 6453 SDValue Op1 = getValue(I.getArgOperand(0)); 6454 SDValue Op2 = getValue(I.getArgOperand(1)); 6455 SDValue Op3 = getValue(I.getArgOperand(2)); 6456 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6457 Op1, Op2, Op3, DAG, TLI)); 6458 return; 6459 } 6460 case Intrinsic::smax: { 6461 SDValue Op1 = getValue(I.getArgOperand(0)); 6462 SDValue Op2 = getValue(I.getArgOperand(1)); 6463 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6464 return; 6465 } 6466 case Intrinsic::smin: { 6467 SDValue Op1 = getValue(I.getArgOperand(0)); 6468 SDValue Op2 = getValue(I.getArgOperand(1)); 6469 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6470 return; 6471 } 6472 case Intrinsic::umax: { 6473 SDValue Op1 = getValue(I.getArgOperand(0)); 6474 SDValue Op2 = getValue(I.getArgOperand(1)); 6475 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6476 return; 6477 } 6478 case Intrinsic::umin: { 6479 SDValue Op1 = getValue(I.getArgOperand(0)); 6480 SDValue Op2 = getValue(I.getArgOperand(1)); 6481 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6482 return; 6483 } 6484 case Intrinsic::abs: { 6485 // TODO: Preserve "int min is poison" arg in SDAG? 6486 SDValue Op1 = getValue(I.getArgOperand(0)); 6487 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6488 return; 6489 } 6490 case Intrinsic::stacksave: { 6491 SDValue Op = getRoot(); 6492 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6493 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6494 setValue(&I, Res); 6495 DAG.setRoot(Res.getValue(1)); 6496 return; 6497 } 6498 case Intrinsic::stackrestore: 6499 Res = getValue(I.getArgOperand(0)); 6500 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6501 return; 6502 case Intrinsic::get_dynamic_area_offset: { 6503 SDValue Op = getRoot(); 6504 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6505 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6506 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6507 // target. 6508 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6509 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6510 " intrinsic!"); 6511 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6512 Op); 6513 DAG.setRoot(Op); 6514 setValue(&I, Res); 6515 return; 6516 } 6517 case Intrinsic::stackguard: { 6518 MachineFunction &MF = DAG.getMachineFunction(); 6519 const Module &M = *MF.getFunction().getParent(); 6520 SDValue Chain = getRoot(); 6521 if (TLI.useLoadStackGuardNode()) { 6522 Res = getLoadStackGuard(DAG, sdl, Chain); 6523 } else { 6524 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6525 const Value *Global = TLI.getSDagStackGuard(M); 6526 Align Align = DL->getPrefTypeAlign(Global->getType()); 6527 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6528 MachinePointerInfo(Global, 0), Align, 6529 MachineMemOperand::MOVolatile); 6530 } 6531 if (TLI.useStackGuardXorFP()) 6532 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6533 DAG.setRoot(Chain); 6534 setValue(&I, Res); 6535 return; 6536 } 6537 case Intrinsic::stackprotector: { 6538 // Emit code into the DAG to store the stack guard onto the stack. 6539 MachineFunction &MF = DAG.getMachineFunction(); 6540 MachineFrameInfo &MFI = MF.getFrameInfo(); 6541 SDValue Src, Chain = getRoot(); 6542 6543 if (TLI.useLoadStackGuardNode()) 6544 Src = getLoadStackGuard(DAG, sdl, Chain); 6545 else 6546 Src = getValue(I.getArgOperand(0)); // The guard's value. 6547 6548 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6549 6550 int FI = FuncInfo.StaticAllocaMap[Slot]; 6551 MFI.setStackProtectorIndex(FI); 6552 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6553 6554 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6555 6556 // Store the stack protector onto the stack. 6557 Res = DAG.getStore( 6558 Chain, sdl, Src, FIN, 6559 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6560 MaybeAlign(), MachineMemOperand::MOVolatile); 6561 setValue(&I, Res); 6562 DAG.setRoot(Res); 6563 return; 6564 } 6565 case Intrinsic::objectsize: 6566 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6567 6568 case Intrinsic::is_constant: 6569 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6570 6571 case Intrinsic::annotation: 6572 case Intrinsic::ptr_annotation: 6573 case Intrinsic::launder_invariant_group: 6574 case Intrinsic::strip_invariant_group: 6575 // Drop the intrinsic, but forward the value 6576 setValue(&I, getValue(I.getOperand(0))); 6577 return; 6578 6579 case Intrinsic::assume: 6580 case Intrinsic::experimental_noalias_scope_decl: 6581 case Intrinsic::var_annotation: 6582 case Intrinsic::sideeffect: 6583 // Discard annotate attributes, noalias scope declarations, assumptions, and 6584 // artificial side-effects. 6585 return; 6586 6587 case Intrinsic::codeview_annotation: { 6588 // Emit a label associated with this metadata. 6589 MachineFunction &MF = DAG.getMachineFunction(); 6590 MCSymbol *Label = 6591 MF.getMMI().getContext().createTempSymbol("annotation", true); 6592 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6593 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6594 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6595 DAG.setRoot(Res); 6596 return; 6597 } 6598 6599 case Intrinsic::init_trampoline: { 6600 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6601 6602 SDValue Ops[6]; 6603 Ops[0] = getRoot(); 6604 Ops[1] = getValue(I.getArgOperand(0)); 6605 Ops[2] = getValue(I.getArgOperand(1)); 6606 Ops[3] = getValue(I.getArgOperand(2)); 6607 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6608 Ops[5] = DAG.getSrcValue(F); 6609 6610 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6611 6612 DAG.setRoot(Res); 6613 return; 6614 } 6615 case Intrinsic::adjust_trampoline: 6616 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6617 TLI.getPointerTy(DAG.getDataLayout()), 6618 getValue(I.getArgOperand(0)))); 6619 return; 6620 case Intrinsic::gcroot: { 6621 assert(DAG.getMachineFunction().getFunction().hasGC() && 6622 "only valid in functions with gc specified, enforced by Verifier"); 6623 assert(GFI && "implied by previous"); 6624 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6625 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6626 6627 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6628 GFI->addStackRoot(FI->getIndex(), TypeMap); 6629 return; 6630 } 6631 case Intrinsic::gcread: 6632 case Intrinsic::gcwrite: 6633 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6634 case Intrinsic::flt_rounds: 6635 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6636 setValue(&I, Res); 6637 DAG.setRoot(Res.getValue(1)); 6638 return; 6639 6640 case Intrinsic::expect: 6641 // Just replace __builtin_expect(exp, c) with EXP. 6642 setValue(&I, getValue(I.getArgOperand(0))); 6643 return; 6644 6645 case Intrinsic::ubsantrap: 6646 case Intrinsic::debugtrap: 6647 case Intrinsic::trap: { 6648 StringRef TrapFuncName = 6649 I.getAttributes() 6650 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6651 .getValueAsString(); 6652 if (TrapFuncName.empty()) { 6653 switch (Intrinsic) { 6654 case Intrinsic::trap: 6655 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6656 break; 6657 case Intrinsic::debugtrap: 6658 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6659 break; 6660 case Intrinsic::ubsantrap: 6661 DAG.setRoot(DAG.getNode( 6662 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6663 DAG.getTargetConstant( 6664 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6665 MVT::i32))); 6666 break; 6667 default: llvm_unreachable("unknown trap intrinsic"); 6668 } 6669 return; 6670 } 6671 TargetLowering::ArgListTy Args; 6672 if (Intrinsic == Intrinsic::ubsantrap) { 6673 Args.push_back(TargetLoweringBase::ArgListEntry()); 6674 Args[0].Val = I.getArgOperand(0); 6675 Args[0].Node = getValue(Args[0].Val); 6676 Args[0].Ty = Args[0].Val->getType(); 6677 } 6678 6679 TargetLowering::CallLoweringInfo CLI(DAG); 6680 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6681 CallingConv::C, I.getType(), 6682 DAG.getExternalSymbol(TrapFuncName.data(), 6683 TLI.getPointerTy(DAG.getDataLayout())), 6684 std::move(Args)); 6685 6686 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6687 DAG.setRoot(Result.second); 6688 return; 6689 } 6690 6691 case Intrinsic::uadd_with_overflow: 6692 case Intrinsic::sadd_with_overflow: 6693 case Intrinsic::usub_with_overflow: 6694 case Intrinsic::ssub_with_overflow: 6695 case Intrinsic::umul_with_overflow: 6696 case Intrinsic::smul_with_overflow: { 6697 ISD::NodeType Op; 6698 switch (Intrinsic) { 6699 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6700 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6701 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6702 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6703 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6704 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6705 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6706 } 6707 SDValue Op1 = getValue(I.getArgOperand(0)); 6708 SDValue Op2 = getValue(I.getArgOperand(1)); 6709 6710 EVT ResultVT = Op1.getValueType(); 6711 EVT OverflowVT = MVT::i1; 6712 if (ResultVT.isVector()) 6713 OverflowVT = EVT::getVectorVT( 6714 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6715 6716 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6717 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6718 return; 6719 } 6720 case Intrinsic::prefetch: { 6721 SDValue Ops[5]; 6722 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6723 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6724 Ops[0] = DAG.getRoot(); 6725 Ops[1] = getValue(I.getArgOperand(0)); 6726 Ops[2] = getValue(I.getArgOperand(1)); 6727 Ops[3] = getValue(I.getArgOperand(2)); 6728 Ops[4] = getValue(I.getArgOperand(3)); 6729 SDValue Result = DAG.getMemIntrinsicNode( 6730 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6731 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6732 /* align */ None, Flags); 6733 6734 // Chain the prefetch in parallell with any pending loads, to stay out of 6735 // the way of later optimizations. 6736 PendingLoads.push_back(Result); 6737 Result = getRoot(); 6738 DAG.setRoot(Result); 6739 return; 6740 } 6741 case Intrinsic::lifetime_start: 6742 case Intrinsic::lifetime_end: { 6743 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6744 // Stack coloring is not enabled in O0, discard region information. 6745 if (TM.getOptLevel() == CodeGenOpt::None) 6746 return; 6747 6748 const int64_t ObjectSize = 6749 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6750 Value *const ObjectPtr = I.getArgOperand(1); 6751 SmallVector<const Value *, 4> Allocas; 6752 getUnderlyingObjects(ObjectPtr, Allocas); 6753 6754 for (const Value *Alloca : Allocas) { 6755 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6756 6757 // Could not find an Alloca. 6758 if (!LifetimeObject) 6759 continue; 6760 6761 // First check that the Alloca is static, otherwise it won't have a 6762 // valid frame index. 6763 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6764 if (SI == FuncInfo.StaticAllocaMap.end()) 6765 return; 6766 6767 const int FrameIndex = SI->second; 6768 int64_t Offset; 6769 if (GetPointerBaseWithConstantOffset( 6770 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6771 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6772 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6773 Offset); 6774 DAG.setRoot(Res); 6775 } 6776 return; 6777 } 6778 case Intrinsic::pseudoprobe: { 6779 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6780 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6781 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6782 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6783 DAG.setRoot(Res); 6784 return; 6785 } 6786 case Intrinsic::invariant_start: 6787 // Discard region information. 6788 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6789 return; 6790 case Intrinsic::invariant_end: 6791 // Discard region information. 6792 return; 6793 case Intrinsic::clear_cache: 6794 /// FunctionName may be null. 6795 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6796 lowerCallToExternalSymbol(I, FunctionName); 6797 return; 6798 case Intrinsic::donothing: 6799 case Intrinsic::seh_try_begin: 6800 case Intrinsic::seh_scope_begin: 6801 case Intrinsic::seh_try_end: 6802 case Intrinsic::seh_scope_end: 6803 // ignore 6804 return; 6805 case Intrinsic::experimental_stackmap: 6806 visitStackmap(I); 6807 return; 6808 case Intrinsic::experimental_patchpoint_void: 6809 case Intrinsic::experimental_patchpoint_i64: 6810 visitPatchpoint(I); 6811 return; 6812 case Intrinsic::experimental_gc_statepoint: 6813 LowerStatepoint(cast<GCStatepointInst>(I)); 6814 return; 6815 case Intrinsic::experimental_gc_result: 6816 visitGCResult(cast<GCResultInst>(I)); 6817 return; 6818 case Intrinsic::experimental_gc_relocate: 6819 visitGCRelocate(cast<GCRelocateInst>(I)); 6820 return; 6821 case Intrinsic::instrprof_increment: 6822 llvm_unreachable("instrprof failed to lower an increment"); 6823 case Intrinsic::instrprof_value_profile: 6824 llvm_unreachable("instrprof failed to lower a value profiling call"); 6825 case Intrinsic::localescape: { 6826 MachineFunction &MF = DAG.getMachineFunction(); 6827 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6828 6829 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6830 // is the same on all targets. 6831 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6832 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6833 if (isa<ConstantPointerNull>(Arg)) 6834 continue; // Skip null pointers. They represent a hole in index space. 6835 AllocaInst *Slot = cast<AllocaInst>(Arg); 6836 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6837 "can only escape static allocas"); 6838 int FI = FuncInfo.StaticAllocaMap[Slot]; 6839 MCSymbol *FrameAllocSym = 6840 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6841 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6842 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6843 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6844 .addSym(FrameAllocSym) 6845 .addFrameIndex(FI); 6846 } 6847 6848 return; 6849 } 6850 6851 case Intrinsic::localrecover: { 6852 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6853 MachineFunction &MF = DAG.getMachineFunction(); 6854 6855 // Get the symbol that defines the frame offset. 6856 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6857 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6858 unsigned IdxVal = 6859 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6860 MCSymbol *FrameAllocSym = 6861 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6862 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6863 6864 Value *FP = I.getArgOperand(1); 6865 SDValue FPVal = getValue(FP); 6866 EVT PtrVT = FPVal.getValueType(); 6867 6868 // Create a MCSymbol for the label to avoid any target lowering 6869 // that would make this PC relative. 6870 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6871 SDValue OffsetVal = 6872 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6873 6874 // Add the offset to the FP. 6875 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6876 setValue(&I, Add); 6877 6878 return; 6879 } 6880 6881 case Intrinsic::eh_exceptionpointer: 6882 case Intrinsic::eh_exceptioncode: { 6883 // Get the exception pointer vreg, copy from it, and resize it to fit. 6884 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6885 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6886 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6887 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6888 SDValue N = 6889 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6890 if (Intrinsic == Intrinsic::eh_exceptioncode) 6891 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6892 setValue(&I, N); 6893 return; 6894 } 6895 case Intrinsic::xray_customevent: { 6896 // Here we want to make sure that the intrinsic behaves as if it has a 6897 // specific calling convention, and only for x86_64. 6898 // FIXME: Support other platforms later. 6899 const auto &Triple = DAG.getTarget().getTargetTriple(); 6900 if (Triple.getArch() != Triple::x86_64) 6901 return; 6902 6903 SDLoc DL = getCurSDLoc(); 6904 SmallVector<SDValue, 8> Ops; 6905 6906 // We want to say that we always want the arguments in registers. 6907 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6908 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6909 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6910 SDValue Chain = getRoot(); 6911 Ops.push_back(LogEntryVal); 6912 Ops.push_back(StrSizeVal); 6913 Ops.push_back(Chain); 6914 6915 // We need to enforce the calling convention for the callsite, so that 6916 // argument ordering is enforced correctly, and that register allocation can 6917 // see that some registers may be assumed clobbered and have to preserve 6918 // them across calls to the intrinsic. 6919 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6920 DL, NodeTys, Ops); 6921 SDValue patchableNode = SDValue(MN, 0); 6922 DAG.setRoot(patchableNode); 6923 setValue(&I, patchableNode); 6924 return; 6925 } 6926 case Intrinsic::xray_typedevent: { 6927 // Here we want to make sure that the intrinsic behaves as if it has a 6928 // specific calling convention, and only for x86_64. 6929 // FIXME: Support other platforms later. 6930 const auto &Triple = DAG.getTarget().getTargetTriple(); 6931 if (Triple.getArch() != Triple::x86_64) 6932 return; 6933 6934 SDLoc DL = getCurSDLoc(); 6935 SmallVector<SDValue, 8> Ops; 6936 6937 // We want to say that we always want the arguments in registers. 6938 // It's unclear to me how manipulating the selection DAG here forces callers 6939 // to provide arguments in registers instead of on the stack. 6940 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6941 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6942 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6943 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6944 SDValue Chain = getRoot(); 6945 Ops.push_back(LogTypeId); 6946 Ops.push_back(LogEntryVal); 6947 Ops.push_back(StrSizeVal); 6948 Ops.push_back(Chain); 6949 6950 // We need to enforce the calling convention for the callsite, so that 6951 // argument ordering is enforced correctly, and that register allocation can 6952 // see that some registers may be assumed clobbered and have to preserve 6953 // them across calls to the intrinsic. 6954 MachineSDNode *MN = DAG.getMachineNode( 6955 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6956 SDValue patchableNode = SDValue(MN, 0); 6957 DAG.setRoot(patchableNode); 6958 setValue(&I, patchableNode); 6959 return; 6960 } 6961 case Intrinsic::experimental_deoptimize: 6962 LowerDeoptimizeCall(&I); 6963 return; 6964 case Intrinsic::experimental_stepvector: 6965 visitStepVector(I); 6966 return; 6967 case Intrinsic::vector_reduce_fadd: 6968 case Intrinsic::vector_reduce_fmul: 6969 case Intrinsic::vector_reduce_add: 6970 case Intrinsic::vector_reduce_mul: 6971 case Intrinsic::vector_reduce_and: 6972 case Intrinsic::vector_reduce_or: 6973 case Intrinsic::vector_reduce_xor: 6974 case Intrinsic::vector_reduce_smax: 6975 case Intrinsic::vector_reduce_smin: 6976 case Intrinsic::vector_reduce_umax: 6977 case Intrinsic::vector_reduce_umin: 6978 case Intrinsic::vector_reduce_fmax: 6979 case Intrinsic::vector_reduce_fmin: 6980 visitVectorReduce(I, Intrinsic); 6981 return; 6982 6983 case Intrinsic::icall_branch_funnel: { 6984 SmallVector<SDValue, 16> Ops; 6985 Ops.push_back(getValue(I.getArgOperand(0))); 6986 6987 int64_t Offset; 6988 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6989 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6990 if (!Base) 6991 report_fatal_error( 6992 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6993 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6994 6995 struct BranchFunnelTarget { 6996 int64_t Offset; 6997 SDValue Target; 6998 }; 6999 SmallVector<BranchFunnelTarget, 8> Targets; 7000 7001 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 7002 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7003 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7004 if (ElemBase != Base) 7005 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7006 "to the same GlobalValue"); 7007 7008 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7009 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7010 if (!GA) 7011 report_fatal_error( 7012 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7013 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7014 GA->getGlobal(), getCurSDLoc(), 7015 Val.getValueType(), GA->getOffset())}); 7016 } 7017 llvm::sort(Targets, 7018 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7019 return T1.Offset < T2.Offset; 7020 }); 7021 7022 for (auto &T : Targets) { 7023 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 7024 Ops.push_back(T.Target); 7025 } 7026 7027 Ops.push_back(DAG.getRoot()); // Chain 7028 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 7029 getCurSDLoc(), MVT::Other, Ops), 7030 0); 7031 DAG.setRoot(N); 7032 setValue(&I, N); 7033 HasTailCall = true; 7034 return; 7035 } 7036 7037 case Intrinsic::wasm_landingpad_index: 7038 // Information this intrinsic contained has been transferred to 7039 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7040 // delete it now. 7041 return; 7042 7043 case Intrinsic::aarch64_settag: 7044 case Intrinsic::aarch64_settag_zero: { 7045 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7046 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7047 SDValue Val = TSI.EmitTargetCodeForSetTag( 7048 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 7049 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7050 ZeroMemory); 7051 DAG.setRoot(Val); 7052 setValue(&I, Val); 7053 return; 7054 } 7055 case Intrinsic::ptrmask: { 7056 SDValue Ptr = getValue(I.getOperand(0)); 7057 SDValue Const = getValue(I.getOperand(1)); 7058 7059 EVT PtrVT = Ptr.getValueType(); 7060 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 7061 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 7062 return; 7063 } 7064 case Intrinsic::get_active_lane_mask: { 7065 auto DL = getCurSDLoc(); 7066 SDValue Index = getValue(I.getOperand(0)); 7067 SDValue TripCount = getValue(I.getOperand(1)); 7068 Type *ElementTy = I.getOperand(0)->getType(); 7069 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7070 unsigned VecWidth = VT.getVectorNumElements(); 7071 7072 SmallVector<SDValue, 16> OpsTripCount; 7073 SmallVector<SDValue, 16> OpsIndex; 7074 SmallVector<SDValue, 16> OpsStepConstants; 7075 for (unsigned i = 0; i < VecWidth; i++) { 7076 OpsTripCount.push_back(TripCount); 7077 OpsIndex.push_back(Index); 7078 OpsStepConstants.push_back( 7079 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 7080 } 7081 7082 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 7083 7084 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 7085 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 7086 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 7087 SDValue VectorInduction = DAG.getNode( 7088 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 7089 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 7090 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 7091 VectorTripCount, ISD::CondCode::SETULT); 7092 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 7093 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 7094 SetCC)); 7095 return; 7096 } 7097 case Intrinsic::experimental_vector_insert: { 7098 auto DL = getCurSDLoc(); 7099 7100 SDValue Vec = getValue(I.getOperand(0)); 7101 SDValue SubVec = getValue(I.getOperand(1)); 7102 SDValue Index = getValue(I.getOperand(2)); 7103 7104 // The intrinsic's index type is i64, but the SDNode requires an index type 7105 // suitable for the target. Convert the index as required. 7106 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7107 if (Index.getValueType() != VectorIdxTy) 7108 Index = DAG.getVectorIdxConstant( 7109 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7110 7111 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7112 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec, 7113 Index)); 7114 return; 7115 } 7116 case Intrinsic::experimental_vector_extract: { 7117 auto DL = getCurSDLoc(); 7118 7119 SDValue Vec = getValue(I.getOperand(0)); 7120 SDValue Index = getValue(I.getOperand(1)); 7121 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7122 7123 // The intrinsic's index type is i64, but the SDNode requires an index type 7124 // suitable for the target. Convert the index as required. 7125 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7126 if (Index.getValueType() != VectorIdxTy) 7127 Index = DAG.getVectorIdxConstant( 7128 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7129 7130 setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index)); 7131 return; 7132 } 7133 case Intrinsic::experimental_vector_reverse: 7134 visitVectorReverse(I); 7135 return; 7136 case Intrinsic::experimental_vector_splice: 7137 visitVectorSplice(I); 7138 return; 7139 } 7140 } 7141 7142 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7143 const ConstrainedFPIntrinsic &FPI) { 7144 SDLoc sdl = getCurSDLoc(); 7145 7146 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7147 SmallVector<EVT, 4> ValueVTs; 7148 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7149 ValueVTs.push_back(MVT::Other); // Out chain 7150 7151 // We do not need to serialize constrained FP intrinsics against 7152 // each other or against (nonvolatile) loads, so they can be 7153 // chained like loads. 7154 SDValue Chain = DAG.getRoot(); 7155 SmallVector<SDValue, 4> Opers; 7156 Opers.push_back(Chain); 7157 if (FPI.isUnaryOp()) { 7158 Opers.push_back(getValue(FPI.getArgOperand(0))); 7159 } else if (FPI.isTernaryOp()) { 7160 Opers.push_back(getValue(FPI.getArgOperand(0))); 7161 Opers.push_back(getValue(FPI.getArgOperand(1))); 7162 Opers.push_back(getValue(FPI.getArgOperand(2))); 7163 } else { 7164 Opers.push_back(getValue(FPI.getArgOperand(0))); 7165 Opers.push_back(getValue(FPI.getArgOperand(1))); 7166 } 7167 7168 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7169 assert(Result.getNode()->getNumValues() == 2); 7170 7171 // Push node to the appropriate list so that future instructions can be 7172 // chained up correctly. 7173 SDValue OutChain = Result.getValue(1); 7174 switch (EB) { 7175 case fp::ExceptionBehavior::ebIgnore: 7176 // The only reason why ebIgnore nodes still need to be chained is that 7177 // they might depend on the current rounding mode, and therefore must 7178 // not be moved across instruction that may change that mode. 7179 LLVM_FALLTHROUGH; 7180 case fp::ExceptionBehavior::ebMayTrap: 7181 // These must not be moved across calls or instructions that may change 7182 // floating-point exception masks. 7183 PendingConstrainedFP.push_back(OutChain); 7184 break; 7185 case fp::ExceptionBehavior::ebStrict: 7186 // These must not be moved across calls or instructions that may change 7187 // floating-point exception masks or read floating-point exception flags. 7188 // In addition, they cannot be optimized out even if unused. 7189 PendingConstrainedFPStrict.push_back(OutChain); 7190 break; 7191 } 7192 }; 7193 7194 SDVTList VTs = DAG.getVTList(ValueVTs); 7195 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7196 7197 SDNodeFlags Flags; 7198 if (EB == fp::ExceptionBehavior::ebIgnore) 7199 Flags.setNoFPExcept(true); 7200 7201 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7202 Flags.copyFMF(*FPOp); 7203 7204 unsigned Opcode; 7205 switch (FPI.getIntrinsicID()) { 7206 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7207 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7208 case Intrinsic::INTRINSIC: \ 7209 Opcode = ISD::STRICT_##DAGN; \ 7210 break; 7211 #include "llvm/IR/ConstrainedOps.def" 7212 case Intrinsic::experimental_constrained_fmuladd: { 7213 Opcode = ISD::STRICT_FMA; 7214 // Break fmuladd into fmul and fadd. 7215 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7216 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7217 ValueVTs[0])) { 7218 Opers.pop_back(); 7219 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7220 pushOutChain(Mul, EB); 7221 Opcode = ISD::STRICT_FADD; 7222 Opers.clear(); 7223 Opers.push_back(Mul.getValue(1)); 7224 Opers.push_back(Mul.getValue(0)); 7225 Opers.push_back(getValue(FPI.getArgOperand(2))); 7226 } 7227 break; 7228 } 7229 } 7230 7231 // A few strict DAG nodes carry additional operands that are not 7232 // set up by the default code above. 7233 switch (Opcode) { 7234 default: break; 7235 case ISD::STRICT_FP_ROUND: 7236 Opers.push_back( 7237 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7238 break; 7239 case ISD::STRICT_FSETCC: 7240 case ISD::STRICT_FSETCCS: { 7241 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7242 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7243 if (TM.Options.NoNaNsFPMath) 7244 Condition = getFCmpCodeWithoutNaN(Condition); 7245 Opers.push_back(DAG.getCondCode(Condition)); 7246 break; 7247 } 7248 } 7249 7250 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7251 pushOutChain(Result, EB); 7252 7253 SDValue FPResult = Result.getValue(0); 7254 setValue(&FPI, FPResult); 7255 } 7256 7257 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7258 Optional<unsigned> ResOPC; 7259 switch (VPIntrin.getIntrinsicID()) { 7260 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN: 7261 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID; 7262 #define END_REGISTER_VP_INTRINSIC(...) break; 7263 #include "llvm/IR/VPIntrinsics.def" 7264 } 7265 7266 if (!ResOPC.hasValue()) 7267 llvm_unreachable( 7268 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7269 7270 return ResOPC.getValue(); 7271 } 7272 7273 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7274 const VPIntrinsic &VPIntrin) { 7275 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7276 7277 SmallVector<EVT, 4> ValueVTs; 7278 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7279 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7280 SDVTList VTs = DAG.getVTList(ValueVTs); 7281 7282 // Request operands. 7283 SmallVector<SDValue, 7> OpValues; 7284 for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i) 7285 OpValues.push_back(getValue(VPIntrin.getArgOperand(i))); 7286 7287 SDLoc DL = getCurSDLoc(); 7288 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7289 setValue(&VPIntrin, Result); 7290 } 7291 7292 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7293 const BasicBlock *EHPadBB, 7294 MCSymbol *&BeginLabel) { 7295 MachineFunction &MF = DAG.getMachineFunction(); 7296 MachineModuleInfo &MMI = MF.getMMI(); 7297 7298 // Insert a label before the invoke call to mark the try range. This can be 7299 // used to detect deletion of the invoke via the MachineModuleInfo. 7300 BeginLabel = MMI.getContext().createTempSymbol(); 7301 7302 // For SjLj, keep track of which landing pads go with which invokes 7303 // so as to maintain the ordering of pads in the LSDA. 7304 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7305 if (CallSiteIndex) { 7306 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7307 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7308 7309 // Now that the call site is handled, stop tracking it. 7310 MMI.setCurrentCallSite(0); 7311 } 7312 7313 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7314 } 7315 7316 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7317 const BasicBlock *EHPadBB, 7318 MCSymbol *BeginLabel) { 7319 assert(BeginLabel && "BeginLabel should've been set"); 7320 7321 MachineFunction &MF = DAG.getMachineFunction(); 7322 MachineModuleInfo &MMI = MF.getMMI(); 7323 7324 // Insert a label at the end of the invoke call to mark the try range. This 7325 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7326 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7327 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7328 7329 // Inform MachineModuleInfo of range. 7330 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7331 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7332 // actually use outlined funclets and their LSDA info style. 7333 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7334 assert(II && "II should've been set"); 7335 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7336 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7337 } else if (!isScopedEHPersonality(Pers)) { 7338 assert(EHPadBB); 7339 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7340 } 7341 7342 return Chain; 7343 } 7344 7345 std::pair<SDValue, SDValue> 7346 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7347 const BasicBlock *EHPadBB) { 7348 MCSymbol *BeginLabel = nullptr; 7349 7350 if (EHPadBB) { 7351 // Both PendingLoads and PendingExports must be flushed here; 7352 // this call might not return. 7353 (void)getRoot(); 7354 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7355 CLI.setChain(getRoot()); 7356 } 7357 7358 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7359 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7360 7361 assert((CLI.IsTailCall || Result.second.getNode()) && 7362 "Non-null chain expected with non-tail call!"); 7363 assert((Result.second.getNode() || !Result.first.getNode()) && 7364 "Null value expected with tail call!"); 7365 7366 if (!Result.second.getNode()) { 7367 // As a special case, a null chain means that a tail call has been emitted 7368 // and the DAG root is already updated. 7369 HasTailCall = true; 7370 7371 // Since there's no actual continuation from this block, nothing can be 7372 // relying on us setting vregs for them. 7373 PendingExports.clear(); 7374 } else { 7375 DAG.setRoot(Result.second); 7376 } 7377 7378 if (EHPadBB) { 7379 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7380 BeginLabel)); 7381 } 7382 7383 return Result; 7384 } 7385 7386 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7387 bool isTailCall, 7388 const BasicBlock *EHPadBB) { 7389 auto &DL = DAG.getDataLayout(); 7390 FunctionType *FTy = CB.getFunctionType(); 7391 Type *RetTy = CB.getType(); 7392 7393 TargetLowering::ArgListTy Args; 7394 Args.reserve(CB.arg_size()); 7395 7396 const Value *SwiftErrorVal = nullptr; 7397 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7398 7399 if (isTailCall) { 7400 // Avoid emitting tail calls in functions with the disable-tail-calls 7401 // attribute. 7402 auto *Caller = CB.getParent()->getParent(); 7403 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7404 "true") 7405 isTailCall = false; 7406 7407 // We can't tail call inside a function with a swifterror argument. Lowering 7408 // does not support this yet. It would have to move into the swifterror 7409 // register before the call. 7410 if (TLI.supportSwiftError() && 7411 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7412 isTailCall = false; 7413 } 7414 7415 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7416 TargetLowering::ArgListEntry Entry; 7417 const Value *V = *I; 7418 7419 // Skip empty types 7420 if (V->getType()->isEmptyTy()) 7421 continue; 7422 7423 SDValue ArgNode = getValue(V); 7424 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7425 7426 Entry.setAttributes(&CB, I - CB.arg_begin()); 7427 7428 // Use swifterror virtual register as input to the call. 7429 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7430 SwiftErrorVal = V; 7431 // We find the virtual register for the actual swifterror argument. 7432 // Instead of using the Value, we use the virtual register instead. 7433 Entry.Node = 7434 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7435 EVT(TLI.getPointerTy(DL))); 7436 } 7437 7438 Args.push_back(Entry); 7439 7440 // If we have an explicit sret argument that is an Instruction, (i.e., it 7441 // might point to function-local memory), we can't meaningfully tail-call. 7442 if (Entry.IsSRet && isa<Instruction>(V)) 7443 isTailCall = false; 7444 } 7445 7446 // If call site has a cfguardtarget operand bundle, create and add an 7447 // additional ArgListEntry. 7448 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7449 TargetLowering::ArgListEntry Entry; 7450 Value *V = Bundle->Inputs[0]; 7451 SDValue ArgNode = getValue(V); 7452 Entry.Node = ArgNode; 7453 Entry.Ty = V->getType(); 7454 Entry.IsCFGuardTarget = true; 7455 Args.push_back(Entry); 7456 } 7457 7458 // Check if target-independent constraints permit a tail call here. 7459 // Target-dependent constraints are checked within TLI->LowerCallTo. 7460 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7461 isTailCall = false; 7462 7463 // Disable tail calls if there is an swifterror argument. Targets have not 7464 // been updated to support tail calls. 7465 if (TLI.supportSwiftError() && SwiftErrorVal) 7466 isTailCall = false; 7467 7468 TargetLowering::CallLoweringInfo CLI(DAG); 7469 CLI.setDebugLoc(getCurSDLoc()) 7470 .setChain(getRoot()) 7471 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7472 .setTailCall(isTailCall) 7473 .setConvergent(CB.isConvergent()) 7474 .setIsPreallocated( 7475 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7476 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7477 7478 if (Result.first.getNode()) { 7479 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7480 setValue(&CB, Result.first); 7481 } 7482 7483 // The last element of CLI.InVals has the SDValue for swifterror return. 7484 // Here we copy it to a virtual register and update SwiftErrorMap for 7485 // book-keeping. 7486 if (SwiftErrorVal && TLI.supportSwiftError()) { 7487 // Get the last element of InVals. 7488 SDValue Src = CLI.InVals.back(); 7489 Register VReg = 7490 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7491 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7492 DAG.setRoot(CopyNode); 7493 } 7494 } 7495 7496 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7497 SelectionDAGBuilder &Builder) { 7498 // Check to see if this load can be trivially constant folded, e.g. if the 7499 // input is from a string literal. 7500 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7501 // Cast pointer to the type we really want to load. 7502 Type *LoadTy = 7503 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7504 if (LoadVT.isVector()) 7505 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7506 7507 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7508 PointerType::getUnqual(LoadTy)); 7509 7510 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7511 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7512 return Builder.getValue(LoadCst); 7513 } 7514 7515 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7516 // still constant memory, the input chain can be the entry node. 7517 SDValue Root; 7518 bool ConstantMemory = false; 7519 7520 // Do not serialize (non-volatile) loads of constant memory with anything. 7521 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7522 Root = Builder.DAG.getEntryNode(); 7523 ConstantMemory = true; 7524 } else { 7525 // Do not serialize non-volatile loads against each other. 7526 Root = Builder.DAG.getRoot(); 7527 } 7528 7529 SDValue Ptr = Builder.getValue(PtrVal); 7530 SDValue LoadVal = 7531 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7532 MachinePointerInfo(PtrVal), Align(1)); 7533 7534 if (!ConstantMemory) 7535 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7536 return LoadVal; 7537 } 7538 7539 /// Record the value for an instruction that produces an integer result, 7540 /// converting the type where necessary. 7541 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7542 SDValue Value, 7543 bool IsSigned) { 7544 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7545 I.getType(), true); 7546 if (IsSigned) 7547 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7548 else 7549 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7550 setValue(&I, Value); 7551 } 7552 7553 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7554 /// true and lower it. Otherwise return false, and it will be lowered like a 7555 /// normal call. 7556 /// The caller already checked that \p I calls the appropriate LibFunc with a 7557 /// correct prototype. 7558 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7559 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7560 const Value *Size = I.getArgOperand(2); 7561 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7562 if (CSize && CSize->getZExtValue() == 0) { 7563 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7564 I.getType(), true); 7565 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7566 return true; 7567 } 7568 7569 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7570 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7571 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7572 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7573 if (Res.first.getNode()) { 7574 processIntegerCallValue(I, Res.first, true); 7575 PendingLoads.push_back(Res.second); 7576 return true; 7577 } 7578 7579 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7580 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7581 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7582 return false; 7583 7584 // If the target has a fast compare for the given size, it will return a 7585 // preferred load type for that size. Require that the load VT is legal and 7586 // that the target supports unaligned loads of that type. Otherwise, return 7587 // INVALID. 7588 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7589 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7590 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7591 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7592 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7593 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7594 // TODO: Check alignment of src and dest ptrs. 7595 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7596 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7597 if (!TLI.isTypeLegal(LVT) || 7598 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7599 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7600 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7601 } 7602 7603 return LVT; 7604 }; 7605 7606 // This turns into unaligned loads. We only do this if the target natively 7607 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7608 // we'll only produce a small number of byte loads. 7609 MVT LoadVT; 7610 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7611 switch (NumBitsToCompare) { 7612 default: 7613 return false; 7614 case 16: 7615 LoadVT = MVT::i16; 7616 break; 7617 case 32: 7618 LoadVT = MVT::i32; 7619 break; 7620 case 64: 7621 case 128: 7622 case 256: 7623 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7624 break; 7625 } 7626 7627 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7628 return false; 7629 7630 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7631 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7632 7633 // Bitcast to a wide integer type if the loads are vectors. 7634 if (LoadVT.isVector()) { 7635 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7636 LoadL = DAG.getBitcast(CmpVT, LoadL); 7637 LoadR = DAG.getBitcast(CmpVT, LoadR); 7638 } 7639 7640 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7641 processIntegerCallValue(I, Cmp, false); 7642 return true; 7643 } 7644 7645 /// See if we can lower a memchr call into an optimized form. If so, return 7646 /// true and lower it. Otherwise return false, and it will be lowered like a 7647 /// normal call. 7648 /// The caller already checked that \p I calls the appropriate LibFunc with a 7649 /// correct prototype. 7650 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7651 const Value *Src = I.getArgOperand(0); 7652 const Value *Char = I.getArgOperand(1); 7653 const Value *Length = I.getArgOperand(2); 7654 7655 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7656 std::pair<SDValue, SDValue> Res = 7657 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7658 getValue(Src), getValue(Char), getValue(Length), 7659 MachinePointerInfo(Src)); 7660 if (Res.first.getNode()) { 7661 setValue(&I, Res.first); 7662 PendingLoads.push_back(Res.second); 7663 return true; 7664 } 7665 7666 return false; 7667 } 7668 7669 /// See if we can lower a mempcpy call into an optimized form. If so, return 7670 /// true and lower it. Otherwise return false, and it will be lowered like a 7671 /// normal call. 7672 /// The caller already checked that \p I calls the appropriate LibFunc with a 7673 /// correct prototype. 7674 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7675 SDValue Dst = getValue(I.getArgOperand(0)); 7676 SDValue Src = getValue(I.getArgOperand(1)); 7677 SDValue Size = getValue(I.getArgOperand(2)); 7678 7679 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7680 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7681 // DAG::getMemcpy needs Alignment to be defined. 7682 Align Alignment = std::min(DstAlign, SrcAlign); 7683 7684 bool isVol = false; 7685 SDLoc sdl = getCurSDLoc(); 7686 7687 // In the mempcpy context we need to pass in a false value for isTailCall 7688 // because the return pointer needs to be adjusted by the size of 7689 // the copied memory. 7690 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7691 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7692 /*isTailCall=*/false, 7693 MachinePointerInfo(I.getArgOperand(0)), 7694 MachinePointerInfo(I.getArgOperand(1))); 7695 assert(MC.getNode() != nullptr && 7696 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7697 DAG.setRoot(MC); 7698 7699 // Check if Size needs to be truncated or extended. 7700 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7701 7702 // Adjust return pointer to point just past the last dst byte. 7703 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7704 Dst, Size); 7705 setValue(&I, DstPlusSize); 7706 return true; 7707 } 7708 7709 /// See if we can lower a strcpy call into an optimized form. If so, return 7710 /// true and lower it, otherwise return false and it will be lowered like a 7711 /// normal call. 7712 /// The caller already checked that \p I calls the appropriate LibFunc with a 7713 /// correct prototype. 7714 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7715 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7716 7717 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7718 std::pair<SDValue, SDValue> Res = 7719 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7720 getValue(Arg0), getValue(Arg1), 7721 MachinePointerInfo(Arg0), 7722 MachinePointerInfo(Arg1), isStpcpy); 7723 if (Res.first.getNode()) { 7724 setValue(&I, Res.first); 7725 DAG.setRoot(Res.second); 7726 return true; 7727 } 7728 7729 return false; 7730 } 7731 7732 /// See if we can lower a strcmp call into an optimized form. If so, return 7733 /// true and lower it, otherwise return false and it will be lowered like a 7734 /// normal call. 7735 /// The caller already checked that \p I calls the appropriate LibFunc with a 7736 /// correct prototype. 7737 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7738 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7739 7740 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7741 std::pair<SDValue, SDValue> Res = 7742 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7743 getValue(Arg0), getValue(Arg1), 7744 MachinePointerInfo(Arg0), 7745 MachinePointerInfo(Arg1)); 7746 if (Res.first.getNode()) { 7747 processIntegerCallValue(I, Res.first, true); 7748 PendingLoads.push_back(Res.second); 7749 return true; 7750 } 7751 7752 return false; 7753 } 7754 7755 /// See if we can lower a strlen call into an optimized form. If so, return 7756 /// true and lower it, otherwise return false and it will be lowered like a 7757 /// normal call. 7758 /// The caller already checked that \p I calls the appropriate LibFunc with a 7759 /// correct prototype. 7760 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7761 const Value *Arg0 = I.getArgOperand(0); 7762 7763 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7764 std::pair<SDValue, SDValue> Res = 7765 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7766 getValue(Arg0), MachinePointerInfo(Arg0)); 7767 if (Res.first.getNode()) { 7768 processIntegerCallValue(I, Res.first, false); 7769 PendingLoads.push_back(Res.second); 7770 return true; 7771 } 7772 7773 return false; 7774 } 7775 7776 /// See if we can lower a strnlen call into an optimized form. If so, return 7777 /// true and lower it, otherwise return false and it will be lowered like a 7778 /// normal call. 7779 /// The caller already checked that \p I calls the appropriate LibFunc with a 7780 /// correct prototype. 7781 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7782 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7783 7784 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7785 std::pair<SDValue, SDValue> Res = 7786 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7787 getValue(Arg0), getValue(Arg1), 7788 MachinePointerInfo(Arg0)); 7789 if (Res.first.getNode()) { 7790 processIntegerCallValue(I, Res.first, false); 7791 PendingLoads.push_back(Res.second); 7792 return true; 7793 } 7794 7795 return false; 7796 } 7797 7798 /// See if we can lower a unary floating-point operation into an SDNode with 7799 /// the specified Opcode. If so, return true and lower it, otherwise return 7800 /// false and it will be lowered like a normal call. 7801 /// The caller already checked that \p I calls the appropriate LibFunc with a 7802 /// correct prototype. 7803 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7804 unsigned Opcode) { 7805 // We already checked this call's prototype; verify it doesn't modify errno. 7806 if (!I.onlyReadsMemory()) 7807 return false; 7808 7809 SDNodeFlags Flags; 7810 Flags.copyFMF(cast<FPMathOperator>(I)); 7811 7812 SDValue Tmp = getValue(I.getArgOperand(0)); 7813 setValue(&I, 7814 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7815 return true; 7816 } 7817 7818 /// See if we can lower a binary floating-point operation into an SDNode with 7819 /// the specified Opcode. If so, return true and lower it. Otherwise return 7820 /// false, and it will be lowered like a normal call. 7821 /// The caller already checked that \p I calls the appropriate LibFunc with a 7822 /// correct prototype. 7823 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7824 unsigned Opcode) { 7825 // We already checked this call's prototype; verify it doesn't modify errno. 7826 if (!I.onlyReadsMemory()) 7827 return false; 7828 7829 SDNodeFlags Flags; 7830 Flags.copyFMF(cast<FPMathOperator>(I)); 7831 7832 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7833 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7834 EVT VT = Tmp0.getValueType(); 7835 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7836 return true; 7837 } 7838 7839 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7840 // Handle inline assembly differently. 7841 if (I.isInlineAsm()) { 7842 visitInlineAsm(I); 7843 return; 7844 } 7845 7846 if (Function *F = I.getCalledFunction()) { 7847 if (F->isDeclaration()) { 7848 // Is this an LLVM intrinsic or a target-specific intrinsic? 7849 unsigned IID = F->getIntrinsicID(); 7850 if (!IID) 7851 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7852 IID = II->getIntrinsicID(F); 7853 7854 if (IID) { 7855 visitIntrinsicCall(I, IID); 7856 return; 7857 } 7858 } 7859 7860 // Check for well-known libc/libm calls. If the function is internal, it 7861 // can't be a library call. Don't do the check if marked as nobuiltin for 7862 // some reason or the call site requires strict floating point semantics. 7863 LibFunc Func; 7864 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7865 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7866 LibInfo->hasOptimizedCodeGen(Func)) { 7867 switch (Func) { 7868 default: break; 7869 case LibFunc_bcmp: 7870 if (visitMemCmpBCmpCall(I)) 7871 return; 7872 break; 7873 case LibFunc_copysign: 7874 case LibFunc_copysignf: 7875 case LibFunc_copysignl: 7876 // We already checked this call's prototype; verify it doesn't modify 7877 // errno. 7878 if (I.onlyReadsMemory()) { 7879 SDValue LHS = getValue(I.getArgOperand(0)); 7880 SDValue RHS = getValue(I.getArgOperand(1)); 7881 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7882 LHS.getValueType(), LHS, RHS)); 7883 return; 7884 } 7885 break; 7886 case LibFunc_fabs: 7887 case LibFunc_fabsf: 7888 case LibFunc_fabsl: 7889 if (visitUnaryFloatCall(I, ISD::FABS)) 7890 return; 7891 break; 7892 case LibFunc_fmin: 7893 case LibFunc_fminf: 7894 case LibFunc_fminl: 7895 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7896 return; 7897 break; 7898 case LibFunc_fmax: 7899 case LibFunc_fmaxf: 7900 case LibFunc_fmaxl: 7901 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7902 return; 7903 break; 7904 case LibFunc_sin: 7905 case LibFunc_sinf: 7906 case LibFunc_sinl: 7907 if (visitUnaryFloatCall(I, ISD::FSIN)) 7908 return; 7909 break; 7910 case LibFunc_cos: 7911 case LibFunc_cosf: 7912 case LibFunc_cosl: 7913 if (visitUnaryFloatCall(I, ISD::FCOS)) 7914 return; 7915 break; 7916 case LibFunc_sqrt: 7917 case LibFunc_sqrtf: 7918 case LibFunc_sqrtl: 7919 case LibFunc_sqrt_finite: 7920 case LibFunc_sqrtf_finite: 7921 case LibFunc_sqrtl_finite: 7922 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7923 return; 7924 break; 7925 case LibFunc_floor: 7926 case LibFunc_floorf: 7927 case LibFunc_floorl: 7928 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7929 return; 7930 break; 7931 case LibFunc_nearbyint: 7932 case LibFunc_nearbyintf: 7933 case LibFunc_nearbyintl: 7934 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7935 return; 7936 break; 7937 case LibFunc_ceil: 7938 case LibFunc_ceilf: 7939 case LibFunc_ceill: 7940 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7941 return; 7942 break; 7943 case LibFunc_rint: 7944 case LibFunc_rintf: 7945 case LibFunc_rintl: 7946 if (visitUnaryFloatCall(I, ISD::FRINT)) 7947 return; 7948 break; 7949 case LibFunc_round: 7950 case LibFunc_roundf: 7951 case LibFunc_roundl: 7952 if (visitUnaryFloatCall(I, ISD::FROUND)) 7953 return; 7954 break; 7955 case LibFunc_trunc: 7956 case LibFunc_truncf: 7957 case LibFunc_truncl: 7958 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7959 return; 7960 break; 7961 case LibFunc_log2: 7962 case LibFunc_log2f: 7963 case LibFunc_log2l: 7964 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7965 return; 7966 break; 7967 case LibFunc_exp2: 7968 case LibFunc_exp2f: 7969 case LibFunc_exp2l: 7970 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7971 return; 7972 break; 7973 case LibFunc_memcmp: 7974 if (visitMemCmpBCmpCall(I)) 7975 return; 7976 break; 7977 case LibFunc_mempcpy: 7978 if (visitMemPCpyCall(I)) 7979 return; 7980 break; 7981 case LibFunc_memchr: 7982 if (visitMemChrCall(I)) 7983 return; 7984 break; 7985 case LibFunc_strcpy: 7986 if (visitStrCpyCall(I, false)) 7987 return; 7988 break; 7989 case LibFunc_stpcpy: 7990 if (visitStrCpyCall(I, true)) 7991 return; 7992 break; 7993 case LibFunc_strcmp: 7994 if (visitStrCmpCall(I)) 7995 return; 7996 break; 7997 case LibFunc_strlen: 7998 if (visitStrLenCall(I)) 7999 return; 8000 break; 8001 case LibFunc_strnlen: 8002 if (visitStrNLenCall(I)) 8003 return; 8004 break; 8005 } 8006 } 8007 } 8008 8009 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8010 // have to do anything here to lower funclet bundles. 8011 // CFGuardTarget bundles are lowered in LowerCallTo. 8012 assert(!I.hasOperandBundlesOtherThan( 8013 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8014 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8015 LLVMContext::OB_clang_arc_attachedcall}) && 8016 "Cannot lower calls with arbitrary operand bundles!"); 8017 8018 SDValue Callee = getValue(I.getCalledOperand()); 8019 8020 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8021 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8022 else 8023 // Check if we can potentially perform a tail call. More detailed checking 8024 // is be done within LowerCallTo, after more information about the call is 8025 // known. 8026 LowerCallTo(I, Callee, I.isTailCall()); 8027 } 8028 8029 namespace { 8030 8031 /// AsmOperandInfo - This contains information for each constraint that we are 8032 /// lowering. 8033 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8034 public: 8035 /// CallOperand - If this is the result output operand or a clobber 8036 /// this is null, otherwise it is the incoming operand to the CallInst. 8037 /// This gets modified as the asm is processed. 8038 SDValue CallOperand; 8039 8040 /// AssignedRegs - If this is a register or register class operand, this 8041 /// contains the set of register corresponding to the operand. 8042 RegsForValue AssignedRegs; 8043 8044 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8045 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8046 } 8047 8048 /// Whether or not this operand accesses memory 8049 bool hasMemory(const TargetLowering &TLI) const { 8050 // Indirect operand accesses access memory. 8051 if (isIndirect) 8052 return true; 8053 8054 for (const auto &Code : Codes) 8055 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8056 return true; 8057 8058 return false; 8059 } 8060 8061 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8062 /// corresponds to. If there is no Value* for this operand, it returns 8063 /// MVT::Other. 8064 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8065 const DataLayout &DL) const { 8066 if (!CallOperandVal) return MVT::Other; 8067 8068 if (isa<BasicBlock>(CallOperandVal)) 8069 return TLI.getProgramPointerTy(DL); 8070 8071 llvm::Type *OpTy = CallOperandVal->getType(); 8072 8073 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8074 // If this is an indirect operand, the operand is a pointer to the 8075 // accessed type. 8076 if (isIndirect) { 8077 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 8078 if (!PtrTy) 8079 report_fatal_error("Indirect operand for inline asm not a pointer!"); 8080 OpTy = PtrTy->getElementType(); 8081 } 8082 8083 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8084 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8085 if (STy->getNumElements() == 1) 8086 OpTy = STy->getElementType(0); 8087 8088 // If OpTy is not a single value, it may be a struct/union that we 8089 // can tile with integers. 8090 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8091 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8092 switch (BitSize) { 8093 default: break; 8094 case 1: 8095 case 8: 8096 case 16: 8097 case 32: 8098 case 64: 8099 case 128: 8100 OpTy = IntegerType::get(Context, BitSize); 8101 break; 8102 } 8103 } 8104 8105 return TLI.getValueType(DL, OpTy, true); 8106 } 8107 }; 8108 8109 8110 } // end anonymous namespace 8111 8112 /// Make sure that the output operand \p OpInfo and its corresponding input 8113 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8114 /// out). 8115 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8116 SDISelAsmOperandInfo &MatchingOpInfo, 8117 SelectionDAG &DAG) { 8118 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8119 return; 8120 8121 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8122 const auto &TLI = DAG.getTargetLoweringInfo(); 8123 8124 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8125 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8126 OpInfo.ConstraintVT); 8127 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8128 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8129 MatchingOpInfo.ConstraintVT); 8130 if ((OpInfo.ConstraintVT.isInteger() != 8131 MatchingOpInfo.ConstraintVT.isInteger()) || 8132 (MatchRC.second != InputRC.second)) { 8133 // FIXME: error out in a more elegant fashion 8134 report_fatal_error("Unsupported asm: input constraint" 8135 " with a matching output constraint of" 8136 " incompatible type!"); 8137 } 8138 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8139 } 8140 8141 /// Get a direct memory input to behave well as an indirect operand. 8142 /// This may introduce stores, hence the need for a \p Chain. 8143 /// \return The (possibly updated) chain. 8144 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8145 SDISelAsmOperandInfo &OpInfo, 8146 SelectionDAG &DAG) { 8147 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8148 8149 // If we don't have an indirect input, put it in the constpool if we can, 8150 // otherwise spill it to a stack slot. 8151 // TODO: This isn't quite right. We need to handle these according to 8152 // the addressing mode that the constraint wants. Also, this may take 8153 // an additional register for the computation and we don't want that 8154 // either. 8155 8156 // If the operand is a float, integer, or vector constant, spill to a 8157 // constant pool entry to get its address. 8158 const Value *OpVal = OpInfo.CallOperandVal; 8159 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8160 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8161 OpInfo.CallOperand = DAG.getConstantPool( 8162 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8163 return Chain; 8164 } 8165 8166 // Otherwise, create a stack slot and emit a store to it before the asm. 8167 Type *Ty = OpVal->getType(); 8168 auto &DL = DAG.getDataLayout(); 8169 uint64_t TySize = DL.getTypeAllocSize(Ty); 8170 MachineFunction &MF = DAG.getMachineFunction(); 8171 int SSFI = MF.getFrameInfo().CreateStackObject( 8172 TySize, DL.getPrefTypeAlign(Ty), false); 8173 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8174 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8175 MachinePointerInfo::getFixedStack(MF, SSFI), 8176 TLI.getMemValueType(DL, Ty)); 8177 OpInfo.CallOperand = StackSlot; 8178 8179 return Chain; 8180 } 8181 8182 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8183 /// specified operand. We prefer to assign virtual registers, to allow the 8184 /// register allocator to handle the assignment process. However, if the asm 8185 /// uses features that we can't model on machineinstrs, we have SDISel do the 8186 /// allocation. This produces generally horrible, but correct, code. 8187 /// 8188 /// OpInfo describes the operand 8189 /// RefOpInfo describes the matching operand if any, the operand otherwise 8190 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8191 SDISelAsmOperandInfo &OpInfo, 8192 SDISelAsmOperandInfo &RefOpInfo) { 8193 LLVMContext &Context = *DAG.getContext(); 8194 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8195 8196 MachineFunction &MF = DAG.getMachineFunction(); 8197 SmallVector<unsigned, 4> Regs; 8198 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8199 8200 // No work to do for memory operations. 8201 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8202 return; 8203 8204 // If this is a constraint for a single physreg, or a constraint for a 8205 // register class, find it. 8206 unsigned AssignedReg; 8207 const TargetRegisterClass *RC; 8208 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8209 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8210 // RC is unset only on failure. Return immediately. 8211 if (!RC) 8212 return; 8213 8214 // Get the actual register value type. This is important, because the user 8215 // may have asked for (e.g.) the AX register in i32 type. We need to 8216 // remember that AX is actually i16 to get the right extension. 8217 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8218 8219 if (OpInfo.ConstraintVT != MVT::Other) { 8220 // If this is an FP operand in an integer register (or visa versa), or more 8221 // generally if the operand value disagrees with the register class we plan 8222 // to stick it in, fix the operand type. 8223 // 8224 // If this is an input value, the bitcast to the new type is done now. 8225 // Bitcast for output value is done at the end of visitInlineAsm(). 8226 if ((OpInfo.Type == InlineAsm::isOutput || 8227 OpInfo.Type == InlineAsm::isInput) && 8228 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8229 // Try to convert to the first EVT that the reg class contains. If the 8230 // types are identical size, use a bitcast to convert (e.g. two differing 8231 // vector types). Note: output bitcast is done at the end of 8232 // visitInlineAsm(). 8233 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8234 // Exclude indirect inputs while they are unsupported because the code 8235 // to perform the load is missing and thus OpInfo.CallOperand still 8236 // refers to the input address rather than the pointed-to value. 8237 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8238 OpInfo.CallOperand = 8239 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8240 OpInfo.ConstraintVT = RegVT; 8241 // If the operand is an FP value and we want it in integer registers, 8242 // use the corresponding integer type. This turns an f64 value into 8243 // i64, which can be passed with two i32 values on a 32-bit machine. 8244 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8245 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8246 if (OpInfo.Type == InlineAsm::isInput) 8247 OpInfo.CallOperand = 8248 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8249 OpInfo.ConstraintVT = VT; 8250 } 8251 } 8252 } 8253 8254 // No need to allocate a matching input constraint since the constraint it's 8255 // matching to has already been allocated. 8256 if (OpInfo.isMatchingInputConstraint()) 8257 return; 8258 8259 EVT ValueVT = OpInfo.ConstraintVT; 8260 if (OpInfo.ConstraintVT == MVT::Other) 8261 ValueVT = RegVT; 8262 8263 // Initialize NumRegs. 8264 unsigned NumRegs = 1; 8265 if (OpInfo.ConstraintVT != MVT::Other) 8266 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8267 8268 // If this is a constraint for a specific physical register, like {r17}, 8269 // assign it now. 8270 8271 // If this associated to a specific register, initialize iterator to correct 8272 // place. If virtual, make sure we have enough registers 8273 8274 // Initialize iterator if necessary 8275 TargetRegisterClass::iterator I = RC->begin(); 8276 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8277 8278 // Do not check for single registers. 8279 if (AssignedReg) { 8280 for (; *I != AssignedReg; ++I) 8281 assert(I != RC->end() && "AssignedReg should be member of RC"); 8282 } 8283 8284 for (; NumRegs; --NumRegs, ++I) { 8285 assert(I != RC->end() && "Ran out of registers to allocate!"); 8286 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8287 Regs.push_back(R); 8288 } 8289 8290 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8291 } 8292 8293 static unsigned 8294 findMatchingInlineAsmOperand(unsigned OperandNo, 8295 const std::vector<SDValue> &AsmNodeOperands) { 8296 // Scan until we find the definition we already emitted of this operand. 8297 unsigned CurOp = InlineAsm::Op_FirstOperand; 8298 for (; OperandNo; --OperandNo) { 8299 // Advance to the next operand. 8300 unsigned OpFlag = 8301 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8302 assert((InlineAsm::isRegDefKind(OpFlag) || 8303 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8304 InlineAsm::isMemKind(OpFlag)) && 8305 "Skipped past definitions?"); 8306 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8307 } 8308 return CurOp; 8309 } 8310 8311 namespace { 8312 8313 class ExtraFlags { 8314 unsigned Flags = 0; 8315 8316 public: 8317 explicit ExtraFlags(const CallBase &Call) { 8318 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8319 if (IA->hasSideEffects()) 8320 Flags |= InlineAsm::Extra_HasSideEffects; 8321 if (IA->isAlignStack()) 8322 Flags |= InlineAsm::Extra_IsAlignStack; 8323 if (Call.isConvergent()) 8324 Flags |= InlineAsm::Extra_IsConvergent; 8325 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8326 } 8327 8328 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8329 // Ideally, we would only check against memory constraints. However, the 8330 // meaning of an Other constraint can be target-specific and we can't easily 8331 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8332 // for Other constraints as well. 8333 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8334 OpInfo.ConstraintType == TargetLowering::C_Other) { 8335 if (OpInfo.Type == InlineAsm::isInput) 8336 Flags |= InlineAsm::Extra_MayLoad; 8337 else if (OpInfo.Type == InlineAsm::isOutput) 8338 Flags |= InlineAsm::Extra_MayStore; 8339 else if (OpInfo.Type == InlineAsm::isClobber) 8340 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8341 } 8342 } 8343 8344 unsigned get() const { return Flags; } 8345 }; 8346 8347 } // end anonymous namespace 8348 8349 /// visitInlineAsm - Handle a call to an InlineAsm object. 8350 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8351 const BasicBlock *EHPadBB) { 8352 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8353 8354 /// ConstraintOperands - Information about all of the constraints. 8355 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8356 8357 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8358 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8359 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8360 8361 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8362 // AsmDialect, MayLoad, MayStore). 8363 bool HasSideEffect = IA->hasSideEffects(); 8364 ExtraFlags ExtraInfo(Call); 8365 8366 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8367 unsigned ResNo = 0; // ResNo - The result number of the next output. 8368 unsigned NumMatchingOps = 0; 8369 for (auto &T : TargetConstraints) { 8370 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8371 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8372 8373 // Compute the value type for each operand. 8374 if (OpInfo.Type == InlineAsm::isInput || 8375 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8376 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8377 8378 // Process the call argument. BasicBlocks are labels, currently appearing 8379 // only in asm's. 8380 if (isa<CallBrInst>(Call) && 8381 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8382 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8383 NumMatchingOps) && 8384 (NumMatchingOps == 0 || 8385 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8386 NumMatchingOps))) { 8387 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8388 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8389 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8390 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8391 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8392 } else { 8393 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8394 } 8395 8396 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8397 DAG.getDataLayout()); 8398 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8399 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8400 // The return value of the call is this value. As such, there is no 8401 // corresponding argument. 8402 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8403 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8404 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8405 DAG.getDataLayout(), STy->getElementType(ResNo)); 8406 } else { 8407 assert(ResNo == 0 && "Asm only has one result!"); 8408 OpInfo.ConstraintVT = 8409 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8410 } 8411 ++ResNo; 8412 } else { 8413 OpInfo.ConstraintVT = MVT::Other; 8414 } 8415 8416 if (OpInfo.hasMatchingInput()) 8417 ++NumMatchingOps; 8418 8419 if (!HasSideEffect) 8420 HasSideEffect = OpInfo.hasMemory(TLI); 8421 8422 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8423 // FIXME: Could we compute this on OpInfo rather than T? 8424 8425 // Compute the constraint code and ConstraintType to use. 8426 TLI.ComputeConstraintToUse(T, SDValue()); 8427 8428 if (T.ConstraintType == TargetLowering::C_Immediate && 8429 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8430 // We've delayed emitting a diagnostic like the "n" constraint because 8431 // inlining could cause an integer showing up. 8432 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8433 "' expects an integer constant " 8434 "expression"); 8435 8436 ExtraInfo.update(T); 8437 } 8438 8439 // We won't need to flush pending loads if this asm doesn't touch 8440 // memory and is nonvolatile. 8441 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8442 8443 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8444 if (EmitEHLabels) { 8445 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8446 } 8447 bool IsCallBr = isa<CallBrInst>(Call); 8448 8449 if (IsCallBr || EmitEHLabels) { 8450 // If this is a callbr or invoke we need to flush pending exports since 8451 // inlineasm_br and invoke are terminators. 8452 // We need to do this before nodes are glued to the inlineasm_br node. 8453 Chain = getControlRoot(); 8454 } 8455 8456 MCSymbol *BeginLabel = nullptr; 8457 if (EmitEHLabels) { 8458 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8459 } 8460 8461 // Second pass over the constraints: compute which constraint option to use. 8462 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8463 // If this is an output operand with a matching input operand, look up the 8464 // matching input. If their types mismatch, e.g. one is an integer, the 8465 // other is floating point, or their sizes are different, flag it as an 8466 // error. 8467 if (OpInfo.hasMatchingInput()) { 8468 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8469 patchMatchingInput(OpInfo, Input, DAG); 8470 } 8471 8472 // Compute the constraint code and ConstraintType to use. 8473 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8474 8475 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8476 OpInfo.Type == InlineAsm::isClobber) 8477 continue; 8478 8479 // If this is a memory input, and if the operand is not indirect, do what we 8480 // need to provide an address for the memory input. 8481 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8482 !OpInfo.isIndirect) { 8483 assert((OpInfo.isMultipleAlternative || 8484 (OpInfo.Type == InlineAsm::isInput)) && 8485 "Can only indirectify direct input operands!"); 8486 8487 // Memory operands really want the address of the value. 8488 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8489 8490 // There is no longer a Value* corresponding to this operand. 8491 OpInfo.CallOperandVal = nullptr; 8492 8493 // It is now an indirect operand. 8494 OpInfo.isIndirect = true; 8495 } 8496 8497 } 8498 8499 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8500 std::vector<SDValue> AsmNodeOperands; 8501 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8502 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8503 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8504 8505 // If we have a !srcloc metadata node associated with it, we want to attach 8506 // this to the ultimately generated inline asm machineinstr. To do this, we 8507 // pass in the third operand as this (potentially null) inline asm MDNode. 8508 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8509 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8510 8511 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8512 // bits as operand 3. 8513 AsmNodeOperands.push_back(DAG.getTargetConstant( 8514 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8515 8516 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8517 // this, assign virtual and physical registers for inputs and otput. 8518 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8519 // Assign Registers. 8520 SDISelAsmOperandInfo &RefOpInfo = 8521 OpInfo.isMatchingInputConstraint() 8522 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8523 : OpInfo; 8524 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8525 8526 auto DetectWriteToReservedRegister = [&]() { 8527 const MachineFunction &MF = DAG.getMachineFunction(); 8528 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8529 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8530 if (Register::isPhysicalRegister(Reg) && 8531 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8532 const char *RegName = TRI.getName(Reg); 8533 emitInlineAsmError(Call, "write to reserved register '" + 8534 Twine(RegName) + "'"); 8535 return true; 8536 } 8537 } 8538 return false; 8539 }; 8540 8541 switch (OpInfo.Type) { 8542 case InlineAsm::isOutput: 8543 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8544 unsigned ConstraintID = 8545 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8546 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8547 "Failed to convert memory constraint code to constraint id."); 8548 8549 // Add information to the INLINEASM node to know about this output. 8550 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8551 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8552 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8553 MVT::i32)); 8554 AsmNodeOperands.push_back(OpInfo.CallOperand); 8555 } else { 8556 // Otherwise, this outputs to a register (directly for C_Register / 8557 // C_RegisterClass, and a target-defined fashion for 8558 // C_Immediate/C_Other). Find a register that we can use. 8559 if (OpInfo.AssignedRegs.Regs.empty()) { 8560 emitInlineAsmError( 8561 Call, "couldn't allocate output register for constraint '" + 8562 Twine(OpInfo.ConstraintCode) + "'"); 8563 return; 8564 } 8565 8566 if (DetectWriteToReservedRegister()) 8567 return; 8568 8569 // Add information to the INLINEASM node to know that this register is 8570 // set. 8571 OpInfo.AssignedRegs.AddInlineAsmOperands( 8572 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8573 : InlineAsm::Kind_RegDef, 8574 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8575 } 8576 break; 8577 8578 case InlineAsm::isInput: { 8579 SDValue InOperandVal = OpInfo.CallOperand; 8580 8581 if (OpInfo.isMatchingInputConstraint()) { 8582 // If this is required to match an output register we have already set, 8583 // just use its register. 8584 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8585 AsmNodeOperands); 8586 unsigned OpFlag = 8587 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8588 if (InlineAsm::isRegDefKind(OpFlag) || 8589 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8590 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8591 if (OpInfo.isIndirect) { 8592 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8593 emitInlineAsmError(Call, "inline asm not supported yet: " 8594 "don't know how to handle tied " 8595 "indirect register inputs"); 8596 return; 8597 } 8598 8599 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8600 SmallVector<unsigned, 4> Regs; 8601 8602 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8603 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8604 MachineRegisterInfo &RegInfo = 8605 DAG.getMachineFunction().getRegInfo(); 8606 for (unsigned i = 0; i != NumRegs; ++i) 8607 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8608 } else { 8609 emitInlineAsmError(Call, 8610 "inline asm error: This value type register " 8611 "class is not natively supported!"); 8612 return; 8613 } 8614 8615 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8616 8617 SDLoc dl = getCurSDLoc(); 8618 // Use the produced MatchedRegs object to 8619 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8620 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8621 true, OpInfo.getMatchedOperand(), dl, 8622 DAG, AsmNodeOperands); 8623 break; 8624 } 8625 8626 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8627 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8628 "Unexpected number of operands"); 8629 // Add information to the INLINEASM node to know about this input. 8630 // See InlineAsm.h isUseOperandTiedToDef. 8631 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8632 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8633 OpInfo.getMatchedOperand()); 8634 AsmNodeOperands.push_back(DAG.getTargetConstant( 8635 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8636 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8637 break; 8638 } 8639 8640 // Treat indirect 'X' constraint as memory. 8641 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8642 OpInfo.isIndirect) 8643 OpInfo.ConstraintType = TargetLowering::C_Memory; 8644 8645 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8646 OpInfo.ConstraintType == TargetLowering::C_Other) { 8647 std::vector<SDValue> Ops; 8648 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8649 Ops, DAG); 8650 if (Ops.empty()) { 8651 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8652 if (isa<ConstantSDNode>(InOperandVal)) { 8653 emitInlineAsmError(Call, "value out of range for constraint '" + 8654 Twine(OpInfo.ConstraintCode) + "'"); 8655 return; 8656 } 8657 8658 emitInlineAsmError(Call, 8659 "invalid operand for inline asm constraint '" + 8660 Twine(OpInfo.ConstraintCode) + "'"); 8661 return; 8662 } 8663 8664 // Add information to the INLINEASM node to know about this input. 8665 unsigned ResOpType = 8666 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8667 AsmNodeOperands.push_back(DAG.getTargetConstant( 8668 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8669 llvm::append_range(AsmNodeOperands, Ops); 8670 break; 8671 } 8672 8673 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8674 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8675 assert(InOperandVal.getValueType() == 8676 TLI.getPointerTy(DAG.getDataLayout()) && 8677 "Memory operands expect pointer values"); 8678 8679 unsigned ConstraintID = 8680 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8681 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8682 "Failed to convert memory constraint code to constraint id."); 8683 8684 // Add information to the INLINEASM node to know about this input. 8685 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8686 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8687 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8688 getCurSDLoc(), 8689 MVT::i32)); 8690 AsmNodeOperands.push_back(InOperandVal); 8691 break; 8692 } 8693 8694 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8695 OpInfo.ConstraintType == TargetLowering::C_Register) && 8696 "Unknown constraint type!"); 8697 8698 // TODO: Support this. 8699 if (OpInfo.isIndirect) { 8700 emitInlineAsmError( 8701 Call, "Don't know how to handle indirect register inputs yet " 8702 "for constraint '" + 8703 Twine(OpInfo.ConstraintCode) + "'"); 8704 return; 8705 } 8706 8707 // Copy the input into the appropriate registers. 8708 if (OpInfo.AssignedRegs.Regs.empty()) { 8709 emitInlineAsmError(Call, 8710 "couldn't allocate input reg for constraint '" + 8711 Twine(OpInfo.ConstraintCode) + "'"); 8712 return; 8713 } 8714 8715 if (DetectWriteToReservedRegister()) 8716 return; 8717 8718 SDLoc dl = getCurSDLoc(); 8719 8720 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8721 &Call); 8722 8723 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8724 dl, DAG, AsmNodeOperands); 8725 break; 8726 } 8727 case InlineAsm::isClobber: 8728 // Add the clobbered value to the operand list, so that the register 8729 // allocator is aware that the physreg got clobbered. 8730 if (!OpInfo.AssignedRegs.Regs.empty()) 8731 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8732 false, 0, getCurSDLoc(), DAG, 8733 AsmNodeOperands); 8734 break; 8735 } 8736 } 8737 8738 // Finish up input operands. Set the input chain and add the flag last. 8739 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8740 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8741 8742 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8743 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8744 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8745 Flag = Chain.getValue(1); 8746 8747 // Do additional work to generate outputs. 8748 8749 SmallVector<EVT, 1> ResultVTs; 8750 SmallVector<SDValue, 1> ResultValues; 8751 SmallVector<SDValue, 8> OutChains; 8752 8753 llvm::Type *CallResultType = Call.getType(); 8754 ArrayRef<Type *> ResultTypes; 8755 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8756 ResultTypes = StructResult->elements(); 8757 else if (!CallResultType->isVoidTy()) 8758 ResultTypes = makeArrayRef(CallResultType); 8759 8760 auto CurResultType = ResultTypes.begin(); 8761 auto handleRegAssign = [&](SDValue V) { 8762 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8763 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8764 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8765 ++CurResultType; 8766 // If the type of the inline asm call site return value is different but has 8767 // same size as the type of the asm output bitcast it. One example of this 8768 // is for vectors with different width / number of elements. This can 8769 // happen for register classes that can contain multiple different value 8770 // types. The preg or vreg allocated may not have the same VT as was 8771 // expected. 8772 // 8773 // This can also happen for a return value that disagrees with the register 8774 // class it is put in, eg. a double in a general-purpose register on a 8775 // 32-bit machine. 8776 if (ResultVT != V.getValueType() && 8777 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8778 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8779 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8780 V.getValueType().isInteger()) { 8781 // If a result value was tied to an input value, the computed result 8782 // may have a wider width than the expected result. Extract the 8783 // relevant portion. 8784 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8785 } 8786 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8787 ResultVTs.push_back(ResultVT); 8788 ResultValues.push_back(V); 8789 }; 8790 8791 // Deal with output operands. 8792 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8793 if (OpInfo.Type == InlineAsm::isOutput) { 8794 SDValue Val; 8795 // Skip trivial output operands. 8796 if (OpInfo.AssignedRegs.Regs.empty()) 8797 continue; 8798 8799 switch (OpInfo.ConstraintType) { 8800 case TargetLowering::C_Register: 8801 case TargetLowering::C_RegisterClass: 8802 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8803 Chain, &Flag, &Call); 8804 break; 8805 case TargetLowering::C_Immediate: 8806 case TargetLowering::C_Other: 8807 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8808 OpInfo, DAG); 8809 break; 8810 case TargetLowering::C_Memory: 8811 break; // Already handled. 8812 case TargetLowering::C_Unknown: 8813 assert(false && "Unexpected unknown constraint"); 8814 } 8815 8816 // Indirect output manifest as stores. Record output chains. 8817 if (OpInfo.isIndirect) { 8818 const Value *Ptr = OpInfo.CallOperandVal; 8819 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8820 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8821 MachinePointerInfo(Ptr)); 8822 OutChains.push_back(Store); 8823 } else { 8824 // generate CopyFromRegs to associated registers. 8825 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8826 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8827 for (const SDValue &V : Val->op_values()) 8828 handleRegAssign(V); 8829 } else 8830 handleRegAssign(Val); 8831 } 8832 } 8833 } 8834 8835 // Set results. 8836 if (!ResultValues.empty()) { 8837 assert(CurResultType == ResultTypes.end() && 8838 "Mismatch in number of ResultTypes"); 8839 assert(ResultValues.size() == ResultTypes.size() && 8840 "Mismatch in number of output operands in asm result"); 8841 8842 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8843 DAG.getVTList(ResultVTs), ResultValues); 8844 setValue(&Call, V); 8845 } 8846 8847 // Collect store chains. 8848 if (!OutChains.empty()) 8849 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8850 8851 if (EmitEHLabels) { 8852 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 8853 } 8854 8855 // Only Update Root if inline assembly has a memory effect. 8856 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 8857 EmitEHLabels) 8858 DAG.setRoot(Chain); 8859 } 8860 8861 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8862 const Twine &Message) { 8863 LLVMContext &Ctx = *DAG.getContext(); 8864 Ctx.emitError(&Call, Message); 8865 8866 // Make sure we leave the DAG in a valid state 8867 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8868 SmallVector<EVT, 1> ValueVTs; 8869 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8870 8871 if (ValueVTs.empty()) 8872 return; 8873 8874 SmallVector<SDValue, 1> Ops; 8875 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8876 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8877 8878 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8879 } 8880 8881 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8882 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8883 MVT::Other, getRoot(), 8884 getValue(I.getArgOperand(0)), 8885 DAG.getSrcValue(I.getArgOperand(0)))); 8886 } 8887 8888 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8889 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8890 const DataLayout &DL = DAG.getDataLayout(); 8891 SDValue V = DAG.getVAArg( 8892 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8893 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8894 DL.getABITypeAlign(I.getType()).value()); 8895 DAG.setRoot(V.getValue(1)); 8896 8897 if (I.getType()->isPointerTy()) 8898 V = DAG.getPtrExtOrTrunc( 8899 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8900 setValue(&I, V); 8901 } 8902 8903 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8904 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8905 MVT::Other, getRoot(), 8906 getValue(I.getArgOperand(0)), 8907 DAG.getSrcValue(I.getArgOperand(0)))); 8908 } 8909 8910 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8911 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8912 MVT::Other, getRoot(), 8913 getValue(I.getArgOperand(0)), 8914 getValue(I.getArgOperand(1)), 8915 DAG.getSrcValue(I.getArgOperand(0)), 8916 DAG.getSrcValue(I.getArgOperand(1)))); 8917 } 8918 8919 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8920 const Instruction &I, 8921 SDValue Op) { 8922 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8923 if (!Range) 8924 return Op; 8925 8926 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8927 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8928 return Op; 8929 8930 APInt Lo = CR.getUnsignedMin(); 8931 if (!Lo.isMinValue()) 8932 return Op; 8933 8934 APInt Hi = CR.getUnsignedMax(); 8935 unsigned Bits = std::max(Hi.getActiveBits(), 8936 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8937 8938 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8939 8940 SDLoc SL = getCurSDLoc(); 8941 8942 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8943 DAG.getValueType(SmallVT)); 8944 unsigned NumVals = Op.getNode()->getNumValues(); 8945 if (NumVals == 1) 8946 return ZExt; 8947 8948 SmallVector<SDValue, 4> Ops; 8949 8950 Ops.push_back(ZExt); 8951 for (unsigned I = 1; I != NumVals; ++I) 8952 Ops.push_back(Op.getValue(I)); 8953 8954 return DAG.getMergeValues(Ops, SL); 8955 } 8956 8957 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8958 /// the call being lowered. 8959 /// 8960 /// This is a helper for lowering intrinsics that follow a target calling 8961 /// convention or require stack pointer adjustment. Only a subset of the 8962 /// intrinsic's operands need to participate in the calling convention. 8963 void SelectionDAGBuilder::populateCallLoweringInfo( 8964 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8965 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8966 bool IsPatchPoint) { 8967 TargetLowering::ArgListTy Args; 8968 Args.reserve(NumArgs); 8969 8970 // Populate the argument list. 8971 // Attributes for args start at offset 1, after the return attribute. 8972 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8973 ArgI != ArgE; ++ArgI) { 8974 const Value *V = Call->getOperand(ArgI); 8975 8976 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8977 8978 TargetLowering::ArgListEntry Entry; 8979 Entry.Node = getValue(V); 8980 Entry.Ty = V->getType(); 8981 Entry.setAttributes(Call, ArgI); 8982 Args.push_back(Entry); 8983 } 8984 8985 CLI.setDebugLoc(getCurSDLoc()) 8986 .setChain(getRoot()) 8987 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8988 .setDiscardResult(Call->use_empty()) 8989 .setIsPatchPoint(IsPatchPoint) 8990 .setIsPreallocated( 8991 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8992 } 8993 8994 /// Add a stack map intrinsic call's live variable operands to a stackmap 8995 /// or patchpoint target node's operand list. 8996 /// 8997 /// Constants are converted to TargetConstants purely as an optimization to 8998 /// avoid constant materialization and register allocation. 8999 /// 9000 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9001 /// generate addess computation nodes, and so FinalizeISel can convert the 9002 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9003 /// address materialization and register allocation, but may also be required 9004 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9005 /// alloca in the entry block, then the runtime may assume that the alloca's 9006 /// StackMap location can be read immediately after compilation and that the 9007 /// location is valid at any point during execution (this is similar to the 9008 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9009 /// only available in a register, then the runtime would need to trap when 9010 /// execution reaches the StackMap in order to read the alloca's location. 9011 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9012 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9013 SelectionDAGBuilder &Builder) { 9014 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 9015 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 9016 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 9017 Ops.push_back( 9018 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 9019 Ops.push_back( 9020 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 9021 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 9022 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 9023 Ops.push_back(Builder.DAG.getTargetFrameIndex( 9024 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 9025 } else 9026 Ops.push_back(OpVal); 9027 } 9028 } 9029 9030 /// Lower llvm.experimental.stackmap directly to its target opcode. 9031 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9032 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 9033 // [live variables...]) 9034 9035 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9036 9037 SDValue Chain, InFlag, Callee, NullPtr; 9038 SmallVector<SDValue, 32> Ops; 9039 9040 SDLoc DL = getCurSDLoc(); 9041 Callee = getValue(CI.getCalledOperand()); 9042 NullPtr = DAG.getIntPtrConstant(0, DL, true); 9043 9044 // The stackmap intrinsic only records the live variables (the arguments 9045 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9046 // intrinsic, this won't be lowered to a function call. This means we don't 9047 // have to worry about calling conventions and target specific lowering code. 9048 // Instead we perform the call lowering right here. 9049 // 9050 // chain, flag = CALLSEQ_START(chain, 0, 0) 9051 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9052 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9053 // 9054 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9055 InFlag = Chain.getValue(1); 9056 9057 // Add the <id> and <numBytes> constants. 9058 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 9059 Ops.push_back(DAG.getTargetConstant( 9060 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 9061 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 9062 Ops.push_back(DAG.getTargetConstant( 9063 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 9064 MVT::i32)); 9065 9066 // Push live variables for the stack map. 9067 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9068 9069 // We are not pushing any register mask info here on the operands list, 9070 // because the stackmap doesn't clobber anything. 9071 9072 // Push the chain and the glue flag. 9073 Ops.push_back(Chain); 9074 Ops.push_back(InFlag); 9075 9076 // Create the STACKMAP node. 9077 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9078 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9079 Chain = SDValue(SM, 0); 9080 InFlag = Chain.getValue(1); 9081 9082 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9083 9084 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9085 9086 // Set the root to the target-lowered call chain. 9087 DAG.setRoot(Chain); 9088 9089 // Inform the Frame Information that we have a stackmap in this function. 9090 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9091 } 9092 9093 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9094 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9095 const BasicBlock *EHPadBB) { 9096 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9097 // i32 <numBytes>, 9098 // i8* <target>, 9099 // i32 <numArgs>, 9100 // [Args...], 9101 // [live variables...]) 9102 9103 CallingConv::ID CC = CB.getCallingConv(); 9104 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9105 bool HasDef = !CB.getType()->isVoidTy(); 9106 SDLoc dl = getCurSDLoc(); 9107 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9108 9109 // Handle immediate and symbolic callees. 9110 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9111 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9112 /*isTarget=*/true); 9113 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9114 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9115 SDLoc(SymbolicCallee), 9116 SymbolicCallee->getValueType(0)); 9117 9118 // Get the real number of arguments participating in the call <numArgs> 9119 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9120 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9121 9122 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9123 // Intrinsics include all meta-operands up to but not including CC. 9124 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9125 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9126 "Not enough arguments provided to the patchpoint intrinsic"); 9127 9128 // For AnyRegCC the arguments are lowered later on manually. 9129 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9130 Type *ReturnTy = 9131 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9132 9133 TargetLowering::CallLoweringInfo CLI(DAG); 9134 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9135 ReturnTy, true); 9136 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9137 9138 SDNode *CallEnd = Result.second.getNode(); 9139 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9140 CallEnd = CallEnd->getOperand(0).getNode(); 9141 9142 /// Get a call instruction from the call sequence chain. 9143 /// Tail calls are not allowed. 9144 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9145 "Expected a callseq node."); 9146 SDNode *Call = CallEnd->getOperand(0).getNode(); 9147 bool HasGlue = Call->getGluedNode(); 9148 9149 // Replace the target specific call node with the patchable intrinsic. 9150 SmallVector<SDValue, 8> Ops; 9151 9152 // Add the <id> and <numBytes> constants. 9153 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9154 Ops.push_back(DAG.getTargetConstant( 9155 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9156 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9157 Ops.push_back(DAG.getTargetConstant( 9158 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9159 MVT::i32)); 9160 9161 // Add the callee. 9162 Ops.push_back(Callee); 9163 9164 // Adjust <numArgs> to account for any arguments that have been passed on the 9165 // stack instead. 9166 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9167 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9168 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9169 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9170 9171 // Add the calling convention 9172 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9173 9174 // Add the arguments we omitted previously. The register allocator should 9175 // place these in any free register. 9176 if (IsAnyRegCC) 9177 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9178 Ops.push_back(getValue(CB.getArgOperand(i))); 9179 9180 // Push the arguments from the call instruction up to the register mask. 9181 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9182 Ops.append(Call->op_begin() + 2, e); 9183 9184 // Push live variables for the stack map. 9185 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9186 9187 // Push the register mask info. 9188 if (HasGlue) 9189 Ops.push_back(*(Call->op_end()-2)); 9190 else 9191 Ops.push_back(*(Call->op_end()-1)); 9192 9193 // Push the chain (this is originally the first operand of the call, but 9194 // becomes now the last or second to last operand). 9195 Ops.push_back(*(Call->op_begin())); 9196 9197 // Push the glue flag (last operand). 9198 if (HasGlue) 9199 Ops.push_back(*(Call->op_end()-1)); 9200 9201 SDVTList NodeTys; 9202 if (IsAnyRegCC && HasDef) { 9203 // Create the return types based on the intrinsic definition 9204 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9205 SmallVector<EVT, 3> ValueVTs; 9206 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9207 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9208 9209 // There is always a chain and a glue type at the end 9210 ValueVTs.push_back(MVT::Other); 9211 ValueVTs.push_back(MVT::Glue); 9212 NodeTys = DAG.getVTList(ValueVTs); 9213 } else 9214 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9215 9216 // Replace the target specific call node with a PATCHPOINT node. 9217 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9218 dl, NodeTys, Ops); 9219 9220 // Update the NodeMap. 9221 if (HasDef) { 9222 if (IsAnyRegCC) 9223 setValue(&CB, SDValue(MN, 0)); 9224 else 9225 setValue(&CB, Result.first); 9226 } 9227 9228 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9229 // call sequence. Furthermore the location of the chain and glue can change 9230 // when the AnyReg calling convention is used and the intrinsic returns a 9231 // value. 9232 if (IsAnyRegCC && HasDef) { 9233 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9234 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9235 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9236 } else 9237 DAG.ReplaceAllUsesWith(Call, MN); 9238 DAG.DeleteNode(Call); 9239 9240 // Inform the Frame Information that we have a patchpoint in this function. 9241 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9242 } 9243 9244 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9245 unsigned Intrinsic) { 9246 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9247 SDValue Op1 = getValue(I.getArgOperand(0)); 9248 SDValue Op2; 9249 if (I.getNumArgOperands() > 1) 9250 Op2 = getValue(I.getArgOperand(1)); 9251 SDLoc dl = getCurSDLoc(); 9252 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9253 SDValue Res; 9254 SDNodeFlags SDFlags; 9255 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9256 SDFlags.copyFMF(*FPMO); 9257 9258 switch (Intrinsic) { 9259 case Intrinsic::vector_reduce_fadd: 9260 if (SDFlags.hasAllowReassociation()) 9261 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9262 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9263 SDFlags); 9264 else 9265 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9266 break; 9267 case Intrinsic::vector_reduce_fmul: 9268 if (SDFlags.hasAllowReassociation()) 9269 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9270 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9271 SDFlags); 9272 else 9273 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9274 break; 9275 case Intrinsic::vector_reduce_add: 9276 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9277 break; 9278 case Intrinsic::vector_reduce_mul: 9279 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9280 break; 9281 case Intrinsic::vector_reduce_and: 9282 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9283 break; 9284 case Intrinsic::vector_reduce_or: 9285 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9286 break; 9287 case Intrinsic::vector_reduce_xor: 9288 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9289 break; 9290 case Intrinsic::vector_reduce_smax: 9291 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9292 break; 9293 case Intrinsic::vector_reduce_smin: 9294 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9295 break; 9296 case Intrinsic::vector_reduce_umax: 9297 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9298 break; 9299 case Intrinsic::vector_reduce_umin: 9300 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9301 break; 9302 case Intrinsic::vector_reduce_fmax: 9303 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9304 break; 9305 case Intrinsic::vector_reduce_fmin: 9306 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9307 break; 9308 default: 9309 llvm_unreachable("Unhandled vector reduce intrinsic"); 9310 } 9311 setValue(&I, Res); 9312 } 9313 9314 /// Returns an AttributeList representing the attributes applied to the return 9315 /// value of the given call. 9316 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9317 SmallVector<Attribute::AttrKind, 2> Attrs; 9318 if (CLI.RetSExt) 9319 Attrs.push_back(Attribute::SExt); 9320 if (CLI.RetZExt) 9321 Attrs.push_back(Attribute::ZExt); 9322 if (CLI.IsInReg) 9323 Attrs.push_back(Attribute::InReg); 9324 9325 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9326 Attrs); 9327 } 9328 9329 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9330 /// implementation, which just calls LowerCall. 9331 /// FIXME: When all targets are 9332 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9333 std::pair<SDValue, SDValue> 9334 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9335 // Handle the incoming return values from the call. 9336 CLI.Ins.clear(); 9337 Type *OrigRetTy = CLI.RetTy; 9338 SmallVector<EVT, 4> RetTys; 9339 SmallVector<uint64_t, 4> Offsets; 9340 auto &DL = CLI.DAG.getDataLayout(); 9341 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9342 9343 if (CLI.IsPostTypeLegalization) { 9344 // If we are lowering a libcall after legalization, split the return type. 9345 SmallVector<EVT, 4> OldRetTys; 9346 SmallVector<uint64_t, 4> OldOffsets; 9347 RetTys.swap(OldRetTys); 9348 Offsets.swap(OldOffsets); 9349 9350 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9351 EVT RetVT = OldRetTys[i]; 9352 uint64_t Offset = OldOffsets[i]; 9353 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9354 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9355 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9356 RetTys.append(NumRegs, RegisterVT); 9357 for (unsigned j = 0; j != NumRegs; ++j) 9358 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9359 } 9360 } 9361 9362 SmallVector<ISD::OutputArg, 4> Outs; 9363 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9364 9365 bool CanLowerReturn = 9366 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9367 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9368 9369 SDValue DemoteStackSlot; 9370 int DemoteStackIdx = -100; 9371 if (!CanLowerReturn) { 9372 // FIXME: equivalent assert? 9373 // assert(!CS.hasInAllocaArgument() && 9374 // "sret demotion is incompatible with inalloca"); 9375 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9376 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9377 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9378 DemoteStackIdx = 9379 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9380 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9381 DL.getAllocaAddrSpace()); 9382 9383 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9384 ArgListEntry Entry; 9385 Entry.Node = DemoteStackSlot; 9386 Entry.Ty = StackSlotPtrType; 9387 Entry.IsSExt = false; 9388 Entry.IsZExt = false; 9389 Entry.IsInReg = false; 9390 Entry.IsSRet = true; 9391 Entry.IsNest = false; 9392 Entry.IsByVal = false; 9393 Entry.IsByRef = false; 9394 Entry.IsReturned = false; 9395 Entry.IsSwiftSelf = false; 9396 Entry.IsSwiftAsync = false; 9397 Entry.IsSwiftError = false; 9398 Entry.IsCFGuardTarget = false; 9399 Entry.Alignment = Alignment; 9400 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9401 CLI.NumFixedArgs += 1; 9402 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9403 9404 // sret demotion isn't compatible with tail-calls, since the sret argument 9405 // points into the callers stack frame. 9406 CLI.IsTailCall = false; 9407 } else { 9408 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9409 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9410 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9411 ISD::ArgFlagsTy Flags; 9412 if (NeedsRegBlock) { 9413 Flags.setInConsecutiveRegs(); 9414 if (I == RetTys.size() - 1) 9415 Flags.setInConsecutiveRegsLast(); 9416 } 9417 EVT VT = RetTys[I]; 9418 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9419 CLI.CallConv, VT); 9420 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9421 CLI.CallConv, VT); 9422 for (unsigned i = 0; i != NumRegs; ++i) { 9423 ISD::InputArg MyFlags; 9424 MyFlags.Flags = Flags; 9425 MyFlags.VT = RegisterVT; 9426 MyFlags.ArgVT = VT; 9427 MyFlags.Used = CLI.IsReturnValueUsed; 9428 if (CLI.RetTy->isPointerTy()) { 9429 MyFlags.Flags.setPointer(); 9430 MyFlags.Flags.setPointerAddrSpace( 9431 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9432 } 9433 if (CLI.RetSExt) 9434 MyFlags.Flags.setSExt(); 9435 if (CLI.RetZExt) 9436 MyFlags.Flags.setZExt(); 9437 if (CLI.IsInReg) 9438 MyFlags.Flags.setInReg(); 9439 CLI.Ins.push_back(MyFlags); 9440 } 9441 } 9442 } 9443 9444 // We push in swifterror return as the last element of CLI.Ins. 9445 ArgListTy &Args = CLI.getArgs(); 9446 if (supportSwiftError()) { 9447 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9448 if (Args[i].IsSwiftError) { 9449 ISD::InputArg MyFlags; 9450 MyFlags.VT = getPointerTy(DL); 9451 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9452 MyFlags.Flags.setSwiftError(); 9453 CLI.Ins.push_back(MyFlags); 9454 } 9455 } 9456 } 9457 9458 // Handle all of the outgoing arguments. 9459 CLI.Outs.clear(); 9460 CLI.OutVals.clear(); 9461 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9462 SmallVector<EVT, 4> ValueVTs; 9463 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9464 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9465 Type *FinalType = Args[i].Ty; 9466 if (Args[i].IsByVal) 9467 FinalType = Args[i].IndirectType; 9468 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9469 FinalType, CLI.CallConv, CLI.IsVarArg); 9470 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9471 ++Value) { 9472 EVT VT = ValueVTs[Value]; 9473 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9474 SDValue Op = SDValue(Args[i].Node.getNode(), 9475 Args[i].Node.getResNo() + Value); 9476 ISD::ArgFlagsTy Flags; 9477 9478 // Certain targets (such as MIPS), may have a different ABI alignment 9479 // for a type depending on the context. Give the target a chance to 9480 // specify the alignment it wants. 9481 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9482 Flags.setOrigAlign(OriginalAlignment); 9483 9484 if (Args[i].Ty->isPointerTy()) { 9485 Flags.setPointer(); 9486 Flags.setPointerAddrSpace( 9487 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9488 } 9489 if (Args[i].IsZExt) 9490 Flags.setZExt(); 9491 if (Args[i].IsSExt) 9492 Flags.setSExt(); 9493 if (Args[i].IsInReg) { 9494 // If we are using vectorcall calling convention, a structure that is 9495 // passed InReg - is surely an HVA 9496 if (CLI.CallConv == CallingConv::X86_VectorCall && 9497 isa<StructType>(FinalType)) { 9498 // The first value of a structure is marked 9499 if (0 == Value) 9500 Flags.setHvaStart(); 9501 Flags.setHva(); 9502 } 9503 // Set InReg Flag 9504 Flags.setInReg(); 9505 } 9506 if (Args[i].IsSRet) 9507 Flags.setSRet(); 9508 if (Args[i].IsSwiftSelf) 9509 Flags.setSwiftSelf(); 9510 if (Args[i].IsSwiftAsync) 9511 Flags.setSwiftAsync(); 9512 if (Args[i].IsSwiftError) 9513 Flags.setSwiftError(); 9514 if (Args[i].IsCFGuardTarget) 9515 Flags.setCFGuardTarget(); 9516 if (Args[i].IsByVal) 9517 Flags.setByVal(); 9518 if (Args[i].IsByRef) 9519 Flags.setByRef(); 9520 if (Args[i].IsPreallocated) { 9521 Flags.setPreallocated(); 9522 // Set the byval flag for CCAssignFn callbacks that don't know about 9523 // preallocated. This way we can know how many bytes we should've 9524 // allocated and how many bytes a callee cleanup function will pop. If 9525 // we port preallocated to more targets, we'll have to add custom 9526 // preallocated handling in the various CC lowering callbacks. 9527 Flags.setByVal(); 9528 } 9529 if (Args[i].IsInAlloca) { 9530 Flags.setInAlloca(); 9531 // Set the byval flag for CCAssignFn callbacks that don't know about 9532 // inalloca. This way we can know how many bytes we should've allocated 9533 // and how many bytes a callee cleanup function will pop. If we port 9534 // inalloca to more targets, we'll have to add custom inalloca handling 9535 // in the various CC lowering callbacks. 9536 Flags.setByVal(); 9537 } 9538 Align MemAlign; 9539 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9540 Type *ElementTy = Args[i].IndirectType; 9541 assert(ElementTy && "Indirect type not set in ArgListEntry"); 9542 9543 unsigned FrameSize = DL.getTypeAllocSize(ElementTy); 9544 Flags.setByValSize(FrameSize); 9545 9546 // info is not there but there are cases it cannot get right. 9547 if (auto MA = Args[i].Alignment) 9548 MemAlign = *MA; 9549 else 9550 MemAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9551 } else if (auto MA = Args[i].Alignment) { 9552 MemAlign = *MA; 9553 } else { 9554 MemAlign = OriginalAlignment; 9555 } 9556 Flags.setMemAlign(MemAlign); 9557 if (Args[i].IsNest) 9558 Flags.setNest(); 9559 if (NeedsRegBlock) 9560 Flags.setInConsecutiveRegs(); 9561 9562 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9563 CLI.CallConv, VT); 9564 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9565 CLI.CallConv, VT); 9566 SmallVector<SDValue, 4> Parts(NumParts); 9567 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9568 9569 if (Args[i].IsSExt) 9570 ExtendKind = ISD::SIGN_EXTEND; 9571 else if (Args[i].IsZExt) 9572 ExtendKind = ISD::ZERO_EXTEND; 9573 9574 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9575 // for now. 9576 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9577 CanLowerReturn) { 9578 assert((CLI.RetTy == Args[i].Ty || 9579 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9580 CLI.RetTy->getPointerAddressSpace() == 9581 Args[i].Ty->getPointerAddressSpace())) && 9582 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9583 // Before passing 'returned' to the target lowering code, ensure that 9584 // either the register MVT and the actual EVT are the same size or that 9585 // the return value and argument are extended in the same way; in these 9586 // cases it's safe to pass the argument register value unchanged as the 9587 // return register value (although it's at the target's option whether 9588 // to do so) 9589 // TODO: allow code generation to take advantage of partially preserved 9590 // registers rather than clobbering the entire register when the 9591 // parameter extension method is not compatible with the return 9592 // extension method 9593 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9594 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9595 CLI.RetZExt == Args[i].IsZExt)) 9596 Flags.setReturned(); 9597 } 9598 9599 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9600 CLI.CallConv, ExtendKind); 9601 9602 for (unsigned j = 0; j != NumParts; ++j) { 9603 // if it isn't first piece, alignment must be 1 9604 // For scalable vectors the scalable part is currently handled 9605 // by individual targets, so we just use the known minimum size here. 9606 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9607 i < CLI.NumFixedArgs, i, 9608 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9609 if (NumParts > 1 && j == 0) 9610 MyFlags.Flags.setSplit(); 9611 else if (j != 0) { 9612 MyFlags.Flags.setOrigAlign(Align(1)); 9613 if (j == NumParts - 1) 9614 MyFlags.Flags.setSplitEnd(); 9615 } 9616 9617 CLI.Outs.push_back(MyFlags); 9618 CLI.OutVals.push_back(Parts[j]); 9619 } 9620 9621 if (NeedsRegBlock && Value == NumValues - 1) 9622 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9623 } 9624 } 9625 9626 SmallVector<SDValue, 4> InVals; 9627 CLI.Chain = LowerCall(CLI, InVals); 9628 9629 // Update CLI.InVals to use outside of this function. 9630 CLI.InVals = InVals; 9631 9632 // Verify that the target's LowerCall behaved as expected. 9633 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9634 "LowerCall didn't return a valid chain!"); 9635 assert((!CLI.IsTailCall || InVals.empty()) && 9636 "LowerCall emitted a return value for a tail call!"); 9637 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9638 "LowerCall didn't emit the correct number of values!"); 9639 9640 // For a tail call, the return value is merely live-out and there aren't 9641 // any nodes in the DAG representing it. Return a special value to 9642 // indicate that a tail call has been emitted and no more Instructions 9643 // should be processed in the current block. 9644 if (CLI.IsTailCall) { 9645 CLI.DAG.setRoot(CLI.Chain); 9646 return std::make_pair(SDValue(), SDValue()); 9647 } 9648 9649 #ifndef NDEBUG 9650 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9651 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9652 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9653 "LowerCall emitted a value with the wrong type!"); 9654 } 9655 #endif 9656 9657 SmallVector<SDValue, 4> ReturnValues; 9658 if (!CanLowerReturn) { 9659 // The instruction result is the result of loading from the 9660 // hidden sret parameter. 9661 SmallVector<EVT, 1> PVTs; 9662 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9663 9664 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9665 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9666 EVT PtrVT = PVTs[0]; 9667 9668 unsigned NumValues = RetTys.size(); 9669 ReturnValues.resize(NumValues); 9670 SmallVector<SDValue, 4> Chains(NumValues); 9671 9672 // An aggregate return value cannot wrap around the address space, so 9673 // offsets to its parts don't wrap either. 9674 SDNodeFlags Flags; 9675 Flags.setNoUnsignedWrap(true); 9676 9677 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9678 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9679 for (unsigned i = 0; i < NumValues; ++i) { 9680 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9681 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9682 PtrVT), Flags); 9683 SDValue L = CLI.DAG.getLoad( 9684 RetTys[i], CLI.DL, CLI.Chain, Add, 9685 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9686 DemoteStackIdx, Offsets[i]), 9687 HiddenSRetAlign); 9688 ReturnValues[i] = L; 9689 Chains[i] = L.getValue(1); 9690 } 9691 9692 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9693 } else { 9694 // Collect the legal value parts into potentially illegal values 9695 // that correspond to the original function's return values. 9696 Optional<ISD::NodeType> AssertOp; 9697 if (CLI.RetSExt) 9698 AssertOp = ISD::AssertSext; 9699 else if (CLI.RetZExt) 9700 AssertOp = ISD::AssertZext; 9701 unsigned CurReg = 0; 9702 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9703 EVT VT = RetTys[I]; 9704 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9705 CLI.CallConv, VT); 9706 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9707 CLI.CallConv, VT); 9708 9709 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9710 NumRegs, RegisterVT, VT, nullptr, 9711 CLI.CallConv, AssertOp)); 9712 CurReg += NumRegs; 9713 } 9714 9715 // For a function returning void, there is no return value. We can't create 9716 // such a node, so we just return a null return value in that case. In 9717 // that case, nothing will actually look at the value. 9718 if (ReturnValues.empty()) 9719 return std::make_pair(SDValue(), CLI.Chain); 9720 } 9721 9722 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9723 CLI.DAG.getVTList(RetTys), ReturnValues); 9724 return std::make_pair(Res, CLI.Chain); 9725 } 9726 9727 /// Places new result values for the node in Results (their number 9728 /// and types must exactly match those of the original return values of 9729 /// the node), or leaves Results empty, which indicates that the node is not 9730 /// to be custom lowered after all. 9731 void TargetLowering::LowerOperationWrapper(SDNode *N, 9732 SmallVectorImpl<SDValue> &Results, 9733 SelectionDAG &DAG) const { 9734 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9735 9736 if (!Res.getNode()) 9737 return; 9738 9739 // If the original node has one result, take the return value from 9740 // LowerOperation as is. It might not be result number 0. 9741 if (N->getNumValues() == 1) { 9742 Results.push_back(Res); 9743 return; 9744 } 9745 9746 // If the original node has multiple results, then the return node should 9747 // have the same number of results. 9748 assert((N->getNumValues() == Res->getNumValues()) && 9749 "Lowering returned the wrong number of results!"); 9750 9751 // Places new result values base on N result number. 9752 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9753 Results.push_back(Res.getValue(I)); 9754 } 9755 9756 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9757 llvm_unreachable("LowerOperation not implemented for this target!"); 9758 } 9759 9760 void 9761 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9762 SDValue Op = getNonRegisterValue(V); 9763 assert((Op.getOpcode() != ISD::CopyFromReg || 9764 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9765 "Copy from a reg to the same reg!"); 9766 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9767 9768 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9769 // If this is an InlineAsm we have to match the registers required, not the 9770 // notional registers required by the type. 9771 9772 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9773 None); // This is not an ABI copy. 9774 SDValue Chain = DAG.getEntryNode(); 9775 9776 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9777 FuncInfo.PreferredExtendType.end()) 9778 ? ISD::ANY_EXTEND 9779 : FuncInfo.PreferredExtendType[V]; 9780 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9781 PendingExports.push_back(Chain); 9782 } 9783 9784 #include "llvm/CodeGen/SelectionDAGISel.h" 9785 9786 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9787 /// entry block, return true. This includes arguments used by switches, since 9788 /// the switch may expand into multiple basic blocks. 9789 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9790 // With FastISel active, we may be splitting blocks, so force creation 9791 // of virtual registers for all non-dead arguments. 9792 if (FastISel) 9793 return A->use_empty(); 9794 9795 const BasicBlock &Entry = A->getParent()->front(); 9796 for (const User *U : A->users()) 9797 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9798 return false; // Use not in entry block. 9799 9800 return true; 9801 } 9802 9803 using ArgCopyElisionMapTy = 9804 DenseMap<const Argument *, 9805 std::pair<const AllocaInst *, const StoreInst *>>; 9806 9807 /// Scan the entry block of the function in FuncInfo for arguments that look 9808 /// like copies into a local alloca. Record any copied arguments in 9809 /// ArgCopyElisionCandidates. 9810 static void 9811 findArgumentCopyElisionCandidates(const DataLayout &DL, 9812 FunctionLoweringInfo *FuncInfo, 9813 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9814 // Record the state of every static alloca used in the entry block. Argument 9815 // allocas are all used in the entry block, so we need approximately as many 9816 // entries as we have arguments. 9817 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9818 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9819 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9820 StaticAllocas.reserve(NumArgs * 2); 9821 9822 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9823 if (!V) 9824 return nullptr; 9825 V = V->stripPointerCasts(); 9826 const auto *AI = dyn_cast<AllocaInst>(V); 9827 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9828 return nullptr; 9829 auto Iter = StaticAllocas.insert({AI, Unknown}); 9830 return &Iter.first->second; 9831 }; 9832 9833 // Look for stores of arguments to static allocas. Look through bitcasts and 9834 // GEPs to handle type coercions, as long as the alloca is fully initialized 9835 // by the store. Any non-store use of an alloca escapes it and any subsequent 9836 // unanalyzed store might write it. 9837 // FIXME: Handle structs initialized with multiple stores. 9838 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9839 // Look for stores, and handle non-store uses conservatively. 9840 const auto *SI = dyn_cast<StoreInst>(&I); 9841 if (!SI) { 9842 // We will look through cast uses, so ignore them completely. 9843 if (I.isCast()) 9844 continue; 9845 // Ignore debug info and pseudo op intrinsics, they don't escape or store 9846 // to allocas. 9847 if (I.isDebugOrPseudoInst()) 9848 continue; 9849 // This is an unknown instruction. Assume it escapes or writes to all 9850 // static alloca operands. 9851 for (const Use &U : I.operands()) { 9852 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9853 *Info = StaticAllocaInfo::Clobbered; 9854 } 9855 continue; 9856 } 9857 9858 // If the stored value is a static alloca, mark it as escaped. 9859 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9860 *Info = StaticAllocaInfo::Clobbered; 9861 9862 // Check if the destination is a static alloca. 9863 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9864 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9865 if (!Info) 9866 continue; 9867 const AllocaInst *AI = cast<AllocaInst>(Dst); 9868 9869 // Skip allocas that have been initialized or clobbered. 9870 if (*Info != StaticAllocaInfo::Unknown) 9871 continue; 9872 9873 // Check if the stored value is an argument, and that this store fully 9874 // initializes the alloca. Don't elide copies from the same argument twice. 9875 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9876 const auto *Arg = dyn_cast<Argument>(Val); 9877 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9878 Arg->getType()->isEmptyTy() || 9879 DL.getTypeStoreSize(Arg->getType()) != 9880 DL.getTypeAllocSize(AI->getAllocatedType()) || 9881 ArgCopyElisionCandidates.count(Arg)) { 9882 *Info = StaticAllocaInfo::Clobbered; 9883 continue; 9884 } 9885 9886 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9887 << '\n'); 9888 9889 // Mark this alloca and store for argument copy elision. 9890 *Info = StaticAllocaInfo::Elidable; 9891 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9892 9893 // Stop scanning if we've seen all arguments. This will happen early in -O0 9894 // builds, which is useful, because -O0 builds have large entry blocks and 9895 // many allocas. 9896 if (ArgCopyElisionCandidates.size() == NumArgs) 9897 break; 9898 } 9899 } 9900 9901 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9902 /// ArgVal is a load from a suitable fixed stack object. 9903 static void tryToElideArgumentCopy( 9904 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9905 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9906 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9907 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9908 SDValue ArgVal, bool &ArgHasUses) { 9909 // Check if this is a load from a fixed stack object. 9910 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9911 if (!LNode) 9912 return; 9913 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9914 if (!FINode) 9915 return; 9916 9917 // Check that the fixed stack object is the right size and alignment. 9918 // Look at the alignment that the user wrote on the alloca instead of looking 9919 // at the stack object. 9920 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9921 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9922 const AllocaInst *AI = ArgCopyIter->second.first; 9923 int FixedIndex = FINode->getIndex(); 9924 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9925 int OldIndex = AllocaIndex; 9926 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9927 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9928 LLVM_DEBUG( 9929 dbgs() << " argument copy elision failed due to bad fixed stack " 9930 "object size\n"); 9931 return; 9932 } 9933 Align RequiredAlignment = AI->getAlign(); 9934 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9935 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9936 "greater than stack argument alignment (" 9937 << DebugStr(RequiredAlignment) << " vs " 9938 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9939 return; 9940 } 9941 9942 // Perform the elision. Delete the old stack object and replace its only use 9943 // in the variable info map. Mark the stack object as mutable. 9944 LLVM_DEBUG({ 9945 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9946 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9947 << '\n'; 9948 }); 9949 MFI.RemoveStackObject(OldIndex); 9950 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9951 AllocaIndex = FixedIndex; 9952 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9953 Chains.push_back(ArgVal.getValue(1)); 9954 9955 // Avoid emitting code for the store implementing the copy. 9956 const StoreInst *SI = ArgCopyIter->second.second; 9957 ElidedArgCopyInstrs.insert(SI); 9958 9959 // Check for uses of the argument again so that we can avoid exporting ArgVal 9960 // if it is't used by anything other than the store. 9961 for (const Value *U : Arg.users()) { 9962 if (U != SI) { 9963 ArgHasUses = true; 9964 break; 9965 } 9966 } 9967 } 9968 9969 void SelectionDAGISel::LowerArguments(const Function &F) { 9970 SelectionDAG &DAG = SDB->DAG; 9971 SDLoc dl = SDB->getCurSDLoc(); 9972 const DataLayout &DL = DAG.getDataLayout(); 9973 SmallVector<ISD::InputArg, 16> Ins; 9974 9975 // In Naked functions we aren't going to save any registers. 9976 if (F.hasFnAttribute(Attribute::Naked)) 9977 return; 9978 9979 if (!FuncInfo->CanLowerReturn) { 9980 // Put in an sret pointer parameter before all the other parameters. 9981 SmallVector<EVT, 1> ValueVTs; 9982 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9983 F.getReturnType()->getPointerTo( 9984 DAG.getDataLayout().getAllocaAddrSpace()), 9985 ValueVTs); 9986 9987 // NOTE: Assuming that a pointer will never break down to more than one VT 9988 // or one register. 9989 ISD::ArgFlagsTy Flags; 9990 Flags.setSRet(); 9991 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9992 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9993 ISD::InputArg::NoArgIndex, 0); 9994 Ins.push_back(RetArg); 9995 } 9996 9997 // Look for stores of arguments to static allocas. Mark such arguments with a 9998 // flag to ask the target to give us the memory location of that argument if 9999 // available. 10000 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10001 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10002 ArgCopyElisionCandidates); 10003 10004 // Set up the incoming argument description vector. 10005 for (const Argument &Arg : F.args()) { 10006 unsigned ArgNo = Arg.getArgNo(); 10007 SmallVector<EVT, 4> ValueVTs; 10008 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10009 bool isArgValueUsed = !Arg.use_empty(); 10010 unsigned PartBase = 0; 10011 Type *FinalType = Arg.getType(); 10012 if (Arg.hasAttribute(Attribute::ByVal)) 10013 FinalType = Arg.getParamByValType(); 10014 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10015 FinalType, F.getCallingConv(), F.isVarArg()); 10016 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10017 Value != NumValues; ++Value) { 10018 EVT VT = ValueVTs[Value]; 10019 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10020 ISD::ArgFlagsTy Flags; 10021 10022 10023 if (Arg.getType()->isPointerTy()) { 10024 Flags.setPointer(); 10025 Flags.setPointerAddrSpace( 10026 cast<PointerType>(Arg.getType())->getAddressSpace()); 10027 } 10028 if (Arg.hasAttribute(Attribute::ZExt)) 10029 Flags.setZExt(); 10030 if (Arg.hasAttribute(Attribute::SExt)) 10031 Flags.setSExt(); 10032 if (Arg.hasAttribute(Attribute::InReg)) { 10033 // If we are using vectorcall calling convention, a structure that is 10034 // passed InReg - is surely an HVA 10035 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10036 isa<StructType>(Arg.getType())) { 10037 // The first value of a structure is marked 10038 if (0 == Value) 10039 Flags.setHvaStart(); 10040 Flags.setHva(); 10041 } 10042 // Set InReg Flag 10043 Flags.setInReg(); 10044 } 10045 if (Arg.hasAttribute(Attribute::StructRet)) 10046 Flags.setSRet(); 10047 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10048 Flags.setSwiftSelf(); 10049 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10050 Flags.setSwiftAsync(); 10051 if (Arg.hasAttribute(Attribute::SwiftError)) 10052 Flags.setSwiftError(); 10053 if (Arg.hasAttribute(Attribute::ByVal)) 10054 Flags.setByVal(); 10055 if (Arg.hasAttribute(Attribute::ByRef)) 10056 Flags.setByRef(); 10057 if (Arg.hasAttribute(Attribute::InAlloca)) { 10058 Flags.setInAlloca(); 10059 // Set the byval flag for CCAssignFn callbacks that don't know about 10060 // inalloca. This way we can know how many bytes we should've allocated 10061 // and how many bytes a callee cleanup function will pop. If we port 10062 // inalloca to more targets, we'll have to add custom inalloca handling 10063 // in the various CC lowering callbacks. 10064 Flags.setByVal(); 10065 } 10066 if (Arg.hasAttribute(Attribute::Preallocated)) { 10067 Flags.setPreallocated(); 10068 // Set the byval flag for CCAssignFn callbacks that don't know about 10069 // preallocated. This way we can know how many bytes we should've 10070 // allocated and how many bytes a callee cleanup function will pop. If 10071 // we port preallocated to more targets, we'll have to add custom 10072 // preallocated handling in the various CC lowering callbacks. 10073 Flags.setByVal(); 10074 } 10075 10076 // Certain targets (such as MIPS), may have a different ABI alignment 10077 // for a type depending on the context. Give the target a chance to 10078 // specify the alignment it wants. 10079 const Align OriginalAlignment( 10080 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10081 Flags.setOrigAlign(OriginalAlignment); 10082 10083 Align MemAlign; 10084 Type *ArgMemTy = nullptr; 10085 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10086 Flags.isByRef()) { 10087 if (!ArgMemTy) 10088 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10089 10090 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10091 10092 // For in-memory arguments, size and alignment should be passed from FE. 10093 // BE will guess if this info is not there but there are cases it cannot 10094 // get right. 10095 if (auto ParamAlign = Arg.getParamStackAlign()) 10096 MemAlign = *ParamAlign; 10097 else if ((ParamAlign = Arg.getParamAlign())) 10098 MemAlign = *ParamAlign; 10099 else 10100 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10101 if (Flags.isByRef()) 10102 Flags.setByRefSize(MemSize); 10103 else 10104 Flags.setByValSize(MemSize); 10105 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10106 MemAlign = *ParamAlign; 10107 } else { 10108 MemAlign = OriginalAlignment; 10109 } 10110 Flags.setMemAlign(MemAlign); 10111 10112 if (Arg.hasAttribute(Attribute::Nest)) 10113 Flags.setNest(); 10114 if (NeedsRegBlock) 10115 Flags.setInConsecutiveRegs(); 10116 if (ArgCopyElisionCandidates.count(&Arg)) 10117 Flags.setCopyElisionCandidate(); 10118 if (Arg.hasAttribute(Attribute::Returned)) 10119 Flags.setReturned(); 10120 10121 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10122 *CurDAG->getContext(), F.getCallingConv(), VT); 10123 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10124 *CurDAG->getContext(), F.getCallingConv(), VT); 10125 for (unsigned i = 0; i != NumRegs; ++i) { 10126 // For scalable vectors, use the minimum size; individual targets 10127 // are responsible for handling scalable vector arguments and 10128 // return values. 10129 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10130 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10131 if (NumRegs > 1 && i == 0) 10132 MyFlags.Flags.setSplit(); 10133 // if it isn't first piece, alignment must be 1 10134 else if (i > 0) { 10135 MyFlags.Flags.setOrigAlign(Align(1)); 10136 if (i == NumRegs - 1) 10137 MyFlags.Flags.setSplitEnd(); 10138 } 10139 Ins.push_back(MyFlags); 10140 } 10141 if (NeedsRegBlock && Value == NumValues - 1) 10142 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10143 PartBase += VT.getStoreSize().getKnownMinSize(); 10144 } 10145 } 10146 10147 // Call the target to set up the argument values. 10148 SmallVector<SDValue, 8> InVals; 10149 SDValue NewRoot = TLI->LowerFormalArguments( 10150 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10151 10152 // Verify that the target's LowerFormalArguments behaved as expected. 10153 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10154 "LowerFormalArguments didn't return a valid chain!"); 10155 assert(InVals.size() == Ins.size() && 10156 "LowerFormalArguments didn't emit the correct number of values!"); 10157 LLVM_DEBUG({ 10158 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10159 assert(InVals[i].getNode() && 10160 "LowerFormalArguments emitted a null value!"); 10161 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10162 "LowerFormalArguments emitted a value with the wrong type!"); 10163 } 10164 }); 10165 10166 // Update the DAG with the new chain value resulting from argument lowering. 10167 DAG.setRoot(NewRoot); 10168 10169 // Set up the argument values. 10170 unsigned i = 0; 10171 if (!FuncInfo->CanLowerReturn) { 10172 // Create a virtual register for the sret pointer, and put in a copy 10173 // from the sret argument into it. 10174 SmallVector<EVT, 1> ValueVTs; 10175 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10176 F.getReturnType()->getPointerTo( 10177 DAG.getDataLayout().getAllocaAddrSpace()), 10178 ValueVTs); 10179 MVT VT = ValueVTs[0].getSimpleVT(); 10180 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10181 Optional<ISD::NodeType> AssertOp = None; 10182 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10183 nullptr, F.getCallingConv(), AssertOp); 10184 10185 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10186 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10187 Register SRetReg = 10188 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10189 FuncInfo->DemoteRegister = SRetReg; 10190 NewRoot = 10191 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10192 DAG.setRoot(NewRoot); 10193 10194 // i indexes lowered arguments. Bump it past the hidden sret argument. 10195 ++i; 10196 } 10197 10198 SmallVector<SDValue, 4> Chains; 10199 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10200 for (const Argument &Arg : F.args()) { 10201 SmallVector<SDValue, 4> ArgValues; 10202 SmallVector<EVT, 4> ValueVTs; 10203 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10204 unsigned NumValues = ValueVTs.size(); 10205 if (NumValues == 0) 10206 continue; 10207 10208 bool ArgHasUses = !Arg.use_empty(); 10209 10210 // Elide the copying store if the target loaded this argument from a 10211 // suitable fixed stack object. 10212 if (Ins[i].Flags.isCopyElisionCandidate()) { 10213 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10214 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10215 InVals[i], ArgHasUses); 10216 } 10217 10218 // If this argument is unused then remember its value. It is used to generate 10219 // debugging information. 10220 bool isSwiftErrorArg = 10221 TLI->supportSwiftError() && 10222 Arg.hasAttribute(Attribute::SwiftError); 10223 if (!ArgHasUses && !isSwiftErrorArg) { 10224 SDB->setUnusedArgValue(&Arg, InVals[i]); 10225 10226 // Also remember any frame index for use in FastISel. 10227 if (FrameIndexSDNode *FI = 10228 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10229 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10230 } 10231 10232 for (unsigned Val = 0; Val != NumValues; ++Val) { 10233 EVT VT = ValueVTs[Val]; 10234 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10235 F.getCallingConv(), VT); 10236 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10237 *CurDAG->getContext(), F.getCallingConv(), VT); 10238 10239 // Even an apparent 'unused' swifterror argument needs to be returned. So 10240 // we do generate a copy for it that can be used on return from the 10241 // function. 10242 if (ArgHasUses || isSwiftErrorArg) { 10243 Optional<ISD::NodeType> AssertOp; 10244 if (Arg.hasAttribute(Attribute::SExt)) 10245 AssertOp = ISD::AssertSext; 10246 else if (Arg.hasAttribute(Attribute::ZExt)) 10247 AssertOp = ISD::AssertZext; 10248 10249 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10250 PartVT, VT, nullptr, 10251 F.getCallingConv(), AssertOp)); 10252 } 10253 10254 i += NumParts; 10255 } 10256 10257 // We don't need to do anything else for unused arguments. 10258 if (ArgValues.empty()) 10259 continue; 10260 10261 // Note down frame index. 10262 if (FrameIndexSDNode *FI = 10263 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10264 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10265 10266 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10267 SDB->getCurSDLoc()); 10268 10269 SDB->setValue(&Arg, Res); 10270 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10271 // We want to associate the argument with the frame index, among 10272 // involved operands, that correspond to the lowest address. The 10273 // getCopyFromParts function, called earlier, is swapping the order of 10274 // the operands to BUILD_PAIR depending on endianness. The result of 10275 // that swapping is that the least significant bits of the argument will 10276 // be in the first operand of the BUILD_PAIR node, and the most 10277 // significant bits will be in the second operand. 10278 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10279 if (LoadSDNode *LNode = 10280 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10281 if (FrameIndexSDNode *FI = 10282 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10283 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10284 } 10285 10286 // Analyses past this point are naive and don't expect an assertion. 10287 if (Res.getOpcode() == ISD::AssertZext) 10288 Res = Res.getOperand(0); 10289 10290 // Update the SwiftErrorVRegDefMap. 10291 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10292 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10293 if (Register::isVirtualRegister(Reg)) 10294 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10295 Reg); 10296 } 10297 10298 // If this argument is live outside of the entry block, insert a copy from 10299 // wherever we got it to the vreg that other BB's will reference it as. 10300 if (Res.getOpcode() == ISD::CopyFromReg) { 10301 // If we can, though, try to skip creating an unnecessary vreg. 10302 // FIXME: This isn't very clean... it would be nice to make this more 10303 // general. 10304 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10305 if (Register::isVirtualRegister(Reg)) { 10306 FuncInfo->ValueMap[&Arg] = Reg; 10307 continue; 10308 } 10309 } 10310 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10311 FuncInfo->InitializeRegForValue(&Arg); 10312 SDB->CopyToExportRegsIfNeeded(&Arg); 10313 } 10314 } 10315 10316 if (!Chains.empty()) { 10317 Chains.push_back(NewRoot); 10318 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10319 } 10320 10321 DAG.setRoot(NewRoot); 10322 10323 assert(i == InVals.size() && "Argument register count mismatch!"); 10324 10325 // If any argument copy elisions occurred and we have debug info, update the 10326 // stale frame indices used in the dbg.declare variable info table. 10327 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10328 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10329 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10330 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10331 if (I != ArgCopyElisionFrameIndexMap.end()) 10332 VI.Slot = I->second; 10333 } 10334 } 10335 10336 // Finally, if the target has anything special to do, allow it to do so. 10337 emitFunctionEntryCode(); 10338 } 10339 10340 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10341 /// ensure constants are generated when needed. Remember the virtual registers 10342 /// that need to be added to the Machine PHI nodes as input. We cannot just 10343 /// directly add them, because expansion might result in multiple MBB's for one 10344 /// BB. As such, the start of the BB might correspond to a different MBB than 10345 /// the end. 10346 void 10347 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10348 const Instruction *TI = LLVMBB->getTerminator(); 10349 10350 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10351 10352 // Check PHI nodes in successors that expect a value to be available from this 10353 // block. 10354 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10355 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10356 if (!isa<PHINode>(SuccBB->begin())) continue; 10357 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10358 10359 // If this terminator has multiple identical successors (common for 10360 // switches), only handle each succ once. 10361 if (!SuccsHandled.insert(SuccMBB).second) 10362 continue; 10363 10364 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10365 10366 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10367 // nodes and Machine PHI nodes, but the incoming operands have not been 10368 // emitted yet. 10369 for (const PHINode &PN : SuccBB->phis()) { 10370 // Ignore dead phi's. 10371 if (PN.use_empty()) 10372 continue; 10373 10374 // Skip empty types 10375 if (PN.getType()->isEmptyTy()) 10376 continue; 10377 10378 unsigned Reg; 10379 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10380 10381 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10382 unsigned &RegOut = ConstantsOut[C]; 10383 if (RegOut == 0) { 10384 RegOut = FuncInfo.CreateRegs(C); 10385 CopyValueToVirtualRegister(C, RegOut); 10386 } 10387 Reg = RegOut; 10388 } else { 10389 DenseMap<const Value *, Register>::iterator I = 10390 FuncInfo.ValueMap.find(PHIOp); 10391 if (I != FuncInfo.ValueMap.end()) 10392 Reg = I->second; 10393 else { 10394 assert(isa<AllocaInst>(PHIOp) && 10395 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10396 "Didn't codegen value into a register!??"); 10397 Reg = FuncInfo.CreateRegs(PHIOp); 10398 CopyValueToVirtualRegister(PHIOp, Reg); 10399 } 10400 } 10401 10402 // Remember that this register needs to added to the machine PHI node as 10403 // the input for this MBB. 10404 SmallVector<EVT, 4> ValueVTs; 10405 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10406 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10407 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10408 EVT VT = ValueVTs[vti]; 10409 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10410 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10411 FuncInfo.PHINodesToUpdate.push_back( 10412 std::make_pair(&*MBBI++, Reg + i)); 10413 Reg += NumRegisters; 10414 } 10415 } 10416 } 10417 10418 ConstantsOut.clear(); 10419 } 10420 10421 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10422 /// is 0. 10423 MachineBasicBlock * 10424 SelectionDAGBuilder::StackProtectorDescriptor:: 10425 AddSuccessorMBB(const BasicBlock *BB, 10426 MachineBasicBlock *ParentMBB, 10427 bool IsLikely, 10428 MachineBasicBlock *SuccMBB) { 10429 // If SuccBB has not been created yet, create it. 10430 if (!SuccMBB) { 10431 MachineFunction *MF = ParentMBB->getParent(); 10432 MachineFunction::iterator BBI(ParentMBB); 10433 SuccMBB = MF->CreateMachineBasicBlock(BB); 10434 MF->insert(++BBI, SuccMBB); 10435 } 10436 // Add it as a successor of ParentMBB. 10437 ParentMBB->addSuccessor( 10438 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10439 return SuccMBB; 10440 } 10441 10442 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10443 MachineFunction::iterator I(MBB); 10444 if (++I == FuncInfo.MF->end()) 10445 return nullptr; 10446 return &*I; 10447 } 10448 10449 /// During lowering new call nodes can be created (such as memset, etc.). 10450 /// Those will become new roots of the current DAG, but complications arise 10451 /// when they are tail calls. In such cases, the call lowering will update 10452 /// the root, but the builder still needs to know that a tail call has been 10453 /// lowered in order to avoid generating an additional return. 10454 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10455 // If the node is null, we do have a tail call. 10456 if (MaybeTC.getNode() != nullptr) 10457 DAG.setRoot(MaybeTC); 10458 else 10459 HasTailCall = true; 10460 } 10461 10462 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10463 MachineBasicBlock *SwitchMBB, 10464 MachineBasicBlock *DefaultMBB) { 10465 MachineFunction *CurMF = FuncInfo.MF; 10466 MachineBasicBlock *NextMBB = nullptr; 10467 MachineFunction::iterator BBI(W.MBB); 10468 if (++BBI != FuncInfo.MF->end()) 10469 NextMBB = &*BBI; 10470 10471 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10472 10473 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10474 10475 if (Size == 2 && W.MBB == SwitchMBB) { 10476 // If any two of the cases has the same destination, and if one value 10477 // is the same as the other, but has one bit unset that the other has set, 10478 // use bit manipulation to do two compares at once. For example: 10479 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10480 // TODO: This could be extended to merge any 2 cases in switches with 3 10481 // cases. 10482 // TODO: Handle cases where W.CaseBB != SwitchBB. 10483 CaseCluster &Small = *W.FirstCluster; 10484 CaseCluster &Big = *W.LastCluster; 10485 10486 if (Small.Low == Small.High && Big.Low == Big.High && 10487 Small.MBB == Big.MBB) { 10488 const APInt &SmallValue = Small.Low->getValue(); 10489 const APInt &BigValue = Big.Low->getValue(); 10490 10491 // Check that there is only one bit different. 10492 APInt CommonBit = BigValue ^ SmallValue; 10493 if (CommonBit.isPowerOf2()) { 10494 SDValue CondLHS = getValue(Cond); 10495 EVT VT = CondLHS.getValueType(); 10496 SDLoc DL = getCurSDLoc(); 10497 10498 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10499 DAG.getConstant(CommonBit, DL, VT)); 10500 SDValue Cond = DAG.getSetCC( 10501 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10502 ISD::SETEQ); 10503 10504 // Update successor info. 10505 // Both Small and Big will jump to Small.BB, so we sum up the 10506 // probabilities. 10507 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10508 if (BPI) 10509 addSuccessorWithProb( 10510 SwitchMBB, DefaultMBB, 10511 // The default destination is the first successor in IR. 10512 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10513 else 10514 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10515 10516 // Insert the true branch. 10517 SDValue BrCond = 10518 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10519 DAG.getBasicBlock(Small.MBB)); 10520 // Insert the false branch. 10521 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10522 DAG.getBasicBlock(DefaultMBB)); 10523 10524 DAG.setRoot(BrCond); 10525 return; 10526 } 10527 } 10528 } 10529 10530 if (TM.getOptLevel() != CodeGenOpt::None) { 10531 // Here, we order cases by probability so the most likely case will be 10532 // checked first. However, two clusters can have the same probability in 10533 // which case their relative ordering is non-deterministic. So we use Low 10534 // as a tie-breaker as clusters are guaranteed to never overlap. 10535 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10536 [](const CaseCluster &a, const CaseCluster &b) { 10537 return a.Prob != b.Prob ? 10538 a.Prob > b.Prob : 10539 a.Low->getValue().slt(b.Low->getValue()); 10540 }); 10541 10542 // Rearrange the case blocks so that the last one falls through if possible 10543 // without changing the order of probabilities. 10544 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10545 --I; 10546 if (I->Prob > W.LastCluster->Prob) 10547 break; 10548 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10549 std::swap(*I, *W.LastCluster); 10550 break; 10551 } 10552 } 10553 } 10554 10555 // Compute total probability. 10556 BranchProbability DefaultProb = W.DefaultProb; 10557 BranchProbability UnhandledProbs = DefaultProb; 10558 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10559 UnhandledProbs += I->Prob; 10560 10561 MachineBasicBlock *CurMBB = W.MBB; 10562 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10563 bool FallthroughUnreachable = false; 10564 MachineBasicBlock *Fallthrough; 10565 if (I == W.LastCluster) { 10566 // For the last cluster, fall through to the default destination. 10567 Fallthrough = DefaultMBB; 10568 FallthroughUnreachable = isa<UnreachableInst>( 10569 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10570 } else { 10571 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10572 CurMF->insert(BBI, Fallthrough); 10573 // Put Cond in a virtual register to make it available from the new blocks. 10574 ExportFromCurrentBlock(Cond); 10575 } 10576 UnhandledProbs -= I->Prob; 10577 10578 switch (I->Kind) { 10579 case CC_JumpTable: { 10580 // FIXME: Optimize away range check based on pivot comparisons. 10581 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10582 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10583 10584 // The jump block hasn't been inserted yet; insert it here. 10585 MachineBasicBlock *JumpMBB = JT->MBB; 10586 CurMF->insert(BBI, JumpMBB); 10587 10588 auto JumpProb = I->Prob; 10589 auto FallthroughProb = UnhandledProbs; 10590 10591 // If the default statement is a target of the jump table, we evenly 10592 // distribute the default probability to successors of CurMBB. Also 10593 // update the probability on the edge from JumpMBB to Fallthrough. 10594 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10595 SE = JumpMBB->succ_end(); 10596 SI != SE; ++SI) { 10597 if (*SI == DefaultMBB) { 10598 JumpProb += DefaultProb / 2; 10599 FallthroughProb -= DefaultProb / 2; 10600 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10601 JumpMBB->normalizeSuccProbs(); 10602 break; 10603 } 10604 } 10605 10606 if (FallthroughUnreachable) { 10607 // Skip the range check if the fallthrough block is unreachable. 10608 JTH->OmitRangeCheck = true; 10609 } 10610 10611 if (!JTH->OmitRangeCheck) 10612 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10613 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10614 CurMBB->normalizeSuccProbs(); 10615 10616 // The jump table header will be inserted in our current block, do the 10617 // range check, and fall through to our fallthrough block. 10618 JTH->HeaderBB = CurMBB; 10619 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10620 10621 // If we're in the right place, emit the jump table header right now. 10622 if (CurMBB == SwitchMBB) { 10623 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10624 JTH->Emitted = true; 10625 } 10626 break; 10627 } 10628 case CC_BitTests: { 10629 // FIXME: Optimize away range check based on pivot comparisons. 10630 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10631 10632 // The bit test blocks haven't been inserted yet; insert them here. 10633 for (BitTestCase &BTC : BTB->Cases) 10634 CurMF->insert(BBI, BTC.ThisBB); 10635 10636 // Fill in fields of the BitTestBlock. 10637 BTB->Parent = CurMBB; 10638 BTB->Default = Fallthrough; 10639 10640 BTB->DefaultProb = UnhandledProbs; 10641 // If the cases in bit test don't form a contiguous range, we evenly 10642 // distribute the probability on the edge to Fallthrough to two 10643 // successors of CurMBB. 10644 if (!BTB->ContiguousRange) { 10645 BTB->Prob += DefaultProb / 2; 10646 BTB->DefaultProb -= DefaultProb / 2; 10647 } 10648 10649 if (FallthroughUnreachable) { 10650 // Skip the range check if the fallthrough block is unreachable. 10651 BTB->OmitRangeCheck = true; 10652 } 10653 10654 // If we're in the right place, emit the bit test header right now. 10655 if (CurMBB == SwitchMBB) { 10656 visitBitTestHeader(*BTB, SwitchMBB); 10657 BTB->Emitted = true; 10658 } 10659 break; 10660 } 10661 case CC_Range: { 10662 const Value *RHS, *LHS, *MHS; 10663 ISD::CondCode CC; 10664 if (I->Low == I->High) { 10665 // Check Cond == I->Low. 10666 CC = ISD::SETEQ; 10667 LHS = Cond; 10668 RHS=I->Low; 10669 MHS = nullptr; 10670 } else { 10671 // Check I->Low <= Cond <= I->High. 10672 CC = ISD::SETLE; 10673 LHS = I->Low; 10674 MHS = Cond; 10675 RHS = I->High; 10676 } 10677 10678 // If Fallthrough is unreachable, fold away the comparison. 10679 if (FallthroughUnreachable) 10680 CC = ISD::SETTRUE; 10681 10682 // The false probability is the sum of all unhandled cases. 10683 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10684 getCurSDLoc(), I->Prob, UnhandledProbs); 10685 10686 if (CurMBB == SwitchMBB) 10687 visitSwitchCase(CB, SwitchMBB); 10688 else 10689 SL->SwitchCases.push_back(CB); 10690 10691 break; 10692 } 10693 } 10694 CurMBB = Fallthrough; 10695 } 10696 } 10697 10698 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10699 CaseClusterIt First, 10700 CaseClusterIt Last) { 10701 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10702 if (X.Prob != CC.Prob) 10703 return X.Prob > CC.Prob; 10704 10705 // Ties are broken by comparing the case value. 10706 return X.Low->getValue().slt(CC.Low->getValue()); 10707 }); 10708 } 10709 10710 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10711 const SwitchWorkListItem &W, 10712 Value *Cond, 10713 MachineBasicBlock *SwitchMBB) { 10714 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10715 "Clusters not sorted?"); 10716 10717 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10718 10719 // Balance the tree based on branch probabilities to create a near-optimal (in 10720 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10721 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10722 CaseClusterIt LastLeft = W.FirstCluster; 10723 CaseClusterIt FirstRight = W.LastCluster; 10724 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10725 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10726 10727 // Move LastLeft and FirstRight towards each other from opposite directions to 10728 // find a partitioning of the clusters which balances the probability on both 10729 // sides. If LeftProb and RightProb are equal, alternate which side is 10730 // taken to ensure 0-probability nodes are distributed evenly. 10731 unsigned I = 0; 10732 while (LastLeft + 1 < FirstRight) { 10733 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10734 LeftProb += (++LastLeft)->Prob; 10735 else 10736 RightProb += (--FirstRight)->Prob; 10737 I++; 10738 } 10739 10740 while (true) { 10741 // Our binary search tree differs from a typical BST in that ours can have up 10742 // to three values in each leaf. The pivot selection above doesn't take that 10743 // into account, which means the tree might require more nodes and be less 10744 // efficient. We compensate for this here. 10745 10746 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10747 unsigned NumRight = W.LastCluster - FirstRight + 1; 10748 10749 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10750 // If one side has less than 3 clusters, and the other has more than 3, 10751 // consider taking a cluster from the other side. 10752 10753 if (NumLeft < NumRight) { 10754 // Consider moving the first cluster on the right to the left side. 10755 CaseCluster &CC = *FirstRight; 10756 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10757 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10758 if (LeftSideRank <= RightSideRank) { 10759 // Moving the cluster to the left does not demote it. 10760 ++LastLeft; 10761 ++FirstRight; 10762 continue; 10763 } 10764 } else { 10765 assert(NumRight < NumLeft); 10766 // Consider moving the last element on the left to the right side. 10767 CaseCluster &CC = *LastLeft; 10768 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10769 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10770 if (RightSideRank <= LeftSideRank) { 10771 // Moving the cluster to the right does not demot it. 10772 --LastLeft; 10773 --FirstRight; 10774 continue; 10775 } 10776 } 10777 } 10778 break; 10779 } 10780 10781 assert(LastLeft + 1 == FirstRight); 10782 assert(LastLeft >= W.FirstCluster); 10783 assert(FirstRight <= W.LastCluster); 10784 10785 // Use the first element on the right as pivot since we will make less-than 10786 // comparisons against it. 10787 CaseClusterIt PivotCluster = FirstRight; 10788 assert(PivotCluster > W.FirstCluster); 10789 assert(PivotCluster <= W.LastCluster); 10790 10791 CaseClusterIt FirstLeft = W.FirstCluster; 10792 CaseClusterIt LastRight = W.LastCluster; 10793 10794 const ConstantInt *Pivot = PivotCluster->Low; 10795 10796 // New blocks will be inserted immediately after the current one. 10797 MachineFunction::iterator BBI(W.MBB); 10798 ++BBI; 10799 10800 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10801 // we can branch to its destination directly if it's squeezed exactly in 10802 // between the known lower bound and Pivot - 1. 10803 MachineBasicBlock *LeftMBB; 10804 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10805 FirstLeft->Low == W.GE && 10806 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10807 LeftMBB = FirstLeft->MBB; 10808 } else { 10809 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10810 FuncInfo.MF->insert(BBI, LeftMBB); 10811 WorkList.push_back( 10812 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10813 // Put Cond in a virtual register to make it available from the new blocks. 10814 ExportFromCurrentBlock(Cond); 10815 } 10816 10817 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10818 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10819 // directly if RHS.High equals the current upper bound. 10820 MachineBasicBlock *RightMBB; 10821 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10822 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10823 RightMBB = FirstRight->MBB; 10824 } else { 10825 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10826 FuncInfo.MF->insert(BBI, RightMBB); 10827 WorkList.push_back( 10828 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10829 // Put Cond in a virtual register to make it available from the new blocks. 10830 ExportFromCurrentBlock(Cond); 10831 } 10832 10833 // Create the CaseBlock record that will be used to lower the branch. 10834 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10835 getCurSDLoc(), LeftProb, RightProb); 10836 10837 if (W.MBB == SwitchMBB) 10838 visitSwitchCase(CB, SwitchMBB); 10839 else 10840 SL->SwitchCases.push_back(CB); 10841 } 10842 10843 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10844 // from the swith statement. 10845 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10846 BranchProbability PeeledCaseProb) { 10847 if (PeeledCaseProb == BranchProbability::getOne()) 10848 return BranchProbability::getZero(); 10849 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10850 10851 uint32_t Numerator = CaseProb.getNumerator(); 10852 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10853 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10854 } 10855 10856 // Try to peel the top probability case if it exceeds the threshold. 10857 // Return current MachineBasicBlock for the switch statement if the peeling 10858 // does not occur. 10859 // If the peeling is performed, return the newly created MachineBasicBlock 10860 // for the peeled switch statement. Also update Clusters to remove the peeled 10861 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10862 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10863 const SwitchInst &SI, CaseClusterVector &Clusters, 10864 BranchProbability &PeeledCaseProb) { 10865 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10866 // Don't perform if there is only one cluster or optimizing for size. 10867 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10868 TM.getOptLevel() == CodeGenOpt::None || 10869 SwitchMBB->getParent()->getFunction().hasMinSize()) 10870 return SwitchMBB; 10871 10872 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10873 unsigned PeeledCaseIndex = 0; 10874 bool SwitchPeeled = false; 10875 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10876 CaseCluster &CC = Clusters[Index]; 10877 if (CC.Prob < TopCaseProb) 10878 continue; 10879 TopCaseProb = CC.Prob; 10880 PeeledCaseIndex = Index; 10881 SwitchPeeled = true; 10882 } 10883 if (!SwitchPeeled) 10884 return SwitchMBB; 10885 10886 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10887 << TopCaseProb << "\n"); 10888 10889 // Record the MBB for the peeled switch statement. 10890 MachineFunction::iterator BBI(SwitchMBB); 10891 ++BBI; 10892 MachineBasicBlock *PeeledSwitchMBB = 10893 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10894 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10895 10896 ExportFromCurrentBlock(SI.getCondition()); 10897 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10898 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10899 nullptr, nullptr, TopCaseProb.getCompl()}; 10900 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10901 10902 Clusters.erase(PeeledCaseIt); 10903 for (CaseCluster &CC : Clusters) { 10904 LLVM_DEBUG( 10905 dbgs() << "Scale the probablity for one cluster, before scaling: " 10906 << CC.Prob << "\n"); 10907 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10908 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10909 } 10910 PeeledCaseProb = TopCaseProb; 10911 return PeeledSwitchMBB; 10912 } 10913 10914 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10915 // Extract cases from the switch. 10916 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10917 CaseClusterVector Clusters; 10918 Clusters.reserve(SI.getNumCases()); 10919 for (auto I : SI.cases()) { 10920 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10921 const ConstantInt *CaseVal = I.getCaseValue(); 10922 BranchProbability Prob = 10923 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10924 : BranchProbability(1, SI.getNumCases() + 1); 10925 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10926 } 10927 10928 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10929 10930 // Cluster adjacent cases with the same destination. We do this at all 10931 // optimization levels because it's cheap to do and will make codegen faster 10932 // if there are many clusters. 10933 sortAndRangeify(Clusters); 10934 10935 // The branch probablity of the peeled case. 10936 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10937 MachineBasicBlock *PeeledSwitchMBB = 10938 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10939 10940 // If there is only the default destination, jump there directly. 10941 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10942 if (Clusters.empty()) { 10943 assert(PeeledSwitchMBB == SwitchMBB); 10944 SwitchMBB->addSuccessor(DefaultMBB); 10945 if (DefaultMBB != NextBlock(SwitchMBB)) { 10946 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10947 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10948 } 10949 return; 10950 } 10951 10952 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10953 SL->findBitTestClusters(Clusters, &SI); 10954 10955 LLVM_DEBUG({ 10956 dbgs() << "Case clusters: "; 10957 for (const CaseCluster &C : Clusters) { 10958 if (C.Kind == CC_JumpTable) 10959 dbgs() << "JT:"; 10960 if (C.Kind == CC_BitTests) 10961 dbgs() << "BT:"; 10962 10963 C.Low->getValue().print(dbgs(), true); 10964 if (C.Low != C.High) { 10965 dbgs() << '-'; 10966 C.High->getValue().print(dbgs(), true); 10967 } 10968 dbgs() << ' '; 10969 } 10970 dbgs() << '\n'; 10971 }); 10972 10973 assert(!Clusters.empty()); 10974 SwitchWorkList WorkList; 10975 CaseClusterIt First = Clusters.begin(); 10976 CaseClusterIt Last = Clusters.end() - 1; 10977 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10978 // Scale the branchprobability for DefaultMBB if the peel occurs and 10979 // DefaultMBB is not replaced. 10980 if (PeeledCaseProb != BranchProbability::getZero() && 10981 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10982 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10983 WorkList.push_back( 10984 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10985 10986 while (!WorkList.empty()) { 10987 SwitchWorkListItem W = WorkList.pop_back_val(); 10988 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10989 10990 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10991 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10992 // For optimized builds, lower large range as a balanced binary tree. 10993 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10994 continue; 10995 } 10996 10997 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10998 } 10999 } 11000 11001 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11002 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11003 auto DL = getCurSDLoc(); 11004 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11005 EVT OpVT = 11006 TLI.getTypeToTransformTo(*DAG.getContext(), ResultVT.getScalarType()); 11007 SDValue Step = DAG.getConstant(1, DL, OpVT); 11008 setValue(&I, DAG.getStepVector(DL, ResultVT, Step)); 11009 } 11010 11011 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11012 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11013 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11014 11015 SDLoc DL = getCurSDLoc(); 11016 SDValue V = getValue(I.getOperand(0)); 11017 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11018 11019 if (VT.isScalableVector()) { 11020 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11021 return; 11022 } 11023 11024 // Use VECTOR_SHUFFLE for the fixed-length vector 11025 // to maintain existing behavior. 11026 SmallVector<int, 8> Mask; 11027 unsigned NumElts = VT.getVectorMinNumElements(); 11028 for (unsigned i = 0; i != NumElts; ++i) 11029 Mask.push_back(NumElts - 1 - i); 11030 11031 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11032 } 11033 11034 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11035 SmallVector<EVT, 4> ValueVTs; 11036 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11037 ValueVTs); 11038 unsigned NumValues = ValueVTs.size(); 11039 if (NumValues == 0) return; 11040 11041 SmallVector<SDValue, 4> Values(NumValues); 11042 SDValue Op = getValue(I.getOperand(0)); 11043 11044 for (unsigned i = 0; i != NumValues; ++i) 11045 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11046 SDValue(Op.getNode(), Op.getResNo() + i)); 11047 11048 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11049 DAG.getVTList(ValueVTs), Values)); 11050 } 11051 11052 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11053 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11054 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11055 11056 SDLoc DL = getCurSDLoc(); 11057 SDValue V1 = getValue(I.getOperand(0)); 11058 SDValue V2 = getValue(I.getOperand(1)); 11059 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11060 11061 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11062 if (VT.isScalableVector()) { 11063 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11064 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11065 DAG.getConstant(Imm, DL, IdxVT))); 11066 return; 11067 } 11068 11069 unsigned NumElts = VT.getVectorNumElements(); 11070 11071 if ((-Imm > NumElts) || (Imm >= NumElts)) { 11072 // Result is undefined if immediate is out-of-bounds. 11073 setValue(&I, DAG.getUNDEF(VT)); 11074 return; 11075 } 11076 11077 uint64_t Idx = (NumElts + Imm) % NumElts; 11078 11079 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11080 SmallVector<int, 8> Mask; 11081 for (unsigned i = 0; i < NumElts; ++i) 11082 Mask.push_back(Idx + i); 11083 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11084 } 11085