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