1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/BlockFrequencyInfo.h" 28 #include "llvm/Analysis/BranchProbabilityInfo.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/Analysis/EHPersonalities.h" 31 #include "llvm/Analysis/Loads.h" 32 #include "llvm/Analysis/MemoryLocation.h" 33 #include "llvm/Analysis/ProfileSummaryInfo.h" 34 #include "llvm/Analysis/TargetLibraryInfo.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/Analysis/VectorUtils.h" 37 #include "llvm/CodeGen/Analysis.h" 38 #include "llvm/CodeGen/FunctionLoweringInfo.h" 39 #include "llvm/CodeGen/GCMetadata.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 53 #include "llvm/CodeGen/StackMaps.h" 54 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 55 #include "llvm/CodeGen/TargetFrameLowering.h" 56 #include "llvm/CodeGen/TargetInstrInfo.h" 57 #include "llvm/CodeGen/TargetOpcodes.h" 58 #include "llvm/CodeGen/TargetRegisterInfo.h" 59 #include "llvm/CodeGen/TargetSubtargetInfo.h" 60 #include "llvm/CodeGen/WinEHFuncInfo.h" 61 #include "llvm/IR/Argument.h" 62 #include "llvm/IR/Attributes.h" 63 #include "llvm/IR/BasicBlock.h" 64 #include "llvm/IR/CFG.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/ConstantRange.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugInfoMetadata.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GetElementPtrTypeIterator.h" 74 #include "llvm/IR/InlineAsm.h" 75 #include "llvm/IR/InstrTypes.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/IntrinsicsAArch64.h" 80 #include "llvm/IR/IntrinsicsWebAssembly.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Operator.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Statepoint.h" 87 #include "llvm/IR/Type.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/MC/MCContext.h" 91 #include "llvm/MC/MCSymbol.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/MathExtras.h" 98 #include "llvm/Support/raw_ostream.h" 99 #include "llvm/Target/TargetIntrinsicInfo.h" 100 #include "llvm/Target/TargetMachine.h" 101 #include "llvm/Target/TargetOptions.h" 102 #include "llvm/Transforms/Utils/Local.h" 103 #include <cstddef> 104 #include <cstring> 105 #include <iterator> 106 #include <limits> 107 #include <numeric> 108 #include <tuple> 109 110 using namespace llvm; 111 using namespace PatternMatch; 112 using namespace SwitchCG; 113 114 #define DEBUG_TYPE "isel" 115 116 /// LimitFloatPrecision - Generate low-precision inline sequences for 117 /// some float libcalls (6, 8 or 12 bits). 118 static unsigned LimitFloatPrecision; 119 120 static cl::opt<bool> 121 InsertAssertAlign("insert-assert-align", cl::init(true), 122 cl::desc("Insert the experimental `assertalign` node."), 123 cl::ReallyHidden); 124 125 static cl::opt<unsigned, true> 126 LimitFPPrecision("limit-float-precision", 127 cl::desc("Generate low-precision inline sequences " 128 "for some float libcalls"), 129 cl::location(LimitFloatPrecision), cl::Hidden, 130 cl::init(0)); 131 132 static cl::opt<unsigned> SwitchPeelThreshold( 133 "switch-peel-threshold", cl::Hidden, cl::init(66), 134 cl::desc("Set the case probability threshold for peeling the case from a " 135 "switch statement. A value greater than 100 will void this " 136 "optimization")); 137 138 // Limit the width of DAG chains. This is important in general to prevent 139 // DAG-based analysis from blowing up. For example, alias analysis and 140 // load clustering may not complete in reasonable time. It is difficult to 141 // recognize and avoid this situation within each individual analysis, and 142 // future analyses are likely to have the same behavior. Limiting DAG width is 143 // the safe approach and will be especially important with global DAGs. 144 // 145 // MaxParallelChains default is arbitrarily high to avoid affecting 146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 147 // sequence over this should have been converted to llvm.memcpy by the 148 // frontend. It is easy to induce this behavior with .ll code such as: 149 // %buffer = alloca [4096 x i8] 150 // %data = load [4096 x i8]* %argPtr 151 // store [4096 x i8] %data, [4096 x i8]* %buffer 152 static const unsigned MaxParallelChains = 64; 153 154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 155 const SDValue *Parts, unsigned NumParts, 156 MVT PartVT, EVT ValueVT, const Value *V, 157 Optional<CallingConv::ID> CC); 158 159 /// getCopyFromParts - Create a value that contains the specified legal parts 160 /// combined into the value they represent. If the parts combine to a type 161 /// larger than ValueVT then AssertOp can be used to specify whether the extra 162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 163 /// (ISD::AssertSext). 164 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 165 const SDValue *Parts, unsigned NumParts, 166 MVT PartVT, EVT ValueVT, const Value *V, 167 Optional<CallingConv::ID> CC = None, 168 Optional<ISD::NodeType> AssertOp = None) { 169 // Let the target assemble the parts if it wants to 170 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 171 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 172 PartVT, ValueVT, CC)) 173 return Val; 174 175 if (ValueVT.isVector()) 176 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 177 CC); 178 179 assert(NumParts > 0 && "No parts to assemble!"); 180 SDValue Val = Parts[0]; 181 182 if (NumParts > 1) { 183 // Assemble the value from multiple parts. 184 if (ValueVT.isInteger()) { 185 unsigned PartBits = PartVT.getSizeInBits(); 186 unsigned ValueBits = ValueVT.getSizeInBits(); 187 188 // Assemble the power of 2 part. 189 unsigned RoundParts = 190 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 191 unsigned RoundBits = PartBits * RoundParts; 192 EVT RoundVT = RoundBits == ValueBits ? 193 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 194 SDValue Lo, Hi; 195 196 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 197 198 if (RoundParts > 2) { 199 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 200 PartVT, HalfVT, V); 201 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 202 RoundParts / 2, PartVT, HalfVT, V); 203 } else { 204 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 205 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 206 } 207 208 if (DAG.getDataLayout().isBigEndian()) 209 std::swap(Lo, Hi); 210 211 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 212 213 if (RoundParts < NumParts) { 214 // Assemble the trailing non-power-of-2 part. 215 unsigned OddParts = NumParts - RoundParts; 216 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 217 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 218 OddVT, V, CC); 219 220 // Combine the round and odd parts. 221 Lo = Val; 222 if (DAG.getDataLayout().isBigEndian()) 223 std::swap(Lo, Hi); 224 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 225 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 226 Hi = 227 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 228 DAG.getConstant(Lo.getValueSizeInBits(), DL, 229 TLI.getPointerTy(DAG.getDataLayout()))); 230 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 231 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 232 } 233 } else if (PartVT.isFloatingPoint()) { 234 // FP split into multiple FP parts (for ppcf128) 235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 236 "Unexpected split"); 237 SDValue Lo, Hi; 238 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 239 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 240 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 241 std::swap(Lo, Hi); 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 243 } else { 244 // FP split into integer parts (soft fp) 245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 246 !PartVT.isVector() && "Unexpected split"); 247 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 249 } 250 } 251 252 // There is now one part, held in Val. Correct it to match ValueVT. 253 // PartEVT is the type of the register class that holds the value. 254 // ValueVT is the type of the inline asm operation. 255 EVT PartEVT = Val.getValueType(); 256 257 if (PartEVT == ValueVT) 258 return Val; 259 260 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 261 ValueVT.bitsLT(PartEVT)) { 262 // For an FP value in an integer part, we need to truncate to the right 263 // width first. 264 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 265 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 266 } 267 268 // Handle types that have the same size. 269 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 270 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 271 272 // Handle types with different sizes. 273 if (PartEVT.isInteger() && ValueVT.isInteger()) { 274 if (ValueVT.bitsLT(PartEVT)) { 275 // For a truncate, see if we have any information to 276 // indicate whether the truncated bits will always be 277 // zero or sign-extension. 278 if (AssertOp.hasValue()) 279 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 280 DAG.getValueType(ValueVT)); 281 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 282 } 283 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 284 } 285 286 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 287 // FP_ROUND's are always exact here. 288 if (ValueVT.bitsLT(Val.getValueType())) 289 return DAG.getNode( 290 ISD::FP_ROUND, DL, ValueVT, Val, 291 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 292 293 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 294 } 295 296 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 297 // then truncating. 298 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 299 ValueVT.bitsLT(PartEVT)) { 300 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 301 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 302 } 303 304 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 305 } 306 307 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 308 const Twine &ErrMsg) { 309 const Instruction *I = dyn_cast_or_null<Instruction>(V); 310 if (!V) 311 return Ctx.emitError(ErrMsg); 312 313 const char *AsmError = ", possible invalid constraint for vector type"; 314 if (const CallInst *CI = dyn_cast<CallInst>(I)) 315 if (CI->isInlineAsm()) 316 return Ctx.emitError(I, ErrMsg + AsmError); 317 318 return Ctx.emitError(I, ErrMsg); 319 } 320 321 /// getCopyFromPartsVector - Create a value that contains the specified legal 322 /// parts combined into the value they represent. If the parts combine to a 323 /// type larger than ValueVT then AssertOp can be used to specify whether the 324 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 325 /// ValueVT (ISD::AssertSext). 326 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 327 const SDValue *Parts, unsigned NumParts, 328 MVT PartVT, EVT ValueVT, const Value *V, 329 Optional<CallingConv::ID> CallConv) { 330 assert(ValueVT.isVector() && "Not a vector value"); 331 assert(NumParts > 0 && "No parts to assemble!"); 332 const bool IsABIRegCopy = CallConv.hasValue(); 333 334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 335 SDValue Val = Parts[0]; 336 337 // Handle a multi-element vector. 338 if (NumParts > 1) { 339 EVT IntermediateVT; 340 MVT RegisterVT; 341 unsigned NumIntermediates; 342 unsigned NumRegs; 343 344 if (IsABIRegCopy) { 345 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 346 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } else { 349 NumRegs = 350 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 351 NumIntermediates, RegisterVT); 352 } 353 354 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 355 NumParts = NumRegs; // Silence a compiler warning. 356 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 357 assert(RegisterVT.getSizeInBits() == 358 Parts[0].getSimpleValueType().getSizeInBits() && 359 "Part type sizes don't match!"); 360 361 // Assemble the parts into intermediate operands. 362 SmallVector<SDValue, 8> Ops(NumIntermediates); 363 if (NumIntermediates == NumParts) { 364 // If the register was not expanded, truncate or copy the value, 365 // as appropriate. 366 for (unsigned i = 0; i != NumParts; ++i) 367 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 368 PartVT, IntermediateVT, V, CallConv); 369 } else if (NumParts > 0) { 370 // If the intermediate type was expanded, build the intermediate 371 // operands from the parts. 372 assert(NumParts % NumIntermediates == 0 && 373 "Must expand into a divisible number of parts!"); 374 unsigned Factor = NumParts / NumIntermediates; 375 for (unsigned i = 0; i != NumIntermediates; ++i) 376 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 377 PartVT, IntermediateVT, V, CallConv); 378 } 379 380 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 381 // intermediate operands. 382 EVT BuiltVectorTy = 383 IntermediateVT.isVector() 384 ? EVT::getVectorVT( 385 *DAG.getContext(), IntermediateVT.getScalarType(), 386 IntermediateVT.getVectorElementCount() * NumParts) 387 : EVT::getVectorVT(*DAG.getContext(), 388 IntermediateVT.getScalarType(), 389 NumIntermediates); 390 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 391 : ISD::BUILD_VECTOR, 392 DL, BuiltVectorTy, Ops); 393 } 394 395 // There is now one part, held in Val. Correct it to match ValueVT. 396 EVT PartEVT = Val.getValueType(); 397 398 if (PartEVT == ValueVT) 399 return Val; 400 401 if (PartEVT.isVector()) { 402 // Vector/Vector bitcast. 403 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 404 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 405 406 // If the element type of the source/dest vectors are the same, but the 407 // parts vector has more elements than the value vector, then we have a 408 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 409 // elements we want. 410 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 411 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 412 ValueVT.getVectorElementCount().getKnownMinValue()) && 413 (PartEVT.getVectorElementCount().isScalable() == 414 ValueVT.getVectorElementCount().isScalable()) && 415 "Cannot narrow, it would be a lossy transformation"); 416 PartEVT = 417 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 418 ValueVT.getVectorElementCount()); 419 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 420 DAG.getVectorIdxConstant(0, DL)); 421 if (PartEVT == ValueVT) 422 return Val; 423 } 424 425 // Promoted vector extract 426 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 427 } 428 429 // Trivial bitcast if the types are the same size and the destination 430 // vector type is legal. 431 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 432 TLI.isTypeLegal(ValueVT)) 433 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 434 435 if (ValueVT.getVectorNumElements() != 1) { 436 // Certain ABIs require that vectors are passed as integers. For vectors 437 // are the same size, this is an obvious bitcast. 438 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 439 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 440 } else if (ValueVT.bitsLT(PartEVT)) { 441 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 442 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 443 // Drop the extra bits. 444 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 445 return DAG.getBitcast(ValueVT, Val); 446 } 447 448 diagnosePossiblyInvalidConstraint( 449 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 450 return DAG.getUNDEF(ValueVT); 451 } 452 453 // Handle cases such as i8 -> <1 x i1> 454 EVT ValueSVT = ValueVT.getVectorElementType(); 455 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 456 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 457 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 458 else 459 Val = ValueVT.isFloatingPoint() 460 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 461 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 462 } 463 464 return DAG.getBuildVector(ValueVT, DL, Val); 465 } 466 467 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 468 SDValue Val, SDValue *Parts, unsigned NumParts, 469 MVT PartVT, const Value *V, 470 Optional<CallingConv::ID> CallConv); 471 472 /// getCopyToParts - Create a series of nodes that contain the specified value 473 /// split into legal parts. If the parts contain more bits than Val, then, for 474 /// integers, ExtendKind can be used to specify how to generate the extra bits. 475 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 476 SDValue *Parts, unsigned NumParts, MVT PartVT, 477 const Value *V, 478 Optional<CallingConv::ID> CallConv = None, 479 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 480 // Let the target split the parts if it wants to 481 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 482 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 483 CallConv)) 484 return; 485 EVT ValueVT = Val.getValueType(); 486 487 // Handle the vector case separately. 488 if (ValueVT.isVector()) 489 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 490 CallConv); 491 492 unsigned PartBits = PartVT.getSizeInBits(); 493 unsigned OrigNumParts = NumParts; 494 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 495 "Copying to an illegal type!"); 496 497 if (NumParts == 0) 498 return; 499 500 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 501 EVT PartEVT = PartVT; 502 if (PartEVT == ValueVT) { 503 assert(NumParts == 1 && "No-op copy with multiple parts!"); 504 Parts[0] = Val; 505 return; 506 } 507 508 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 509 // If the parts cover more bits than the value has, promote the value. 510 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 511 assert(NumParts == 1 && "Do not know what to promote to!"); 512 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 513 } else { 514 if (ValueVT.isFloatingPoint()) { 515 // FP values need to be bitcast, then extended if they are being put 516 // into a larger container. 517 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 518 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 519 } 520 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 521 ValueVT.isInteger() && 522 "Unknown mismatch!"); 523 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 524 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 525 if (PartVT == MVT::x86mmx) 526 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 527 } 528 } else if (PartBits == ValueVT.getSizeInBits()) { 529 // Different types of the same size. 530 assert(NumParts == 1 && PartEVT != ValueVT); 531 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 532 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 533 // If the parts cover less bits than value has, truncate the value. 534 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 535 ValueVT.isInteger() && 536 "Unknown mismatch!"); 537 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 538 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 539 if (PartVT == MVT::x86mmx) 540 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 541 } 542 543 // The value may have changed - recompute ValueVT. 544 ValueVT = Val.getValueType(); 545 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 546 "Failed to tile the value with PartVT!"); 547 548 if (NumParts == 1) { 549 if (PartEVT != ValueVT) { 550 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 551 "scalar-to-vector conversion failed"); 552 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 553 } 554 555 Parts[0] = Val; 556 return; 557 } 558 559 // Expand the value into multiple parts. 560 if (NumParts & (NumParts - 1)) { 561 // The number of parts is not a power of 2. Split off and copy the tail. 562 assert(PartVT.isInteger() && ValueVT.isInteger() && 563 "Do not know what to expand to!"); 564 unsigned RoundParts = 1 << Log2_32(NumParts); 565 unsigned RoundBits = RoundParts * PartBits; 566 unsigned OddParts = NumParts - RoundParts; 567 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 568 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 569 570 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 571 CallConv); 572 573 if (DAG.getDataLayout().isBigEndian()) 574 // The odd parts were reversed by getCopyToParts - unreverse them. 575 std::reverse(Parts + RoundParts, Parts + NumParts); 576 577 NumParts = RoundParts; 578 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 579 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 580 } 581 582 // The number of parts is a power of 2. Repeatedly bisect the value using 583 // EXTRACT_ELEMENT. 584 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 585 EVT::getIntegerVT(*DAG.getContext(), 586 ValueVT.getSizeInBits()), 587 Val); 588 589 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 590 for (unsigned i = 0; i < NumParts; i += StepSize) { 591 unsigned ThisBits = StepSize * PartBits / 2; 592 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 593 SDValue &Part0 = Parts[i]; 594 SDValue &Part1 = Parts[i+StepSize/2]; 595 596 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 597 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 598 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 599 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 600 601 if (ThisBits == PartBits && ThisVT != PartVT) { 602 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 603 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 604 } 605 } 606 } 607 608 if (DAG.getDataLayout().isBigEndian()) 609 std::reverse(Parts, Parts + OrigNumParts); 610 } 611 612 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 613 const SDLoc &DL, EVT PartVT) { 614 if (!PartVT.isVector()) 615 return SDValue(); 616 617 EVT ValueVT = Val.getValueType(); 618 ElementCount PartNumElts = PartVT.getVectorElementCount(); 619 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 620 621 // We only support widening vectors with equivalent element types and 622 // fixed/scalable properties. If a target needs to widen a fixed-length type 623 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 624 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 625 PartNumElts.isScalable() != ValueNumElts.isScalable() || 626 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 627 return SDValue(); 628 629 // Widening a scalable vector to another scalable vector is done by inserting 630 // the vector into a larger undef one. 631 if (PartNumElts.isScalable()) 632 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 633 Val, DAG.getVectorIdxConstant(0, DL)); 634 635 EVT ElementVT = PartVT.getVectorElementType(); 636 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 637 // undef elements. 638 SmallVector<SDValue, 16> Ops; 639 DAG.ExtractVectorElements(Val, Ops); 640 SDValue EltUndef = DAG.getUNDEF(ElementVT); 641 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 642 643 // FIXME: Use CONCAT for 2x -> 4x. 644 return DAG.getBuildVector(PartVT, DL, Ops); 645 } 646 647 /// getCopyToPartsVector - Create a series of nodes that contain the specified 648 /// value split into legal parts. 649 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 650 SDValue Val, SDValue *Parts, unsigned NumParts, 651 MVT PartVT, const Value *V, 652 Optional<CallingConv::ID> CallConv) { 653 EVT ValueVT = Val.getValueType(); 654 assert(ValueVT.isVector() && "Not a vector"); 655 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 656 const bool IsABIRegCopy = CallConv.hasValue(); 657 658 if (NumParts == 1) { 659 EVT PartEVT = PartVT; 660 if (PartEVT == ValueVT) { 661 // Nothing to do. 662 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 663 // Bitconvert vector->vector case. 664 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 665 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 666 Val = Widened; 667 } else if (PartVT.isVector() && 668 PartEVT.getVectorElementType().bitsGE( 669 ValueVT.getVectorElementType()) && 670 PartEVT.getVectorElementCount() == 671 ValueVT.getVectorElementCount()) { 672 673 // Promoted vector extract 674 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 675 } else { 676 if (ValueVT.getVectorElementCount().isScalar()) { 677 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 678 DAG.getVectorIdxConstant(0, DL)); 679 } else { 680 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 681 assert(PartVT.getFixedSizeInBits() > ValueSize && 682 "lossy conversion of vector to scalar type"); 683 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 684 Val = DAG.getBitcast(IntermediateType, Val); 685 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 686 } 687 } 688 689 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 690 Parts[0] = Val; 691 return; 692 } 693 694 // Handle a multi-element vector. 695 EVT IntermediateVT; 696 MVT RegisterVT; 697 unsigned NumIntermediates; 698 unsigned NumRegs; 699 if (IsABIRegCopy) { 700 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 701 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 702 NumIntermediates, RegisterVT); 703 } else { 704 NumRegs = 705 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 706 NumIntermediates, RegisterVT); 707 } 708 709 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 710 NumParts = NumRegs; // Silence a compiler warning. 711 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 712 713 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 714 "Mixing scalable and fixed vectors when copying in parts"); 715 716 Optional<ElementCount> DestEltCnt; 717 718 if (IntermediateVT.isVector()) 719 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 720 else 721 DestEltCnt = ElementCount::getFixed(NumIntermediates); 722 723 EVT BuiltVectorTy = EVT::getVectorVT( 724 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 725 726 if (ValueVT == BuiltVectorTy) { 727 // Nothing to do. 728 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 729 // Bitconvert vector->vector case. 730 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 731 } else { 732 if (BuiltVectorTy.getVectorElementType().bitsGT( 733 ValueVT.getVectorElementType())) { 734 // Integer promotion. 735 ValueVT = EVT::getVectorVT(*DAG.getContext(), 736 BuiltVectorTy.getVectorElementType(), 737 ValueVT.getVectorElementCount()); 738 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 739 } 740 741 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 742 Val = Widened; 743 } 744 } 745 746 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 747 748 // Split the vector into intermediate operands. 749 SmallVector<SDValue, 8> Ops(NumIntermediates); 750 for (unsigned i = 0; i != NumIntermediates; ++i) { 751 if (IntermediateVT.isVector()) { 752 // This does something sensible for scalable vectors - see the 753 // definition of EXTRACT_SUBVECTOR for further details. 754 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 755 Ops[i] = 756 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 757 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 758 } else { 759 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 760 DAG.getVectorIdxConstant(i, DL)); 761 } 762 } 763 764 // Split the intermediate operands into legal parts. 765 if (NumParts == NumIntermediates) { 766 // If the register was not expanded, promote or copy the value, 767 // as appropriate. 768 for (unsigned i = 0; i != NumParts; ++i) 769 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 770 } else if (NumParts > 0) { 771 // If the intermediate type was expanded, split each the value into 772 // legal parts. 773 assert(NumIntermediates != 0 && "division by zero"); 774 assert(NumParts % NumIntermediates == 0 && 775 "Must expand into a divisible number of parts!"); 776 unsigned Factor = NumParts / NumIntermediates; 777 for (unsigned i = 0; i != NumIntermediates; ++i) 778 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 779 CallConv); 780 } 781 } 782 783 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 784 EVT valuevt, Optional<CallingConv::ID> CC) 785 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 786 RegCount(1, regs.size()), CallConv(CC) {} 787 788 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 789 const DataLayout &DL, unsigned Reg, Type *Ty, 790 Optional<CallingConv::ID> CC) { 791 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 792 793 CallConv = CC; 794 795 for (EVT ValueVT : ValueVTs) { 796 unsigned NumRegs = 797 isABIMangled() 798 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 799 : TLI.getNumRegisters(Context, ValueVT); 800 MVT RegisterVT = 801 isABIMangled() 802 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 803 : TLI.getRegisterType(Context, ValueVT); 804 for (unsigned i = 0; i != NumRegs; ++i) 805 Regs.push_back(Reg + i); 806 RegVTs.push_back(RegisterVT); 807 RegCount.push_back(NumRegs); 808 Reg += NumRegs; 809 } 810 } 811 812 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 813 FunctionLoweringInfo &FuncInfo, 814 const SDLoc &dl, SDValue &Chain, 815 SDValue *Flag, const Value *V) const { 816 // A Value with type {} or [0 x %t] needs no registers. 817 if (ValueVTs.empty()) 818 return SDValue(); 819 820 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 821 822 // Assemble the legal parts into the final values. 823 SmallVector<SDValue, 4> Values(ValueVTs.size()); 824 SmallVector<SDValue, 8> Parts; 825 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 826 // Copy the legal parts from the registers. 827 EVT ValueVT = ValueVTs[Value]; 828 unsigned NumRegs = RegCount[Value]; 829 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 830 *DAG.getContext(), 831 CallConv.getValue(), RegVTs[Value]) 832 : RegVTs[Value]; 833 834 Parts.resize(NumRegs); 835 for (unsigned i = 0; i != NumRegs; ++i) { 836 SDValue P; 837 if (!Flag) { 838 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 839 } else { 840 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 841 *Flag = P.getValue(2); 842 } 843 844 Chain = P.getValue(1); 845 Parts[i] = P; 846 847 // If the source register was virtual and if we know something about it, 848 // add an assert node. 849 if (!Register::isVirtualRegister(Regs[Part + i]) || 850 !RegisterVT.isInteger()) 851 continue; 852 853 const FunctionLoweringInfo::LiveOutInfo *LOI = 854 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 855 if (!LOI) 856 continue; 857 858 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 859 unsigned NumSignBits = LOI->NumSignBits; 860 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 861 862 if (NumZeroBits == RegSize) { 863 // The current value is a zero. 864 // Explicitly express that as it would be easier for 865 // optimizations to kick in. 866 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 867 continue; 868 } 869 870 // FIXME: We capture more information than the dag can represent. For 871 // now, just use the tightest assertzext/assertsext possible. 872 bool isSExt; 873 EVT FromVT(MVT::Other); 874 if (NumZeroBits) { 875 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 876 isSExt = false; 877 } else if (NumSignBits > 1) { 878 FromVT = 879 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 880 isSExt = true; 881 } else { 882 continue; 883 } 884 // Add an assertion node. 885 assert(FromVT != MVT::Other); 886 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 887 RegisterVT, P, DAG.getValueType(FromVT)); 888 } 889 890 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 891 RegisterVT, ValueVT, V, CallConv); 892 Part += NumRegs; 893 Parts.clear(); 894 } 895 896 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 897 } 898 899 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 900 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 901 const Value *V, 902 ISD::NodeType PreferredExtendType) const { 903 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 904 ISD::NodeType ExtendKind = PreferredExtendType; 905 906 // Get the list of the values's legal parts. 907 unsigned NumRegs = Regs.size(); 908 SmallVector<SDValue, 8> Parts(NumRegs); 909 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 910 unsigned NumParts = RegCount[Value]; 911 912 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 913 *DAG.getContext(), 914 CallConv.getValue(), RegVTs[Value]) 915 : RegVTs[Value]; 916 917 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 918 ExtendKind = ISD::ZERO_EXTEND; 919 920 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 921 NumParts, RegisterVT, V, CallConv, ExtendKind); 922 Part += NumParts; 923 } 924 925 // Copy the parts into the registers. 926 SmallVector<SDValue, 8> Chains(NumRegs); 927 for (unsigned i = 0; i != NumRegs; ++i) { 928 SDValue Part; 929 if (!Flag) { 930 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 931 } else { 932 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 933 *Flag = Part.getValue(1); 934 } 935 936 Chains[i] = Part.getValue(0); 937 } 938 939 if (NumRegs == 1 || Flag) 940 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 941 // flagged to it. That is the CopyToReg nodes and the user are considered 942 // a single scheduling unit. If we create a TokenFactor and return it as 943 // chain, then the TokenFactor is both a predecessor (operand) of the 944 // user as well as a successor (the TF operands are flagged to the user). 945 // c1, f1 = CopyToReg 946 // c2, f2 = CopyToReg 947 // c3 = TokenFactor c1, c2 948 // ... 949 // = op c3, ..., f2 950 Chain = Chains[NumRegs-1]; 951 else 952 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 953 } 954 955 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 956 unsigned MatchingIdx, const SDLoc &dl, 957 SelectionDAG &DAG, 958 std::vector<SDValue> &Ops) const { 959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 960 961 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 962 if (HasMatching) 963 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 964 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 965 // Put the register class of the virtual registers in the flag word. That 966 // way, later passes can recompute register class constraints for inline 967 // assembly as well as normal instructions. 968 // Don't do this for tied operands that can use the regclass information 969 // from the def. 970 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 971 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 972 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 973 } 974 975 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 976 Ops.push_back(Res); 977 978 if (Code == InlineAsm::Kind_Clobber) { 979 // Clobbers should always have a 1:1 mapping with registers, and may 980 // reference registers that have illegal (e.g. vector) types. Hence, we 981 // shouldn't try to apply any sort of splitting logic to them. 982 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 983 "No 1:1 mapping from clobbers to regs?"); 984 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 985 (void)SP; 986 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 987 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 988 assert( 989 (Regs[I] != SP || 990 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 991 "If we clobbered the stack pointer, MFI should know about it."); 992 } 993 return; 994 } 995 996 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 997 MVT RegisterVT = RegVTs[Value]; 998 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 999 RegisterVT); 1000 for (unsigned i = 0; i != NumRegs; ++i) { 1001 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1002 unsigned TheReg = Regs[Reg++]; 1003 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1004 } 1005 } 1006 } 1007 1008 SmallVector<std::pair<unsigned, TypeSize>, 4> 1009 RegsForValue::getRegsAndSizes() const { 1010 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1011 unsigned I = 0; 1012 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1013 unsigned RegCount = std::get<0>(CountAndVT); 1014 MVT RegisterVT = std::get<1>(CountAndVT); 1015 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1016 for (unsigned E = I + RegCount; I != E; ++I) 1017 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1018 } 1019 return OutVec; 1020 } 1021 1022 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1023 const TargetLibraryInfo *li) { 1024 AA = aa; 1025 GFI = gfi; 1026 LibInfo = li; 1027 DL = &DAG.getDataLayout(); 1028 Context = DAG.getContext(); 1029 LPadToCallSiteMap.clear(); 1030 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1031 } 1032 1033 void SelectionDAGBuilder::clear() { 1034 NodeMap.clear(); 1035 UnusedArgNodeMap.clear(); 1036 PendingLoads.clear(); 1037 PendingExports.clear(); 1038 PendingConstrainedFP.clear(); 1039 PendingConstrainedFPStrict.clear(); 1040 CurInst = nullptr; 1041 HasTailCall = false; 1042 SDNodeOrder = LowestSDNodeOrder; 1043 StatepointLowering.clear(); 1044 } 1045 1046 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1047 DanglingDebugInfoMap.clear(); 1048 } 1049 1050 // Update DAG root to include dependencies on Pending chains. 1051 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1052 SDValue Root = DAG.getRoot(); 1053 1054 if (Pending.empty()) 1055 return Root; 1056 1057 // Add current root to PendingChains, unless we already indirectly 1058 // depend on it. 1059 if (Root.getOpcode() != ISD::EntryToken) { 1060 unsigned i = 0, e = Pending.size(); 1061 for (; i != e; ++i) { 1062 assert(Pending[i].getNode()->getNumOperands() > 1); 1063 if (Pending[i].getNode()->getOperand(0) == Root) 1064 break; // Don't add the root if we already indirectly depend on it. 1065 } 1066 1067 if (i == e) 1068 Pending.push_back(Root); 1069 } 1070 1071 if (Pending.size() == 1) 1072 Root = Pending[0]; 1073 else 1074 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1075 1076 DAG.setRoot(Root); 1077 Pending.clear(); 1078 return Root; 1079 } 1080 1081 SDValue SelectionDAGBuilder::getMemoryRoot() { 1082 return updateRoot(PendingLoads); 1083 } 1084 1085 SDValue SelectionDAGBuilder::getRoot() { 1086 // Chain up all pending constrained intrinsics together with all 1087 // pending loads, by simply appending them to PendingLoads and 1088 // then calling getMemoryRoot(). 1089 PendingLoads.reserve(PendingLoads.size() + 1090 PendingConstrainedFP.size() + 1091 PendingConstrainedFPStrict.size()); 1092 PendingLoads.append(PendingConstrainedFP.begin(), 1093 PendingConstrainedFP.end()); 1094 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1095 PendingConstrainedFPStrict.end()); 1096 PendingConstrainedFP.clear(); 1097 PendingConstrainedFPStrict.clear(); 1098 return getMemoryRoot(); 1099 } 1100 1101 SDValue SelectionDAGBuilder::getControlRoot() { 1102 // We need to emit pending fpexcept.strict constrained intrinsics, 1103 // so append them to the PendingExports list. 1104 PendingExports.append(PendingConstrainedFPStrict.begin(), 1105 PendingConstrainedFPStrict.end()); 1106 PendingConstrainedFPStrict.clear(); 1107 return updateRoot(PendingExports); 1108 } 1109 1110 void SelectionDAGBuilder::visit(const Instruction &I) { 1111 // Set up outgoing PHI node register values before emitting the terminator. 1112 if (I.isTerminator()) { 1113 HandlePHINodesInSuccessorBlocks(I.getParent()); 1114 } 1115 1116 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1117 if (!isa<DbgInfoIntrinsic>(I)) 1118 ++SDNodeOrder; 1119 1120 CurInst = &I; 1121 1122 visit(I.getOpcode(), I); 1123 1124 if (!I.isTerminator() && !HasTailCall && 1125 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1126 CopyToExportRegsIfNeeded(&I); 1127 1128 CurInst = nullptr; 1129 } 1130 1131 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1132 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1133 } 1134 1135 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1136 // Note: this doesn't use InstVisitor, because it has to work with 1137 // ConstantExpr's in addition to instructions. 1138 switch (Opcode) { 1139 default: llvm_unreachable("Unknown instruction type encountered!"); 1140 // Build the switch statement using the Instruction.def file. 1141 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1142 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1143 #include "llvm/IR/Instruction.def" 1144 } 1145 } 1146 1147 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1148 DebugLoc DL, unsigned Order) { 1149 // We treat variadic dbg_values differently at this stage. 1150 if (DI->hasArgList()) { 1151 // For variadic dbg_values we will now insert an undef. 1152 // FIXME: We can potentially recover these! 1153 SmallVector<SDDbgOperand, 2> Locs; 1154 for (const Value *V : DI->getValues()) { 1155 auto Undef = UndefValue::get(V->getType()); 1156 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1157 } 1158 SDDbgValue *SDV = DAG.getDbgValueList( 1159 DI->getVariable(), DI->getExpression(), Locs, {}, 1160 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1161 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1162 } else { 1163 // TODO: Dangling debug info will eventually either be resolved or produce 1164 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1165 // between the original dbg.value location and its resolved DBG_VALUE, 1166 // which we should ideally fill with an extra Undef DBG_VALUE. 1167 assert(DI->getNumVariableLocationOps() == 1 && 1168 "DbgValueInst without an ArgList should have a single location " 1169 "operand."); 1170 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1171 } 1172 } 1173 1174 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1175 const DIExpression *Expr) { 1176 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1177 const DbgValueInst *DI = DDI.getDI(); 1178 DIVariable *DanglingVariable = DI->getVariable(); 1179 DIExpression *DanglingExpr = DI->getExpression(); 1180 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1181 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1182 return true; 1183 } 1184 return false; 1185 }; 1186 1187 for (auto &DDIMI : DanglingDebugInfoMap) { 1188 DanglingDebugInfoVector &DDIV = DDIMI.second; 1189 1190 // If debug info is to be dropped, run it through final checks to see 1191 // whether it can be salvaged. 1192 for (auto &DDI : DDIV) 1193 if (isMatchingDbgValue(DDI)) 1194 salvageUnresolvedDbgValue(DDI); 1195 1196 erase_if(DDIV, isMatchingDbgValue); 1197 } 1198 } 1199 1200 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1201 // generate the debug data structures now that we've seen its definition. 1202 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1203 SDValue Val) { 1204 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1205 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1206 return; 1207 1208 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1209 for (auto &DDI : DDIV) { 1210 const DbgValueInst *DI = DDI.getDI(); 1211 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1212 assert(DI && "Ill-formed DanglingDebugInfo"); 1213 DebugLoc dl = DDI.getdl(); 1214 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1215 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1216 DILocalVariable *Variable = DI->getVariable(); 1217 DIExpression *Expr = DI->getExpression(); 1218 assert(Variable->isValidLocationForIntrinsic(dl) && 1219 "Expected inlined-at fields to agree"); 1220 SDDbgValue *SDV; 1221 if (Val.getNode()) { 1222 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1223 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1224 // we couldn't resolve it directly when examining the DbgValue intrinsic 1225 // in the first place we should not be more successful here). Unless we 1226 // have some test case that prove this to be correct we should avoid 1227 // calling EmitFuncArgumentDbgValue here. 1228 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1229 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1230 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1231 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1232 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1233 // inserted after the definition of Val when emitting the instructions 1234 // after ISel. An alternative could be to teach 1235 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1236 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1237 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1238 << ValSDNodeOrder << "\n"); 1239 SDV = getDbgValue(Val, Variable, Expr, dl, 1240 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1241 DAG.AddDbgValue(SDV, false); 1242 } else 1243 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1244 << "in EmitFuncArgumentDbgValue\n"); 1245 } else { 1246 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1247 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1248 auto SDV = 1249 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1250 DAG.AddDbgValue(SDV, false); 1251 } 1252 } 1253 DDIV.clear(); 1254 } 1255 1256 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1257 // TODO: For the variadic implementation, instead of only checking the fail 1258 // state of `handleDebugValue`, we need know specifically which values were 1259 // invalid, so that we attempt to salvage only those values when processing 1260 // a DIArgList. 1261 assert(!DDI.getDI()->hasArgList() && 1262 "Not implemented for variadic dbg_values"); 1263 Value *V = DDI.getDI()->getValue(0); 1264 DILocalVariable *Var = DDI.getDI()->getVariable(); 1265 DIExpression *Expr = DDI.getDI()->getExpression(); 1266 DebugLoc DL = DDI.getdl(); 1267 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1268 unsigned SDOrder = DDI.getSDNodeOrder(); 1269 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1270 // that DW_OP_stack_value is desired. 1271 assert(isa<DbgValueInst>(DDI.getDI())); 1272 bool StackValue = true; 1273 1274 // Can this Value can be encoded without any further work? 1275 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1276 return; 1277 1278 // Attempt to salvage back through as many instructions as possible. Bail if 1279 // a non-instruction is seen, such as a constant expression or global 1280 // variable. FIXME: Further work could recover those too. 1281 while (isa<Instruction>(V)) { 1282 Instruction &VAsInst = *cast<Instruction>(V); 1283 // Temporary "0", awaiting real implementation. 1284 SmallVector<uint64_t, 16> Ops; 1285 SmallVector<Value *, 4> AdditionalValues; 1286 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1287 AdditionalValues); 1288 // If we cannot salvage any further, and haven't yet found a suitable debug 1289 // expression, bail out. 1290 if (!V) 1291 break; 1292 1293 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1294 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1295 // here for variadic dbg_values, remove that condition. 1296 if (!AdditionalValues.empty()) 1297 break; 1298 1299 // New value and expr now represent this debuginfo. 1300 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1301 1302 // Some kind of simplification occurred: check whether the operand of the 1303 // salvaged debug expression can be encoded in this DAG. 1304 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1305 /*IsVariadic=*/false)) { 1306 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1307 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1308 return; 1309 } 1310 } 1311 1312 // This was the final opportunity to salvage this debug information, and it 1313 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1314 // any earlier variable location. 1315 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1316 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1317 DAG.AddDbgValue(SDV, false); 1318 1319 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1320 << "\n"); 1321 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1322 << "\n"); 1323 } 1324 1325 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1326 DILocalVariable *Var, 1327 DIExpression *Expr, DebugLoc dl, 1328 DebugLoc InstDL, unsigned Order, 1329 bool IsVariadic) { 1330 if (Values.empty()) 1331 return true; 1332 SmallVector<SDDbgOperand> LocationOps; 1333 SmallVector<SDNode *> Dependencies; 1334 for (const Value *V : Values) { 1335 // Constant value. 1336 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1337 isa<ConstantPointerNull>(V)) { 1338 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1339 continue; 1340 } 1341 1342 // If the Value is a frame index, we can create a FrameIndex debug value 1343 // without relying on the DAG at all. 1344 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1345 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1346 if (SI != FuncInfo.StaticAllocaMap.end()) { 1347 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1348 continue; 1349 } 1350 } 1351 1352 // Do not use getValue() in here; we don't want to generate code at 1353 // this point if it hasn't been done yet. 1354 SDValue N = NodeMap[V]; 1355 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1356 N = UnusedArgNodeMap[V]; 1357 if (N.getNode()) { 1358 // Only emit func arg dbg value for non-variadic dbg.values for now. 1359 if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1360 return true; 1361 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1362 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1363 // describe stack slot locations. 1364 // 1365 // Consider "int x = 0; int *px = &x;". There are two kinds of 1366 // interesting debug values here after optimization: 1367 // 1368 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1369 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1370 // 1371 // Both describe the direct values of their associated variables. 1372 Dependencies.push_back(N.getNode()); 1373 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1374 continue; 1375 } 1376 LocationOps.emplace_back( 1377 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1378 continue; 1379 } 1380 1381 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1382 // Special rules apply for the first dbg.values of parameter variables in a 1383 // function. Identify them by the fact they reference Argument Values, that 1384 // they're parameters, and they are parameters of the current function. We 1385 // need to let them dangle until they get an SDNode. 1386 bool IsParamOfFunc = 1387 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1388 if (IsParamOfFunc) 1389 return false; 1390 1391 // The value is not used in this block yet (or it would have an SDNode). 1392 // We still want the value to appear for the user if possible -- if it has 1393 // an associated VReg, we can refer to that instead. 1394 auto VMI = FuncInfo.ValueMap.find(V); 1395 if (VMI != FuncInfo.ValueMap.end()) { 1396 unsigned Reg = VMI->second; 1397 // If this is a PHI node, it may be split up into several MI PHI nodes 1398 // (in FunctionLoweringInfo::set). 1399 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1400 V->getType(), None); 1401 if (RFV.occupiesMultipleRegs()) { 1402 // FIXME: We could potentially support variadic dbg_values here. 1403 if (IsVariadic) 1404 return false; 1405 unsigned Offset = 0; 1406 unsigned BitsToDescribe = 0; 1407 if (auto VarSize = Var->getSizeInBits()) 1408 BitsToDescribe = *VarSize; 1409 if (auto Fragment = Expr->getFragmentInfo()) 1410 BitsToDescribe = Fragment->SizeInBits; 1411 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1412 // Bail out if all bits are described already. 1413 if (Offset >= BitsToDescribe) 1414 break; 1415 // TODO: handle scalable vectors. 1416 unsigned RegisterSize = RegAndSize.second; 1417 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1418 ? BitsToDescribe - Offset 1419 : RegisterSize; 1420 auto FragmentExpr = DIExpression::createFragmentExpression( 1421 Expr, Offset, FragmentSize); 1422 if (!FragmentExpr) 1423 continue; 1424 SDDbgValue *SDV = DAG.getVRegDbgValue( 1425 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1426 DAG.AddDbgValue(SDV, false); 1427 Offset += RegisterSize; 1428 } 1429 return true; 1430 } 1431 // We can use simple vreg locations for variadic dbg_values as well. 1432 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1433 continue; 1434 } 1435 // We failed to create a SDDbgOperand for V. 1436 return false; 1437 } 1438 1439 // We have created a SDDbgOperand for each Value in Values. 1440 // Should use Order instead of SDNodeOrder? 1441 assert(!LocationOps.empty()); 1442 SDDbgValue *SDV = 1443 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1444 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1445 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1446 return true; 1447 } 1448 1449 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1450 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1451 for (auto &Pair : DanglingDebugInfoMap) 1452 for (auto &DDI : Pair.second) 1453 salvageUnresolvedDbgValue(DDI); 1454 clearDanglingDebugInfo(); 1455 } 1456 1457 /// getCopyFromRegs - If there was virtual register allocated for the value V 1458 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1459 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1460 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1461 SDValue Result; 1462 1463 if (It != FuncInfo.ValueMap.end()) { 1464 Register InReg = It->second; 1465 1466 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1467 DAG.getDataLayout(), InReg, Ty, 1468 None); // This is not an ABI copy. 1469 SDValue Chain = DAG.getEntryNode(); 1470 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1471 V); 1472 resolveDanglingDebugInfo(V, Result); 1473 } 1474 1475 return Result; 1476 } 1477 1478 /// getValue - Return an SDValue for the given Value. 1479 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1480 // If we already have an SDValue for this value, use it. It's important 1481 // to do this first, so that we don't create a CopyFromReg if we already 1482 // have a regular SDValue. 1483 SDValue &N = NodeMap[V]; 1484 if (N.getNode()) return N; 1485 1486 // If there's a virtual register allocated and initialized for this 1487 // value, use it. 1488 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1489 return copyFromReg; 1490 1491 // Otherwise create a new SDValue and remember it. 1492 SDValue Val = getValueImpl(V); 1493 NodeMap[V] = Val; 1494 resolveDanglingDebugInfo(V, Val); 1495 return Val; 1496 } 1497 1498 /// getNonRegisterValue - Return an SDValue for the given Value, but 1499 /// don't look in FuncInfo.ValueMap for a virtual register. 1500 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1501 // If we already have an SDValue for this value, use it. 1502 SDValue &N = NodeMap[V]; 1503 if (N.getNode()) { 1504 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1505 // Remove the debug location from the node as the node is about to be used 1506 // in a location which may differ from the original debug location. This 1507 // is relevant to Constant and ConstantFP nodes because they can appear 1508 // as constant expressions inside PHI nodes. 1509 N->setDebugLoc(DebugLoc()); 1510 } 1511 return N; 1512 } 1513 1514 // Otherwise create a new SDValue and remember it. 1515 SDValue Val = getValueImpl(V); 1516 NodeMap[V] = Val; 1517 resolveDanglingDebugInfo(V, Val); 1518 return Val; 1519 } 1520 1521 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1522 /// Create an SDValue for the given value. 1523 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1524 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1525 1526 if (const Constant *C = dyn_cast<Constant>(V)) { 1527 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1528 1529 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1530 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1531 1532 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1533 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1534 1535 if (isa<ConstantPointerNull>(C)) { 1536 unsigned AS = V->getType()->getPointerAddressSpace(); 1537 return DAG.getConstant(0, getCurSDLoc(), 1538 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1539 } 1540 1541 if (match(C, m_VScale(DAG.getDataLayout()))) 1542 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1543 1544 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1545 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1546 1547 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1548 return DAG.getUNDEF(VT); 1549 1550 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1551 visit(CE->getOpcode(), *CE); 1552 SDValue N1 = NodeMap[V]; 1553 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1554 return N1; 1555 } 1556 1557 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1558 SmallVector<SDValue, 4> Constants; 1559 for (const Use &U : C->operands()) { 1560 SDNode *Val = getValue(U).getNode(); 1561 // If the operand is an empty aggregate, there are no values. 1562 if (!Val) continue; 1563 // Add each leaf value from the operand to the Constants list 1564 // to form a flattened list of all the values. 1565 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1566 Constants.push_back(SDValue(Val, i)); 1567 } 1568 1569 return DAG.getMergeValues(Constants, getCurSDLoc()); 1570 } 1571 1572 if (const ConstantDataSequential *CDS = 1573 dyn_cast<ConstantDataSequential>(C)) { 1574 SmallVector<SDValue, 4> Ops; 1575 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1576 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1577 // Add each leaf value from the operand to the Constants list 1578 // to form a flattened list of all the values. 1579 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1580 Ops.push_back(SDValue(Val, i)); 1581 } 1582 1583 if (isa<ArrayType>(CDS->getType())) 1584 return DAG.getMergeValues(Ops, getCurSDLoc()); 1585 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1586 } 1587 1588 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1589 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1590 "Unknown struct or array constant!"); 1591 1592 SmallVector<EVT, 4> ValueVTs; 1593 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1594 unsigned NumElts = ValueVTs.size(); 1595 if (NumElts == 0) 1596 return SDValue(); // empty struct 1597 SmallVector<SDValue, 4> Constants(NumElts); 1598 for (unsigned i = 0; i != NumElts; ++i) { 1599 EVT EltVT = ValueVTs[i]; 1600 if (isa<UndefValue>(C)) 1601 Constants[i] = DAG.getUNDEF(EltVT); 1602 else if (EltVT.isFloatingPoint()) 1603 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1604 else 1605 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1606 } 1607 1608 return DAG.getMergeValues(Constants, getCurSDLoc()); 1609 } 1610 1611 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1612 return DAG.getBlockAddress(BA, VT); 1613 1614 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1615 return getValue(Equiv->getGlobalValue()); 1616 1617 VectorType *VecTy = cast<VectorType>(V->getType()); 1618 1619 // Now that we know the number and type of the elements, get that number of 1620 // elements into the Ops array based on what kind of constant it is. 1621 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1622 SmallVector<SDValue, 16> Ops; 1623 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1624 for (unsigned i = 0; i != NumElements; ++i) 1625 Ops.push_back(getValue(CV->getOperand(i))); 1626 1627 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1628 } else if (isa<ConstantAggregateZero>(C)) { 1629 EVT EltVT = 1630 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1631 1632 SDValue Op; 1633 if (EltVT.isFloatingPoint()) 1634 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1635 else 1636 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1637 1638 if (isa<ScalableVectorType>(VecTy)) 1639 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1640 else { 1641 SmallVector<SDValue, 16> Ops; 1642 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1643 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1644 } 1645 } 1646 llvm_unreachable("Unknown vector constant"); 1647 } 1648 1649 // If this is a static alloca, generate it as the frameindex instead of 1650 // computation. 1651 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1652 DenseMap<const AllocaInst*, int>::iterator SI = 1653 FuncInfo.StaticAllocaMap.find(AI); 1654 if (SI != FuncInfo.StaticAllocaMap.end()) 1655 return DAG.getFrameIndex(SI->second, 1656 TLI.getFrameIndexTy(DAG.getDataLayout())); 1657 } 1658 1659 // If this is an instruction which fast-isel has deferred, select it now. 1660 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1661 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1662 1663 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1664 Inst->getType(), None); 1665 SDValue Chain = DAG.getEntryNode(); 1666 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1667 } 1668 1669 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1670 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1671 } 1672 llvm_unreachable("Can't get register for value!"); 1673 } 1674 1675 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1676 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1677 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1678 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1679 bool IsSEH = isAsynchronousEHPersonality(Pers); 1680 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1681 if (!IsSEH) 1682 CatchPadMBB->setIsEHScopeEntry(); 1683 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1684 if (IsMSVCCXX || IsCoreCLR) 1685 CatchPadMBB->setIsEHFuncletEntry(); 1686 } 1687 1688 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1689 // Update machine-CFG edge. 1690 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1691 FuncInfo.MBB->addSuccessor(TargetMBB); 1692 TargetMBB->setIsEHCatchretTarget(true); 1693 DAG.getMachineFunction().setHasEHCatchret(true); 1694 1695 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1696 bool IsSEH = isAsynchronousEHPersonality(Pers); 1697 if (IsSEH) { 1698 // If this is not a fall-through branch or optimizations are switched off, 1699 // emit the branch. 1700 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1701 TM.getOptLevel() == CodeGenOpt::None) 1702 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1703 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1704 return; 1705 } 1706 1707 // Figure out the funclet membership for the catchret's successor. 1708 // This will be used by the FuncletLayout pass to determine how to order the 1709 // BB's. 1710 // A 'catchret' returns to the outer scope's color. 1711 Value *ParentPad = I.getCatchSwitchParentPad(); 1712 const BasicBlock *SuccessorColor; 1713 if (isa<ConstantTokenNone>(ParentPad)) 1714 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1715 else 1716 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1717 assert(SuccessorColor && "No parent funclet for catchret!"); 1718 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1719 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1720 1721 // Create the terminator node. 1722 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1723 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1724 DAG.getBasicBlock(SuccessorColorMBB)); 1725 DAG.setRoot(Ret); 1726 } 1727 1728 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1729 // Don't emit any special code for the cleanuppad instruction. It just marks 1730 // the start of an EH scope/funclet. 1731 FuncInfo.MBB->setIsEHScopeEntry(); 1732 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1733 if (Pers != EHPersonality::Wasm_CXX) { 1734 FuncInfo.MBB->setIsEHFuncletEntry(); 1735 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1736 } 1737 } 1738 1739 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1740 // not match, it is OK to add only the first unwind destination catchpad to the 1741 // successors, because there will be at least one invoke instruction within the 1742 // catch scope that points to the next unwind destination, if one exists, so 1743 // CFGSort cannot mess up with BB sorting order. 1744 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1745 // call within them, and catchpads only consisting of 'catch (...)' have a 1746 // '__cxa_end_catch' call within them, both of which generate invokes in case 1747 // the next unwind destination exists, i.e., the next unwind destination is not 1748 // the caller.) 1749 // 1750 // Having at most one EH pad successor is also simpler and helps later 1751 // transformations. 1752 // 1753 // For example, 1754 // current: 1755 // invoke void @foo to ... unwind label %catch.dispatch 1756 // catch.dispatch: 1757 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1758 // catch.start: 1759 // ... 1760 // ... in this BB or some other child BB dominated by this BB there will be an 1761 // invoke that points to 'next' BB as an unwind destination 1762 // 1763 // next: ; We don't need to add this to 'current' BB's successor 1764 // ... 1765 static void findWasmUnwindDestinations( 1766 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1767 BranchProbability Prob, 1768 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1769 &UnwindDests) { 1770 while (EHPadBB) { 1771 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1772 if (isa<CleanupPadInst>(Pad)) { 1773 // Stop on cleanup pads. 1774 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1775 UnwindDests.back().first->setIsEHScopeEntry(); 1776 break; 1777 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1778 // Add the catchpad handlers to the possible destinations. We don't 1779 // continue to the unwind destination of the catchswitch for wasm. 1780 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1781 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1782 UnwindDests.back().first->setIsEHScopeEntry(); 1783 } 1784 break; 1785 } else { 1786 continue; 1787 } 1788 } 1789 } 1790 1791 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1792 /// many places it could ultimately go. In the IR, we have a single unwind 1793 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1794 /// This function skips over imaginary basic blocks that hold catchswitch 1795 /// instructions, and finds all the "real" machine 1796 /// basic block destinations. As those destinations may not be successors of 1797 /// EHPadBB, here we also calculate the edge probability to those destinations. 1798 /// The passed-in Prob is the edge probability to EHPadBB. 1799 static void findUnwindDestinations( 1800 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1801 BranchProbability Prob, 1802 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1803 &UnwindDests) { 1804 EHPersonality Personality = 1805 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1806 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1807 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1808 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1809 bool IsSEH = isAsynchronousEHPersonality(Personality); 1810 1811 if (IsWasmCXX) { 1812 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1813 assert(UnwindDests.size() <= 1 && 1814 "There should be at most one unwind destination for wasm"); 1815 return; 1816 } 1817 1818 while (EHPadBB) { 1819 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1820 BasicBlock *NewEHPadBB = nullptr; 1821 if (isa<LandingPadInst>(Pad)) { 1822 // Stop on landingpads. They are not funclets. 1823 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1824 break; 1825 } else if (isa<CleanupPadInst>(Pad)) { 1826 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1827 // personalities. 1828 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1829 UnwindDests.back().first->setIsEHScopeEntry(); 1830 UnwindDests.back().first->setIsEHFuncletEntry(); 1831 break; 1832 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1833 // Add the catchpad handlers to the possible destinations. 1834 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1835 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1836 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1837 if (IsMSVCCXX || IsCoreCLR) 1838 UnwindDests.back().first->setIsEHFuncletEntry(); 1839 if (!IsSEH) 1840 UnwindDests.back().first->setIsEHScopeEntry(); 1841 } 1842 NewEHPadBB = CatchSwitch->getUnwindDest(); 1843 } else { 1844 continue; 1845 } 1846 1847 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1848 if (BPI && NewEHPadBB) 1849 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1850 EHPadBB = NewEHPadBB; 1851 } 1852 } 1853 1854 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1855 // Update successor info. 1856 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1857 auto UnwindDest = I.getUnwindDest(); 1858 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1859 BranchProbability UnwindDestProb = 1860 (BPI && UnwindDest) 1861 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1862 : BranchProbability::getZero(); 1863 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1864 for (auto &UnwindDest : UnwindDests) { 1865 UnwindDest.first->setIsEHPad(); 1866 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1867 } 1868 FuncInfo.MBB->normalizeSuccProbs(); 1869 1870 // Create the terminator node. 1871 SDValue Ret = 1872 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1873 DAG.setRoot(Ret); 1874 } 1875 1876 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1877 report_fatal_error("visitCatchSwitch not yet implemented!"); 1878 } 1879 1880 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1881 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1882 auto &DL = DAG.getDataLayout(); 1883 SDValue Chain = getControlRoot(); 1884 SmallVector<ISD::OutputArg, 8> Outs; 1885 SmallVector<SDValue, 8> OutVals; 1886 1887 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1888 // lower 1889 // 1890 // %val = call <ty> @llvm.experimental.deoptimize() 1891 // ret <ty> %val 1892 // 1893 // differently. 1894 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1895 LowerDeoptimizingReturn(); 1896 return; 1897 } 1898 1899 if (!FuncInfo.CanLowerReturn) { 1900 unsigned DemoteReg = FuncInfo.DemoteRegister; 1901 const Function *F = I.getParent()->getParent(); 1902 1903 // Emit a store of the return value through the virtual register. 1904 // Leave Outs empty so that LowerReturn won't try to load return 1905 // registers the usual way. 1906 SmallVector<EVT, 1> PtrValueVTs; 1907 ComputeValueVTs(TLI, DL, 1908 F->getReturnType()->getPointerTo( 1909 DAG.getDataLayout().getAllocaAddrSpace()), 1910 PtrValueVTs); 1911 1912 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1913 DemoteReg, PtrValueVTs[0]); 1914 SDValue RetOp = getValue(I.getOperand(0)); 1915 1916 SmallVector<EVT, 4> ValueVTs, MemVTs; 1917 SmallVector<uint64_t, 4> Offsets; 1918 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1919 &Offsets); 1920 unsigned NumValues = ValueVTs.size(); 1921 1922 SmallVector<SDValue, 4> Chains(NumValues); 1923 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1924 for (unsigned i = 0; i != NumValues; ++i) { 1925 // An aggregate return value cannot wrap around the address space, so 1926 // offsets to its parts don't wrap either. 1927 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1928 TypeSize::Fixed(Offsets[i])); 1929 1930 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1931 if (MemVTs[i] != ValueVTs[i]) 1932 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1933 Chains[i] = DAG.getStore( 1934 Chain, getCurSDLoc(), Val, 1935 // FIXME: better loc info would be nice. 1936 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1937 commonAlignment(BaseAlign, Offsets[i])); 1938 } 1939 1940 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1941 MVT::Other, Chains); 1942 } else if (I.getNumOperands() != 0) { 1943 SmallVector<EVT, 4> ValueVTs; 1944 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1945 unsigned NumValues = ValueVTs.size(); 1946 if (NumValues) { 1947 SDValue RetOp = getValue(I.getOperand(0)); 1948 1949 const Function *F = I.getParent()->getParent(); 1950 1951 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1952 I.getOperand(0)->getType(), F->getCallingConv(), 1953 /*IsVarArg*/ false, DL); 1954 1955 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1956 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 1957 ExtendKind = ISD::SIGN_EXTEND; 1958 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 1959 ExtendKind = ISD::ZERO_EXTEND; 1960 1961 LLVMContext &Context = F->getContext(); 1962 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 1963 1964 for (unsigned j = 0; j != NumValues; ++j) { 1965 EVT VT = ValueVTs[j]; 1966 1967 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1968 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1969 1970 CallingConv::ID CC = F->getCallingConv(); 1971 1972 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1973 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1974 SmallVector<SDValue, 4> Parts(NumParts); 1975 getCopyToParts(DAG, getCurSDLoc(), 1976 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1977 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1978 1979 // 'inreg' on function refers to return value 1980 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1981 if (RetInReg) 1982 Flags.setInReg(); 1983 1984 if (I.getOperand(0)->getType()->isPointerTy()) { 1985 Flags.setPointer(); 1986 Flags.setPointerAddrSpace( 1987 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1988 } 1989 1990 if (NeedsRegBlock) { 1991 Flags.setInConsecutiveRegs(); 1992 if (j == NumValues - 1) 1993 Flags.setInConsecutiveRegsLast(); 1994 } 1995 1996 // Propagate extension type if any 1997 if (ExtendKind == ISD::SIGN_EXTEND) 1998 Flags.setSExt(); 1999 else if (ExtendKind == ISD::ZERO_EXTEND) 2000 Flags.setZExt(); 2001 2002 for (unsigned i = 0; i < NumParts; ++i) { 2003 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 2004 VT, /*isfixed=*/true, 0, 0)); 2005 OutVals.push_back(Parts[i]); 2006 } 2007 } 2008 } 2009 } 2010 2011 // Push in swifterror virtual register as the last element of Outs. This makes 2012 // sure swifterror virtual register will be returned in the swifterror 2013 // physical register. 2014 const Function *F = I.getParent()->getParent(); 2015 if (TLI.supportSwiftError() && 2016 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2017 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2018 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2019 Flags.setSwiftError(); 2020 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 2021 EVT(TLI.getPointerTy(DL)) /*argvt*/, 2022 true /*isfixed*/, 1 /*origidx*/, 2023 0 /*partOffs*/)); 2024 // Create SDNode for the swifterror virtual register. 2025 OutVals.push_back( 2026 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2027 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2028 EVT(TLI.getPointerTy(DL)))); 2029 } 2030 2031 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2032 CallingConv::ID CallConv = 2033 DAG.getMachineFunction().getFunction().getCallingConv(); 2034 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2035 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2036 2037 // Verify that the target's LowerReturn behaved as expected. 2038 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2039 "LowerReturn didn't return a valid chain!"); 2040 2041 // Update the DAG with the new chain value resulting from return lowering. 2042 DAG.setRoot(Chain); 2043 } 2044 2045 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2046 /// created for it, emit nodes to copy the value into the virtual 2047 /// registers. 2048 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2049 // Skip empty types 2050 if (V->getType()->isEmptyTy()) 2051 return; 2052 2053 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2054 if (VMI != FuncInfo.ValueMap.end()) { 2055 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2056 CopyValueToVirtualRegister(V, VMI->second); 2057 } 2058 } 2059 2060 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2061 /// the current basic block, add it to ValueMap now so that we'll get a 2062 /// CopyTo/FromReg. 2063 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2064 // No need to export constants. 2065 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2066 2067 // Already exported? 2068 if (FuncInfo.isExportedInst(V)) return; 2069 2070 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2071 CopyValueToVirtualRegister(V, Reg); 2072 } 2073 2074 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2075 const BasicBlock *FromBB) { 2076 // The operands of the setcc have to be in this block. We don't know 2077 // how to export them from some other block. 2078 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2079 // Can export from current BB. 2080 if (VI->getParent() == FromBB) 2081 return true; 2082 2083 // Is already exported, noop. 2084 return FuncInfo.isExportedInst(V); 2085 } 2086 2087 // If this is an argument, we can export it if the BB is the entry block or 2088 // if it is already exported. 2089 if (isa<Argument>(V)) { 2090 if (FromBB->isEntryBlock()) 2091 return true; 2092 2093 // Otherwise, can only export this if it is already exported. 2094 return FuncInfo.isExportedInst(V); 2095 } 2096 2097 // Otherwise, constants can always be exported. 2098 return true; 2099 } 2100 2101 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2102 BranchProbability 2103 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2104 const MachineBasicBlock *Dst) const { 2105 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2106 const BasicBlock *SrcBB = Src->getBasicBlock(); 2107 const BasicBlock *DstBB = Dst->getBasicBlock(); 2108 if (!BPI) { 2109 // If BPI is not available, set the default probability as 1 / N, where N is 2110 // the number of successors. 2111 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2112 return BranchProbability(1, SuccSize); 2113 } 2114 return BPI->getEdgeProbability(SrcBB, DstBB); 2115 } 2116 2117 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2118 MachineBasicBlock *Dst, 2119 BranchProbability Prob) { 2120 if (!FuncInfo.BPI) 2121 Src->addSuccessorWithoutProb(Dst); 2122 else { 2123 if (Prob.isUnknown()) 2124 Prob = getEdgeProbability(Src, Dst); 2125 Src->addSuccessor(Dst, Prob); 2126 } 2127 } 2128 2129 static bool InBlock(const Value *V, const BasicBlock *BB) { 2130 if (const Instruction *I = dyn_cast<Instruction>(V)) 2131 return I->getParent() == BB; 2132 return true; 2133 } 2134 2135 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2136 /// This function emits a branch and is used at the leaves of an OR or an 2137 /// AND operator tree. 2138 void 2139 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2140 MachineBasicBlock *TBB, 2141 MachineBasicBlock *FBB, 2142 MachineBasicBlock *CurBB, 2143 MachineBasicBlock *SwitchBB, 2144 BranchProbability TProb, 2145 BranchProbability FProb, 2146 bool InvertCond) { 2147 const BasicBlock *BB = CurBB->getBasicBlock(); 2148 2149 // If the leaf of the tree is a comparison, merge the condition into 2150 // the caseblock. 2151 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2152 // The operands of the cmp have to be in this block. We don't know 2153 // how to export them from some other block. If this is the first block 2154 // of the sequence, no exporting is needed. 2155 if (CurBB == SwitchBB || 2156 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2157 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2158 ISD::CondCode Condition; 2159 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2160 ICmpInst::Predicate Pred = 2161 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2162 Condition = getICmpCondCode(Pred); 2163 } else { 2164 const FCmpInst *FC = cast<FCmpInst>(Cond); 2165 FCmpInst::Predicate Pred = 2166 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2167 Condition = getFCmpCondCode(Pred); 2168 if (TM.Options.NoNaNsFPMath) 2169 Condition = getFCmpCodeWithoutNaN(Condition); 2170 } 2171 2172 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2173 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2174 SL->SwitchCases.push_back(CB); 2175 return; 2176 } 2177 } 2178 2179 // Create a CaseBlock record representing this branch. 2180 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2181 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2182 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2183 SL->SwitchCases.push_back(CB); 2184 } 2185 2186 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2187 MachineBasicBlock *TBB, 2188 MachineBasicBlock *FBB, 2189 MachineBasicBlock *CurBB, 2190 MachineBasicBlock *SwitchBB, 2191 Instruction::BinaryOps Opc, 2192 BranchProbability TProb, 2193 BranchProbability FProb, 2194 bool InvertCond) { 2195 // Skip over not part of the tree and remember to invert op and operands at 2196 // next level. 2197 Value *NotCond; 2198 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2199 InBlock(NotCond, CurBB->getBasicBlock())) { 2200 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2201 !InvertCond); 2202 return; 2203 } 2204 2205 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2206 const Value *BOpOp0, *BOpOp1; 2207 // Compute the effective opcode for Cond, taking into account whether it needs 2208 // to be inverted, e.g. 2209 // and (not (or A, B)), C 2210 // gets lowered as 2211 // and (and (not A, not B), C) 2212 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2213 if (BOp) { 2214 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2215 ? Instruction::And 2216 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2217 ? Instruction::Or 2218 : (Instruction::BinaryOps)0); 2219 if (InvertCond) { 2220 if (BOpc == Instruction::And) 2221 BOpc = Instruction::Or; 2222 else if (BOpc == Instruction::Or) 2223 BOpc = Instruction::And; 2224 } 2225 } 2226 2227 // If this node is not part of the or/and tree, emit it as a branch. 2228 // Note that all nodes in the tree should have same opcode. 2229 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2230 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2231 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2232 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2233 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2234 TProb, FProb, InvertCond); 2235 return; 2236 } 2237 2238 // Create TmpBB after CurBB. 2239 MachineFunction::iterator BBI(CurBB); 2240 MachineFunction &MF = DAG.getMachineFunction(); 2241 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2242 CurBB->getParent()->insert(++BBI, TmpBB); 2243 2244 if (Opc == Instruction::Or) { 2245 // Codegen X | Y as: 2246 // BB1: 2247 // jmp_if_X TBB 2248 // jmp TmpBB 2249 // TmpBB: 2250 // jmp_if_Y TBB 2251 // jmp FBB 2252 // 2253 2254 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2255 // The requirement is that 2256 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2257 // = TrueProb for original BB. 2258 // Assuming the original probabilities are A and B, one choice is to set 2259 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2260 // A/(1+B) and 2B/(1+B). This choice assumes that 2261 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2262 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2263 // TmpBB, but the math is more complicated. 2264 2265 auto NewTrueProb = TProb / 2; 2266 auto NewFalseProb = TProb / 2 + FProb; 2267 // Emit the LHS condition. 2268 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2269 NewFalseProb, InvertCond); 2270 2271 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2272 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2273 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2274 // Emit the RHS condition into TmpBB. 2275 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2276 Probs[1], InvertCond); 2277 } else { 2278 assert(Opc == Instruction::And && "Unknown merge op!"); 2279 // Codegen X & Y as: 2280 // BB1: 2281 // jmp_if_X TmpBB 2282 // jmp FBB 2283 // TmpBB: 2284 // jmp_if_Y TBB 2285 // jmp FBB 2286 // 2287 // This requires creation of TmpBB after CurBB. 2288 2289 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2290 // The requirement is that 2291 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2292 // = FalseProb for original BB. 2293 // Assuming the original probabilities are A and B, one choice is to set 2294 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2295 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2296 // TrueProb for BB1 * FalseProb for TmpBB. 2297 2298 auto NewTrueProb = TProb + FProb / 2; 2299 auto NewFalseProb = FProb / 2; 2300 // Emit the LHS condition. 2301 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2302 NewFalseProb, InvertCond); 2303 2304 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2305 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2306 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2307 // Emit the RHS condition into TmpBB. 2308 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2309 Probs[1], InvertCond); 2310 } 2311 } 2312 2313 /// If the set of cases should be emitted as a series of branches, return true. 2314 /// If we should emit this as a bunch of and/or'd together conditions, return 2315 /// false. 2316 bool 2317 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2318 if (Cases.size() != 2) return true; 2319 2320 // If this is two comparisons of the same values or'd or and'd together, they 2321 // will get folded into a single comparison, so don't emit two blocks. 2322 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2323 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2324 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2325 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2326 return false; 2327 } 2328 2329 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2330 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2331 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2332 Cases[0].CC == Cases[1].CC && 2333 isa<Constant>(Cases[0].CmpRHS) && 2334 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2335 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2336 return false; 2337 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2338 return false; 2339 } 2340 2341 return true; 2342 } 2343 2344 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2345 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2346 2347 // Update machine-CFG edges. 2348 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2349 2350 if (I.isUnconditional()) { 2351 // Update machine-CFG edges. 2352 BrMBB->addSuccessor(Succ0MBB); 2353 2354 // If this is not a fall-through branch or optimizations are switched off, 2355 // emit the branch. 2356 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2357 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2358 MVT::Other, getControlRoot(), 2359 DAG.getBasicBlock(Succ0MBB))); 2360 2361 return; 2362 } 2363 2364 // If this condition is one of the special cases we handle, do special stuff 2365 // now. 2366 const Value *CondVal = I.getCondition(); 2367 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2368 2369 // If this is a series of conditions that are or'd or and'd together, emit 2370 // this as a sequence of branches instead of setcc's with and/or operations. 2371 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2372 // unpredictable branches, and vector extracts because those jumps are likely 2373 // expensive for any target), this should improve performance. 2374 // For example, instead of something like: 2375 // cmp A, B 2376 // C = seteq 2377 // cmp D, E 2378 // F = setle 2379 // or C, F 2380 // jnz foo 2381 // Emit: 2382 // cmp A, B 2383 // je foo 2384 // cmp D, E 2385 // jle foo 2386 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2387 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2388 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2389 Value *Vec; 2390 const Value *BOp0, *BOp1; 2391 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2392 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2393 Opcode = Instruction::And; 2394 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2395 Opcode = Instruction::Or; 2396 2397 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2398 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2399 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2400 getEdgeProbability(BrMBB, Succ0MBB), 2401 getEdgeProbability(BrMBB, Succ1MBB), 2402 /*InvertCond=*/false); 2403 // If the compares in later blocks need to use values not currently 2404 // exported from this block, export them now. This block should always 2405 // be the first entry. 2406 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2407 2408 // Allow some cases to be rejected. 2409 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2410 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2411 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2412 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2413 } 2414 2415 // Emit the branch for this block. 2416 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2417 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2418 return; 2419 } 2420 2421 // Okay, we decided not to do this, remove any inserted MBB's and clear 2422 // SwitchCases. 2423 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2424 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2425 2426 SL->SwitchCases.clear(); 2427 } 2428 } 2429 2430 // Create a CaseBlock record representing this branch. 2431 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2432 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2433 2434 // Use visitSwitchCase to actually insert the fast branch sequence for this 2435 // cond branch. 2436 visitSwitchCase(CB, BrMBB); 2437 } 2438 2439 /// visitSwitchCase - Emits the necessary code to represent a single node in 2440 /// the binary search tree resulting from lowering a switch instruction. 2441 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2442 MachineBasicBlock *SwitchBB) { 2443 SDValue Cond; 2444 SDValue CondLHS = getValue(CB.CmpLHS); 2445 SDLoc dl = CB.DL; 2446 2447 if (CB.CC == ISD::SETTRUE) { 2448 // Branch or fall through to TrueBB. 2449 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2450 SwitchBB->normalizeSuccProbs(); 2451 if (CB.TrueBB != NextBlock(SwitchBB)) { 2452 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2453 DAG.getBasicBlock(CB.TrueBB))); 2454 } 2455 return; 2456 } 2457 2458 auto &TLI = DAG.getTargetLoweringInfo(); 2459 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2460 2461 // Build the setcc now. 2462 if (!CB.CmpMHS) { 2463 // Fold "(X == true)" to X and "(X == false)" to !X to 2464 // handle common cases produced by branch lowering. 2465 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2466 CB.CC == ISD::SETEQ) 2467 Cond = CondLHS; 2468 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2469 CB.CC == ISD::SETEQ) { 2470 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2471 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2472 } else { 2473 SDValue CondRHS = getValue(CB.CmpRHS); 2474 2475 // If a pointer's DAG type is larger than its memory type then the DAG 2476 // values are zero-extended. This breaks signed comparisons so truncate 2477 // back to the underlying type before doing the compare. 2478 if (CondLHS.getValueType() != MemVT) { 2479 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2480 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2481 } 2482 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2483 } 2484 } else { 2485 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2486 2487 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2488 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2489 2490 SDValue CmpOp = getValue(CB.CmpMHS); 2491 EVT VT = CmpOp.getValueType(); 2492 2493 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2494 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2495 ISD::SETLE); 2496 } else { 2497 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2498 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2499 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2500 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2501 } 2502 } 2503 2504 // Update successor info 2505 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2506 // TrueBB and FalseBB are always different unless the incoming IR is 2507 // degenerate. This only happens when running llc on weird IR. 2508 if (CB.TrueBB != CB.FalseBB) 2509 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2510 SwitchBB->normalizeSuccProbs(); 2511 2512 // If the lhs block is the next block, invert the condition so that we can 2513 // fall through to the lhs instead of the rhs block. 2514 if (CB.TrueBB == NextBlock(SwitchBB)) { 2515 std::swap(CB.TrueBB, CB.FalseBB); 2516 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2517 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2518 } 2519 2520 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2521 MVT::Other, getControlRoot(), Cond, 2522 DAG.getBasicBlock(CB.TrueBB)); 2523 2524 // Insert the false branch. Do this even if it's a fall through branch, 2525 // this makes it easier to do DAG optimizations which require inverting 2526 // the branch condition. 2527 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2528 DAG.getBasicBlock(CB.FalseBB)); 2529 2530 DAG.setRoot(BrCond); 2531 } 2532 2533 /// visitJumpTable - Emit JumpTable node in the current MBB 2534 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2535 // Emit the code for the jump table 2536 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2537 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2538 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2539 JT.Reg, PTy); 2540 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2541 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2542 MVT::Other, Index.getValue(1), 2543 Table, Index); 2544 DAG.setRoot(BrJumpTable); 2545 } 2546 2547 /// visitJumpTableHeader - This function emits necessary code to produce index 2548 /// in the JumpTable from switch case. 2549 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2550 JumpTableHeader &JTH, 2551 MachineBasicBlock *SwitchBB) { 2552 SDLoc dl = getCurSDLoc(); 2553 2554 // Subtract the lowest switch case value from the value being switched on. 2555 SDValue SwitchOp = getValue(JTH.SValue); 2556 EVT VT = SwitchOp.getValueType(); 2557 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2558 DAG.getConstant(JTH.First, dl, VT)); 2559 2560 // The SDNode we just created, which holds the value being switched on minus 2561 // the smallest case value, needs to be copied to a virtual register so it 2562 // can be used as an index into the jump table in a subsequent basic block. 2563 // This value may be smaller or larger than the target's pointer type, and 2564 // therefore require extension or truncating. 2565 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2566 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2567 2568 unsigned JumpTableReg = 2569 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2570 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2571 JumpTableReg, SwitchOp); 2572 JT.Reg = JumpTableReg; 2573 2574 if (!JTH.OmitRangeCheck) { 2575 // Emit the range check for the jump table, and branch to the default block 2576 // for the switch statement if the value being switched on exceeds the 2577 // largest case in the switch. 2578 SDValue CMP = DAG.getSetCC( 2579 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2580 Sub.getValueType()), 2581 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2582 2583 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2584 MVT::Other, CopyTo, CMP, 2585 DAG.getBasicBlock(JT.Default)); 2586 2587 // Avoid emitting unnecessary branches to the next block. 2588 if (JT.MBB != NextBlock(SwitchBB)) 2589 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2590 DAG.getBasicBlock(JT.MBB)); 2591 2592 DAG.setRoot(BrCond); 2593 } else { 2594 // Avoid emitting unnecessary branches to the next block. 2595 if (JT.MBB != NextBlock(SwitchBB)) 2596 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2597 DAG.getBasicBlock(JT.MBB))); 2598 else 2599 DAG.setRoot(CopyTo); 2600 } 2601 } 2602 2603 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2604 /// variable if there exists one. 2605 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2606 SDValue &Chain) { 2607 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2608 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2609 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2610 MachineFunction &MF = DAG.getMachineFunction(); 2611 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2612 MachineSDNode *Node = 2613 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2614 if (Global) { 2615 MachinePointerInfo MPInfo(Global); 2616 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2617 MachineMemOperand::MODereferenceable; 2618 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2619 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2620 DAG.setNodeMemRefs(Node, {MemRef}); 2621 } 2622 if (PtrTy != PtrMemTy) 2623 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2624 return SDValue(Node, 0); 2625 } 2626 2627 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2628 /// tail spliced into a stack protector check success bb. 2629 /// 2630 /// For a high level explanation of how this fits into the stack protector 2631 /// generation see the comment on the declaration of class 2632 /// StackProtectorDescriptor. 2633 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2634 MachineBasicBlock *ParentBB) { 2635 2636 // First create the loads to the guard/stack slot for the comparison. 2637 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2638 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2639 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2640 2641 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2642 int FI = MFI.getStackProtectorIndex(); 2643 2644 SDValue Guard; 2645 SDLoc dl = getCurSDLoc(); 2646 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2647 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2648 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2649 2650 // Generate code to load the content of the guard slot. 2651 SDValue GuardVal = DAG.getLoad( 2652 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2653 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2654 MachineMemOperand::MOVolatile); 2655 2656 if (TLI.useStackGuardXorFP()) 2657 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2658 2659 // Retrieve guard check function, nullptr if instrumentation is inlined. 2660 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2661 // The target provides a guard check function to validate the guard value. 2662 // Generate a call to that function with the content of the guard slot as 2663 // argument. 2664 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2665 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2666 2667 TargetLowering::ArgListTy Args; 2668 TargetLowering::ArgListEntry Entry; 2669 Entry.Node = GuardVal; 2670 Entry.Ty = FnTy->getParamType(0); 2671 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2672 Entry.IsInReg = true; 2673 Args.push_back(Entry); 2674 2675 TargetLowering::CallLoweringInfo CLI(DAG); 2676 CLI.setDebugLoc(getCurSDLoc()) 2677 .setChain(DAG.getEntryNode()) 2678 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2679 getValue(GuardCheckFn), std::move(Args)); 2680 2681 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2682 DAG.setRoot(Result.second); 2683 return; 2684 } 2685 2686 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2687 // Otherwise, emit a volatile load to retrieve the stack guard value. 2688 SDValue Chain = DAG.getEntryNode(); 2689 if (TLI.useLoadStackGuardNode()) { 2690 Guard = getLoadStackGuard(DAG, dl, Chain); 2691 } else { 2692 const Value *IRGuard = TLI.getSDagStackGuard(M); 2693 SDValue GuardPtr = getValue(IRGuard); 2694 2695 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2696 MachinePointerInfo(IRGuard, 0), Align, 2697 MachineMemOperand::MOVolatile); 2698 } 2699 2700 // Perform the comparison via a getsetcc. 2701 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2702 *DAG.getContext(), 2703 Guard.getValueType()), 2704 Guard, GuardVal, ISD::SETNE); 2705 2706 // If the guard/stackslot do not equal, branch to failure MBB. 2707 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2708 MVT::Other, GuardVal.getOperand(0), 2709 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2710 // Otherwise branch to success MBB. 2711 SDValue Br = DAG.getNode(ISD::BR, dl, 2712 MVT::Other, BrCond, 2713 DAG.getBasicBlock(SPD.getSuccessMBB())); 2714 2715 DAG.setRoot(Br); 2716 } 2717 2718 /// Codegen the failure basic block for a stack protector check. 2719 /// 2720 /// A failure stack protector machine basic block consists simply of a call to 2721 /// __stack_chk_fail(). 2722 /// 2723 /// For a high level explanation of how this fits into the stack protector 2724 /// generation see the comment on the declaration of class 2725 /// StackProtectorDescriptor. 2726 void 2727 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2728 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2729 TargetLowering::MakeLibCallOptions CallOptions; 2730 CallOptions.setDiscardResult(true); 2731 SDValue Chain = 2732 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2733 None, CallOptions, getCurSDLoc()).second; 2734 // On PS4, the "return address" must still be within the calling function, 2735 // even if it's at the very end, so emit an explicit TRAP here. 2736 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2737 if (TM.getTargetTriple().isPS4CPU()) 2738 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2739 // WebAssembly needs an unreachable instruction after a non-returning call, 2740 // because the function return type can be different from __stack_chk_fail's 2741 // return type (void). 2742 if (TM.getTargetTriple().isWasm()) 2743 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2744 2745 DAG.setRoot(Chain); 2746 } 2747 2748 /// visitBitTestHeader - This function emits necessary code to produce value 2749 /// suitable for "bit tests" 2750 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2751 MachineBasicBlock *SwitchBB) { 2752 SDLoc dl = getCurSDLoc(); 2753 2754 // Subtract the minimum value. 2755 SDValue SwitchOp = getValue(B.SValue); 2756 EVT VT = SwitchOp.getValueType(); 2757 SDValue RangeSub = 2758 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2759 2760 // Determine the type of the test operands. 2761 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2762 bool UsePtrType = false; 2763 if (!TLI.isTypeLegal(VT)) { 2764 UsePtrType = true; 2765 } else { 2766 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2767 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2768 // Switch table case range are encoded into series of masks. 2769 // Just use pointer type, it's guaranteed to fit. 2770 UsePtrType = true; 2771 break; 2772 } 2773 } 2774 SDValue Sub = RangeSub; 2775 if (UsePtrType) { 2776 VT = TLI.getPointerTy(DAG.getDataLayout()); 2777 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2778 } 2779 2780 B.RegVT = VT.getSimpleVT(); 2781 B.Reg = FuncInfo.CreateReg(B.RegVT); 2782 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2783 2784 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2785 2786 if (!B.OmitRangeCheck) 2787 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2788 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2789 SwitchBB->normalizeSuccProbs(); 2790 2791 SDValue Root = CopyTo; 2792 if (!B.OmitRangeCheck) { 2793 // Conditional branch to the default block. 2794 SDValue RangeCmp = DAG.getSetCC(dl, 2795 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2796 RangeSub.getValueType()), 2797 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2798 ISD::SETUGT); 2799 2800 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2801 DAG.getBasicBlock(B.Default)); 2802 } 2803 2804 // Avoid emitting unnecessary branches to the next block. 2805 if (MBB != NextBlock(SwitchBB)) 2806 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2807 2808 DAG.setRoot(Root); 2809 } 2810 2811 /// visitBitTestCase - this function produces one "bit test" 2812 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2813 MachineBasicBlock* NextMBB, 2814 BranchProbability BranchProbToNext, 2815 unsigned Reg, 2816 BitTestCase &B, 2817 MachineBasicBlock *SwitchBB) { 2818 SDLoc dl = getCurSDLoc(); 2819 MVT VT = BB.RegVT; 2820 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2821 SDValue Cmp; 2822 unsigned PopCount = countPopulation(B.Mask); 2823 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2824 if (PopCount == 1) { 2825 // Testing for a single bit; just compare the shift count with what it 2826 // would need to be to shift a 1 bit in that position. 2827 Cmp = DAG.getSetCC( 2828 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2829 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2830 ISD::SETEQ); 2831 } else if (PopCount == BB.Range) { 2832 // There is only one zero bit in the range, test for it directly. 2833 Cmp = DAG.getSetCC( 2834 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2835 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2836 ISD::SETNE); 2837 } else { 2838 // Make desired shift 2839 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2840 DAG.getConstant(1, dl, VT), ShiftOp); 2841 2842 // Emit bit tests and jumps 2843 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2844 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2845 Cmp = DAG.getSetCC( 2846 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2847 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2848 } 2849 2850 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2851 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2852 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2853 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2854 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2855 // one as they are relative probabilities (and thus work more like weights), 2856 // and hence we need to normalize them to let the sum of them become one. 2857 SwitchBB->normalizeSuccProbs(); 2858 2859 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2860 MVT::Other, getControlRoot(), 2861 Cmp, DAG.getBasicBlock(B.TargetBB)); 2862 2863 // Avoid emitting unnecessary branches to the next block. 2864 if (NextMBB != NextBlock(SwitchBB)) 2865 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2866 DAG.getBasicBlock(NextMBB)); 2867 2868 DAG.setRoot(BrAnd); 2869 } 2870 2871 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2872 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2873 2874 // Retrieve successors. Look through artificial IR level blocks like 2875 // catchswitch for successors. 2876 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2877 const BasicBlock *EHPadBB = I.getSuccessor(1); 2878 2879 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2880 // have to do anything here to lower funclet bundles. 2881 assert(!I.hasOperandBundlesOtherThan( 2882 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2883 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2884 LLVMContext::OB_cfguardtarget, 2885 LLVMContext::OB_clang_arc_attachedcall}) && 2886 "Cannot lower invokes with arbitrary operand bundles yet!"); 2887 2888 const Value *Callee(I.getCalledOperand()); 2889 const Function *Fn = dyn_cast<Function>(Callee); 2890 if (isa<InlineAsm>(Callee)) 2891 visitInlineAsm(I, EHPadBB); 2892 else if (Fn && Fn->isIntrinsic()) { 2893 switch (Fn->getIntrinsicID()) { 2894 default: 2895 llvm_unreachable("Cannot invoke this intrinsic"); 2896 case Intrinsic::donothing: 2897 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2898 case Intrinsic::seh_try_begin: 2899 case Intrinsic::seh_scope_begin: 2900 case Intrinsic::seh_try_end: 2901 case Intrinsic::seh_scope_end: 2902 break; 2903 case Intrinsic::experimental_patchpoint_void: 2904 case Intrinsic::experimental_patchpoint_i64: 2905 visitPatchpoint(I, EHPadBB); 2906 break; 2907 case Intrinsic::experimental_gc_statepoint: 2908 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2909 break; 2910 case Intrinsic::wasm_rethrow: { 2911 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2912 // special because it can be invoked, so we manually lower it to a DAG 2913 // node here. 2914 SmallVector<SDValue, 8> Ops; 2915 Ops.push_back(getRoot()); // inchain 2916 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2917 Ops.push_back( 2918 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2919 TLI.getPointerTy(DAG.getDataLayout()))); 2920 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2921 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2922 break; 2923 } 2924 } 2925 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2926 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2927 // Eventually we will support lowering the @llvm.experimental.deoptimize 2928 // intrinsic, and right now there are no plans to support other intrinsics 2929 // with deopt state. 2930 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2931 } else { 2932 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 2933 } 2934 2935 // If the value of the invoke is used outside of its defining block, make it 2936 // available as a virtual register. 2937 // We already took care of the exported value for the statepoint instruction 2938 // during call to the LowerStatepoint. 2939 if (!isa<GCStatepointInst>(I)) { 2940 CopyToExportRegsIfNeeded(&I); 2941 } 2942 2943 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2944 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2945 BranchProbability EHPadBBProb = 2946 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2947 : BranchProbability::getZero(); 2948 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2949 2950 // Update successor info. 2951 addSuccessorWithProb(InvokeMBB, Return); 2952 for (auto &UnwindDest : UnwindDests) { 2953 UnwindDest.first->setIsEHPad(); 2954 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2955 } 2956 InvokeMBB->normalizeSuccProbs(); 2957 2958 // Drop into normal successor. 2959 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2960 DAG.getBasicBlock(Return))); 2961 } 2962 2963 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2964 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2965 2966 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2967 // have to do anything here to lower funclet bundles. 2968 assert(!I.hasOperandBundlesOtherThan( 2969 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2970 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2971 2972 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2973 visitInlineAsm(I); 2974 CopyToExportRegsIfNeeded(&I); 2975 2976 // Retrieve successors. 2977 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2978 2979 // Update successor info. 2980 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2981 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2982 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2983 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2984 Target->setIsInlineAsmBrIndirectTarget(); 2985 } 2986 CallBrMBB->normalizeSuccProbs(); 2987 2988 // Drop into default successor. 2989 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2990 MVT::Other, getControlRoot(), 2991 DAG.getBasicBlock(Return))); 2992 } 2993 2994 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2995 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2996 } 2997 2998 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2999 assert(FuncInfo.MBB->isEHPad() && 3000 "Call to landingpad not in landing pad!"); 3001 3002 // If there aren't registers to copy the values into (e.g., during SjLj 3003 // exceptions), then don't bother to create these DAG nodes. 3004 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3005 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3006 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3007 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3008 return; 3009 3010 // If landingpad's return type is token type, we don't create DAG nodes 3011 // for its exception pointer and selector value. The extraction of exception 3012 // pointer or selector value from token type landingpads is not currently 3013 // supported. 3014 if (LP.getType()->isTokenTy()) 3015 return; 3016 3017 SmallVector<EVT, 2> ValueVTs; 3018 SDLoc dl = getCurSDLoc(); 3019 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3020 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3021 3022 // Get the two live-in registers as SDValues. The physregs have already been 3023 // copied into virtual registers. 3024 SDValue Ops[2]; 3025 if (FuncInfo.ExceptionPointerVirtReg) { 3026 Ops[0] = DAG.getZExtOrTrunc( 3027 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3028 FuncInfo.ExceptionPointerVirtReg, 3029 TLI.getPointerTy(DAG.getDataLayout())), 3030 dl, ValueVTs[0]); 3031 } else { 3032 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3033 } 3034 Ops[1] = DAG.getZExtOrTrunc( 3035 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3036 FuncInfo.ExceptionSelectorVirtReg, 3037 TLI.getPointerTy(DAG.getDataLayout())), 3038 dl, ValueVTs[1]); 3039 3040 // Merge into one. 3041 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3042 DAG.getVTList(ValueVTs), Ops); 3043 setValue(&LP, Res); 3044 } 3045 3046 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3047 MachineBasicBlock *Last) { 3048 // Update JTCases. 3049 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 3050 if (SL->JTCases[i].first.HeaderBB == First) 3051 SL->JTCases[i].first.HeaderBB = Last; 3052 3053 // Update BitTestCases. 3054 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 3055 if (SL->BitTestCases[i].Parent == First) 3056 SL->BitTestCases[i].Parent = Last; 3057 } 3058 3059 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3060 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3061 3062 // Update machine-CFG edges with unique successors. 3063 SmallSet<BasicBlock*, 32> Done; 3064 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3065 BasicBlock *BB = I.getSuccessor(i); 3066 bool Inserted = Done.insert(BB).second; 3067 if (!Inserted) 3068 continue; 3069 3070 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3071 addSuccessorWithProb(IndirectBrMBB, Succ); 3072 } 3073 IndirectBrMBB->normalizeSuccProbs(); 3074 3075 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3076 MVT::Other, getControlRoot(), 3077 getValue(I.getAddress()))); 3078 } 3079 3080 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3081 if (!DAG.getTarget().Options.TrapUnreachable) 3082 return; 3083 3084 // We may be able to ignore unreachable behind a noreturn call. 3085 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3086 const BasicBlock &BB = *I.getParent(); 3087 if (&I != &BB.front()) { 3088 BasicBlock::const_iterator PredI = 3089 std::prev(BasicBlock::const_iterator(&I)); 3090 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3091 if (Call->doesNotReturn()) 3092 return; 3093 } 3094 } 3095 } 3096 3097 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3098 } 3099 3100 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3101 SDNodeFlags Flags; 3102 3103 SDValue Op = getValue(I.getOperand(0)); 3104 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3105 Op, Flags); 3106 setValue(&I, UnNodeValue); 3107 } 3108 3109 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3110 SDNodeFlags Flags; 3111 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3112 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3113 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3114 } 3115 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3116 Flags.setExact(ExactOp->isExact()); 3117 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3118 Flags.copyFMF(*FPOp); 3119 3120 SDValue Op1 = getValue(I.getOperand(0)); 3121 SDValue Op2 = getValue(I.getOperand(1)); 3122 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3123 Op1, Op2, Flags); 3124 setValue(&I, BinNodeValue); 3125 } 3126 3127 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3128 SDValue Op1 = getValue(I.getOperand(0)); 3129 SDValue Op2 = getValue(I.getOperand(1)); 3130 3131 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3132 Op1.getValueType(), DAG.getDataLayout()); 3133 3134 // Coerce the shift amount to the right type if we can. 3135 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3136 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3137 unsigned Op2Size = Op2.getValueSizeInBits(); 3138 SDLoc DL = getCurSDLoc(); 3139 3140 // If the operand is smaller than the shift count type, promote it. 3141 if (ShiftSize > Op2Size) 3142 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3143 3144 // If the operand is larger than the shift count type but the shift 3145 // count type has enough bits to represent any shift value, truncate 3146 // it now. This is a common case and it exposes the truncate to 3147 // optimization early. 3148 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3149 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3150 // Otherwise we'll need to temporarily settle for some other convenient 3151 // type. Type legalization will make adjustments once the shiftee is split. 3152 else 3153 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3154 } 3155 3156 bool nuw = false; 3157 bool nsw = false; 3158 bool exact = false; 3159 3160 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3161 3162 if (const OverflowingBinaryOperator *OFBinOp = 3163 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3164 nuw = OFBinOp->hasNoUnsignedWrap(); 3165 nsw = OFBinOp->hasNoSignedWrap(); 3166 } 3167 if (const PossiblyExactOperator *ExactOp = 3168 dyn_cast<const PossiblyExactOperator>(&I)) 3169 exact = ExactOp->isExact(); 3170 } 3171 SDNodeFlags Flags; 3172 Flags.setExact(exact); 3173 Flags.setNoSignedWrap(nsw); 3174 Flags.setNoUnsignedWrap(nuw); 3175 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3176 Flags); 3177 setValue(&I, Res); 3178 } 3179 3180 void SelectionDAGBuilder::visitSDiv(const User &I) { 3181 SDValue Op1 = getValue(I.getOperand(0)); 3182 SDValue Op2 = getValue(I.getOperand(1)); 3183 3184 SDNodeFlags Flags; 3185 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3186 cast<PossiblyExactOperator>(&I)->isExact()); 3187 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3188 Op2, Flags)); 3189 } 3190 3191 void SelectionDAGBuilder::visitICmp(const User &I) { 3192 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3193 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3194 predicate = IC->getPredicate(); 3195 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3196 predicate = ICmpInst::Predicate(IC->getPredicate()); 3197 SDValue Op1 = getValue(I.getOperand(0)); 3198 SDValue Op2 = getValue(I.getOperand(1)); 3199 ISD::CondCode Opcode = getICmpCondCode(predicate); 3200 3201 auto &TLI = DAG.getTargetLoweringInfo(); 3202 EVT MemVT = 3203 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3204 3205 // If a pointer's DAG type is larger than its memory type then the DAG values 3206 // are zero-extended. This breaks signed comparisons so truncate back to the 3207 // underlying type before doing the compare. 3208 if (Op1.getValueType() != MemVT) { 3209 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3210 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3211 } 3212 3213 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3214 I.getType()); 3215 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3216 } 3217 3218 void SelectionDAGBuilder::visitFCmp(const User &I) { 3219 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3220 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3221 predicate = FC->getPredicate(); 3222 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3223 predicate = FCmpInst::Predicate(FC->getPredicate()); 3224 SDValue Op1 = getValue(I.getOperand(0)); 3225 SDValue Op2 = getValue(I.getOperand(1)); 3226 3227 ISD::CondCode Condition = getFCmpCondCode(predicate); 3228 auto *FPMO = cast<FPMathOperator>(&I); 3229 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3230 Condition = getFCmpCodeWithoutNaN(Condition); 3231 3232 SDNodeFlags Flags; 3233 Flags.copyFMF(*FPMO); 3234 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3235 3236 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3237 I.getType()); 3238 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3239 } 3240 3241 // Check if the condition of the select has one use or two users that are both 3242 // selects with the same condition. 3243 static bool hasOnlySelectUsers(const Value *Cond) { 3244 return llvm::all_of(Cond->users(), [](const Value *V) { 3245 return isa<SelectInst>(V); 3246 }); 3247 } 3248 3249 void SelectionDAGBuilder::visitSelect(const User &I) { 3250 SmallVector<EVT, 4> ValueVTs; 3251 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3252 ValueVTs); 3253 unsigned NumValues = ValueVTs.size(); 3254 if (NumValues == 0) return; 3255 3256 SmallVector<SDValue, 4> Values(NumValues); 3257 SDValue Cond = getValue(I.getOperand(0)); 3258 SDValue LHSVal = getValue(I.getOperand(1)); 3259 SDValue RHSVal = getValue(I.getOperand(2)); 3260 SmallVector<SDValue, 1> BaseOps(1, Cond); 3261 ISD::NodeType OpCode = 3262 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3263 3264 bool IsUnaryAbs = false; 3265 bool Negate = false; 3266 3267 SDNodeFlags Flags; 3268 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3269 Flags.copyFMF(*FPOp); 3270 3271 // Min/max matching is only viable if all output VTs are the same. 3272 if (is_splat(ValueVTs)) { 3273 EVT VT = ValueVTs[0]; 3274 LLVMContext &Ctx = *DAG.getContext(); 3275 auto &TLI = DAG.getTargetLoweringInfo(); 3276 3277 // We care about the legality of the operation after it has been type 3278 // legalized. 3279 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3280 VT = TLI.getTypeToTransformTo(Ctx, VT); 3281 3282 // If the vselect is legal, assume we want to leave this as a vector setcc + 3283 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3284 // min/max is legal on the scalar type. 3285 bool UseScalarMinMax = VT.isVector() && 3286 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3287 3288 Value *LHS, *RHS; 3289 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3290 ISD::NodeType Opc = ISD::DELETED_NODE; 3291 switch (SPR.Flavor) { 3292 case SPF_UMAX: Opc = ISD::UMAX; break; 3293 case SPF_UMIN: Opc = ISD::UMIN; break; 3294 case SPF_SMAX: Opc = ISD::SMAX; break; 3295 case SPF_SMIN: Opc = ISD::SMIN; break; 3296 case SPF_FMINNUM: 3297 switch (SPR.NaNBehavior) { 3298 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3299 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3300 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3301 case SPNB_RETURNS_ANY: { 3302 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3303 Opc = ISD::FMINNUM; 3304 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3305 Opc = ISD::FMINIMUM; 3306 else if (UseScalarMinMax) 3307 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3308 ISD::FMINNUM : ISD::FMINIMUM; 3309 break; 3310 } 3311 } 3312 break; 3313 case SPF_FMAXNUM: 3314 switch (SPR.NaNBehavior) { 3315 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3316 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3317 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3318 case SPNB_RETURNS_ANY: 3319 3320 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3321 Opc = ISD::FMAXNUM; 3322 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3323 Opc = ISD::FMAXIMUM; 3324 else if (UseScalarMinMax) 3325 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3326 ISD::FMAXNUM : ISD::FMAXIMUM; 3327 break; 3328 } 3329 break; 3330 case SPF_NABS: 3331 Negate = true; 3332 LLVM_FALLTHROUGH; 3333 case SPF_ABS: 3334 IsUnaryAbs = true; 3335 Opc = ISD::ABS; 3336 break; 3337 default: break; 3338 } 3339 3340 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3341 (TLI.isOperationLegalOrCustom(Opc, VT) || 3342 (UseScalarMinMax && 3343 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3344 // If the underlying comparison instruction is used by any other 3345 // instruction, the consumed instructions won't be destroyed, so it is 3346 // not profitable to convert to a min/max. 3347 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3348 OpCode = Opc; 3349 LHSVal = getValue(LHS); 3350 RHSVal = getValue(RHS); 3351 BaseOps.clear(); 3352 } 3353 3354 if (IsUnaryAbs) { 3355 OpCode = Opc; 3356 LHSVal = getValue(LHS); 3357 BaseOps.clear(); 3358 } 3359 } 3360 3361 if (IsUnaryAbs) { 3362 for (unsigned i = 0; i != NumValues; ++i) { 3363 SDLoc dl = getCurSDLoc(); 3364 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3365 Values[i] = 3366 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3367 if (Negate) 3368 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3369 Values[i]); 3370 } 3371 } else { 3372 for (unsigned i = 0; i != NumValues; ++i) { 3373 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3374 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3375 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3376 Values[i] = DAG.getNode( 3377 OpCode, getCurSDLoc(), 3378 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3379 } 3380 } 3381 3382 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3383 DAG.getVTList(ValueVTs), Values)); 3384 } 3385 3386 void SelectionDAGBuilder::visitTrunc(const User &I) { 3387 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3388 SDValue N = getValue(I.getOperand(0)); 3389 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3390 I.getType()); 3391 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3392 } 3393 3394 void SelectionDAGBuilder::visitZExt(const User &I) { 3395 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3396 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3397 SDValue N = getValue(I.getOperand(0)); 3398 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3399 I.getType()); 3400 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3401 } 3402 3403 void SelectionDAGBuilder::visitSExt(const User &I) { 3404 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3405 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3406 SDValue N = getValue(I.getOperand(0)); 3407 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3408 I.getType()); 3409 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3410 } 3411 3412 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3413 // FPTrunc is never a no-op cast, no need to check 3414 SDValue N = getValue(I.getOperand(0)); 3415 SDLoc dl = getCurSDLoc(); 3416 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3417 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3418 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3419 DAG.getTargetConstant( 3420 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3421 } 3422 3423 void SelectionDAGBuilder::visitFPExt(const User &I) { 3424 // FPExt is never a no-op cast, no need to check 3425 SDValue N = getValue(I.getOperand(0)); 3426 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3427 I.getType()); 3428 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3429 } 3430 3431 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3432 // FPToUI is never a no-op cast, no need to check 3433 SDValue N = getValue(I.getOperand(0)); 3434 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3435 I.getType()); 3436 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3437 } 3438 3439 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3440 // FPToSI is never a no-op cast, no need to check 3441 SDValue N = getValue(I.getOperand(0)); 3442 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3443 I.getType()); 3444 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3445 } 3446 3447 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3448 // UIToFP is never a no-op cast, no need to check 3449 SDValue N = getValue(I.getOperand(0)); 3450 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3451 I.getType()); 3452 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3453 } 3454 3455 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3456 // SIToFP is never a no-op cast, no need to check 3457 SDValue N = getValue(I.getOperand(0)); 3458 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3459 I.getType()); 3460 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3461 } 3462 3463 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3464 // What to do depends on the size of the integer and the size of the pointer. 3465 // We can either truncate, zero extend, or no-op, accordingly. 3466 SDValue N = getValue(I.getOperand(0)); 3467 auto &TLI = DAG.getTargetLoweringInfo(); 3468 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3469 I.getType()); 3470 EVT PtrMemVT = 3471 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3472 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3473 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3474 setValue(&I, N); 3475 } 3476 3477 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3478 // What to do depends on the size of the integer and the size of the pointer. 3479 // We can either truncate, zero extend, or no-op, accordingly. 3480 SDValue N = getValue(I.getOperand(0)); 3481 auto &TLI = DAG.getTargetLoweringInfo(); 3482 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3483 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3484 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3485 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3486 setValue(&I, N); 3487 } 3488 3489 void SelectionDAGBuilder::visitBitCast(const User &I) { 3490 SDValue N = getValue(I.getOperand(0)); 3491 SDLoc dl = getCurSDLoc(); 3492 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3493 I.getType()); 3494 3495 // BitCast assures us that source and destination are the same size so this is 3496 // either a BITCAST or a no-op. 3497 if (DestVT != N.getValueType()) 3498 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3499 DestVT, N)); // convert types. 3500 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3501 // might fold any kind of constant expression to an integer constant and that 3502 // is not what we are looking for. Only recognize a bitcast of a genuine 3503 // constant integer as an opaque constant. 3504 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3505 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3506 /*isOpaque*/true)); 3507 else 3508 setValue(&I, N); // noop cast. 3509 } 3510 3511 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3512 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3513 const Value *SV = I.getOperand(0); 3514 SDValue N = getValue(SV); 3515 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3516 3517 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3518 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3519 3520 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3521 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3522 3523 setValue(&I, N); 3524 } 3525 3526 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3527 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3528 SDValue InVec = getValue(I.getOperand(0)); 3529 SDValue InVal = getValue(I.getOperand(1)); 3530 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3531 TLI.getVectorIdxTy(DAG.getDataLayout())); 3532 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3533 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3534 InVec, InVal, InIdx)); 3535 } 3536 3537 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3538 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3539 SDValue InVec = getValue(I.getOperand(0)); 3540 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3541 TLI.getVectorIdxTy(DAG.getDataLayout())); 3542 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3543 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3544 InVec, InIdx)); 3545 } 3546 3547 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3548 SDValue Src1 = getValue(I.getOperand(0)); 3549 SDValue Src2 = getValue(I.getOperand(1)); 3550 ArrayRef<int> Mask; 3551 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3552 Mask = SVI->getShuffleMask(); 3553 else 3554 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3555 SDLoc DL = getCurSDLoc(); 3556 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3557 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3558 EVT SrcVT = Src1.getValueType(); 3559 3560 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3561 VT.isScalableVector()) { 3562 // Canonical splat form of first element of first input vector. 3563 SDValue FirstElt = 3564 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3565 DAG.getVectorIdxConstant(0, DL)); 3566 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3567 return; 3568 } 3569 3570 // For now, we only handle splats for scalable vectors. 3571 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3572 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3573 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3574 3575 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3576 unsigned MaskNumElts = Mask.size(); 3577 3578 if (SrcNumElts == MaskNumElts) { 3579 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3580 return; 3581 } 3582 3583 // Normalize the shuffle vector since mask and vector length don't match. 3584 if (SrcNumElts < MaskNumElts) { 3585 // Mask is longer than the source vectors. We can use concatenate vector to 3586 // make the mask and vectors lengths match. 3587 3588 if (MaskNumElts % SrcNumElts == 0) { 3589 // Mask length is a multiple of the source vector length. 3590 // Check if the shuffle is some kind of concatenation of the input 3591 // vectors. 3592 unsigned NumConcat = MaskNumElts / SrcNumElts; 3593 bool IsConcat = true; 3594 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3595 for (unsigned i = 0; i != MaskNumElts; ++i) { 3596 int Idx = Mask[i]; 3597 if (Idx < 0) 3598 continue; 3599 // Ensure the indices in each SrcVT sized piece are sequential and that 3600 // the same source is used for the whole piece. 3601 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3602 (ConcatSrcs[i / SrcNumElts] >= 0 && 3603 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3604 IsConcat = false; 3605 break; 3606 } 3607 // Remember which source this index came from. 3608 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3609 } 3610 3611 // The shuffle is concatenating multiple vectors together. Just emit 3612 // a CONCAT_VECTORS operation. 3613 if (IsConcat) { 3614 SmallVector<SDValue, 8> ConcatOps; 3615 for (auto Src : ConcatSrcs) { 3616 if (Src < 0) 3617 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3618 else if (Src == 0) 3619 ConcatOps.push_back(Src1); 3620 else 3621 ConcatOps.push_back(Src2); 3622 } 3623 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3624 return; 3625 } 3626 } 3627 3628 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3629 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3630 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3631 PaddedMaskNumElts); 3632 3633 // Pad both vectors with undefs to make them the same length as the mask. 3634 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3635 3636 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3637 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3638 MOps1[0] = Src1; 3639 MOps2[0] = Src2; 3640 3641 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3642 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3643 3644 // Readjust mask for new input vector length. 3645 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3646 for (unsigned i = 0; i != MaskNumElts; ++i) { 3647 int Idx = Mask[i]; 3648 if (Idx >= (int)SrcNumElts) 3649 Idx -= SrcNumElts - PaddedMaskNumElts; 3650 MappedOps[i] = Idx; 3651 } 3652 3653 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3654 3655 // If the concatenated vector was padded, extract a subvector with the 3656 // correct number of elements. 3657 if (MaskNumElts != PaddedMaskNumElts) 3658 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3659 DAG.getVectorIdxConstant(0, DL)); 3660 3661 setValue(&I, Result); 3662 return; 3663 } 3664 3665 if (SrcNumElts > MaskNumElts) { 3666 // Analyze the access pattern of the vector to see if we can extract 3667 // two subvectors and do the shuffle. 3668 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3669 bool CanExtract = true; 3670 for (int Idx : Mask) { 3671 unsigned Input = 0; 3672 if (Idx < 0) 3673 continue; 3674 3675 if (Idx >= (int)SrcNumElts) { 3676 Input = 1; 3677 Idx -= SrcNumElts; 3678 } 3679 3680 // If all the indices come from the same MaskNumElts sized portion of 3681 // the sources we can use extract. Also make sure the extract wouldn't 3682 // extract past the end of the source. 3683 int NewStartIdx = alignDown(Idx, MaskNumElts); 3684 if (NewStartIdx + MaskNumElts > SrcNumElts || 3685 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3686 CanExtract = false; 3687 // Make sure we always update StartIdx as we use it to track if all 3688 // elements are undef. 3689 StartIdx[Input] = NewStartIdx; 3690 } 3691 3692 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3693 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3694 return; 3695 } 3696 if (CanExtract) { 3697 // Extract appropriate subvector and generate a vector shuffle 3698 for (unsigned Input = 0; Input < 2; ++Input) { 3699 SDValue &Src = Input == 0 ? Src1 : Src2; 3700 if (StartIdx[Input] < 0) 3701 Src = DAG.getUNDEF(VT); 3702 else { 3703 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3704 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3705 } 3706 } 3707 3708 // Calculate new mask. 3709 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3710 for (int &Idx : MappedOps) { 3711 if (Idx >= (int)SrcNumElts) 3712 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3713 else if (Idx >= 0) 3714 Idx -= StartIdx[0]; 3715 } 3716 3717 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3718 return; 3719 } 3720 } 3721 3722 // We can't use either concat vectors or extract subvectors so fall back to 3723 // replacing the shuffle with extract and build vector. 3724 // to insert and build vector. 3725 EVT EltVT = VT.getVectorElementType(); 3726 SmallVector<SDValue,8> Ops; 3727 for (int Idx : Mask) { 3728 SDValue Res; 3729 3730 if (Idx < 0) { 3731 Res = DAG.getUNDEF(EltVT); 3732 } else { 3733 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3734 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3735 3736 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3737 DAG.getVectorIdxConstant(Idx, DL)); 3738 } 3739 3740 Ops.push_back(Res); 3741 } 3742 3743 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3744 } 3745 3746 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3747 ArrayRef<unsigned> Indices; 3748 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3749 Indices = IV->getIndices(); 3750 else 3751 Indices = cast<ConstantExpr>(&I)->getIndices(); 3752 3753 const Value *Op0 = I.getOperand(0); 3754 const Value *Op1 = I.getOperand(1); 3755 Type *AggTy = I.getType(); 3756 Type *ValTy = Op1->getType(); 3757 bool IntoUndef = isa<UndefValue>(Op0); 3758 bool FromUndef = isa<UndefValue>(Op1); 3759 3760 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3761 3762 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3763 SmallVector<EVT, 4> AggValueVTs; 3764 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3765 SmallVector<EVT, 4> ValValueVTs; 3766 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3767 3768 unsigned NumAggValues = AggValueVTs.size(); 3769 unsigned NumValValues = ValValueVTs.size(); 3770 SmallVector<SDValue, 4> Values(NumAggValues); 3771 3772 // Ignore an insertvalue that produces an empty object 3773 if (!NumAggValues) { 3774 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3775 return; 3776 } 3777 3778 SDValue Agg = getValue(Op0); 3779 unsigned i = 0; 3780 // Copy the beginning value(s) from the original aggregate. 3781 for (; i != LinearIndex; ++i) 3782 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3783 SDValue(Agg.getNode(), Agg.getResNo() + i); 3784 // Copy values from the inserted value(s). 3785 if (NumValValues) { 3786 SDValue Val = getValue(Op1); 3787 for (; i != LinearIndex + NumValValues; ++i) 3788 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3789 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3790 } 3791 // Copy remaining value(s) from the original aggregate. 3792 for (; i != NumAggValues; ++i) 3793 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3794 SDValue(Agg.getNode(), Agg.getResNo() + i); 3795 3796 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3797 DAG.getVTList(AggValueVTs), Values)); 3798 } 3799 3800 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3801 ArrayRef<unsigned> Indices; 3802 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3803 Indices = EV->getIndices(); 3804 else 3805 Indices = cast<ConstantExpr>(&I)->getIndices(); 3806 3807 const Value *Op0 = I.getOperand(0); 3808 Type *AggTy = Op0->getType(); 3809 Type *ValTy = I.getType(); 3810 bool OutOfUndef = isa<UndefValue>(Op0); 3811 3812 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3813 3814 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3815 SmallVector<EVT, 4> ValValueVTs; 3816 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3817 3818 unsigned NumValValues = ValValueVTs.size(); 3819 3820 // Ignore a extractvalue that produces an empty object 3821 if (!NumValValues) { 3822 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3823 return; 3824 } 3825 3826 SmallVector<SDValue, 4> Values(NumValValues); 3827 3828 SDValue Agg = getValue(Op0); 3829 // Copy out the selected value(s). 3830 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3831 Values[i - LinearIndex] = 3832 OutOfUndef ? 3833 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3834 SDValue(Agg.getNode(), Agg.getResNo() + i); 3835 3836 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3837 DAG.getVTList(ValValueVTs), Values)); 3838 } 3839 3840 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3841 Value *Op0 = I.getOperand(0); 3842 // Note that the pointer operand may be a vector of pointers. Take the scalar 3843 // element which holds a pointer. 3844 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3845 SDValue N = getValue(Op0); 3846 SDLoc dl = getCurSDLoc(); 3847 auto &TLI = DAG.getTargetLoweringInfo(); 3848 3849 // Normalize Vector GEP - all scalar operands should be converted to the 3850 // splat vector. 3851 bool IsVectorGEP = I.getType()->isVectorTy(); 3852 ElementCount VectorElementCount = 3853 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3854 : ElementCount::getFixed(0); 3855 3856 if (IsVectorGEP && !N.getValueType().isVector()) { 3857 LLVMContext &Context = *DAG.getContext(); 3858 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3859 if (VectorElementCount.isScalable()) 3860 N = DAG.getSplatVector(VT, dl, N); 3861 else 3862 N = DAG.getSplatBuildVector(VT, dl, N); 3863 } 3864 3865 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3866 GTI != E; ++GTI) { 3867 const Value *Idx = GTI.getOperand(); 3868 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3869 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3870 if (Field) { 3871 // N = N + Offset 3872 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3873 3874 // In an inbounds GEP with an offset that is nonnegative even when 3875 // interpreted as signed, assume there is no unsigned overflow. 3876 SDNodeFlags Flags; 3877 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3878 Flags.setNoUnsignedWrap(true); 3879 3880 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3881 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3882 } 3883 } else { 3884 // IdxSize is the width of the arithmetic according to IR semantics. 3885 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3886 // (and fix up the result later). 3887 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3888 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3889 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3890 // We intentionally mask away the high bits here; ElementSize may not 3891 // fit in IdxTy. 3892 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3893 bool ElementScalable = ElementSize.isScalable(); 3894 3895 // If this is a scalar constant or a splat vector of constants, 3896 // handle it quickly. 3897 const auto *C = dyn_cast<Constant>(Idx); 3898 if (C && isa<VectorType>(C->getType())) 3899 C = C->getSplatValue(); 3900 3901 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3902 if (CI && CI->isZero()) 3903 continue; 3904 if (CI && !ElementScalable) { 3905 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3906 LLVMContext &Context = *DAG.getContext(); 3907 SDValue OffsVal; 3908 if (IsVectorGEP) 3909 OffsVal = DAG.getConstant( 3910 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3911 else 3912 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3913 3914 // In an inbounds GEP with an offset that is nonnegative even when 3915 // interpreted as signed, assume there is no unsigned overflow. 3916 SDNodeFlags Flags; 3917 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3918 Flags.setNoUnsignedWrap(true); 3919 3920 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3921 3922 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3923 continue; 3924 } 3925 3926 // N = N + Idx * ElementMul; 3927 SDValue IdxN = getValue(Idx); 3928 3929 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3930 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3931 VectorElementCount); 3932 if (VectorElementCount.isScalable()) 3933 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3934 else 3935 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3936 } 3937 3938 // If the index is smaller or larger than intptr_t, truncate or extend 3939 // it. 3940 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3941 3942 if (ElementScalable) { 3943 EVT VScaleTy = N.getValueType().getScalarType(); 3944 SDValue VScale = DAG.getNode( 3945 ISD::VSCALE, dl, VScaleTy, 3946 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3947 if (IsVectorGEP) 3948 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3949 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3950 } else { 3951 // If this is a multiply by a power of two, turn it into a shl 3952 // immediately. This is a very common case. 3953 if (ElementMul != 1) { 3954 if (ElementMul.isPowerOf2()) { 3955 unsigned Amt = ElementMul.logBase2(); 3956 IdxN = DAG.getNode(ISD::SHL, dl, 3957 N.getValueType(), IdxN, 3958 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3959 } else { 3960 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3961 IdxN.getValueType()); 3962 IdxN = DAG.getNode(ISD::MUL, dl, 3963 N.getValueType(), IdxN, Scale); 3964 } 3965 } 3966 } 3967 3968 N = DAG.getNode(ISD::ADD, dl, 3969 N.getValueType(), N, IdxN); 3970 } 3971 } 3972 3973 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3974 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3975 if (IsVectorGEP) { 3976 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3977 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3978 } 3979 3980 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3981 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3982 3983 setValue(&I, N); 3984 } 3985 3986 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3987 // If this is a fixed sized alloca in the entry block of the function, 3988 // allocate it statically on the stack. 3989 if (FuncInfo.StaticAllocaMap.count(&I)) 3990 return; // getValue will auto-populate this. 3991 3992 SDLoc dl = getCurSDLoc(); 3993 Type *Ty = I.getAllocatedType(); 3994 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3995 auto &DL = DAG.getDataLayout(); 3996 uint64_t TySize = DL.getTypeAllocSize(Ty); 3997 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3998 3999 SDValue AllocSize = getValue(I.getArraySize()); 4000 4001 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 4002 if (AllocSize.getValueType() != IntPtr) 4003 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4004 4005 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 4006 AllocSize, 4007 DAG.getConstant(TySize, dl, IntPtr)); 4008 4009 // Handle alignment. If the requested alignment is less than or equal to 4010 // the stack alignment, ignore it. If the size is greater than or equal to 4011 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4012 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4013 if (*Alignment <= StackAlign) 4014 Alignment = None; 4015 4016 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4017 // Round the size of the allocation up to the stack alignment size 4018 // by add SA-1 to the size. This doesn't overflow because we're computing 4019 // an address inside an alloca. 4020 SDNodeFlags Flags; 4021 Flags.setNoUnsignedWrap(true); 4022 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4023 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4024 4025 // Mask out the low bits for alignment purposes. 4026 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4027 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4028 4029 SDValue Ops[] = { 4030 getRoot(), AllocSize, 4031 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4032 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4033 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4034 setValue(&I, DSA); 4035 DAG.setRoot(DSA.getValue(1)); 4036 4037 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4038 } 4039 4040 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4041 if (I.isAtomic()) 4042 return visitAtomicLoad(I); 4043 4044 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4045 const Value *SV = I.getOperand(0); 4046 if (TLI.supportSwiftError()) { 4047 // Swifterror values can come from either a function parameter with 4048 // swifterror attribute or an alloca with swifterror attribute. 4049 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4050 if (Arg->hasSwiftErrorAttr()) 4051 return visitLoadFromSwiftError(I); 4052 } 4053 4054 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4055 if (Alloca->isSwiftError()) 4056 return visitLoadFromSwiftError(I); 4057 } 4058 } 4059 4060 SDValue Ptr = getValue(SV); 4061 4062 Type *Ty = I.getType(); 4063 Align Alignment = I.getAlign(); 4064 4065 AAMDNodes AAInfo; 4066 I.getAAMetadata(AAInfo); 4067 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4068 4069 SmallVector<EVT, 4> ValueVTs, MemVTs; 4070 SmallVector<uint64_t, 4> Offsets; 4071 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4072 unsigned NumValues = ValueVTs.size(); 4073 if (NumValues == 0) 4074 return; 4075 4076 bool isVolatile = I.isVolatile(); 4077 4078 SDValue Root; 4079 bool ConstantMemory = false; 4080 if (isVolatile) 4081 // Serialize volatile loads with other side effects. 4082 Root = getRoot(); 4083 else if (NumValues > MaxParallelChains) 4084 Root = getMemoryRoot(); 4085 else if (AA && 4086 AA->pointsToConstantMemory(MemoryLocation( 4087 SV, 4088 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4089 AAInfo))) { 4090 // Do not serialize (non-volatile) loads of constant memory with anything. 4091 Root = DAG.getEntryNode(); 4092 ConstantMemory = true; 4093 } else { 4094 // Do not serialize non-volatile loads against each other. 4095 Root = DAG.getRoot(); 4096 } 4097 4098 SDLoc dl = getCurSDLoc(); 4099 4100 if (isVolatile) 4101 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4102 4103 // An aggregate load cannot wrap around the address space, so offsets to its 4104 // parts don't wrap either. 4105 SDNodeFlags Flags; 4106 Flags.setNoUnsignedWrap(true); 4107 4108 SmallVector<SDValue, 4> Values(NumValues); 4109 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4110 EVT PtrVT = Ptr.getValueType(); 4111 4112 MachineMemOperand::Flags MMOFlags 4113 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4114 4115 unsigned ChainI = 0; 4116 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4117 // Serializing loads here may result in excessive register pressure, and 4118 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4119 // could recover a bit by hoisting nodes upward in the chain by recognizing 4120 // they are side-effect free or do not alias. The optimizer should really 4121 // avoid this case by converting large object/array copies to llvm.memcpy 4122 // (MaxParallelChains should always remain as failsafe). 4123 if (ChainI == MaxParallelChains) { 4124 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4125 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4126 makeArrayRef(Chains.data(), ChainI)); 4127 Root = Chain; 4128 ChainI = 0; 4129 } 4130 SDValue A = DAG.getNode(ISD::ADD, dl, 4131 PtrVT, Ptr, 4132 DAG.getConstant(Offsets[i], dl, PtrVT), 4133 Flags); 4134 4135 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4136 MachinePointerInfo(SV, Offsets[i]), Alignment, 4137 MMOFlags, AAInfo, Ranges); 4138 Chains[ChainI] = L.getValue(1); 4139 4140 if (MemVTs[i] != ValueVTs[i]) 4141 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4142 4143 Values[i] = L; 4144 } 4145 4146 if (!ConstantMemory) { 4147 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4148 makeArrayRef(Chains.data(), ChainI)); 4149 if (isVolatile) 4150 DAG.setRoot(Chain); 4151 else 4152 PendingLoads.push_back(Chain); 4153 } 4154 4155 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4156 DAG.getVTList(ValueVTs), Values)); 4157 } 4158 4159 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4160 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4161 "call visitStoreToSwiftError when backend supports swifterror"); 4162 4163 SmallVector<EVT, 4> ValueVTs; 4164 SmallVector<uint64_t, 4> Offsets; 4165 const Value *SrcV = I.getOperand(0); 4166 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4167 SrcV->getType(), ValueVTs, &Offsets); 4168 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4169 "expect a single EVT for swifterror"); 4170 4171 SDValue Src = getValue(SrcV); 4172 // Create a virtual register, then update the virtual register. 4173 Register VReg = 4174 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4175 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4176 // Chain can be getRoot or getControlRoot. 4177 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4178 SDValue(Src.getNode(), Src.getResNo())); 4179 DAG.setRoot(CopyNode); 4180 } 4181 4182 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4183 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4184 "call visitLoadFromSwiftError when backend supports swifterror"); 4185 4186 assert(!I.isVolatile() && 4187 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4188 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4189 "Support volatile, non temporal, invariant for load_from_swift_error"); 4190 4191 const Value *SV = I.getOperand(0); 4192 Type *Ty = I.getType(); 4193 AAMDNodes AAInfo; 4194 I.getAAMetadata(AAInfo); 4195 assert( 4196 (!AA || 4197 !AA->pointsToConstantMemory(MemoryLocation( 4198 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4199 AAInfo))) && 4200 "load_from_swift_error should not be constant memory"); 4201 4202 SmallVector<EVT, 4> ValueVTs; 4203 SmallVector<uint64_t, 4> Offsets; 4204 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4205 ValueVTs, &Offsets); 4206 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4207 "expect a single EVT for swifterror"); 4208 4209 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4210 SDValue L = DAG.getCopyFromReg( 4211 getRoot(), getCurSDLoc(), 4212 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4213 4214 setValue(&I, L); 4215 } 4216 4217 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4218 if (I.isAtomic()) 4219 return visitAtomicStore(I); 4220 4221 const Value *SrcV = I.getOperand(0); 4222 const Value *PtrV = I.getOperand(1); 4223 4224 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4225 if (TLI.supportSwiftError()) { 4226 // Swifterror values can come from either a function parameter with 4227 // swifterror attribute or an alloca with swifterror attribute. 4228 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4229 if (Arg->hasSwiftErrorAttr()) 4230 return visitStoreToSwiftError(I); 4231 } 4232 4233 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4234 if (Alloca->isSwiftError()) 4235 return visitStoreToSwiftError(I); 4236 } 4237 } 4238 4239 SmallVector<EVT, 4> ValueVTs, MemVTs; 4240 SmallVector<uint64_t, 4> Offsets; 4241 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4242 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4243 unsigned NumValues = ValueVTs.size(); 4244 if (NumValues == 0) 4245 return; 4246 4247 // Get the lowered operands. Note that we do this after 4248 // checking if NumResults is zero, because with zero results 4249 // the operands won't have values in the map. 4250 SDValue Src = getValue(SrcV); 4251 SDValue Ptr = getValue(PtrV); 4252 4253 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4254 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4255 SDLoc dl = getCurSDLoc(); 4256 Align Alignment = I.getAlign(); 4257 AAMDNodes AAInfo; 4258 I.getAAMetadata(AAInfo); 4259 4260 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4261 4262 // An aggregate load cannot wrap around the address space, so offsets to its 4263 // parts don't wrap either. 4264 SDNodeFlags Flags; 4265 Flags.setNoUnsignedWrap(true); 4266 4267 unsigned ChainI = 0; 4268 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4269 // See visitLoad comments. 4270 if (ChainI == MaxParallelChains) { 4271 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4272 makeArrayRef(Chains.data(), ChainI)); 4273 Root = Chain; 4274 ChainI = 0; 4275 } 4276 SDValue Add = 4277 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4278 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4279 if (MemVTs[i] != ValueVTs[i]) 4280 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4281 SDValue St = 4282 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4283 Alignment, MMOFlags, AAInfo); 4284 Chains[ChainI] = St; 4285 } 4286 4287 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4288 makeArrayRef(Chains.data(), ChainI)); 4289 DAG.setRoot(StoreNode); 4290 } 4291 4292 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4293 bool IsCompressing) { 4294 SDLoc sdl = getCurSDLoc(); 4295 4296 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4297 MaybeAlign &Alignment) { 4298 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4299 Src0 = I.getArgOperand(0); 4300 Ptr = I.getArgOperand(1); 4301 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4302 Mask = I.getArgOperand(3); 4303 }; 4304 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4305 MaybeAlign &Alignment) { 4306 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4307 Src0 = I.getArgOperand(0); 4308 Ptr = I.getArgOperand(1); 4309 Mask = I.getArgOperand(2); 4310 Alignment = None; 4311 }; 4312 4313 Value *PtrOperand, *MaskOperand, *Src0Operand; 4314 MaybeAlign Alignment; 4315 if (IsCompressing) 4316 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4317 else 4318 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4319 4320 SDValue Ptr = getValue(PtrOperand); 4321 SDValue Src0 = getValue(Src0Operand); 4322 SDValue Mask = getValue(MaskOperand); 4323 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4324 4325 EVT VT = Src0.getValueType(); 4326 if (!Alignment) 4327 Alignment = DAG.getEVTAlign(VT); 4328 4329 AAMDNodes AAInfo; 4330 I.getAAMetadata(AAInfo); 4331 4332 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4333 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4334 // TODO: Make MachineMemOperands aware of scalable 4335 // vectors. 4336 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4337 SDValue StoreNode = 4338 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4339 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4340 DAG.setRoot(StoreNode); 4341 setValue(&I, StoreNode); 4342 } 4343 4344 // Get a uniform base for the Gather/Scatter intrinsic. 4345 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4346 // We try to represent it as a base pointer + vector of indices. 4347 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4348 // The first operand of the GEP may be a single pointer or a vector of pointers 4349 // Example: 4350 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4351 // or 4352 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4353 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4354 // 4355 // When the first GEP operand is a single pointer - it is the uniform base we 4356 // are looking for. If first operand of the GEP is a splat vector - we 4357 // extract the splat value and use it as a uniform base. 4358 // In all other cases the function returns 'false'. 4359 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4360 ISD::MemIndexType &IndexType, SDValue &Scale, 4361 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4362 SelectionDAG& DAG = SDB->DAG; 4363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4364 const DataLayout &DL = DAG.getDataLayout(); 4365 4366 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4367 4368 // Handle splat constant pointer. 4369 if (auto *C = dyn_cast<Constant>(Ptr)) { 4370 C = C->getSplatValue(); 4371 if (!C) 4372 return false; 4373 4374 Base = SDB->getValue(C); 4375 4376 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4377 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4378 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4379 IndexType = ISD::SIGNED_SCALED; 4380 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4381 return true; 4382 } 4383 4384 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4385 if (!GEP || GEP->getParent() != CurBB) 4386 return false; 4387 4388 if (GEP->getNumOperands() != 2) 4389 return false; 4390 4391 const Value *BasePtr = GEP->getPointerOperand(); 4392 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4393 4394 // Make sure the base is scalar and the index is a vector. 4395 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4396 return false; 4397 4398 Base = SDB->getValue(BasePtr); 4399 Index = SDB->getValue(IndexVal); 4400 IndexType = ISD::SIGNED_SCALED; 4401 Scale = DAG.getTargetConstant( 4402 DL.getTypeAllocSize(GEP->getResultElementType()), 4403 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4404 return true; 4405 } 4406 4407 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4408 SDLoc sdl = getCurSDLoc(); 4409 4410 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4411 const Value *Ptr = I.getArgOperand(1); 4412 SDValue Src0 = getValue(I.getArgOperand(0)); 4413 SDValue Mask = getValue(I.getArgOperand(3)); 4414 EVT VT = Src0.getValueType(); 4415 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4416 ->getMaybeAlignValue() 4417 .getValueOr(DAG.getEVTAlign(VT.getScalarType())); 4418 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4419 4420 AAMDNodes AAInfo; 4421 I.getAAMetadata(AAInfo); 4422 4423 SDValue Base; 4424 SDValue Index; 4425 ISD::MemIndexType IndexType; 4426 SDValue Scale; 4427 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4428 I.getParent()); 4429 4430 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4431 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4432 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4433 // TODO: Make MachineMemOperands aware of scalable 4434 // vectors. 4435 MemoryLocation::UnknownSize, Alignment, AAInfo); 4436 if (!UniformBase) { 4437 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4438 Index = getValue(Ptr); 4439 IndexType = ISD::SIGNED_UNSCALED; 4440 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4441 } 4442 4443 EVT IdxVT = Index.getValueType(); 4444 EVT EltTy = IdxVT.getVectorElementType(); 4445 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4446 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4447 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4448 } 4449 4450 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4451 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4452 Ops, MMO, IndexType, false); 4453 DAG.setRoot(Scatter); 4454 setValue(&I, Scatter); 4455 } 4456 4457 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4458 SDLoc sdl = getCurSDLoc(); 4459 4460 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4461 MaybeAlign &Alignment) { 4462 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4463 Ptr = I.getArgOperand(0); 4464 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4465 Mask = I.getArgOperand(2); 4466 Src0 = I.getArgOperand(3); 4467 }; 4468 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4469 MaybeAlign &Alignment) { 4470 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4471 Ptr = I.getArgOperand(0); 4472 Alignment = None; 4473 Mask = I.getArgOperand(1); 4474 Src0 = I.getArgOperand(2); 4475 }; 4476 4477 Value *PtrOperand, *MaskOperand, *Src0Operand; 4478 MaybeAlign Alignment; 4479 if (IsExpanding) 4480 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4481 else 4482 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4483 4484 SDValue Ptr = getValue(PtrOperand); 4485 SDValue Src0 = getValue(Src0Operand); 4486 SDValue Mask = getValue(MaskOperand); 4487 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4488 4489 EVT VT = Src0.getValueType(); 4490 if (!Alignment) 4491 Alignment = DAG.getEVTAlign(VT); 4492 4493 AAMDNodes AAInfo; 4494 I.getAAMetadata(AAInfo); 4495 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4496 4497 // Do not serialize masked loads of constant memory with anything. 4498 MemoryLocation ML; 4499 if (VT.isScalableVector()) 4500 ML = MemoryLocation::getAfter(PtrOperand); 4501 else 4502 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4503 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4504 AAInfo); 4505 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4506 4507 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4508 4509 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4510 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4511 // TODO: Make MachineMemOperands aware of scalable 4512 // vectors. 4513 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4514 4515 SDValue Load = 4516 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4517 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4518 if (AddToChain) 4519 PendingLoads.push_back(Load.getValue(1)); 4520 setValue(&I, Load); 4521 } 4522 4523 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4524 SDLoc sdl = getCurSDLoc(); 4525 4526 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4527 const Value *Ptr = I.getArgOperand(0); 4528 SDValue Src0 = getValue(I.getArgOperand(3)); 4529 SDValue Mask = getValue(I.getArgOperand(2)); 4530 4531 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4532 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4533 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4534 ->getMaybeAlignValue() 4535 .getValueOr(DAG.getEVTAlign(VT.getScalarType())); 4536 4537 AAMDNodes AAInfo; 4538 I.getAAMetadata(AAInfo); 4539 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4540 4541 SDValue Root = DAG.getRoot(); 4542 SDValue Base; 4543 SDValue Index; 4544 ISD::MemIndexType IndexType; 4545 SDValue Scale; 4546 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4547 I.getParent()); 4548 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4549 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4550 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4551 // TODO: Make MachineMemOperands aware of scalable 4552 // vectors. 4553 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4554 4555 if (!UniformBase) { 4556 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4557 Index = getValue(Ptr); 4558 IndexType = ISD::SIGNED_UNSCALED; 4559 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4560 } 4561 4562 EVT IdxVT = Index.getValueType(); 4563 EVT EltTy = IdxVT.getVectorElementType(); 4564 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4565 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4566 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4567 } 4568 4569 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4570 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4571 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4572 4573 PendingLoads.push_back(Gather.getValue(1)); 4574 setValue(&I, Gather); 4575 } 4576 4577 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4578 SDLoc dl = getCurSDLoc(); 4579 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4580 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4581 SyncScope::ID SSID = I.getSyncScopeID(); 4582 4583 SDValue InChain = getRoot(); 4584 4585 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4586 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4587 4588 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4589 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4590 4591 MachineFunction &MF = DAG.getMachineFunction(); 4592 MachineMemOperand *MMO = MF.getMachineMemOperand( 4593 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4594 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4595 FailureOrdering); 4596 4597 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4598 dl, MemVT, VTs, InChain, 4599 getValue(I.getPointerOperand()), 4600 getValue(I.getCompareOperand()), 4601 getValue(I.getNewValOperand()), MMO); 4602 4603 SDValue OutChain = L.getValue(2); 4604 4605 setValue(&I, L); 4606 DAG.setRoot(OutChain); 4607 } 4608 4609 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4610 SDLoc dl = getCurSDLoc(); 4611 ISD::NodeType NT; 4612 switch (I.getOperation()) { 4613 default: llvm_unreachable("Unknown atomicrmw operation"); 4614 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4615 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4616 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4617 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4618 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4619 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4620 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4621 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4622 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4623 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4624 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4625 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4626 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4627 } 4628 AtomicOrdering Ordering = I.getOrdering(); 4629 SyncScope::ID SSID = I.getSyncScopeID(); 4630 4631 SDValue InChain = getRoot(); 4632 4633 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4634 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4635 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4636 4637 MachineFunction &MF = DAG.getMachineFunction(); 4638 MachineMemOperand *MMO = MF.getMachineMemOperand( 4639 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4640 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4641 4642 SDValue L = 4643 DAG.getAtomic(NT, dl, MemVT, InChain, 4644 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4645 MMO); 4646 4647 SDValue OutChain = L.getValue(1); 4648 4649 setValue(&I, L); 4650 DAG.setRoot(OutChain); 4651 } 4652 4653 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4654 SDLoc dl = getCurSDLoc(); 4655 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4656 SDValue Ops[3]; 4657 Ops[0] = getRoot(); 4658 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4659 TLI.getFenceOperandTy(DAG.getDataLayout())); 4660 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4661 TLI.getFenceOperandTy(DAG.getDataLayout())); 4662 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4663 } 4664 4665 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4666 SDLoc dl = getCurSDLoc(); 4667 AtomicOrdering Order = I.getOrdering(); 4668 SyncScope::ID SSID = I.getSyncScopeID(); 4669 4670 SDValue InChain = getRoot(); 4671 4672 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4673 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4674 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4675 4676 if (!TLI.supportsUnalignedAtomics() && 4677 I.getAlignment() < MemVT.getSizeInBits() / 8) 4678 report_fatal_error("Cannot generate unaligned atomic load"); 4679 4680 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4681 4682 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4683 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4684 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4685 4686 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4687 4688 SDValue Ptr = getValue(I.getPointerOperand()); 4689 4690 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4691 // TODO: Once this is better exercised by tests, it should be merged with 4692 // the normal path for loads to prevent future divergence. 4693 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4694 if (MemVT != VT) 4695 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4696 4697 setValue(&I, L); 4698 SDValue OutChain = L.getValue(1); 4699 if (!I.isUnordered()) 4700 DAG.setRoot(OutChain); 4701 else 4702 PendingLoads.push_back(OutChain); 4703 return; 4704 } 4705 4706 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4707 Ptr, MMO); 4708 4709 SDValue OutChain = L.getValue(1); 4710 if (MemVT != VT) 4711 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4712 4713 setValue(&I, L); 4714 DAG.setRoot(OutChain); 4715 } 4716 4717 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4718 SDLoc dl = getCurSDLoc(); 4719 4720 AtomicOrdering Ordering = I.getOrdering(); 4721 SyncScope::ID SSID = I.getSyncScopeID(); 4722 4723 SDValue InChain = getRoot(); 4724 4725 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4726 EVT MemVT = 4727 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4728 4729 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4730 report_fatal_error("Cannot generate unaligned atomic store"); 4731 4732 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4733 4734 MachineFunction &MF = DAG.getMachineFunction(); 4735 MachineMemOperand *MMO = MF.getMachineMemOperand( 4736 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4737 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4738 4739 SDValue Val = getValue(I.getValueOperand()); 4740 if (Val.getValueType() != MemVT) 4741 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4742 SDValue Ptr = getValue(I.getPointerOperand()); 4743 4744 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4745 // TODO: Once this is better exercised by tests, it should be merged with 4746 // the normal path for stores to prevent future divergence. 4747 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4748 DAG.setRoot(S); 4749 return; 4750 } 4751 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4752 Ptr, Val, MMO); 4753 4754 4755 DAG.setRoot(OutChain); 4756 } 4757 4758 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4759 /// node. 4760 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4761 unsigned Intrinsic) { 4762 // Ignore the callsite's attributes. A specific call site may be marked with 4763 // readnone, but the lowering code will expect the chain based on the 4764 // definition. 4765 const Function *F = I.getCalledFunction(); 4766 bool HasChain = !F->doesNotAccessMemory(); 4767 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4768 4769 // Build the operand list. 4770 SmallVector<SDValue, 8> Ops; 4771 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4772 if (OnlyLoad) { 4773 // We don't need to serialize loads against other loads. 4774 Ops.push_back(DAG.getRoot()); 4775 } else { 4776 Ops.push_back(getRoot()); 4777 } 4778 } 4779 4780 // Info is set by getTgtMemInstrinsic 4781 TargetLowering::IntrinsicInfo Info; 4782 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4783 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4784 DAG.getMachineFunction(), 4785 Intrinsic); 4786 4787 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4788 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4789 Info.opc == ISD::INTRINSIC_W_CHAIN) 4790 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4791 TLI.getPointerTy(DAG.getDataLayout()))); 4792 4793 // Add all operands of the call to the operand list. 4794 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4795 const Value *Arg = I.getArgOperand(i); 4796 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4797 Ops.push_back(getValue(Arg)); 4798 continue; 4799 } 4800 4801 // Use TargetConstant instead of a regular constant for immarg. 4802 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4803 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4804 assert(CI->getBitWidth() <= 64 && 4805 "large intrinsic immediates not handled"); 4806 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4807 } else { 4808 Ops.push_back( 4809 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4810 } 4811 } 4812 4813 SmallVector<EVT, 4> ValueVTs; 4814 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4815 4816 if (HasChain) 4817 ValueVTs.push_back(MVT::Other); 4818 4819 SDVTList VTs = DAG.getVTList(ValueVTs); 4820 4821 // Propagate fast-math-flags from IR to node(s). 4822 SDNodeFlags Flags; 4823 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4824 Flags.copyFMF(*FPMO); 4825 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4826 4827 // Create the node. 4828 SDValue Result; 4829 if (IsTgtIntrinsic) { 4830 // This is target intrinsic that touches memory 4831 AAMDNodes AAInfo; 4832 I.getAAMetadata(AAInfo); 4833 Result = 4834 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4835 MachinePointerInfo(Info.ptrVal, Info.offset), 4836 Info.align, Info.flags, Info.size, AAInfo); 4837 } else if (!HasChain) { 4838 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4839 } else if (!I.getType()->isVoidTy()) { 4840 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4841 } else { 4842 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4843 } 4844 4845 if (HasChain) { 4846 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4847 if (OnlyLoad) 4848 PendingLoads.push_back(Chain); 4849 else 4850 DAG.setRoot(Chain); 4851 } 4852 4853 if (!I.getType()->isVoidTy()) { 4854 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4855 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4856 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4857 } else 4858 Result = lowerRangeToAssertZExt(DAG, I, Result); 4859 4860 MaybeAlign Alignment = I.getRetAlign(); 4861 if (!Alignment) 4862 Alignment = F->getAttributes().getRetAlignment(); 4863 // Insert `assertalign` node if there's an alignment. 4864 if (InsertAssertAlign && Alignment) { 4865 Result = 4866 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4867 } 4868 4869 setValue(&I, Result); 4870 } 4871 } 4872 4873 /// GetSignificand - Get the significand and build it into a floating-point 4874 /// number with exponent of 1: 4875 /// 4876 /// Op = (Op & 0x007fffff) | 0x3f800000; 4877 /// 4878 /// where Op is the hexadecimal representation of floating point value. 4879 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4880 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4881 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4882 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4883 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4884 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4885 } 4886 4887 /// GetExponent - Get the exponent: 4888 /// 4889 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4890 /// 4891 /// where Op is the hexadecimal representation of floating point value. 4892 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4893 const TargetLowering &TLI, const SDLoc &dl) { 4894 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4895 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4896 SDValue t1 = DAG.getNode( 4897 ISD::SRL, dl, MVT::i32, t0, 4898 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4899 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4900 DAG.getConstant(127, dl, MVT::i32)); 4901 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4902 } 4903 4904 /// getF32Constant - Get 32-bit floating point constant. 4905 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4906 const SDLoc &dl) { 4907 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4908 MVT::f32); 4909 } 4910 4911 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4912 SelectionDAG &DAG) { 4913 // TODO: What fast-math-flags should be set on the floating-point nodes? 4914 4915 // IntegerPartOfX = ((int32_t)(t0); 4916 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4917 4918 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4919 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4920 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4921 4922 // IntegerPartOfX <<= 23; 4923 IntegerPartOfX = DAG.getNode( 4924 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4925 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4926 DAG.getDataLayout()))); 4927 4928 SDValue TwoToFractionalPartOfX; 4929 if (LimitFloatPrecision <= 6) { 4930 // For floating-point precision of 6: 4931 // 4932 // TwoToFractionalPartOfX = 4933 // 0.997535578f + 4934 // (0.735607626f + 0.252464424f * x) * x; 4935 // 4936 // error 0.0144103317, which is 6 bits 4937 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4938 getF32Constant(DAG, 0x3e814304, dl)); 4939 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4940 getF32Constant(DAG, 0x3f3c50c8, dl)); 4941 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4942 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4943 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4944 } else if (LimitFloatPrecision <= 12) { 4945 // For floating-point precision of 12: 4946 // 4947 // TwoToFractionalPartOfX = 4948 // 0.999892986f + 4949 // (0.696457318f + 4950 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4951 // 4952 // error 0.000107046256, which is 13 to 14 bits 4953 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4954 getF32Constant(DAG, 0x3da235e3, dl)); 4955 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4956 getF32Constant(DAG, 0x3e65b8f3, dl)); 4957 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4958 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4959 getF32Constant(DAG, 0x3f324b07, dl)); 4960 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4961 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4962 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4963 } else { // LimitFloatPrecision <= 18 4964 // For floating-point precision of 18: 4965 // 4966 // TwoToFractionalPartOfX = 4967 // 0.999999982f + 4968 // (0.693148872f + 4969 // (0.240227044f + 4970 // (0.554906021e-1f + 4971 // (0.961591928e-2f + 4972 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4973 // error 2.47208000*10^(-7), which is better than 18 bits 4974 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4975 getF32Constant(DAG, 0x3924b03e, dl)); 4976 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4977 getF32Constant(DAG, 0x3ab24b87, dl)); 4978 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4979 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4980 getF32Constant(DAG, 0x3c1d8c17, dl)); 4981 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4982 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4983 getF32Constant(DAG, 0x3d634a1d, dl)); 4984 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4985 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4986 getF32Constant(DAG, 0x3e75fe14, dl)); 4987 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4988 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4989 getF32Constant(DAG, 0x3f317234, dl)); 4990 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4991 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4992 getF32Constant(DAG, 0x3f800000, dl)); 4993 } 4994 4995 // Add the exponent into the result in integer domain. 4996 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4997 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4998 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4999 } 5000 5001 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5002 /// limited-precision mode. 5003 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5004 const TargetLowering &TLI, SDNodeFlags Flags) { 5005 if (Op.getValueType() == MVT::f32 && 5006 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5007 5008 // Put the exponent in the right bit position for later addition to the 5009 // final result: 5010 // 5011 // t0 = Op * log2(e) 5012 5013 // TODO: What fast-math-flags should be set here? 5014 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5015 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5016 return getLimitedPrecisionExp2(t0, dl, DAG); 5017 } 5018 5019 // No special expansion. 5020 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5021 } 5022 5023 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5024 /// limited-precision mode. 5025 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5026 const TargetLowering &TLI, SDNodeFlags Flags) { 5027 // TODO: What fast-math-flags should be set on the floating-point nodes? 5028 5029 if (Op.getValueType() == MVT::f32 && 5030 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5031 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5032 5033 // Scale the exponent by log(2). 5034 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5035 SDValue LogOfExponent = 5036 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5037 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5038 5039 // Get the significand and build it into a floating-point number with 5040 // exponent of 1. 5041 SDValue X = GetSignificand(DAG, Op1, dl); 5042 5043 SDValue LogOfMantissa; 5044 if (LimitFloatPrecision <= 6) { 5045 // For floating-point precision of 6: 5046 // 5047 // LogofMantissa = 5048 // -1.1609546f + 5049 // (1.4034025f - 0.23903021f * x) * x; 5050 // 5051 // error 0.0034276066, which is better than 8 bits 5052 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5053 getF32Constant(DAG, 0xbe74c456, dl)); 5054 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5055 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5056 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5057 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5058 getF32Constant(DAG, 0x3f949a29, dl)); 5059 } else if (LimitFloatPrecision <= 12) { 5060 // For floating-point precision of 12: 5061 // 5062 // LogOfMantissa = 5063 // -1.7417939f + 5064 // (2.8212026f + 5065 // (-1.4699568f + 5066 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5067 // 5068 // error 0.000061011436, which is 14 bits 5069 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5070 getF32Constant(DAG, 0xbd67b6d6, dl)); 5071 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5072 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5073 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5074 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5075 getF32Constant(DAG, 0x3fbc278b, dl)); 5076 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5077 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5078 getF32Constant(DAG, 0x40348e95, dl)); 5079 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5080 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5081 getF32Constant(DAG, 0x3fdef31a, dl)); 5082 } else { // LimitFloatPrecision <= 18 5083 // For floating-point precision of 18: 5084 // 5085 // LogOfMantissa = 5086 // -2.1072184f + 5087 // (4.2372794f + 5088 // (-3.7029485f + 5089 // (2.2781945f + 5090 // (-0.87823314f + 5091 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5092 // 5093 // error 0.0000023660568, which is better than 18 bits 5094 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5095 getF32Constant(DAG, 0xbc91e5ac, dl)); 5096 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5097 getF32Constant(DAG, 0x3e4350aa, dl)); 5098 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5099 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5100 getF32Constant(DAG, 0x3f60d3e3, dl)); 5101 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5102 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5103 getF32Constant(DAG, 0x4011cdf0, dl)); 5104 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5105 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5106 getF32Constant(DAG, 0x406cfd1c, dl)); 5107 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5108 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5109 getF32Constant(DAG, 0x408797cb, dl)); 5110 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5111 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5112 getF32Constant(DAG, 0x4006dcab, dl)); 5113 } 5114 5115 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5116 } 5117 5118 // No special expansion. 5119 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5120 } 5121 5122 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5123 /// limited-precision mode. 5124 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5125 const TargetLowering &TLI, SDNodeFlags Flags) { 5126 // TODO: What fast-math-flags should be set on the floating-point nodes? 5127 5128 if (Op.getValueType() == MVT::f32 && 5129 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5130 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5131 5132 // Get the exponent. 5133 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5134 5135 // Get the significand and build it into a floating-point number with 5136 // exponent of 1. 5137 SDValue X = GetSignificand(DAG, Op1, dl); 5138 5139 // Different possible minimax approximations of significand in 5140 // floating-point for various degrees of accuracy over [1,2]. 5141 SDValue Log2ofMantissa; 5142 if (LimitFloatPrecision <= 6) { 5143 // For floating-point precision of 6: 5144 // 5145 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5146 // 5147 // error 0.0049451742, which is more than 7 bits 5148 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5149 getF32Constant(DAG, 0xbeb08fe0, dl)); 5150 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5151 getF32Constant(DAG, 0x40019463, dl)); 5152 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5153 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5154 getF32Constant(DAG, 0x3fd6633d, dl)); 5155 } else if (LimitFloatPrecision <= 12) { 5156 // For floating-point precision of 12: 5157 // 5158 // Log2ofMantissa = 5159 // -2.51285454f + 5160 // (4.07009056f + 5161 // (-2.12067489f + 5162 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5163 // 5164 // error 0.0000876136000, which is better than 13 bits 5165 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5166 getF32Constant(DAG, 0xbda7262e, dl)); 5167 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5168 getF32Constant(DAG, 0x3f25280b, dl)); 5169 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5170 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5171 getF32Constant(DAG, 0x4007b923, dl)); 5172 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5173 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5174 getF32Constant(DAG, 0x40823e2f, dl)); 5175 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5176 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5177 getF32Constant(DAG, 0x4020d29c, dl)); 5178 } else { // LimitFloatPrecision <= 18 5179 // For floating-point precision of 18: 5180 // 5181 // Log2ofMantissa = 5182 // -3.0400495f + 5183 // (6.1129976f + 5184 // (-5.3420409f + 5185 // (3.2865683f + 5186 // (-1.2669343f + 5187 // (0.27515199f - 5188 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5189 // 5190 // error 0.0000018516, which is better than 18 bits 5191 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5192 getF32Constant(DAG, 0xbcd2769e, dl)); 5193 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5194 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5195 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5196 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5197 getF32Constant(DAG, 0x3fa22ae7, dl)); 5198 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5199 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5200 getF32Constant(DAG, 0x40525723, dl)); 5201 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5202 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5203 getF32Constant(DAG, 0x40aaf200, dl)); 5204 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5205 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5206 getF32Constant(DAG, 0x40c39dad, dl)); 5207 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5208 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5209 getF32Constant(DAG, 0x4042902c, dl)); 5210 } 5211 5212 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5213 } 5214 5215 // No special expansion. 5216 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5217 } 5218 5219 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5220 /// limited-precision mode. 5221 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5222 const TargetLowering &TLI, SDNodeFlags Flags) { 5223 // TODO: What fast-math-flags should be set on the floating-point nodes? 5224 5225 if (Op.getValueType() == MVT::f32 && 5226 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5227 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5228 5229 // Scale the exponent by log10(2) [0.30102999f]. 5230 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5231 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5232 getF32Constant(DAG, 0x3e9a209a, dl)); 5233 5234 // Get the significand and build it into a floating-point number with 5235 // exponent of 1. 5236 SDValue X = GetSignificand(DAG, Op1, dl); 5237 5238 SDValue Log10ofMantissa; 5239 if (LimitFloatPrecision <= 6) { 5240 // For floating-point precision of 6: 5241 // 5242 // Log10ofMantissa = 5243 // -0.50419619f + 5244 // (0.60948995f - 0.10380950f * x) * x; 5245 // 5246 // error 0.0014886165, which is 6 bits 5247 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5248 getF32Constant(DAG, 0xbdd49a13, dl)); 5249 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5250 getF32Constant(DAG, 0x3f1c0789, dl)); 5251 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5252 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5253 getF32Constant(DAG, 0x3f011300, dl)); 5254 } else if (LimitFloatPrecision <= 12) { 5255 // For floating-point precision of 12: 5256 // 5257 // Log10ofMantissa = 5258 // -0.64831180f + 5259 // (0.91751397f + 5260 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5261 // 5262 // error 0.00019228036, which is better than 12 bits 5263 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5264 getF32Constant(DAG, 0x3d431f31, dl)); 5265 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5266 getF32Constant(DAG, 0x3ea21fb2, dl)); 5267 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5268 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5269 getF32Constant(DAG, 0x3f6ae232, dl)); 5270 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5271 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5272 getF32Constant(DAG, 0x3f25f7c3, dl)); 5273 } else { // LimitFloatPrecision <= 18 5274 // For floating-point precision of 18: 5275 // 5276 // Log10ofMantissa = 5277 // -0.84299375f + 5278 // (1.5327582f + 5279 // (-1.0688956f + 5280 // (0.49102474f + 5281 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5282 // 5283 // error 0.0000037995730, which is better than 18 bits 5284 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5285 getF32Constant(DAG, 0x3c5d51ce, dl)); 5286 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5287 getF32Constant(DAG, 0x3e00685a, dl)); 5288 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5289 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5290 getF32Constant(DAG, 0x3efb6798, dl)); 5291 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5292 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5293 getF32Constant(DAG, 0x3f88d192, dl)); 5294 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5295 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5296 getF32Constant(DAG, 0x3fc4316c, dl)); 5297 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5298 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5299 getF32Constant(DAG, 0x3f57ce70, dl)); 5300 } 5301 5302 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5303 } 5304 5305 // No special expansion. 5306 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5307 } 5308 5309 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5310 /// limited-precision mode. 5311 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5312 const TargetLowering &TLI, SDNodeFlags Flags) { 5313 if (Op.getValueType() == MVT::f32 && 5314 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5315 return getLimitedPrecisionExp2(Op, dl, DAG); 5316 5317 // No special expansion. 5318 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5319 } 5320 5321 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5322 /// limited-precision mode with x == 10.0f. 5323 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5324 SelectionDAG &DAG, const TargetLowering &TLI, 5325 SDNodeFlags Flags) { 5326 bool IsExp10 = false; 5327 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5328 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5329 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5330 APFloat Ten(10.0f); 5331 IsExp10 = LHSC->isExactlyValue(Ten); 5332 } 5333 } 5334 5335 // TODO: What fast-math-flags should be set on the FMUL node? 5336 if (IsExp10) { 5337 // Put the exponent in the right bit position for later addition to the 5338 // final result: 5339 // 5340 // #define LOG2OF10 3.3219281f 5341 // t0 = Op * LOG2OF10; 5342 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5343 getF32Constant(DAG, 0x40549a78, dl)); 5344 return getLimitedPrecisionExp2(t0, dl, DAG); 5345 } 5346 5347 // No special expansion. 5348 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5349 } 5350 5351 /// ExpandPowI - Expand a llvm.powi intrinsic. 5352 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5353 SelectionDAG &DAG) { 5354 // If RHS is a constant, we can expand this out to a multiplication tree, 5355 // otherwise we end up lowering to a call to __powidf2 (for example). When 5356 // optimizing for size, we only want to do this if the expansion would produce 5357 // a small number of multiplies, otherwise we do the full expansion. 5358 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5359 // Get the exponent as a positive value. 5360 unsigned Val = RHSC->getSExtValue(); 5361 if ((int)Val < 0) Val = -Val; 5362 5363 // powi(x, 0) -> 1.0 5364 if (Val == 0) 5365 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5366 5367 bool OptForSize = DAG.shouldOptForSize(); 5368 if (!OptForSize || 5369 // If optimizing for size, don't insert too many multiplies. 5370 // This inserts up to 5 multiplies. 5371 countPopulation(Val) + Log2_32(Val) < 7) { 5372 // We use the simple binary decomposition method to generate the multiply 5373 // sequence. There are more optimal ways to do this (for example, 5374 // powi(x,15) generates one more multiply than it should), but this has 5375 // the benefit of being both really simple and much better than a libcall. 5376 SDValue Res; // Logically starts equal to 1.0 5377 SDValue CurSquare = LHS; 5378 // TODO: Intrinsics should have fast-math-flags that propagate to these 5379 // nodes. 5380 while (Val) { 5381 if (Val & 1) { 5382 if (Res.getNode()) 5383 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5384 else 5385 Res = CurSquare; // 1.0*CurSquare. 5386 } 5387 5388 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5389 CurSquare, CurSquare); 5390 Val >>= 1; 5391 } 5392 5393 // If the original was negative, invert the result, producing 1/(x*x*x). 5394 if (RHSC->getSExtValue() < 0) 5395 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5396 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5397 return Res; 5398 } 5399 } 5400 5401 // Otherwise, expand to a libcall. 5402 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5403 } 5404 5405 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5406 SDValue LHS, SDValue RHS, SDValue Scale, 5407 SelectionDAG &DAG, const TargetLowering &TLI) { 5408 EVT VT = LHS.getValueType(); 5409 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5410 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5411 LLVMContext &Ctx = *DAG.getContext(); 5412 5413 // If the type is legal but the operation isn't, this node might survive all 5414 // the way to operation legalization. If we end up there and we do not have 5415 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5416 // node. 5417 5418 // Coax the legalizer into expanding the node during type legalization instead 5419 // by bumping the size by one bit. This will force it to Promote, enabling the 5420 // early expansion and avoiding the need to expand later. 5421 5422 // We don't have to do this if Scale is 0; that can always be expanded, unless 5423 // it's a saturating signed operation. Those can experience true integer 5424 // division overflow, a case which we must avoid. 5425 5426 // FIXME: We wouldn't have to do this (or any of the early 5427 // expansion/promotion) if it was possible to expand a libcall of an 5428 // illegal type during operation legalization. But it's not, so things 5429 // get a bit hacky. 5430 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5431 if ((ScaleInt > 0 || (Saturating && Signed)) && 5432 (TLI.isTypeLegal(VT) || 5433 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5434 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5435 Opcode, VT, ScaleInt); 5436 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5437 EVT PromVT; 5438 if (VT.isScalarInteger()) 5439 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5440 else if (VT.isVector()) { 5441 PromVT = VT.getVectorElementType(); 5442 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5443 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5444 } else 5445 llvm_unreachable("Wrong VT for DIVFIX?"); 5446 if (Signed) { 5447 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5448 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5449 } else { 5450 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5451 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5452 } 5453 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5454 // For saturating operations, we need to shift up the LHS to get the 5455 // proper saturation width, and then shift down again afterwards. 5456 if (Saturating) 5457 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5458 DAG.getConstant(1, DL, ShiftTy)); 5459 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5460 if (Saturating) 5461 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5462 DAG.getConstant(1, DL, ShiftTy)); 5463 return DAG.getZExtOrTrunc(Res, DL, VT); 5464 } 5465 } 5466 5467 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5468 } 5469 5470 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5471 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5472 static void 5473 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5474 const SDValue &N) { 5475 switch (N.getOpcode()) { 5476 case ISD::CopyFromReg: { 5477 SDValue Op = N.getOperand(1); 5478 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5479 Op.getValueType().getSizeInBits()); 5480 return; 5481 } 5482 case ISD::BITCAST: 5483 case ISD::AssertZext: 5484 case ISD::AssertSext: 5485 case ISD::TRUNCATE: 5486 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5487 return; 5488 case ISD::BUILD_PAIR: 5489 case ISD::BUILD_VECTOR: 5490 case ISD::CONCAT_VECTORS: 5491 for (SDValue Op : N->op_values()) 5492 getUnderlyingArgRegs(Regs, Op); 5493 return; 5494 default: 5495 return; 5496 } 5497 } 5498 5499 /// If the DbgValueInst is a dbg_value of a function argument, create the 5500 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5501 /// instruction selection, they will be inserted to the entry BB. 5502 /// We don't currently support this for variadic dbg_values, as they shouldn't 5503 /// appear for function arguments or in the prologue. 5504 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5505 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5506 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5507 const Argument *Arg = dyn_cast<Argument>(V); 5508 if (!Arg) 5509 return false; 5510 5511 MachineFunction &MF = DAG.getMachineFunction(); 5512 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5513 5514 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5515 // we've been asked to pursue. 5516 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5517 bool Indirect) { 5518 if (Reg.isVirtual() && TM.Options.ValueTrackingVariableLocations) { 5519 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5520 // pointing at the VReg, which will be patched up later. 5521 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5522 auto MIB = BuildMI(MF, DL, Inst); 5523 MIB.addReg(Reg, RegState::Debug); 5524 MIB.addImm(0); 5525 MIB.addMetadata(Variable); 5526 auto *NewDIExpr = FragExpr; 5527 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5528 // the DIExpression. 5529 if (Indirect) 5530 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5531 MIB.addMetadata(NewDIExpr); 5532 return MIB; 5533 } else { 5534 // Create a completely standard DBG_VALUE. 5535 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5536 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5537 } 5538 }; 5539 5540 if (!IsDbgDeclare) { 5541 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5542 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5543 // the entry block. 5544 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5545 if (!IsInEntryBlock) 5546 return false; 5547 5548 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5549 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5550 // variable that also is a param. 5551 // 5552 // Although, if we are at the top of the entry block already, we can still 5553 // emit using ArgDbgValue. This might catch some situations when the 5554 // dbg.value refers to an argument that isn't used in the entry block, so 5555 // any CopyToReg node would be optimized out and the only way to express 5556 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5557 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5558 // we should only emit as ArgDbgValue if the Variable is an argument to the 5559 // current function, and the dbg.value intrinsic is found in the entry 5560 // block. 5561 bool VariableIsFunctionInputArg = Variable->isParameter() && 5562 !DL->getInlinedAt(); 5563 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5564 if (!IsInPrologue && !VariableIsFunctionInputArg) 5565 return false; 5566 5567 // Here we assume that a function argument on IR level only can be used to 5568 // describe one input parameter on source level. If we for example have 5569 // source code like this 5570 // 5571 // struct A { long x, y; }; 5572 // void foo(struct A a, long b) { 5573 // ... 5574 // b = a.x; 5575 // ... 5576 // } 5577 // 5578 // and IR like this 5579 // 5580 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5581 // entry: 5582 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5583 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5584 // call void @llvm.dbg.value(metadata i32 %b, "b", 5585 // ... 5586 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5587 // ... 5588 // 5589 // then the last dbg.value is describing a parameter "b" using a value that 5590 // is an argument. But since we already has used %a1 to describe a parameter 5591 // we should not handle that last dbg.value here (that would result in an 5592 // incorrect hoisting of the DBG_VALUE to the function entry). 5593 // Notice that we allow one dbg.value per IR level argument, to accommodate 5594 // for the situation with fragments above. 5595 if (VariableIsFunctionInputArg) { 5596 unsigned ArgNo = Arg->getArgNo(); 5597 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5598 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5599 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5600 return false; 5601 FuncInfo.DescribedArgs.set(ArgNo); 5602 } 5603 } 5604 5605 bool IsIndirect = false; 5606 Optional<MachineOperand> Op; 5607 // Some arguments' frame index is recorded during argument lowering. 5608 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5609 if (FI != std::numeric_limits<int>::max()) 5610 Op = MachineOperand::CreateFI(FI); 5611 5612 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5613 if (!Op && N.getNode()) { 5614 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5615 Register Reg; 5616 if (ArgRegsAndSizes.size() == 1) 5617 Reg = ArgRegsAndSizes.front().first; 5618 5619 if (Reg && Reg.isVirtual()) { 5620 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5621 Register PR = RegInfo.getLiveInPhysReg(Reg); 5622 if (PR) 5623 Reg = PR; 5624 } 5625 if (Reg) { 5626 Op = MachineOperand::CreateReg(Reg, false); 5627 IsIndirect = IsDbgDeclare; 5628 } 5629 } 5630 5631 if (!Op && N.getNode()) { 5632 // Check if frame index is available. 5633 SDValue LCandidate = peekThroughBitcasts(N); 5634 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5635 if (FrameIndexSDNode *FINode = 5636 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5637 Op = MachineOperand::CreateFI(FINode->getIndex()); 5638 } 5639 5640 if (!Op) { 5641 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5642 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5643 SplitRegs) { 5644 unsigned Offset = 0; 5645 for (auto RegAndSize : SplitRegs) { 5646 // If the expression is already a fragment, the current register 5647 // offset+size might extend beyond the fragment. In this case, only 5648 // the register bits that are inside the fragment are relevant. 5649 int RegFragmentSizeInBits = RegAndSize.second; 5650 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5651 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5652 // The register is entirely outside the expression fragment, 5653 // so is irrelevant for debug info. 5654 if (Offset >= ExprFragmentSizeInBits) 5655 break; 5656 // The register is partially outside the expression fragment, only 5657 // the low bits within the fragment are relevant for debug info. 5658 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5659 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5660 } 5661 } 5662 5663 auto FragmentExpr = DIExpression::createFragmentExpression( 5664 Expr, Offset, RegFragmentSizeInBits); 5665 Offset += RegAndSize.second; 5666 // If a valid fragment expression cannot be created, the variable's 5667 // correct value cannot be determined and so it is set as Undef. 5668 if (!FragmentExpr) { 5669 SDDbgValue *SDV = DAG.getConstantDbgValue( 5670 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5671 DAG.AddDbgValue(SDV, false); 5672 continue; 5673 } 5674 MachineInstr *NewMI = 5675 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare); 5676 FuncInfo.ArgDbgValues.push_back(NewMI); 5677 } 5678 }; 5679 5680 // Check if ValueMap has reg number. 5681 DenseMap<const Value *, Register>::const_iterator 5682 VMI = FuncInfo.ValueMap.find(V); 5683 if (VMI != FuncInfo.ValueMap.end()) { 5684 const auto &TLI = DAG.getTargetLoweringInfo(); 5685 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5686 V->getType(), None); 5687 if (RFV.occupiesMultipleRegs()) { 5688 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5689 return true; 5690 } 5691 5692 Op = MachineOperand::CreateReg(VMI->second, false); 5693 IsIndirect = IsDbgDeclare; 5694 } else if (ArgRegsAndSizes.size() > 1) { 5695 // This was split due to the calling convention, and no virtual register 5696 // mapping exists for the value. 5697 splitMultiRegDbgValue(ArgRegsAndSizes); 5698 return true; 5699 } 5700 } 5701 5702 if (!Op) 5703 return false; 5704 5705 assert(Variable->isValidLocationForIntrinsic(DL) && 5706 "Expected inlined-at fields to agree"); 5707 MachineInstr *NewMI = nullptr; 5708 5709 if (Op->isReg()) 5710 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5711 else 5712 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5713 Variable, Expr); 5714 5715 FuncInfo.ArgDbgValues.push_back(NewMI); 5716 return true; 5717 } 5718 5719 /// Return the appropriate SDDbgValue based on N. 5720 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5721 DILocalVariable *Variable, 5722 DIExpression *Expr, 5723 const DebugLoc &dl, 5724 unsigned DbgSDNodeOrder) { 5725 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5726 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5727 // stack slot locations. 5728 // 5729 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5730 // debug values here after optimization: 5731 // 5732 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5733 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5734 // 5735 // Both describe the direct values of their associated variables. 5736 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5737 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5738 } 5739 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5740 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5741 } 5742 5743 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5744 switch (Intrinsic) { 5745 case Intrinsic::smul_fix: 5746 return ISD::SMULFIX; 5747 case Intrinsic::umul_fix: 5748 return ISD::UMULFIX; 5749 case Intrinsic::smul_fix_sat: 5750 return ISD::SMULFIXSAT; 5751 case Intrinsic::umul_fix_sat: 5752 return ISD::UMULFIXSAT; 5753 case Intrinsic::sdiv_fix: 5754 return ISD::SDIVFIX; 5755 case Intrinsic::udiv_fix: 5756 return ISD::UDIVFIX; 5757 case Intrinsic::sdiv_fix_sat: 5758 return ISD::SDIVFIXSAT; 5759 case Intrinsic::udiv_fix_sat: 5760 return ISD::UDIVFIXSAT; 5761 default: 5762 llvm_unreachable("Unhandled fixed point intrinsic"); 5763 } 5764 } 5765 5766 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5767 const char *FunctionName) { 5768 assert(FunctionName && "FunctionName must not be nullptr"); 5769 SDValue Callee = DAG.getExternalSymbol( 5770 FunctionName, 5771 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5772 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5773 } 5774 5775 /// Given a @llvm.call.preallocated.setup, return the corresponding 5776 /// preallocated call. 5777 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5778 assert(cast<CallBase>(PreallocatedSetup) 5779 ->getCalledFunction() 5780 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5781 "expected call_preallocated_setup Value"); 5782 for (auto *U : PreallocatedSetup->users()) { 5783 auto *UseCall = cast<CallBase>(U); 5784 const Function *Fn = UseCall->getCalledFunction(); 5785 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5786 return UseCall; 5787 } 5788 } 5789 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5790 } 5791 5792 /// Lower the call to the specified intrinsic function. 5793 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5794 unsigned Intrinsic) { 5795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5796 SDLoc sdl = getCurSDLoc(); 5797 DebugLoc dl = getCurDebugLoc(); 5798 SDValue Res; 5799 5800 SDNodeFlags Flags; 5801 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5802 Flags.copyFMF(*FPOp); 5803 5804 switch (Intrinsic) { 5805 default: 5806 // By default, turn this into a target intrinsic node. 5807 visitTargetIntrinsic(I, Intrinsic); 5808 return; 5809 case Intrinsic::vscale: { 5810 match(&I, m_VScale(DAG.getDataLayout())); 5811 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5812 setValue(&I, 5813 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5814 return; 5815 } 5816 case Intrinsic::vastart: visitVAStart(I); return; 5817 case Intrinsic::vaend: visitVAEnd(I); return; 5818 case Intrinsic::vacopy: visitVACopy(I); return; 5819 case Intrinsic::returnaddress: 5820 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5821 TLI.getPointerTy(DAG.getDataLayout()), 5822 getValue(I.getArgOperand(0)))); 5823 return; 5824 case Intrinsic::addressofreturnaddress: 5825 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5826 TLI.getPointerTy(DAG.getDataLayout()))); 5827 return; 5828 case Intrinsic::sponentry: 5829 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5830 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5831 return; 5832 case Intrinsic::frameaddress: 5833 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5834 TLI.getFrameIndexTy(DAG.getDataLayout()), 5835 getValue(I.getArgOperand(0)))); 5836 return; 5837 case Intrinsic::read_volatile_register: 5838 case Intrinsic::read_register: { 5839 Value *Reg = I.getArgOperand(0); 5840 SDValue Chain = getRoot(); 5841 SDValue RegName = 5842 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5843 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5844 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5845 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5846 setValue(&I, Res); 5847 DAG.setRoot(Res.getValue(1)); 5848 return; 5849 } 5850 case Intrinsic::write_register: { 5851 Value *Reg = I.getArgOperand(0); 5852 Value *RegValue = I.getArgOperand(1); 5853 SDValue Chain = getRoot(); 5854 SDValue RegName = 5855 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5856 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5857 RegName, getValue(RegValue))); 5858 return; 5859 } 5860 case Intrinsic::memcpy: { 5861 const auto &MCI = cast<MemCpyInst>(I); 5862 SDValue Op1 = getValue(I.getArgOperand(0)); 5863 SDValue Op2 = getValue(I.getArgOperand(1)); 5864 SDValue Op3 = getValue(I.getArgOperand(2)); 5865 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5866 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5867 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5868 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5869 bool isVol = MCI.isVolatile(); 5870 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5871 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5872 // node. 5873 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5874 AAMDNodes AAInfo; 5875 I.getAAMetadata(AAInfo); 5876 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5877 /* AlwaysInline */ false, isTC, 5878 MachinePointerInfo(I.getArgOperand(0)), 5879 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 5880 updateDAGForMaybeTailCall(MC); 5881 return; 5882 } 5883 case Intrinsic::memcpy_inline: { 5884 const auto &MCI = cast<MemCpyInlineInst>(I); 5885 SDValue Dst = getValue(I.getArgOperand(0)); 5886 SDValue Src = getValue(I.getArgOperand(1)); 5887 SDValue Size = getValue(I.getArgOperand(2)); 5888 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5889 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5890 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5891 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5892 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5893 bool isVol = MCI.isVolatile(); 5894 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5895 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5896 // node. 5897 AAMDNodes AAInfo; 5898 I.getAAMetadata(AAInfo); 5899 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5900 /* AlwaysInline */ true, isTC, 5901 MachinePointerInfo(I.getArgOperand(0)), 5902 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 5903 updateDAGForMaybeTailCall(MC); 5904 return; 5905 } 5906 case Intrinsic::memset: { 5907 const auto &MSI = cast<MemSetInst>(I); 5908 SDValue Op1 = getValue(I.getArgOperand(0)); 5909 SDValue Op2 = getValue(I.getArgOperand(1)); 5910 SDValue Op3 = getValue(I.getArgOperand(2)); 5911 // @llvm.memset defines 0 and 1 to both mean no alignment. 5912 Align Alignment = MSI.getDestAlign().valueOrOne(); 5913 bool isVol = MSI.isVolatile(); 5914 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5915 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5916 AAMDNodes AAInfo; 5917 I.getAAMetadata(AAInfo); 5918 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5919 MachinePointerInfo(I.getArgOperand(0)), AAInfo); 5920 updateDAGForMaybeTailCall(MS); 5921 return; 5922 } 5923 case Intrinsic::memmove: { 5924 const auto &MMI = cast<MemMoveInst>(I); 5925 SDValue Op1 = getValue(I.getArgOperand(0)); 5926 SDValue Op2 = getValue(I.getArgOperand(1)); 5927 SDValue Op3 = getValue(I.getArgOperand(2)); 5928 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5929 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5930 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5931 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5932 bool isVol = MMI.isVolatile(); 5933 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5934 // FIXME: Support passing different dest/src alignments to the memmove DAG 5935 // node. 5936 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5937 AAMDNodes AAInfo; 5938 I.getAAMetadata(AAInfo); 5939 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5940 isTC, MachinePointerInfo(I.getArgOperand(0)), 5941 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 5942 updateDAGForMaybeTailCall(MM); 5943 return; 5944 } 5945 case Intrinsic::memcpy_element_unordered_atomic: { 5946 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5947 SDValue Dst = getValue(MI.getRawDest()); 5948 SDValue Src = getValue(MI.getRawSource()); 5949 SDValue Length = getValue(MI.getLength()); 5950 5951 unsigned DstAlign = MI.getDestAlignment(); 5952 unsigned SrcAlign = MI.getSourceAlignment(); 5953 Type *LengthTy = MI.getLength()->getType(); 5954 unsigned ElemSz = MI.getElementSizeInBytes(); 5955 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5956 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5957 SrcAlign, Length, LengthTy, ElemSz, isTC, 5958 MachinePointerInfo(MI.getRawDest()), 5959 MachinePointerInfo(MI.getRawSource())); 5960 updateDAGForMaybeTailCall(MC); 5961 return; 5962 } 5963 case Intrinsic::memmove_element_unordered_atomic: { 5964 auto &MI = cast<AtomicMemMoveInst>(I); 5965 SDValue Dst = getValue(MI.getRawDest()); 5966 SDValue Src = getValue(MI.getRawSource()); 5967 SDValue Length = getValue(MI.getLength()); 5968 5969 unsigned DstAlign = MI.getDestAlignment(); 5970 unsigned SrcAlign = MI.getSourceAlignment(); 5971 Type *LengthTy = MI.getLength()->getType(); 5972 unsigned ElemSz = MI.getElementSizeInBytes(); 5973 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5974 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5975 SrcAlign, Length, LengthTy, ElemSz, isTC, 5976 MachinePointerInfo(MI.getRawDest()), 5977 MachinePointerInfo(MI.getRawSource())); 5978 updateDAGForMaybeTailCall(MC); 5979 return; 5980 } 5981 case Intrinsic::memset_element_unordered_atomic: { 5982 auto &MI = cast<AtomicMemSetInst>(I); 5983 SDValue Dst = getValue(MI.getRawDest()); 5984 SDValue Val = getValue(MI.getValue()); 5985 SDValue Length = getValue(MI.getLength()); 5986 5987 unsigned DstAlign = MI.getDestAlignment(); 5988 Type *LengthTy = MI.getLength()->getType(); 5989 unsigned ElemSz = MI.getElementSizeInBytes(); 5990 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5991 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5992 LengthTy, ElemSz, isTC, 5993 MachinePointerInfo(MI.getRawDest())); 5994 updateDAGForMaybeTailCall(MC); 5995 return; 5996 } 5997 case Intrinsic::call_preallocated_setup: { 5998 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5999 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6000 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6001 getRoot(), SrcValue); 6002 setValue(&I, Res); 6003 DAG.setRoot(Res); 6004 return; 6005 } 6006 case Intrinsic::call_preallocated_arg: { 6007 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6008 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6009 SDValue Ops[3]; 6010 Ops[0] = getRoot(); 6011 Ops[1] = SrcValue; 6012 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6013 MVT::i32); // arg index 6014 SDValue Res = DAG.getNode( 6015 ISD::PREALLOCATED_ARG, sdl, 6016 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6017 setValue(&I, Res); 6018 DAG.setRoot(Res.getValue(1)); 6019 return; 6020 } 6021 case Intrinsic::dbg_addr: 6022 case Intrinsic::dbg_declare: { 6023 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6024 // they are non-variadic. 6025 const auto &DI = cast<DbgVariableIntrinsic>(I); 6026 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6027 DILocalVariable *Variable = DI.getVariable(); 6028 DIExpression *Expression = DI.getExpression(); 6029 dropDanglingDebugInfo(Variable, Expression); 6030 assert(Variable && "Missing variable"); 6031 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6032 << "\n"); 6033 // Check if address has undef value. 6034 const Value *Address = DI.getVariableLocationOp(0); 6035 if (!Address || isa<UndefValue>(Address) || 6036 (Address->use_empty() && !isa<Argument>(Address))) { 6037 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6038 << " (bad/undef/unused-arg address)\n"); 6039 return; 6040 } 6041 6042 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6043 6044 // Check if this variable can be described by a frame index, typically 6045 // either as a static alloca or a byval parameter. 6046 int FI = std::numeric_limits<int>::max(); 6047 if (const auto *AI = 6048 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6049 if (AI->isStaticAlloca()) { 6050 auto I = FuncInfo.StaticAllocaMap.find(AI); 6051 if (I != FuncInfo.StaticAllocaMap.end()) 6052 FI = I->second; 6053 } 6054 } else if (const auto *Arg = dyn_cast<Argument>( 6055 Address->stripInBoundsConstantOffsets())) { 6056 FI = FuncInfo.getArgumentFrameIndex(Arg); 6057 } 6058 6059 // llvm.dbg.addr is control dependent and always generates indirect 6060 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6061 // the MachineFunction variable table. 6062 if (FI != std::numeric_limits<int>::max()) { 6063 if (Intrinsic == Intrinsic::dbg_addr) { 6064 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6065 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6066 dl, SDNodeOrder); 6067 DAG.AddDbgValue(SDV, isParameter); 6068 } else { 6069 LLVM_DEBUG(dbgs() << "Skipping " << DI 6070 << " (variable info stashed in MF side table)\n"); 6071 } 6072 return; 6073 } 6074 6075 SDValue &N = NodeMap[Address]; 6076 if (!N.getNode() && isa<Argument>(Address)) 6077 // Check unused arguments map. 6078 N = UnusedArgNodeMap[Address]; 6079 SDDbgValue *SDV; 6080 if (N.getNode()) { 6081 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6082 Address = BCI->getOperand(0); 6083 // Parameters are handled specially. 6084 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6085 if (isParameter && FINode) { 6086 // Byval parameter. We have a frame index at this point. 6087 SDV = 6088 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6089 /*IsIndirect*/ true, dl, SDNodeOrder); 6090 } else if (isa<Argument>(Address)) { 6091 // Address is an argument, so try to emit its dbg value using 6092 // virtual register info from the FuncInfo.ValueMap. 6093 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6094 return; 6095 } else { 6096 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6097 true, dl, SDNodeOrder); 6098 } 6099 DAG.AddDbgValue(SDV, isParameter); 6100 } else { 6101 // If Address is an argument then try to emit its dbg value using 6102 // virtual register info from the FuncInfo.ValueMap. 6103 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6104 N)) { 6105 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6106 << " (could not emit func-arg dbg_value)\n"); 6107 } 6108 } 6109 return; 6110 } 6111 case Intrinsic::dbg_label: { 6112 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6113 DILabel *Label = DI.getLabel(); 6114 assert(Label && "Missing label"); 6115 6116 SDDbgLabel *SDV; 6117 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6118 DAG.AddDbgLabel(SDV); 6119 return; 6120 } 6121 case Intrinsic::dbg_value: { 6122 const DbgValueInst &DI = cast<DbgValueInst>(I); 6123 assert(DI.getVariable() && "Missing variable"); 6124 6125 DILocalVariable *Variable = DI.getVariable(); 6126 DIExpression *Expression = DI.getExpression(); 6127 dropDanglingDebugInfo(Variable, Expression); 6128 SmallVector<Value *, 4> Values(DI.getValues()); 6129 if (Values.empty()) 6130 return; 6131 6132 if (std::count(Values.begin(), Values.end(), nullptr)) 6133 return; 6134 6135 bool IsVariadic = DI.hasArgList(); 6136 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6137 SDNodeOrder, IsVariadic)) 6138 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6139 return; 6140 } 6141 6142 case Intrinsic::eh_typeid_for: { 6143 // Find the type id for the given typeinfo. 6144 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6145 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6146 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6147 setValue(&I, Res); 6148 return; 6149 } 6150 6151 case Intrinsic::eh_return_i32: 6152 case Intrinsic::eh_return_i64: 6153 DAG.getMachineFunction().setCallsEHReturn(true); 6154 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6155 MVT::Other, 6156 getControlRoot(), 6157 getValue(I.getArgOperand(0)), 6158 getValue(I.getArgOperand(1)))); 6159 return; 6160 case Intrinsic::eh_unwind_init: 6161 DAG.getMachineFunction().setCallsUnwindInit(true); 6162 return; 6163 case Intrinsic::eh_dwarf_cfa: 6164 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6165 TLI.getPointerTy(DAG.getDataLayout()), 6166 getValue(I.getArgOperand(0)))); 6167 return; 6168 case Intrinsic::eh_sjlj_callsite: { 6169 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6170 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6171 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6172 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6173 6174 MMI.setCurrentCallSite(CI->getZExtValue()); 6175 return; 6176 } 6177 case Intrinsic::eh_sjlj_functioncontext: { 6178 // Get and store the index of the function context. 6179 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6180 AllocaInst *FnCtx = 6181 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6182 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6183 MFI.setFunctionContextIndex(FI); 6184 return; 6185 } 6186 case Intrinsic::eh_sjlj_setjmp: { 6187 SDValue Ops[2]; 6188 Ops[0] = getRoot(); 6189 Ops[1] = getValue(I.getArgOperand(0)); 6190 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6191 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6192 setValue(&I, Op.getValue(0)); 6193 DAG.setRoot(Op.getValue(1)); 6194 return; 6195 } 6196 case Intrinsic::eh_sjlj_longjmp: 6197 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6198 getRoot(), getValue(I.getArgOperand(0)))); 6199 return; 6200 case Intrinsic::eh_sjlj_setup_dispatch: 6201 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6202 getRoot())); 6203 return; 6204 case Intrinsic::masked_gather: 6205 visitMaskedGather(I); 6206 return; 6207 case Intrinsic::masked_load: 6208 visitMaskedLoad(I); 6209 return; 6210 case Intrinsic::masked_scatter: 6211 visitMaskedScatter(I); 6212 return; 6213 case Intrinsic::masked_store: 6214 visitMaskedStore(I); 6215 return; 6216 case Intrinsic::masked_expandload: 6217 visitMaskedLoad(I, true /* IsExpanding */); 6218 return; 6219 case Intrinsic::masked_compressstore: 6220 visitMaskedStore(I, true /* IsCompressing */); 6221 return; 6222 case Intrinsic::powi: 6223 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6224 getValue(I.getArgOperand(1)), DAG)); 6225 return; 6226 case Intrinsic::log: 6227 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6228 return; 6229 case Intrinsic::log2: 6230 setValue(&I, 6231 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6232 return; 6233 case Intrinsic::log10: 6234 setValue(&I, 6235 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6236 return; 6237 case Intrinsic::exp: 6238 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6239 return; 6240 case Intrinsic::exp2: 6241 setValue(&I, 6242 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6243 return; 6244 case Intrinsic::pow: 6245 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6246 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6247 return; 6248 case Intrinsic::sqrt: 6249 case Intrinsic::fabs: 6250 case Intrinsic::sin: 6251 case Intrinsic::cos: 6252 case Intrinsic::floor: 6253 case Intrinsic::ceil: 6254 case Intrinsic::trunc: 6255 case Intrinsic::rint: 6256 case Intrinsic::nearbyint: 6257 case Intrinsic::round: 6258 case Intrinsic::roundeven: 6259 case Intrinsic::canonicalize: { 6260 unsigned Opcode; 6261 switch (Intrinsic) { 6262 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6263 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6264 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6265 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6266 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6267 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6268 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6269 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6270 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6271 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6272 case Intrinsic::round: Opcode = ISD::FROUND; break; 6273 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6274 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6275 } 6276 6277 setValue(&I, DAG.getNode(Opcode, sdl, 6278 getValue(I.getArgOperand(0)).getValueType(), 6279 getValue(I.getArgOperand(0)), Flags)); 6280 return; 6281 } 6282 case Intrinsic::lround: 6283 case Intrinsic::llround: 6284 case Intrinsic::lrint: 6285 case Intrinsic::llrint: { 6286 unsigned Opcode; 6287 switch (Intrinsic) { 6288 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6289 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6290 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6291 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6292 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6293 } 6294 6295 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6296 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6297 getValue(I.getArgOperand(0)))); 6298 return; 6299 } 6300 case Intrinsic::minnum: 6301 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6302 getValue(I.getArgOperand(0)).getValueType(), 6303 getValue(I.getArgOperand(0)), 6304 getValue(I.getArgOperand(1)), Flags)); 6305 return; 6306 case Intrinsic::maxnum: 6307 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6308 getValue(I.getArgOperand(0)).getValueType(), 6309 getValue(I.getArgOperand(0)), 6310 getValue(I.getArgOperand(1)), Flags)); 6311 return; 6312 case Intrinsic::minimum: 6313 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6314 getValue(I.getArgOperand(0)).getValueType(), 6315 getValue(I.getArgOperand(0)), 6316 getValue(I.getArgOperand(1)), Flags)); 6317 return; 6318 case Intrinsic::maximum: 6319 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6320 getValue(I.getArgOperand(0)).getValueType(), 6321 getValue(I.getArgOperand(0)), 6322 getValue(I.getArgOperand(1)), Flags)); 6323 return; 6324 case Intrinsic::copysign: 6325 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6326 getValue(I.getArgOperand(0)).getValueType(), 6327 getValue(I.getArgOperand(0)), 6328 getValue(I.getArgOperand(1)), Flags)); 6329 return; 6330 case Intrinsic::arithmetic_fence: { 6331 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6332 getValue(I.getArgOperand(0)).getValueType(), 6333 getValue(I.getArgOperand(0)), Flags)); 6334 return; 6335 } 6336 case Intrinsic::fma: 6337 setValue(&I, DAG.getNode( 6338 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6339 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6340 getValue(I.getArgOperand(2)), Flags)); 6341 return; 6342 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6343 case Intrinsic::INTRINSIC: 6344 #include "llvm/IR/ConstrainedOps.def" 6345 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6346 return; 6347 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6348 #include "llvm/IR/VPIntrinsics.def" 6349 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6350 return; 6351 case Intrinsic::fmuladd: { 6352 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6353 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6354 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6355 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6356 getValue(I.getArgOperand(0)).getValueType(), 6357 getValue(I.getArgOperand(0)), 6358 getValue(I.getArgOperand(1)), 6359 getValue(I.getArgOperand(2)), Flags)); 6360 } else { 6361 // TODO: Intrinsic calls should have fast-math-flags. 6362 SDValue Mul = DAG.getNode( 6363 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6364 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6365 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6366 getValue(I.getArgOperand(0)).getValueType(), 6367 Mul, getValue(I.getArgOperand(2)), Flags); 6368 setValue(&I, Add); 6369 } 6370 return; 6371 } 6372 case Intrinsic::convert_to_fp16: 6373 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6374 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6375 getValue(I.getArgOperand(0)), 6376 DAG.getTargetConstant(0, sdl, 6377 MVT::i32)))); 6378 return; 6379 case Intrinsic::convert_from_fp16: 6380 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6381 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6382 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6383 getValue(I.getArgOperand(0))))); 6384 return; 6385 case Intrinsic::fptosi_sat: { 6386 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6387 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6388 getValue(I.getArgOperand(0)), 6389 DAG.getValueType(VT.getScalarType()))); 6390 return; 6391 } 6392 case Intrinsic::fptoui_sat: { 6393 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6394 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6395 getValue(I.getArgOperand(0)), 6396 DAG.getValueType(VT.getScalarType()))); 6397 return; 6398 } 6399 case Intrinsic::set_rounding: 6400 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6401 {getRoot(), getValue(I.getArgOperand(0))}); 6402 setValue(&I, Res); 6403 DAG.setRoot(Res.getValue(0)); 6404 return; 6405 case Intrinsic::pcmarker: { 6406 SDValue Tmp = getValue(I.getArgOperand(0)); 6407 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6408 return; 6409 } 6410 case Intrinsic::isnan: { 6411 const DataLayout DLayout = DAG.getDataLayout(); 6412 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6413 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6414 MachineFunction &MF = DAG.getMachineFunction(); 6415 const Function &F = MF.getFunction(); 6416 SDValue Op = getValue(I.getArgOperand(0)); 6417 SDNodeFlags Flags; 6418 Flags.setNoFPExcept( 6419 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6420 6421 // If ISD::ISNAN should be expanded, do it right now, because the expansion 6422 // can use illegal types. Making expansion early allows to legalize these 6423 // types prior to selection. 6424 if (!TLI.isOperationLegalOrCustom(ISD::ISNAN, ArgVT)) { 6425 SDValue Result = TLI.expandISNAN(DestVT, Op, Flags, sdl, DAG); 6426 setValue(&I, Result); 6427 return; 6428 } 6429 6430 SDValue V = DAG.getNode(ISD::ISNAN, sdl, DestVT, Op, Flags); 6431 setValue(&I, V); 6432 return; 6433 } 6434 case Intrinsic::readcyclecounter: { 6435 SDValue Op = getRoot(); 6436 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6437 DAG.getVTList(MVT::i64, MVT::Other), Op); 6438 setValue(&I, Res); 6439 DAG.setRoot(Res.getValue(1)); 6440 return; 6441 } 6442 case Intrinsic::bitreverse: 6443 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6444 getValue(I.getArgOperand(0)).getValueType(), 6445 getValue(I.getArgOperand(0)))); 6446 return; 6447 case Intrinsic::bswap: 6448 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6449 getValue(I.getArgOperand(0)).getValueType(), 6450 getValue(I.getArgOperand(0)))); 6451 return; 6452 case Intrinsic::cttz: { 6453 SDValue Arg = getValue(I.getArgOperand(0)); 6454 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6455 EVT Ty = Arg.getValueType(); 6456 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6457 sdl, Ty, Arg)); 6458 return; 6459 } 6460 case Intrinsic::ctlz: { 6461 SDValue Arg = getValue(I.getArgOperand(0)); 6462 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6463 EVT Ty = Arg.getValueType(); 6464 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6465 sdl, Ty, Arg)); 6466 return; 6467 } 6468 case Intrinsic::ctpop: { 6469 SDValue Arg = getValue(I.getArgOperand(0)); 6470 EVT Ty = Arg.getValueType(); 6471 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6472 return; 6473 } 6474 case Intrinsic::fshl: 6475 case Intrinsic::fshr: { 6476 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6477 SDValue X = getValue(I.getArgOperand(0)); 6478 SDValue Y = getValue(I.getArgOperand(1)); 6479 SDValue Z = getValue(I.getArgOperand(2)); 6480 EVT VT = X.getValueType(); 6481 6482 if (X == Y) { 6483 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6484 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6485 } else { 6486 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6487 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6488 } 6489 return; 6490 } 6491 case Intrinsic::sadd_sat: { 6492 SDValue Op1 = getValue(I.getArgOperand(0)); 6493 SDValue Op2 = getValue(I.getArgOperand(1)); 6494 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6495 return; 6496 } 6497 case Intrinsic::uadd_sat: { 6498 SDValue Op1 = getValue(I.getArgOperand(0)); 6499 SDValue Op2 = getValue(I.getArgOperand(1)); 6500 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6501 return; 6502 } 6503 case Intrinsic::ssub_sat: { 6504 SDValue Op1 = getValue(I.getArgOperand(0)); 6505 SDValue Op2 = getValue(I.getArgOperand(1)); 6506 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6507 return; 6508 } 6509 case Intrinsic::usub_sat: { 6510 SDValue Op1 = getValue(I.getArgOperand(0)); 6511 SDValue Op2 = getValue(I.getArgOperand(1)); 6512 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6513 return; 6514 } 6515 case Intrinsic::sshl_sat: { 6516 SDValue Op1 = getValue(I.getArgOperand(0)); 6517 SDValue Op2 = getValue(I.getArgOperand(1)); 6518 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6519 return; 6520 } 6521 case Intrinsic::ushl_sat: { 6522 SDValue Op1 = getValue(I.getArgOperand(0)); 6523 SDValue Op2 = getValue(I.getArgOperand(1)); 6524 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6525 return; 6526 } 6527 case Intrinsic::smul_fix: 6528 case Intrinsic::umul_fix: 6529 case Intrinsic::smul_fix_sat: 6530 case Intrinsic::umul_fix_sat: { 6531 SDValue Op1 = getValue(I.getArgOperand(0)); 6532 SDValue Op2 = getValue(I.getArgOperand(1)); 6533 SDValue Op3 = getValue(I.getArgOperand(2)); 6534 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6535 Op1.getValueType(), Op1, Op2, Op3)); 6536 return; 6537 } 6538 case Intrinsic::sdiv_fix: 6539 case Intrinsic::udiv_fix: 6540 case Intrinsic::sdiv_fix_sat: 6541 case Intrinsic::udiv_fix_sat: { 6542 SDValue Op1 = getValue(I.getArgOperand(0)); 6543 SDValue Op2 = getValue(I.getArgOperand(1)); 6544 SDValue Op3 = getValue(I.getArgOperand(2)); 6545 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6546 Op1, Op2, Op3, DAG, TLI)); 6547 return; 6548 } 6549 case Intrinsic::smax: { 6550 SDValue Op1 = getValue(I.getArgOperand(0)); 6551 SDValue Op2 = getValue(I.getArgOperand(1)); 6552 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6553 return; 6554 } 6555 case Intrinsic::smin: { 6556 SDValue Op1 = getValue(I.getArgOperand(0)); 6557 SDValue Op2 = getValue(I.getArgOperand(1)); 6558 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6559 return; 6560 } 6561 case Intrinsic::umax: { 6562 SDValue Op1 = getValue(I.getArgOperand(0)); 6563 SDValue Op2 = getValue(I.getArgOperand(1)); 6564 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6565 return; 6566 } 6567 case Intrinsic::umin: { 6568 SDValue Op1 = getValue(I.getArgOperand(0)); 6569 SDValue Op2 = getValue(I.getArgOperand(1)); 6570 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6571 return; 6572 } 6573 case Intrinsic::abs: { 6574 // TODO: Preserve "int min is poison" arg in SDAG? 6575 SDValue Op1 = getValue(I.getArgOperand(0)); 6576 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6577 return; 6578 } 6579 case Intrinsic::stacksave: { 6580 SDValue Op = getRoot(); 6581 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6582 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6583 setValue(&I, Res); 6584 DAG.setRoot(Res.getValue(1)); 6585 return; 6586 } 6587 case Intrinsic::stackrestore: 6588 Res = getValue(I.getArgOperand(0)); 6589 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6590 return; 6591 case Intrinsic::get_dynamic_area_offset: { 6592 SDValue Op = getRoot(); 6593 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6594 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6595 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6596 // target. 6597 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6598 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6599 " intrinsic!"); 6600 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6601 Op); 6602 DAG.setRoot(Op); 6603 setValue(&I, Res); 6604 return; 6605 } 6606 case Intrinsic::stackguard: { 6607 MachineFunction &MF = DAG.getMachineFunction(); 6608 const Module &M = *MF.getFunction().getParent(); 6609 SDValue Chain = getRoot(); 6610 if (TLI.useLoadStackGuardNode()) { 6611 Res = getLoadStackGuard(DAG, sdl, Chain); 6612 } else { 6613 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6614 const Value *Global = TLI.getSDagStackGuard(M); 6615 Align Align = DL->getPrefTypeAlign(Global->getType()); 6616 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6617 MachinePointerInfo(Global, 0), Align, 6618 MachineMemOperand::MOVolatile); 6619 } 6620 if (TLI.useStackGuardXorFP()) 6621 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6622 DAG.setRoot(Chain); 6623 setValue(&I, Res); 6624 return; 6625 } 6626 case Intrinsic::stackprotector: { 6627 // Emit code into the DAG to store the stack guard onto the stack. 6628 MachineFunction &MF = DAG.getMachineFunction(); 6629 MachineFrameInfo &MFI = MF.getFrameInfo(); 6630 SDValue Src, Chain = getRoot(); 6631 6632 if (TLI.useLoadStackGuardNode()) 6633 Src = getLoadStackGuard(DAG, sdl, Chain); 6634 else 6635 Src = getValue(I.getArgOperand(0)); // The guard's value. 6636 6637 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6638 6639 int FI = FuncInfo.StaticAllocaMap[Slot]; 6640 MFI.setStackProtectorIndex(FI); 6641 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6642 6643 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6644 6645 // Store the stack protector onto the stack. 6646 Res = DAG.getStore( 6647 Chain, sdl, Src, FIN, 6648 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6649 MaybeAlign(), MachineMemOperand::MOVolatile); 6650 setValue(&I, Res); 6651 DAG.setRoot(Res); 6652 return; 6653 } 6654 case Intrinsic::objectsize: 6655 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6656 6657 case Intrinsic::is_constant: 6658 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6659 6660 case Intrinsic::annotation: 6661 case Intrinsic::ptr_annotation: 6662 case Intrinsic::launder_invariant_group: 6663 case Intrinsic::strip_invariant_group: 6664 // Drop the intrinsic, but forward the value 6665 setValue(&I, getValue(I.getOperand(0))); 6666 return; 6667 6668 case Intrinsic::assume: 6669 case Intrinsic::experimental_noalias_scope_decl: 6670 case Intrinsic::var_annotation: 6671 case Intrinsic::sideeffect: 6672 // Discard annotate attributes, noalias scope declarations, assumptions, and 6673 // artificial side-effects. 6674 return; 6675 6676 case Intrinsic::codeview_annotation: { 6677 // Emit a label associated with this metadata. 6678 MachineFunction &MF = DAG.getMachineFunction(); 6679 MCSymbol *Label = 6680 MF.getMMI().getContext().createTempSymbol("annotation", true); 6681 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6682 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6683 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6684 DAG.setRoot(Res); 6685 return; 6686 } 6687 6688 case Intrinsic::init_trampoline: { 6689 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6690 6691 SDValue Ops[6]; 6692 Ops[0] = getRoot(); 6693 Ops[1] = getValue(I.getArgOperand(0)); 6694 Ops[2] = getValue(I.getArgOperand(1)); 6695 Ops[3] = getValue(I.getArgOperand(2)); 6696 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6697 Ops[5] = DAG.getSrcValue(F); 6698 6699 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6700 6701 DAG.setRoot(Res); 6702 return; 6703 } 6704 case Intrinsic::adjust_trampoline: 6705 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6706 TLI.getPointerTy(DAG.getDataLayout()), 6707 getValue(I.getArgOperand(0)))); 6708 return; 6709 case Intrinsic::gcroot: { 6710 assert(DAG.getMachineFunction().getFunction().hasGC() && 6711 "only valid in functions with gc specified, enforced by Verifier"); 6712 assert(GFI && "implied by previous"); 6713 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6714 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6715 6716 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6717 GFI->addStackRoot(FI->getIndex(), TypeMap); 6718 return; 6719 } 6720 case Intrinsic::gcread: 6721 case Intrinsic::gcwrite: 6722 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6723 case Intrinsic::flt_rounds: 6724 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6725 setValue(&I, Res); 6726 DAG.setRoot(Res.getValue(1)); 6727 return; 6728 6729 case Intrinsic::expect: 6730 // Just replace __builtin_expect(exp, c) with EXP. 6731 setValue(&I, getValue(I.getArgOperand(0))); 6732 return; 6733 6734 case Intrinsic::ubsantrap: 6735 case Intrinsic::debugtrap: 6736 case Intrinsic::trap: { 6737 StringRef TrapFuncName = 6738 I.getAttributes() 6739 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6740 .getValueAsString(); 6741 if (TrapFuncName.empty()) { 6742 switch (Intrinsic) { 6743 case Intrinsic::trap: 6744 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6745 break; 6746 case Intrinsic::debugtrap: 6747 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6748 break; 6749 case Intrinsic::ubsantrap: 6750 DAG.setRoot(DAG.getNode( 6751 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6752 DAG.getTargetConstant( 6753 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6754 MVT::i32))); 6755 break; 6756 default: llvm_unreachable("unknown trap intrinsic"); 6757 } 6758 return; 6759 } 6760 TargetLowering::ArgListTy Args; 6761 if (Intrinsic == Intrinsic::ubsantrap) { 6762 Args.push_back(TargetLoweringBase::ArgListEntry()); 6763 Args[0].Val = I.getArgOperand(0); 6764 Args[0].Node = getValue(Args[0].Val); 6765 Args[0].Ty = Args[0].Val->getType(); 6766 } 6767 6768 TargetLowering::CallLoweringInfo CLI(DAG); 6769 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6770 CallingConv::C, I.getType(), 6771 DAG.getExternalSymbol(TrapFuncName.data(), 6772 TLI.getPointerTy(DAG.getDataLayout())), 6773 std::move(Args)); 6774 6775 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6776 DAG.setRoot(Result.second); 6777 return; 6778 } 6779 6780 case Intrinsic::uadd_with_overflow: 6781 case Intrinsic::sadd_with_overflow: 6782 case Intrinsic::usub_with_overflow: 6783 case Intrinsic::ssub_with_overflow: 6784 case Intrinsic::umul_with_overflow: 6785 case Intrinsic::smul_with_overflow: { 6786 ISD::NodeType Op; 6787 switch (Intrinsic) { 6788 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6789 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6790 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6791 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6792 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6793 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6794 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6795 } 6796 SDValue Op1 = getValue(I.getArgOperand(0)); 6797 SDValue Op2 = getValue(I.getArgOperand(1)); 6798 6799 EVT ResultVT = Op1.getValueType(); 6800 EVT OverflowVT = MVT::i1; 6801 if (ResultVT.isVector()) 6802 OverflowVT = EVT::getVectorVT( 6803 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6804 6805 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6806 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6807 return; 6808 } 6809 case Intrinsic::prefetch: { 6810 SDValue Ops[5]; 6811 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6812 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6813 Ops[0] = DAG.getRoot(); 6814 Ops[1] = getValue(I.getArgOperand(0)); 6815 Ops[2] = getValue(I.getArgOperand(1)); 6816 Ops[3] = getValue(I.getArgOperand(2)); 6817 Ops[4] = getValue(I.getArgOperand(3)); 6818 SDValue Result = DAG.getMemIntrinsicNode( 6819 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6820 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6821 /* align */ None, Flags); 6822 6823 // Chain the prefetch in parallell with any pending loads, to stay out of 6824 // the way of later optimizations. 6825 PendingLoads.push_back(Result); 6826 Result = getRoot(); 6827 DAG.setRoot(Result); 6828 return; 6829 } 6830 case Intrinsic::lifetime_start: 6831 case Intrinsic::lifetime_end: { 6832 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6833 // Stack coloring is not enabled in O0, discard region information. 6834 if (TM.getOptLevel() == CodeGenOpt::None) 6835 return; 6836 6837 const int64_t ObjectSize = 6838 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6839 Value *const ObjectPtr = I.getArgOperand(1); 6840 SmallVector<const Value *, 4> Allocas; 6841 getUnderlyingObjects(ObjectPtr, Allocas); 6842 6843 for (const Value *Alloca : Allocas) { 6844 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6845 6846 // Could not find an Alloca. 6847 if (!LifetimeObject) 6848 continue; 6849 6850 // First check that the Alloca is static, otherwise it won't have a 6851 // valid frame index. 6852 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6853 if (SI == FuncInfo.StaticAllocaMap.end()) 6854 return; 6855 6856 const int FrameIndex = SI->second; 6857 int64_t Offset; 6858 if (GetPointerBaseWithConstantOffset( 6859 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6860 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6861 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6862 Offset); 6863 DAG.setRoot(Res); 6864 } 6865 return; 6866 } 6867 case Intrinsic::pseudoprobe: { 6868 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6869 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6870 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6871 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6872 DAG.setRoot(Res); 6873 return; 6874 } 6875 case Intrinsic::invariant_start: 6876 // Discard region information. 6877 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6878 return; 6879 case Intrinsic::invariant_end: 6880 // Discard region information. 6881 return; 6882 case Intrinsic::clear_cache: 6883 /// FunctionName may be null. 6884 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6885 lowerCallToExternalSymbol(I, FunctionName); 6886 return; 6887 case Intrinsic::donothing: 6888 case Intrinsic::seh_try_begin: 6889 case Intrinsic::seh_scope_begin: 6890 case Intrinsic::seh_try_end: 6891 case Intrinsic::seh_scope_end: 6892 // ignore 6893 return; 6894 case Intrinsic::experimental_stackmap: 6895 visitStackmap(I); 6896 return; 6897 case Intrinsic::experimental_patchpoint_void: 6898 case Intrinsic::experimental_patchpoint_i64: 6899 visitPatchpoint(I); 6900 return; 6901 case Intrinsic::experimental_gc_statepoint: 6902 LowerStatepoint(cast<GCStatepointInst>(I)); 6903 return; 6904 case Intrinsic::experimental_gc_result: 6905 visitGCResult(cast<GCResultInst>(I)); 6906 return; 6907 case Intrinsic::experimental_gc_relocate: 6908 visitGCRelocate(cast<GCRelocateInst>(I)); 6909 return; 6910 case Intrinsic::instrprof_increment: 6911 llvm_unreachable("instrprof failed to lower an increment"); 6912 case Intrinsic::instrprof_value_profile: 6913 llvm_unreachable("instrprof failed to lower a value profiling call"); 6914 case Intrinsic::localescape: { 6915 MachineFunction &MF = DAG.getMachineFunction(); 6916 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6917 6918 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6919 // is the same on all targets. 6920 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6921 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6922 if (isa<ConstantPointerNull>(Arg)) 6923 continue; // Skip null pointers. They represent a hole in index space. 6924 AllocaInst *Slot = cast<AllocaInst>(Arg); 6925 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6926 "can only escape static allocas"); 6927 int FI = FuncInfo.StaticAllocaMap[Slot]; 6928 MCSymbol *FrameAllocSym = 6929 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6930 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6931 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6932 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6933 .addSym(FrameAllocSym) 6934 .addFrameIndex(FI); 6935 } 6936 6937 return; 6938 } 6939 6940 case Intrinsic::localrecover: { 6941 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6942 MachineFunction &MF = DAG.getMachineFunction(); 6943 6944 // Get the symbol that defines the frame offset. 6945 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6946 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6947 unsigned IdxVal = 6948 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6949 MCSymbol *FrameAllocSym = 6950 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6951 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6952 6953 Value *FP = I.getArgOperand(1); 6954 SDValue FPVal = getValue(FP); 6955 EVT PtrVT = FPVal.getValueType(); 6956 6957 // Create a MCSymbol for the label to avoid any target lowering 6958 // that would make this PC relative. 6959 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6960 SDValue OffsetVal = 6961 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6962 6963 // Add the offset to the FP. 6964 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6965 setValue(&I, Add); 6966 6967 return; 6968 } 6969 6970 case Intrinsic::eh_exceptionpointer: 6971 case Intrinsic::eh_exceptioncode: { 6972 // Get the exception pointer vreg, copy from it, and resize it to fit. 6973 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6974 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6975 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6976 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6977 SDValue N = 6978 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6979 if (Intrinsic == Intrinsic::eh_exceptioncode) 6980 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6981 setValue(&I, N); 6982 return; 6983 } 6984 case Intrinsic::xray_customevent: { 6985 // Here we want to make sure that the intrinsic behaves as if it has a 6986 // specific calling convention, and only for x86_64. 6987 // FIXME: Support other platforms later. 6988 const auto &Triple = DAG.getTarget().getTargetTriple(); 6989 if (Triple.getArch() != Triple::x86_64) 6990 return; 6991 6992 SDLoc DL = getCurSDLoc(); 6993 SmallVector<SDValue, 8> Ops; 6994 6995 // We want to say that we always want the arguments in registers. 6996 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6997 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6998 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6999 SDValue Chain = getRoot(); 7000 Ops.push_back(LogEntryVal); 7001 Ops.push_back(StrSizeVal); 7002 Ops.push_back(Chain); 7003 7004 // We need to enforce the calling convention for the callsite, so that 7005 // argument ordering is enforced correctly, and that register allocation can 7006 // see that some registers may be assumed clobbered and have to preserve 7007 // them across calls to the intrinsic. 7008 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7009 DL, NodeTys, Ops); 7010 SDValue patchableNode = SDValue(MN, 0); 7011 DAG.setRoot(patchableNode); 7012 setValue(&I, patchableNode); 7013 return; 7014 } 7015 case Intrinsic::xray_typedevent: { 7016 // Here we want to make sure that the intrinsic behaves as if it has a 7017 // specific calling convention, and only for x86_64. 7018 // FIXME: Support other platforms later. 7019 const auto &Triple = DAG.getTarget().getTargetTriple(); 7020 if (Triple.getArch() != Triple::x86_64) 7021 return; 7022 7023 SDLoc DL = getCurSDLoc(); 7024 SmallVector<SDValue, 8> Ops; 7025 7026 // We want to say that we always want the arguments in registers. 7027 // It's unclear to me how manipulating the selection DAG here forces callers 7028 // to provide arguments in registers instead of on the stack. 7029 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7030 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7031 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7032 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7033 SDValue Chain = getRoot(); 7034 Ops.push_back(LogTypeId); 7035 Ops.push_back(LogEntryVal); 7036 Ops.push_back(StrSizeVal); 7037 Ops.push_back(Chain); 7038 7039 // We need to enforce the calling convention for the callsite, so that 7040 // argument ordering is enforced correctly, and that register allocation can 7041 // see that some registers may be assumed clobbered and have to preserve 7042 // them across calls to the intrinsic. 7043 MachineSDNode *MN = DAG.getMachineNode( 7044 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 7045 SDValue patchableNode = SDValue(MN, 0); 7046 DAG.setRoot(patchableNode); 7047 setValue(&I, patchableNode); 7048 return; 7049 } 7050 case Intrinsic::experimental_deoptimize: 7051 LowerDeoptimizeCall(&I); 7052 return; 7053 case Intrinsic::experimental_stepvector: 7054 visitStepVector(I); 7055 return; 7056 case Intrinsic::vector_reduce_fadd: 7057 case Intrinsic::vector_reduce_fmul: 7058 case Intrinsic::vector_reduce_add: 7059 case Intrinsic::vector_reduce_mul: 7060 case Intrinsic::vector_reduce_and: 7061 case Intrinsic::vector_reduce_or: 7062 case Intrinsic::vector_reduce_xor: 7063 case Intrinsic::vector_reduce_smax: 7064 case Intrinsic::vector_reduce_smin: 7065 case Intrinsic::vector_reduce_umax: 7066 case Intrinsic::vector_reduce_umin: 7067 case Intrinsic::vector_reduce_fmax: 7068 case Intrinsic::vector_reduce_fmin: 7069 visitVectorReduce(I, Intrinsic); 7070 return; 7071 7072 case Intrinsic::icall_branch_funnel: { 7073 SmallVector<SDValue, 16> Ops; 7074 Ops.push_back(getValue(I.getArgOperand(0))); 7075 7076 int64_t Offset; 7077 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7078 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7079 if (!Base) 7080 report_fatal_error( 7081 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7082 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 7083 7084 struct BranchFunnelTarget { 7085 int64_t Offset; 7086 SDValue Target; 7087 }; 7088 SmallVector<BranchFunnelTarget, 8> Targets; 7089 7090 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 7091 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7092 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7093 if (ElemBase != Base) 7094 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7095 "to the same GlobalValue"); 7096 7097 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7098 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7099 if (!GA) 7100 report_fatal_error( 7101 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7102 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7103 GA->getGlobal(), getCurSDLoc(), 7104 Val.getValueType(), GA->getOffset())}); 7105 } 7106 llvm::sort(Targets, 7107 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7108 return T1.Offset < T2.Offset; 7109 }); 7110 7111 for (auto &T : Targets) { 7112 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 7113 Ops.push_back(T.Target); 7114 } 7115 7116 Ops.push_back(DAG.getRoot()); // Chain 7117 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 7118 getCurSDLoc(), MVT::Other, Ops), 7119 0); 7120 DAG.setRoot(N); 7121 setValue(&I, N); 7122 HasTailCall = true; 7123 return; 7124 } 7125 7126 case Intrinsic::wasm_landingpad_index: 7127 // Information this intrinsic contained has been transferred to 7128 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7129 // delete it now. 7130 return; 7131 7132 case Intrinsic::aarch64_settag: 7133 case Intrinsic::aarch64_settag_zero: { 7134 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7135 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7136 SDValue Val = TSI.EmitTargetCodeForSetTag( 7137 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 7138 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7139 ZeroMemory); 7140 DAG.setRoot(Val); 7141 setValue(&I, Val); 7142 return; 7143 } 7144 case Intrinsic::ptrmask: { 7145 SDValue Ptr = getValue(I.getOperand(0)); 7146 SDValue Const = getValue(I.getOperand(1)); 7147 7148 EVT PtrVT = Ptr.getValueType(); 7149 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 7150 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 7151 return; 7152 } 7153 case Intrinsic::get_active_lane_mask: { 7154 auto DL = getCurSDLoc(); 7155 SDValue Index = getValue(I.getOperand(0)); 7156 SDValue TripCount = getValue(I.getOperand(1)); 7157 Type *ElementTy = I.getOperand(0)->getType(); 7158 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7159 unsigned VecWidth = VT.getVectorNumElements(); 7160 7161 SmallVector<SDValue, 16> OpsTripCount; 7162 SmallVector<SDValue, 16> OpsIndex; 7163 SmallVector<SDValue, 16> OpsStepConstants; 7164 for (unsigned i = 0; i < VecWidth; i++) { 7165 OpsTripCount.push_back(TripCount); 7166 OpsIndex.push_back(Index); 7167 OpsStepConstants.push_back( 7168 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 7169 } 7170 7171 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 7172 7173 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 7174 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 7175 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 7176 SDValue VectorInduction = DAG.getNode( 7177 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 7178 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 7179 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 7180 VectorTripCount, ISD::CondCode::SETULT); 7181 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 7182 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 7183 SetCC)); 7184 return; 7185 } 7186 case Intrinsic::experimental_vector_insert: { 7187 auto DL = getCurSDLoc(); 7188 7189 SDValue Vec = getValue(I.getOperand(0)); 7190 SDValue SubVec = getValue(I.getOperand(1)); 7191 SDValue Index = getValue(I.getOperand(2)); 7192 7193 // The intrinsic's index type is i64, but the SDNode requires an index type 7194 // suitable for the target. Convert the index as required. 7195 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7196 if (Index.getValueType() != VectorIdxTy) 7197 Index = DAG.getVectorIdxConstant( 7198 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7199 7200 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7201 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec, 7202 Index)); 7203 return; 7204 } 7205 case Intrinsic::experimental_vector_extract: { 7206 auto DL = getCurSDLoc(); 7207 7208 SDValue Vec = getValue(I.getOperand(0)); 7209 SDValue Index = getValue(I.getOperand(1)); 7210 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7211 7212 // The intrinsic's index type is i64, but the SDNode requires an index type 7213 // suitable for the target. Convert the index as required. 7214 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7215 if (Index.getValueType() != VectorIdxTy) 7216 Index = DAG.getVectorIdxConstant( 7217 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7218 7219 setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index)); 7220 return; 7221 } 7222 case Intrinsic::experimental_vector_reverse: 7223 visitVectorReverse(I); 7224 return; 7225 case Intrinsic::experimental_vector_splice: 7226 visitVectorSplice(I); 7227 return; 7228 } 7229 } 7230 7231 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7232 const ConstrainedFPIntrinsic &FPI) { 7233 SDLoc sdl = getCurSDLoc(); 7234 7235 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7236 SmallVector<EVT, 4> ValueVTs; 7237 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7238 ValueVTs.push_back(MVT::Other); // Out chain 7239 7240 // We do not need to serialize constrained FP intrinsics against 7241 // each other or against (nonvolatile) loads, so they can be 7242 // chained like loads. 7243 SDValue Chain = DAG.getRoot(); 7244 SmallVector<SDValue, 4> Opers; 7245 Opers.push_back(Chain); 7246 if (FPI.isUnaryOp()) { 7247 Opers.push_back(getValue(FPI.getArgOperand(0))); 7248 } else if (FPI.isTernaryOp()) { 7249 Opers.push_back(getValue(FPI.getArgOperand(0))); 7250 Opers.push_back(getValue(FPI.getArgOperand(1))); 7251 Opers.push_back(getValue(FPI.getArgOperand(2))); 7252 } else { 7253 Opers.push_back(getValue(FPI.getArgOperand(0))); 7254 Opers.push_back(getValue(FPI.getArgOperand(1))); 7255 } 7256 7257 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7258 assert(Result.getNode()->getNumValues() == 2); 7259 7260 // Push node to the appropriate list so that future instructions can be 7261 // chained up correctly. 7262 SDValue OutChain = Result.getValue(1); 7263 switch (EB) { 7264 case fp::ExceptionBehavior::ebIgnore: 7265 // The only reason why ebIgnore nodes still need to be chained is that 7266 // they might depend on the current rounding mode, and therefore must 7267 // not be moved across instruction that may change that mode. 7268 LLVM_FALLTHROUGH; 7269 case fp::ExceptionBehavior::ebMayTrap: 7270 // These must not be moved across calls or instructions that may change 7271 // floating-point exception masks. 7272 PendingConstrainedFP.push_back(OutChain); 7273 break; 7274 case fp::ExceptionBehavior::ebStrict: 7275 // These must not be moved across calls or instructions that may change 7276 // floating-point exception masks or read floating-point exception flags. 7277 // In addition, they cannot be optimized out even if unused. 7278 PendingConstrainedFPStrict.push_back(OutChain); 7279 break; 7280 } 7281 }; 7282 7283 SDVTList VTs = DAG.getVTList(ValueVTs); 7284 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7285 7286 SDNodeFlags Flags; 7287 if (EB == fp::ExceptionBehavior::ebIgnore) 7288 Flags.setNoFPExcept(true); 7289 7290 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7291 Flags.copyFMF(*FPOp); 7292 7293 unsigned Opcode; 7294 switch (FPI.getIntrinsicID()) { 7295 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7296 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7297 case Intrinsic::INTRINSIC: \ 7298 Opcode = ISD::STRICT_##DAGN; \ 7299 break; 7300 #include "llvm/IR/ConstrainedOps.def" 7301 case Intrinsic::experimental_constrained_fmuladd: { 7302 Opcode = ISD::STRICT_FMA; 7303 // Break fmuladd into fmul and fadd. 7304 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7305 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7306 ValueVTs[0])) { 7307 Opers.pop_back(); 7308 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7309 pushOutChain(Mul, EB); 7310 Opcode = ISD::STRICT_FADD; 7311 Opers.clear(); 7312 Opers.push_back(Mul.getValue(1)); 7313 Opers.push_back(Mul.getValue(0)); 7314 Opers.push_back(getValue(FPI.getArgOperand(2))); 7315 } 7316 break; 7317 } 7318 } 7319 7320 // A few strict DAG nodes carry additional operands that are not 7321 // set up by the default code above. 7322 switch (Opcode) { 7323 default: break; 7324 case ISD::STRICT_FP_ROUND: 7325 Opers.push_back( 7326 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7327 break; 7328 case ISD::STRICT_FSETCC: 7329 case ISD::STRICT_FSETCCS: { 7330 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7331 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7332 if (TM.Options.NoNaNsFPMath) 7333 Condition = getFCmpCodeWithoutNaN(Condition); 7334 Opers.push_back(DAG.getCondCode(Condition)); 7335 break; 7336 } 7337 } 7338 7339 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7340 pushOutChain(Result, EB); 7341 7342 SDValue FPResult = Result.getValue(0); 7343 setValue(&FPI, FPResult); 7344 } 7345 7346 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7347 Optional<unsigned> ResOPC; 7348 switch (VPIntrin.getIntrinsicID()) { 7349 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN: 7350 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID; 7351 #define END_REGISTER_VP_INTRINSIC(...) break; 7352 #include "llvm/IR/VPIntrinsics.def" 7353 } 7354 7355 if (!ResOPC.hasValue()) 7356 llvm_unreachable( 7357 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7358 7359 return ResOPC.getValue(); 7360 } 7361 7362 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7363 const VPIntrinsic &VPIntrin) { 7364 SDLoc DL = getCurSDLoc(); 7365 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7366 7367 SmallVector<EVT, 4> ValueVTs; 7368 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7369 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7370 SDVTList VTs = DAG.getVTList(ValueVTs); 7371 7372 auto EVLParamPos = 7373 VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID()); 7374 7375 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7376 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7377 "Unexpected target EVL type"); 7378 7379 // Request operands. 7380 SmallVector<SDValue, 7> OpValues; 7381 for (unsigned I = 0; I < VPIntrin.getNumArgOperands(); ++I) { 7382 auto Op = getValue(VPIntrin.getArgOperand(I)); 7383 if (I == EVLParamPos) 7384 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7385 OpValues.push_back(Op); 7386 } 7387 7388 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7389 setValue(&VPIntrin, Result); 7390 } 7391 7392 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7393 const BasicBlock *EHPadBB, 7394 MCSymbol *&BeginLabel) { 7395 MachineFunction &MF = DAG.getMachineFunction(); 7396 MachineModuleInfo &MMI = MF.getMMI(); 7397 7398 // Insert a label before the invoke call to mark the try range. This can be 7399 // used to detect deletion of the invoke via the MachineModuleInfo. 7400 BeginLabel = MMI.getContext().createTempSymbol(); 7401 7402 // For SjLj, keep track of which landing pads go with which invokes 7403 // so as to maintain the ordering of pads in the LSDA. 7404 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7405 if (CallSiteIndex) { 7406 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7407 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7408 7409 // Now that the call site is handled, stop tracking it. 7410 MMI.setCurrentCallSite(0); 7411 } 7412 7413 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7414 } 7415 7416 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7417 const BasicBlock *EHPadBB, 7418 MCSymbol *BeginLabel) { 7419 assert(BeginLabel && "BeginLabel should've been set"); 7420 7421 MachineFunction &MF = DAG.getMachineFunction(); 7422 MachineModuleInfo &MMI = MF.getMMI(); 7423 7424 // Insert a label at the end of the invoke call to mark the try range. This 7425 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7426 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7427 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7428 7429 // Inform MachineModuleInfo of range. 7430 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7431 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7432 // actually use outlined funclets and their LSDA info style. 7433 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7434 assert(II && "II should've been set"); 7435 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7436 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7437 } else if (!isScopedEHPersonality(Pers)) { 7438 assert(EHPadBB); 7439 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7440 } 7441 7442 return Chain; 7443 } 7444 7445 std::pair<SDValue, SDValue> 7446 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7447 const BasicBlock *EHPadBB) { 7448 MCSymbol *BeginLabel = nullptr; 7449 7450 if (EHPadBB) { 7451 // Both PendingLoads and PendingExports must be flushed here; 7452 // this call might not return. 7453 (void)getRoot(); 7454 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7455 CLI.setChain(getRoot()); 7456 } 7457 7458 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7459 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7460 7461 assert((CLI.IsTailCall || Result.second.getNode()) && 7462 "Non-null chain expected with non-tail call!"); 7463 assert((Result.second.getNode() || !Result.first.getNode()) && 7464 "Null value expected with tail call!"); 7465 7466 if (!Result.second.getNode()) { 7467 // As a special case, a null chain means that a tail call has been emitted 7468 // and the DAG root is already updated. 7469 HasTailCall = true; 7470 7471 // Since there's no actual continuation from this block, nothing can be 7472 // relying on us setting vregs for them. 7473 PendingExports.clear(); 7474 } else { 7475 DAG.setRoot(Result.second); 7476 } 7477 7478 if (EHPadBB) { 7479 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7480 BeginLabel)); 7481 } 7482 7483 return Result; 7484 } 7485 7486 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7487 bool isTailCall, 7488 bool isMustTailCall, 7489 const BasicBlock *EHPadBB) { 7490 auto &DL = DAG.getDataLayout(); 7491 FunctionType *FTy = CB.getFunctionType(); 7492 Type *RetTy = CB.getType(); 7493 7494 TargetLowering::ArgListTy Args; 7495 Args.reserve(CB.arg_size()); 7496 7497 const Value *SwiftErrorVal = nullptr; 7498 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7499 7500 if (isTailCall) { 7501 // Avoid emitting tail calls in functions with the disable-tail-calls 7502 // attribute. 7503 auto *Caller = CB.getParent()->getParent(); 7504 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7505 "true" && !isMustTailCall) 7506 isTailCall = false; 7507 7508 // We can't tail call inside a function with a swifterror argument. Lowering 7509 // does not support this yet. It would have to move into the swifterror 7510 // register before the call. 7511 if (TLI.supportSwiftError() && 7512 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7513 isTailCall = false; 7514 } 7515 7516 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7517 TargetLowering::ArgListEntry Entry; 7518 const Value *V = *I; 7519 7520 // Skip empty types 7521 if (V->getType()->isEmptyTy()) 7522 continue; 7523 7524 SDValue ArgNode = getValue(V); 7525 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7526 7527 Entry.setAttributes(&CB, I - CB.arg_begin()); 7528 7529 // Use swifterror virtual register as input to the call. 7530 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7531 SwiftErrorVal = V; 7532 // We find the virtual register for the actual swifterror argument. 7533 // Instead of using the Value, we use the virtual register instead. 7534 Entry.Node = 7535 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7536 EVT(TLI.getPointerTy(DL))); 7537 } 7538 7539 Args.push_back(Entry); 7540 7541 // If we have an explicit sret argument that is an Instruction, (i.e., it 7542 // might point to function-local memory), we can't meaningfully tail-call. 7543 if (Entry.IsSRet && isa<Instruction>(V)) 7544 isTailCall = false; 7545 } 7546 7547 // If call site has a cfguardtarget operand bundle, create and add an 7548 // additional ArgListEntry. 7549 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7550 TargetLowering::ArgListEntry Entry; 7551 Value *V = Bundle->Inputs[0]; 7552 SDValue ArgNode = getValue(V); 7553 Entry.Node = ArgNode; 7554 Entry.Ty = V->getType(); 7555 Entry.IsCFGuardTarget = true; 7556 Args.push_back(Entry); 7557 } 7558 7559 // Check if target-independent constraints permit a tail call here. 7560 // Target-dependent constraints are checked within TLI->LowerCallTo. 7561 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7562 isTailCall = false; 7563 7564 // Disable tail calls if there is an swifterror argument. Targets have not 7565 // been updated to support tail calls. 7566 if (TLI.supportSwiftError() && SwiftErrorVal) 7567 isTailCall = false; 7568 7569 TargetLowering::CallLoweringInfo CLI(DAG); 7570 CLI.setDebugLoc(getCurSDLoc()) 7571 .setChain(getRoot()) 7572 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7573 .setTailCall(isTailCall) 7574 .setConvergent(CB.isConvergent()) 7575 .setIsPreallocated( 7576 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7577 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7578 7579 if (Result.first.getNode()) { 7580 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7581 setValue(&CB, Result.first); 7582 } 7583 7584 // The last element of CLI.InVals has the SDValue for swifterror return. 7585 // Here we copy it to a virtual register and update SwiftErrorMap for 7586 // book-keeping. 7587 if (SwiftErrorVal && TLI.supportSwiftError()) { 7588 // Get the last element of InVals. 7589 SDValue Src = CLI.InVals.back(); 7590 Register VReg = 7591 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7592 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7593 DAG.setRoot(CopyNode); 7594 } 7595 } 7596 7597 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7598 SelectionDAGBuilder &Builder) { 7599 // Check to see if this load can be trivially constant folded, e.g. if the 7600 // input is from a string literal. 7601 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7602 // Cast pointer to the type we really want to load. 7603 Type *LoadTy = 7604 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7605 if (LoadVT.isVector()) 7606 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7607 7608 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7609 PointerType::getUnqual(LoadTy)); 7610 7611 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7612 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7613 return Builder.getValue(LoadCst); 7614 } 7615 7616 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7617 // still constant memory, the input chain can be the entry node. 7618 SDValue Root; 7619 bool ConstantMemory = false; 7620 7621 // Do not serialize (non-volatile) loads of constant memory with anything. 7622 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7623 Root = Builder.DAG.getEntryNode(); 7624 ConstantMemory = true; 7625 } else { 7626 // Do not serialize non-volatile loads against each other. 7627 Root = Builder.DAG.getRoot(); 7628 } 7629 7630 SDValue Ptr = Builder.getValue(PtrVal); 7631 SDValue LoadVal = 7632 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7633 MachinePointerInfo(PtrVal), Align(1)); 7634 7635 if (!ConstantMemory) 7636 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7637 return LoadVal; 7638 } 7639 7640 /// Record the value for an instruction that produces an integer result, 7641 /// converting the type where necessary. 7642 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7643 SDValue Value, 7644 bool IsSigned) { 7645 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7646 I.getType(), true); 7647 if (IsSigned) 7648 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7649 else 7650 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7651 setValue(&I, Value); 7652 } 7653 7654 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7655 /// true and lower it. Otherwise return false, and it will be lowered like a 7656 /// normal call. 7657 /// The caller already checked that \p I calls the appropriate LibFunc with a 7658 /// correct prototype. 7659 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7660 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7661 const Value *Size = I.getArgOperand(2); 7662 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7663 if (CSize && CSize->getZExtValue() == 0) { 7664 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7665 I.getType(), true); 7666 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7667 return true; 7668 } 7669 7670 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7671 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7672 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7673 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7674 if (Res.first.getNode()) { 7675 processIntegerCallValue(I, Res.first, true); 7676 PendingLoads.push_back(Res.second); 7677 return true; 7678 } 7679 7680 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7681 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7682 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7683 return false; 7684 7685 // If the target has a fast compare for the given size, it will return a 7686 // preferred load type for that size. Require that the load VT is legal and 7687 // that the target supports unaligned loads of that type. Otherwise, return 7688 // INVALID. 7689 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7690 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7691 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7692 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7693 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7694 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7695 // TODO: Check alignment of src and dest ptrs. 7696 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7697 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7698 if (!TLI.isTypeLegal(LVT) || 7699 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7700 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7701 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7702 } 7703 7704 return LVT; 7705 }; 7706 7707 // This turns into unaligned loads. We only do this if the target natively 7708 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7709 // we'll only produce a small number of byte loads. 7710 MVT LoadVT; 7711 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7712 switch (NumBitsToCompare) { 7713 default: 7714 return false; 7715 case 16: 7716 LoadVT = MVT::i16; 7717 break; 7718 case 32: 7719 LoadVT = MVT::i32; 7720 break; 7721 case 64: 7722 case 128: 7723 case 256: 7724 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7725 break; 7726 } 7727 7728 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7729 return false; 7730 7731 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7732 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7733 7734 // Bitcast to a wide integer type if the loads are vectors. 7735 if (LoadVT.isVector()) { 7736 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7737 LoadL = DAG.getBitcast(CmpVT, LoadL); 7738 LoadR = DAG.getBitcast(CmpVT, LoadR); 7739 } 7740 7741 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7742 processIntegerCallValue(I, Cmp, false); 7743 return true; 7744 } 7745 7746 /// See if we can lower a memchr call into an optimized form. If so, return 7747 /// true and lower it. Otherwise return false, and it will be lowered like a 7748 /// normal call. 7749 /// The caller already checked that \p I calls the appropriate LibFunc with a 7750 /// correct prototype. 7751 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7752 const Value *Src = I.getArgOperand(0); 7753 const Value *Char = I.getArgOperand(1); 7754 const Value *Length = I.getArgOperand(2); 7755 7756 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7757 std::pair<SDValue, SDValue> Res = 7758 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7759 getValue(Src), getValue(Char), getValue(Length), 7760 MachinePointerInfo(Src)); 7761 if (Res.first.getNode()) { 7762 setValue(&I, Res.first); 7763 PendingLoads.push_back(Res.second); 7764 return true; 7765 } 7766 7767 return false; 7768 } 7769 7770 /// See if we can lower a mempcpy call into an optimized form. If so, return 7771 /// true and lower it. Otherwise return false, and it will be lowered like a 7772 /// normal call. 7773 /// The caller already checked that \p I calls the appropriate LibFunc with a 7774 /// correct prototype. 7775 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7776 SDValue Dst = getValue(I.getArgOperand(0)); 7777 SDValue Src = getValue(I.getArgOperand(1)); 7778 SDValue Size = getValue(I.getArgOperand(2)); 7779 7780 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7781 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7782 // DAG::getMemcpy needs Alignment to be defined. 7783 Align Alignment = std::min(DstAlign, SrcAlign); 7784 7785 bool isVol = false; 7786 SDLoc sdl = getCurSDLoc(); 7787 7788 // In the mempcpy context we need to pass in a false value for isTailCall 7789 // because the return pointer needs to be adjusted by the size of 7790 // the copied memory. 7791 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7792 AAMDNodes AAInfo; 7793 I.getAAMetadata(AAInfo); 7794 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7795 /*isTailCall=*/false, 7796 MachinePointerInfo(I.getArgOperand(0)), 7797 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 7798 assert(MC.getNode() != nullptr && 7799 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7800 DAG.setRoot(MC); 7801 7802 // Check if Size needs to be truncated or extended. 7803 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7804 7805 // Adjust return pointer to point just past the last dst byte. 7806 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7807 Dst, Size); 7808 setValue(&I, DstPlusSize); 7809 return true; 7810 } 7811 7812 /// See if we can lower a strcpy call into an optimized form. If so, return 7813 /// true and lower it, otherwise return false and it will be lowered like a 7814 /// normal call. 7815 /// The caller already checked that \p I calls the appropriate LibFunc with a 7816 /// correct prototype. 7817 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7818 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7819 7820 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7821 std::pair<SDValue, SDValue> Res = 7822 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7823 getValue(Arg0), getValue(Arg1), 7824 MachinePointerInfo(Arg0), 7825 MachinePointerInfo(Arg1), isStpcpy); 7826 if (Res.first.getNode()) { 7827 setValue(&I, Res.first); 7828 DAG.setRoot(Res.second); 7829 return true; 7830 } 7831 7832 return false; 7833 } 7834 7835 /// See if we can lower a strcmp call into an optimized form. If so, return 7836 /// true and lower it, otherwise return false and it will be lowered like a 7837 /// normal call. 7838 /// The caller already checked that \p I calls the appropriate LibFunc with a 7839 /// correct prototype. 7840 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7841 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7842 7843 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7844 std::pair<SDValue, SDValue> Res = 7845 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7846 getValue(Arg0), getValue(Arg1), 7847 MachinePointerInfo(Arg0), 7848 MachinePointerInfo(Arg1)); 7849 if (Res.first.getNode()) { 7850 processIntegerCallValue(I, Res.first, true); 7851 PendingLoads.push_back(Res.second); 7852 return true; 7853 } 7854 7855 return false; 7856 } 7857 7858 /// See if we can lower a strlen call into an optimized form. If so, return 7859 /// true and lower it, otherwise return false and it will be lowered like a 7860 /// normal call. 7861 /// The caller already checked that \p I calls the appropriate LibFunc with a 7862 /// correct prototype. 7863 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7864 const Value *Arg0 = I.getArgOperand(0); 7865 7866 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7867 std::pair<SDValue, SDValue> Res = 7868 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7869 getValue(Arg0), MachinePointerInfo(Arg0)); 7870 if (Res.first.getNode()) { 7871 processIntegerCallValue(I, Res.first, false); 7872 PendingLoads.push_back(Res.second); 7873 return true; 7874 } 7875 7876 return false; 7877 } 7878 7879 /// See if we can lower a strnlen call into an optimized form. If so, return 7880 /// true and lower it, otherwise return false and it will be lowered like a 7881 /// normal call. 7882 /// The caller already checked that \p I calls the appropriate LibFunc with a 7883 /// correct prototype. 7884 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7885 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7886 7887 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7888 std::pair<SDValue, SDValue> Res = 7889 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7890 getValue(Arg0), getValue(Arg1), 7891 MachinePointerInfo(Arg0)); 7892 if (Res.first.getNode()) { 7893 processIntegerCallValue(I, Res.first, false); 7894 PendingLoads.push_back(Res.second); 7895 return true; 7896 } 7897 7898 return false; 7899 } 7900 7901 /// See if we can lower a unary floating-point operation into an SDNode with 7902 /// the specified Opcode. If so, return true and lower it, otherwise return 7903 /// false and it will be lowered like a normal call. 7904 /// The caller already checked that \p I calls the appropriate LibFunc with a 7905 /// correct prototype. 7906 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7907 unsigned Opcode) { 7908 // We already checked this call's prototype; verify it doesn't modify errno. 7909 if (!I.onlyReadsMemory()) 7910 return false; 7911 7912 SDNodeFlags Flags; 7913 Flags.copyFMF(cast<FPMathOperator>(I)); 7914 7915 SDValue Tmp = getValue(I.getArgOperand(0)); 7916 setValue(&I, 7917 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7918 return true; 7919 } 7920 7921 /// See if we can lower a binary floating-point operation into an SDNode with 7922 /// the specified Opcode. If so, return true and lower it. Otherwise return 7923 /// false, and it will be lowered like a normal call. 7924 /// The caller already checked that \p I calls the appropriate LibFunc with a 7925 /// correct prototype. 7926 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7927 unsigned Opcode) { 7928 // We already checked this call's prototype; verify it doesn't modify errno. 7929 if (!I.onlyReadsMemory()) 7930 return false; 7931 7932 SDNodeFlags Flags; 7933 Flags.copyFMF(cast<FPMathOperator>(I)); 7934 7935 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7936 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7937 EVT VT = Tmp0.getValueType(); 7938 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7939 return true; 7940 } 7941 7942 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7943 // Handle inline assembly differently. 7944 if (I.isInlineAsm()) { 7945 visitInlineAsm(I); 7946 return; 7947 } 7948 7949 if (Function *F = I.getCalledFunction()) { 7950 if (F->isDeclaration()) { 7951 // Is this an LLVM intrinsic or a target-specific intrinsic? 7952 unsigned IID = F->getIntrinsicID(); 7953 if (!IID) 7954 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7955 IID = II->getIntrinsicID(F); 7956 7957 if (IID) { 7958 visitIntrinsicCall(I, IID); 7959 return; 7960 } 7961 } 7962 7963 // Check for well-known libc/libm calls. If the function is internal, it 7964 // can't be a library call. Don't do the check if marked as nobuiltin for 7965 // some reason or the call site requires strict floating point semantics. 7966 LibFunc Func; 7967 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7968 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7969 LibInfo->hasOptimizedCodeGen(Func)) { 7970 switch (Func) { 7971 default: break; 7972 case LibFunc_bcmp: 7973 if (visitMemCmpBCmpCall(I)) 7974 return; 7975 break; 7976 case LibFunc_copysign: 7977 case LibFunc_copysignf: 7978 case LibFunc_copysignl: 7979 // We already checked this call's prototype; verify it doesn't modify 7980 // errno. 7981 if (I.onlyReadsMemory()) { 7982 SDValue LHS = getValue(I.getArgOperand(0)); 7983 SDValue RHS = getValue(I.getArgOperand(1)); 7984 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7985 LHS.getValueType(), LHS, RHS)); 7986 return; 7987 } 7988 break; 7989 case LibFunc_fabs: 7990 case LibFunc_fabsf: 7991 case LibFunc_fabsl: 7992 if (visitUnaryFloatCall(I, ISD::FABS)) 7993 return; 7994 break; 7995 case LibFunc_fmin: 7996 case LibFunc_fminf: 7997 case LibFunc_fminl: 7998 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7999 return; 8000 break; 8001 case LibFunc_fmax: 8002 case LibFunc_fmaxf: 8003 case LibFunc_fmaxl: 8004 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8005 return; 8006 break; 8007 case LibFunc_sin: 8008 case LibFunc_sinf: 8009 case LibFunc_sinl: 8010 if (visitUnaryFloatCall(I, ISD::FSIN)) 8011 return; 8012 break; 8013 case LibFunc_cos: 8014 case LibFunc_cosf: 8015 case LibFunc_cosl: 8016 if (visitUnaryFloatCall(I, ISD::FCOS)) 8017 return; 8018 break; 8019 case LibFunc_sqrt: 8020 case LibFunc_sqrtf: 8021 case LibFunc_sqrtl: 8022 case LibFunc_sqrt_finite: 8023 case LibFunc_sqrtf_finite: 8024 case LibFunc_sqrtl_finite: 8025 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8026 return; 8027 break; 8028 case LibFunc_floor: 8029 case LibFunc_floorf: 8030 case LibFunc_floorl: 8031 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8032 return; 8033 break; 8034 case LibFunc_nearbyint: 8035 case LibFunc_nearbyintf: 8036 case LibFunc_nearbyintl: 8037 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8038 return; 8039 break; 8040 case LibFunc_ceil: 8041 case LibFunc_ceilf: 8042 case LibFunc_ceill: 8043 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8044 return; 8045 break; 8046 case LibFunc_rint: 8047 case LibFunc_rintf: 8048 case LibFunc_rintl: 8049 if (visitUnaryFloatCall(I, ISD::FRINT)) 8050 return; 8051 break; 8052 case LibFunc_round: 8053 case LibFunc_roundf: 8054 case LibFunc_roundl: 8055 if (visitUnaryFloatCall(I, ISD::FROUND)) 8056 return; 8057 break; 8058 case LibFunc_trunc: 8059 case LibFunc_truncf: 8060 case LibFunc_truncl: 8061 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8062 return; 8063 break; 8064 case LibFunc_log2: 8065 case LibFunc_log2f: 8066 case LibFunc_log2l: 8067 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8068 return; 8069 break; 8070 case LibFunc_exp2: 8071 case LibFunc_exp2f: 8072 case LibFunc_exp2l: 8073 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8074 return; 8075 break; 8076 case LibFunc_memcmp: 8077 if (visitMemCmpBCmpCall(I)) 8078 return; 8079 break; 8080 case LibFunc_mempcpy: 8081 if (visitMemPCpyCall(I)) 8082 return; 8083 break; 8084 case LibFunc_memchr: 8085 if (visitMemChrCall(I)) 8086 return; 8087 break; 8088 case LibFunc_strcpy: 8089 if (visitStrCpyCall(I, false)) 8090 return; 8091 break; 8092 case LibFunc_stpcpy: 8093 if (visitStrCpyCall(I, true)) 8094 return; 8095 break; 8096 case LibFunc_strcmp: 8097 if (visitStrCmpCall(I)) 8098 return; 8099 break; 8100 case LibFunc_strlen: 8101 if (visitStrLenCall(I)) 8102 return; 8103 break; 8104 case LibFunc_strnlen: 8105 if (visitStrNLenCall(I)) 8106 return; 8107 break; 8108 } 8109 } 8110 } 8111 8112 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8113 // have to do anything here to lower funclet bundles. 8114 // CFGuardTarget bundles are lowered in LowerCallTo. 8115 assert(!I.hasOperandBundlesOtherThan( 8116 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8117 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8118 LLVMContext::OB_clang_arc_attachedcall}) && 8119 "Cannot lower calls with arbitrary operand bundles!"); 8120 8121 SDValue Callee = getValue(I.getCalledOperand()); 8122 8123 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8124 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8125 else 8126 // Check if we can potentially perform a tail call. More detailed checking 8127 // is be done within LowerCallTo, after more information about the call is 8128 // known. 8129 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8130 } 8131 8132 namespace { 8133 8134 /// AsmOperandInfo - This contains information for each constraint that we are 8135 /// lowering. 8136 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8137 public: 8138 /// CallOperand - If this is the result output operand or a clobber 8139 /// this is null, otherwise it is the incoming operand to the CallInst. 8140 /// This gets modified as the asm is processed. 8141 SDValue CallOperand; 8142 8143 /// AssignedRegs - If this is a register or register class operand, this 8144 /// contains the set of register corresponding to the operand. 8145 RegsForValue AssignedRegs; 8146 8147 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8148 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8149 } 8150 8151 /// Whether or not this operand accesses memory 8152 bool hasMemory(const TargetLowering &TLI) const { 8153 // Indirect operand accesses access memory. 8154 if (isIndirect) 8155 return true; 8156 8157 for (const auto &Code : Codes) 8158 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8159 return true; 8160 8161 return false; 8162 } 8163 8164 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8165 /// corresponds to. If there is no Value* for this operand, it returns 8166 /// MVT::Other. 8167 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8168 const DataLayout &DL) const { 8169 if (!CallOperandVal) return MVT::Other; 8170 8171 if (isa<BasicBlock>(CallOperandVal)) 8172 return TLI.getProgramPointerTy(DL); 8173 8174 llvm::Type *OpTy = CallOperandVal->getType(); 8175 8176 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8177 // If this is an indirect operand, the operand is a pointer to the 8178 // accessed type. 8179 if (isIndirect) { 8180 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 8181 if (!PtrTy) 8182 report_fatal_error("Indirect operand for inline asm not a pointer!"); 8183 OpTy = PtrTy->getElementType(); 8184 } 8185 8186 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8187 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8188 if (STy->getNumElements() == 1) 8189 OpTy = STy->getElementType(0); 8190 8191 // If OpTy is not a single value, it may be a struct/union that we 8192 // can tile with integers. 8193 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8194 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8195 switch (BitSize) { 8196 default: break; 8197 case 1: 8198 case 8: 8199 case 16: 8200 case 32: 8201 case 64: 8202 case 128: 8203 OpTy = IntegerType::get(Context, BitSize); 8204 break; 8205 } 8206 } 8207 8208 return TLI.getAsmOperandValueType(DL, OpTy, true); 8209 } 8210 }; 8211 8212 8213 } // end anonymous namespace 8214 8215 /// Make sure that the output operand \p OpInfo and its corresponding input 8216 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8217 /// out). 8218 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8219 SDISelAsmOperandInfo &MatchingOpInfo, 8220 SelectionDAG &DAG) { 8221 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8222 return; 8223 8224 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8225 const auto &TLI = DAG.getTargetLoweringInfo(); 8226 8227 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8228 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8229 OpInfo.ConstraintVT); 8230 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8231 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8232 MatchingOpInfo.ConstraintVT); 8233 if ((OpInfo.ConstraintVT.isInteger() != 8234 MatchingOpInfo.ConstraintVT.isInteger()) || 8235 (MatchRC.second != InputRC.second)) { 8236 // FIXME: error out in a more elegant fashion 8237 report_fatal_error("Unsupported asm: input constraint" 8238 " with a matching output constraint of" 8239 " incompatible type!"); 8240 } 8241 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8242 } 8243 8244 /// Get a direct memory input to behave well as an indirect operand. 8245 /// This may introduce stores, hence the need for a \p Chain. 8246 /// \return The (possibly updated) chain. 8247 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8248 SDISelAsmOperandInfo &OpInfo, 8249 SelectionDAG &DAG) { 8250 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8251 8252 // If we don't have an indirect input, put it in the constpool if we can, 8253 // otherwise spill it to a stack slot. 8254 // TODO: This isn't quite right. We need to handle these according to 8255 // the addressing mode that the constraint wants. Also, this may take 8256 // an additional register for the computation and we don't want that 8257 // either. 8258 8259 // If the operand is a float, integer, or vector constant, spill to a 8260 // constant pool entry to get its address. 8261 const Value *OpVal = OpInfo.CallOperandVal; 8262 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8263 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8264 OpInfo.CallOperand = DAG.getConstantPool( 8265 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8266 return Chain; 8267 } 8268 8269 // Otherwise, create a stack slot and emit a store to it before the asm. 8270 Type *Ty = OpVal->getType(); 8271 auto &DL = DAG.getDataLayout(); 8272 uint64_t TySize = DL.getTypeAllocSize(Ty); 8273 MachineFunction &MF = DAG.getMachineFunction(); 8274 int SSFI = MF.getFrameInfo().CreateStackObject( 8275 TySize, DL.getPrefTypeAlign(Ty), false); 8276 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8277 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8278 MachinePointerInfo::getFixedStack(MF, SSFI), 8279 TLI.getMemValueType(DL, Ty)); 8280 OpInfo.CallOperand = StackSlot; 8281 8282 return Chain; 8283 } 8284 8285 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8286 /// specified operand. We prefer to assign virtual registers, to allow the 8287 /// register allocator to handle the assignment process. However, if the asm 8288 /// uses features that we can't model on machineinstrs, we have SDISel do the 8289 /// allocation. This produces generally horrible, but correct, code. 8290 /// 8291 /// OpInfo describes the operand 8292 /// RefOpInfo describes the matching operand if any, the operand otherwise 8293 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8294 SDISelAsmOperandInfo &OpInfo, 8295 SDISelAsmOperandInfo &RefOpInfo) { 8296 LLVMContext &Context = *DAG.getContext(); 8297 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8298 8299 MachineFunction &MF = DAG.getMachineFunction(); 8300 SmallVector<unsigned, 4> Regs; 8301 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8302 8303 // No work to do for memory operations. 8304 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8305 return; 8306 8307 // If this is a constraint for a single physreg, or a constraint for a 8308 // register class, find it. 8309 unsigned AssignedReg; 8310 const TargetRegisterClass *RC; 8311 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8312 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8313 // RC is unset only on failure. Return immediately. 8314 if (!RC) 8315 return; 8316 8317 // Get the actual register value type. This is important, because the user 8318 // may have asked for (e.g.) the AX register in i32 type. We need to 8319 // remember that AX is actually i16 to get the right extension. 8320 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8321 8322 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8323 // If this is an FP operand in an integer register (or visa versa), or more 8324 // generally if the operand value disagrees with the register class we plan 8325 // to stick it in, fix the operand type. 8326 // 8327 // If this is an input value, the bitcast to the new type is done now. 8328 // Bitcast for output value is done at the end of visitInlineAsm(). 8329 if ((OpInfo.Type == InlineAsm::isOutput || 8330 OpInfo.Type == InlineAsm::isInput) && 8331 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8332 // Try to convert to the first EVT that the reg class contains. If the 8333 // types are identical size, use a bitcast to convert (e.g. two differing 8334 // vector types). Note: output bitcast is done at the end of 8335 // visitInlineAsm(). 8336 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8337 // Exclude indirect inputs while they are unsupported because the code 8338 // to perform the load is missing and thus OpInfo.CallOperand still 8339 // refers to the input address rather than the pointed-to value. 8340 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8341 OpInfo.CallOperand = 8342 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8343 OpInfo.ConstraintVT = RegVT; 8344 // If the operand is an FP value and we want it in integer registers, 8345 // use the corresponding integer type. This turns an f64 value into 8346 // i64, which can be passed with two i32 values on a 32-bit machine. 8347 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8348 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8349 if (OpInfo.Type == InlineAsm::isInput) 8350 OpInfo.CallOperand = 8351 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8352 OpInfo.ConstraintVT = VT; 8353 } 8354 } 8355 } 8356 8357 // No need to allocate a matching input constraint since the constraint it's 8358 // matching to has already been allocated. 8359 if (OpInfo.isMatchingInputConstraint()) 8360 return; 8361 8362 EVT ValueVT = OpInfo.ConstraintVT; 8363 if (OpInfo.ConstraintVT == MVT::Other) 8364 ValueVT = RegVT; 8365 8366 // Initialize NumRegs. 8367 unsigned NumRegs = 1; 8368 if (OpInfo.ConstraintVT != MVT::Other) 8369 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8370 8371 // If this is a constraint for a specific physical register, like {r17}, 8372 // assign it now. 8373 8374 // If this associated to a specific register, initialize iterator to correct 8375 // place. If virtual, make sure we have enough registers 8376 8377 // Initialize iterator if necessary 8378 TargetRegisterClass::iterator I = RC->begin(); 8379 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8380 8381 // Do not check for single registers. 8382 if (AssignedReg) { 8383 for (; *I != AssignedReg; ++I) 8384 assert(I != RC->end() && "AssignedReg should be member of RC"); 8385 } 8386 8387 for (; NumRegs; --NumRegs, ++I) { 8388 assert(I != RC->end() && "Ran out of registers to allocate!"); 8389 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8390 Regs.push_back(R); 8391 } 8392 8393 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8394 } 8395 8396 static unsigned 8397 findMatchingInlineAsmOperand(unsigned OperandNo, 8398 const std::vector<SDValue> &AsmNodeOperands) { 8399 // Scan until we find the definition we already emitted of this operand. 8400 unsigned CurOp = InlineAsm::Op_FirstOperand; 8401 for (; OperandNo; --OperandNo) { 8402 // Advance to the next operand. 8403 unsigned OpFlag = 8404 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8405 assert((InlineAsm::isRegDefKind(OpFlag) || 8406 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8407 InlineAsm::isMemKind(OpFlag)) && 8408 "Skipped past definitions?"); 8409 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8410 } 8411 return CurOp; 8412 } 8413 8414 namespace { 8415 8416 class ExtraFlags { 8417 unsigned Flags = 0; 8418 8419 public: 8420 explicit ExtraFlags(const CallBase &Call) { 8421 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8422 if (IA->hasSideEffects()) 8423 Flags |= InlineAsm::Extra_HasSideEffects; 8424 if (IA->isAlignStack()) 8425 Flags |= InlineAsm::Extra_IsAlignStack; 8426 if (Call.isConvergent()) 8427 Flags |= InlineAsm::Extra_IsConvergent; 8428 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8429 } 8430 8431 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8432 // Ideally, we would only check against memory constraints. However, the 8433 // meaning of an Other constraint can be target-specific and we can't easily 8434 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8435 // for Other constraints as well. 8436 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8437 OpInfo.ConstraintType == TargetLowering::C_Other) { 8438 if (OpInfo.Type == InlineAsm::isInput) 8439 Flags |= InlineAsm::Extra_MayLoad; 8440 else if (OpInfo.Type == InlineAsm::isOutput) 8441 Flags |= InlineAsm::Extra_MayStore; 8442 else if (OpInfo.Type == InlineAsm::isClobber) 8443 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8444 } 8445 } 8446 8447 unsigned get() const { return Flags; } 8448 }; 8449 8450 } // end anonymous namespace 8451 8452 /// visitInlineAsm - Handle a call to an InlineAsm object. 8453 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8454 const BasicBlock *EHPadBB) { 8455 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8456 8457 /// ConstraintOperands - Information about all of the constraints. 8458 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8459 8460 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8461 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8462 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8463 8464 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8465 // AsmDialect, MayLoad, MayStore). 8466 bool HasSideEffect = IA->hasSideEffects(); 8467 ExtraFlags ExtraInfo(Call); 8468 8469 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8470 unsigned ResNo = 0; // ResNo - The result number of the next output. 8471 unsigned NumMatchingOps = 0; 8472 for (auto &T : TargetConstraints) { 8473 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8474 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8475 8476 // Compute the value type for each operand. 8477 if (OpInfo.Type == InlineAsm::isInput || 8478 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8479 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8480 8481 // Process the call argument. BasicBlocks are labels, currently appearing 8482 // only in asm's. 8483 if (isa<CallBrInst>(Call) && 8484 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8485 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8486 NumMatchingOps) && 8487 (NumMatchingOps == 0 || 8488 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8489 NumMatchingOps))) { 8490 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8491 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8492 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8493 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8494 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8495 } else { 8496 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8497 } 8498 8499 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8500 DAG.getDataLayout()); 8501 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8502 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8503 // The return value of the call is this value. As such, there is no 8504 // corresponding argument. 8505 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8506 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8507 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8508 DAG.getDataLayout(), STy->getElementType(ResNo)); 8509 } else { 8510 assert(ResNo == 0 && "Asm only has one result!"); 8511 OpInfo.ConstraintVT = TLI.getAsmOperandValueType( 8512 DAG.getDataLayout(), Call.getType()).getSimpleVT(); 8513 } 8514 ++ResNo; 8515 } else { 8516 OpInfo.ConstraintVT = MVT::Other; 8517 } 8518 8519 if (OpInfo.hasMatchingInput()) 8520 ++NumMatchingOps; 8521 8522 if (!HasSideEffect) 8523 HasSideEffect = OpInfo.hasMemory(TLI); 8524 8525 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8526 // FIXME: Could we compute this on OpInfo rather than T? 8527 8528 // Compute the constraint code and ConstraintType to use. 8529 TLI.ComputeConstraintToUse(T, SDValue()); 8530 8531 if (T.ConstraintType == TargetLowering::C_Immediate && 8532 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8533 // We've delayed emitting a diagnostic like the "n" constraint because 8534 // inlining could cause an integer showing up. 8535 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8536 "' expects an integer constant " 8537 "expression"); 8538 8539 ExtraInfo.update(T); 8540 } 8541 8542 // We won't need to flush pending loads if this asm doesn't touch 8543 // memory and is nonvolatile. 8544 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8545 8546 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8547 if (EmitEHLabels) { 8548 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8549 } 8550 bool IsCallBr = isa<CallBrInst>(Call); 8551 8552 if (IsCallBr || EmitEHLabels) { 8553 // If this is a callbr or invoke we need to flush pending exports since 8554 // inlineasm_br and invoke are terminators. 8555 // We need to do this before nodes are glued to the inlineasm_br node. 8556 Chain = getControlRoot(); 8557 } 8558 8559 MCSymbol *BeginLabel = nullptr; 8560 if (EmitEHLabels) { 8561 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8562 } 8563 8564 // Second pass over the constraints: compute which constraint option to use. 8565 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8566 // If this is an output operand with a matching input operand, look up the 8567 // matching input. If their types mismatch, e.g. one is an integer, the 8568 // other is floating point, or their sizes are different, flag it as an 8569 // error. 8570 if (OpInfo.hasMatchingInput()) { 8571 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8572 patchMatchingInput(OpInfo, Input, DAG); 8573 } 8574 8575 // Compute the constraint code and ConstraintType to use. 8576 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8577 8578 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8579 OpInfo.Type == InlineAsm::isClobber) 8580 continue; 8581 8582 // If this is a memory input, and if the operand is not indirect, do what we 8583 // need to provide an address for the memory input. 8584 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8585 !OpInfo.isIndirect) { 8586 assert((OpInfo.isMultipleAlternative || 8587 (OpInfo.Type == InlineAsm::isInput)) && 8588 "Can only indirectify direct input operands!"); 8589 8590 // Memory operands really want the address of the value. 8591 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8592 8593 // There is no longer a Value* corresponding to this operand. 8594 OpInfo.CallOperandVal = nullptr; 8595 8596 // It is now an indirect operand. 8597 OpInfo.isIndirect = true; 8598 } 8599 8600 } 8601 8602 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8603 std::vector<SDValue> AsmNodeOperands; 8604 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8605 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8606 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8607 8608 // If we have a !srcloc metadata node associated with it, we want to attach 8609 // this to the ultimately generated inline asm machineinstr. To do this, we 8610 // pass in the third operand as this (potentially null) inline asm MDNode. 8611 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8612 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8613 8614 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8615 // bits as operand 3. 8616 AsmNodeOperands.push_back(DAG.getTargetConstant( 8617 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8618 8619 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8620 // this, assign virtual and physical registers for inputs and otput. 8621 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8622 // Assign Registers. 8623 SDISelAsmOperandInfo &RefOpInfo = 8624 OpInfo.isMatchingInputConstraint() 8625 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8626 : OpInfo; 8627 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8628 8629 auto DetectWriteToReservedRegister = [&]() { 8630 const MachineFunction &MF = DAG.getMachineFunction(); 8631 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8632 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8633 if (Register::isPhysicalRegister(Reg) && 8634 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8635 const char *RegName = TRI.getName(Reg); 8636 emitInlineAsmError(Call, "write to reserved register '" + 8637 Twine(RegName) + "'"); 8638 return true; 8639 } 8640 } 8641 return false; 8642 }; 8643 8644 switch (OpInfo.Type) { 8645 case InlineAsm::isOutput: 8646 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8647 unsigned ConstraintID = 8648 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8649 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8650 "Failed to convert memory constraint code to constraint id."); 8651 8652 // Add information to the INLINEASM node to know about this output. 8653 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8654 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8655 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8656 MVT::i32)); 8657 AsmNodeOperands.push_back(OpInfo.CallOperand); 8658 } else { 8659 // Otherwise, this outputs to a register (directly for C_Register / 8660 // C_RegisterClass, and a target-defined fashion for 8661 // C_Immediate/C_Other). Find a register that we can use. 8662 if (OpInfo.AssignedRegs.Regs.empty()) { 8663 emitInlineAsmError( 8664 Call, "couldn't allocate output register for constraint '" + 8665 Twine(OpInfo.ConstraintCode) + "'"); 8666 return; 8667 } 8668 8669 if (DetectWriteToReservedRegister()) 8670 return; 8671 8672 // Add information to the INLINEASM node to know that this register is 8673 // set. 8674 OpInfo.AssignedRegs.AddInlineAsmOperands( 8675 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8676 : InlineAsm::Kind_RegDef, 8677 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8678 } 8679 break; 8680 8681 case InlineAsm::isInput: { 8682 SDValue InOperandVal = OpInfo.CallOperand; 8683 8684 if (OpInfo.isMatchingInputConstraint()) { 8685 // If this is required to match an output register we have already set, 8686 // just use its register. 8687 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8688 AsmNodeOperands); 8689 unsigned OpFlag = 8690 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8691 if (InlineAsm::isRegDefKind(OpFlag) || 8692 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8693 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8694 if (OpInfo.isIndirect) { 8695 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8696 emitInlineAsmError(Call, "inline asm not supported yet: " 8697 "don't know how to handle tied " 8698 "indirect register inputs"); 8699 return; 8700 } 8701 8702 SmallVector<unsigned, 4> Regs; 8703 MachineFunction &MF = DAG.getMachineFunction(); 8704 MachineRegisterInfo &MRI = MF.getRegInfo(); 8705 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8706 RegisterSDNode *R = dyn_cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 8707 Register TiedReg = R->getReg(); 8708 MVT RegVT = R->getSimpleValueType(0); 8709 const TargetRegisterClass *RC = TiedReg.isVirtual() ? 8710 MRI.getRegClass(TiedReg) : TRI.getMinimalPhysRegClass(TiedReg); 8711 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8712 for (unsigned i = 0; i != NumRegs; ++i) 8713 Regs.push_back(MRI.createVirtualRegister(RC)); 8714 8715 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8716 8717 SDLoc dl = getCurSDLoc(); 8718 // Use the produced MatchedRegs object to 8719 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8720 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8721 true, OpInfo.getMatchedOperand(), dl, 8722 DAG, AsmNodeOperands); 8723 break; 8724 } 8725 8726 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8727 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8728 "Unexpected number of operands"); 8729 // Add information to the INLINEASM node to know about this input. 8730 // See InlineAsm.h isUseOperandTiedToDef. 8731 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8732 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8733 OpInfo.getMatchedOperand()); 8734 AsmNodeOperands.push_back(DAG.getTargetConstant( 8735 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8736 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8737 break; 8738 } 8739 8740 // Treat indirect 'X' constraint as memory. 8741 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8742 OpInfo.isIndirect) 8743 OpInfo.ConstraintType = TargetLowering::C_Memory; 8744 8745 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8746 OpInfo.ConstraintType == TargetLowering::C_Other) { 8747 std::vector<SDValue> Ops; 8748 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8749 Ops, DAG); 8750 if (Ops.empty()) { 8751 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8752 if (isa<ConstantSDNode>(InOperandVal)) { 8753 emitInlineAsmError(Call, "value out of range for constraint '" + 8754 Twine(OpInfo.ConstraintCode) + "'"); 8755 return; 8756 } 8757 8758 emitInlineAsmError(Call, 8759 "invalid operand for inline asm constraint '" + 8760 Twine(OpInfo.ConstraintCode) + "'"); 8761 return; 8762 } 8763 8764 // Add information to the INLINEASM node to know about this input. 8765 unsigned ResOpType = 8766 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8767 AsmNodeOperands.push_back(DAG.getTargetConstant( 8768 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8769 llvm::append_range(AsmNodeOperands, Ops); 8770 break; 8771 } 8772 8773 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8774 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8775 assert(InOperandVal.getValueType() == 8776 TLI.getPointerTy(DAG.getDataLayout()) && 8777 "Memory operands expect pointer values"); 8778 8779 unsigned ConstraintID = 8780 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8781 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8782 "Failed to convert memory constraint code to constraint id."); 8783 8784 // Add information to the INLINEASM node to know about this input. 8785 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8786 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8787 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8788 getCurSDLoc(), 8789 MVT::i32)); 8790 AsmNodeOperands.push_back(InOperandVal); 8791 break; 8792 } 8793 8794 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8795 OpInfo.ConstraintType == TargetLowering::C_Register) && 8796 "Unknown constraint type!"); 8797 8798 // TODO: Support this. 8799 if (OpInfo.isIndirect) { 8800 emitInlineAsmError( 8801 Call, "Don't know how to handle indirect register inputs yet " 8802 "for constraint '" + 8803 Twine(OpInfo.ConstraintCode) + "'"); 8804 return; 8805 } 8806 8807 // Copy the input into the appropriate registers. 8808 if (OpInfo.AssignedRegs.Regs.empty()) { 8809 emitInlineAsmError(Call, 8810 "couldn't allocate input reg for constraint '" + 8811 Twine(OpInfo.ConstraintCode) + "'"); 8812 return; 8813 } 8814 8815 if (DetectWriteToReservedRegister()) 8816 return; 8817 8818 SDLoc dl = getCurSDLoc(); 8819 8820 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8821 &Call); 8822 8823 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8824 dl, DAG, AsmNodeOperands); 8825 break; 8826 } 8827 case InlineAsm::isClobber: 8828 // Add the clobbered value to the operand list, so that the register 8829 // allocator is aware that the physreg got clobbered. 8830 if (!OpInfo.AssignedRegs.Regs.empty()) 8831 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8832 false, 0, getCurSDLoc(), DAG, 8833 AsmNodeOperands); 8834 break; 8835 } 8836 } 8837 8838 // Finish up input operands. Set the input chain and add the flag last. 8839 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8840 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8841 8842 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8843 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8844 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8845 Flag = Chain.getValue(1); 8846 8847 // Do additional work to generate outputs. 8848 8849 SmallVector<EVT, 1> ResultVTs; 8850 SmallVector<SDValue, 1> ResultValues; 8851 SmallVector<SDValue, 8> OutChains; 8852 8853 llvm::Type *CallResultType = Call.getType(); 8854 ArrayRef<Type *> ResultTypes; 8855 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8856 ResultTypes = StructResult->elements(); 8857 else if (!CallResultType->isVoidTy()) 8858 ResultTypes = makeArrayRef(CallResultType); 8859 8860 auto CurResultType = ResultTypes.begin(); 8861 auto handleRegAssign = [&](SDValue V) { 8862 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8863 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8864 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8865 ++CurResultType; 8866 // If the type of the inline asm call site return value is different but has 8867 // same size as the type of the asm output bitcast it. One example of this 8868 // is for vectors with different width / number of elements. This can 8869 // happen for register classes that can contain multiple different value 8870 // types. The preg or vreg allocated may not have the same VT as was 8871 // expected. 8872 // 8873 // This can also happen for a return value that disagrees with the register 8874 // class it is put in, eg. a double in a general-purpose register on a 8875 // 32-bit machine. 8876 if (ResultVT != V.getValueType() && 8877 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8878 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8879 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8880 V.getValueType().isInteger()) { 8881 // If a result value was tied to an input value, the computed result 8882 // may have a wider width than the expected result. Extract the 8883 // relevant portion. 8884 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8885 } 8886 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8887 ResultVTs.push_back(ResultVT); 8888 ResultValues.push_back(V); 8889 }; 8890 8891 // Deal with output operands. 8892 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8893 if (OpInfo.Type == InlineAsm::isOutput) { 8894 SDValue Val; 8895 // Skip trivial output operands. 8896 if (OpInfo.AssignedRegs.Regs.empty()) 8897 continue; 8898 8899 switch (OpInfo.ConstraintType) { 8900 case TargetLowering::C_Register: 8901 case TargetLowering::C_RegisterClass: 8902 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8903 Chain, &Flag, &Call); 8904 break; 8905 case TargetLowering::C_Immediate: 8906 case TargetLowering::C_Other: 8907 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8908 OpInfo, DAG); 8909 break; 8910 case TargetLowering::C_Memory: 8911 break; // Already handled. 8912 case TargetLowering::C_Unknown: 8913 assert(false && "Unexpected unknown constraint"); 8914 } 8915 8916 // Indirect output manifest as stores. Record output chains. 8917 if (OpInfo.isIndirect) { 8918 const Value *Ptr = OpInfo.CallOperandVal; 8919 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8920 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8921 MachinePointerInfo(Ptr)); 8922 OutChains.push_back(Store); 8923 } else { 8924 // generate CopyFromRegs to associated registers. 8925 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8926 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8927 for (const SDValue &V : Val->op_values()) 8928 handleRegAssign(V); 8929 } else 8930 handleRegAssign(Val); 8931 } 8932 } 8933 } 8934 8935 // Set results. 8936 if (!ResultValues.empty()) { 8937 assert(CurResultType == ResultTypes.end() && 8938 "Mismatch in number of ResultTypes"); 8939 assert(ResultValues.size() == ResultTypes.size() && 8940 "Mismatch in number of output operands in asm result"); 8941 8942 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8943 DAG.getVTList(ResultVTs), ResultValues); 8944 setValue(&Call, V); 8945 } 8946 8947 // Collect store chains. 8948 if (!OutChains.empty()) 8949 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8950 8951 if (EmitEHLabels) { 8952 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 8953 } 8954 8955 // Only Update Root if inline assembly has a memory effect. 8956 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 8957 EmitEHLabels) 8958 DAG.setRoot(Chain); 8959 } 8960 8961 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8962 const Twine &Message) { 8963 LLVMContext &Ctx = *DAG.getContext(); 8964 Ctx.emitError(&Call, Message); 8965 8966 // Make sure we leave the DAG in a valid state 8967 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8968 SmallVector<EVT, 1> ValueVTs; 8969 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8970 8971 if (ValueVTs.empty()) 8972 return; 8973 8974 SmallVector<SDValue, 1> Ops; 8975 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8976 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8977 8978 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8979 } 8980 8981 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8982 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8983 MVT::Other, getRoot(), 8984 getValue(I.getArgOperand(0)), 8985 DAG.getSrcValue(I.getArgOperand(0)))); 8986 } 8987 8988 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8989 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8990 const DataLayout &DL = DAG.getDataLayout(); 8991 SDValue V = DAG.getVAArg( 8992 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8993 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8994 DL.getABITypeAlign(I.getType()).value()); 8995 DAG.setRoot(V.getValue(1)); 8996 8997 if (I.getType()->isPointerTy()) 8998 V = DAG.getPtrExtOrTrunc( 8999 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9000 setValue(&I, V); 9001 } 9002 9003 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9004 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9005 MVT::Other, getRoot(), 9006 getValue(I.getArgOperand(0)), 9007 DAG.getSrcValue(I.getArgOperand(0)))); 9008 } 9009 9010 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9011 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9012 MVT::Other, getRoot(), 9013 getValue(I.getArgOperand(0)), 9014 getValue(I.getArgOperand(1)), 9015 DAG.getSrcValue(I.getArgOperand(0)), 9016 DAG.getSrcValue(I.getArgOperand(1)))); 9017 } 9018 9019 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9020 const Instruction &I, 9021 SDValue Op) { 9022 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9023 if (!Range) 9024 return Op; 9025 9026 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9027 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9028 return Op; 9029 9030 APInt Lo = CR.getUnsignedMin(); 9031 if (!Lo.isMinValue()) 9032 return Op; 9033 9034 APInt Hi = CR.getUnsignedMax(); 9035 unsigned Bits = std::max(Hi.getActiveBits(), 9036 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9037 9038 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9039 9040 SDLoc SL = getCurSDLoc(); 9041 9042 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9043 DAG.getValueType(SmallVT)); 9044 unsigned NumVals = Op.getNode()->getNumValues(); 9045 if (NumVals == 1) 9046 return ZExt; 9047 9048 SmallVector<SDValue, 4> Ops; 9049 9050 Ops.push_back(ZExt); 9051 for (unsigned I = 1; I != NumVals; ++I) 9052 Ops.push_back(Op.getValue(I)); 9053 9054 return DAG.getMergeValues(Ops, SL); 9055 } 9056 9057 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9058 /// the call being lowered. 9059 /// 9060 /// This is a helper for lowering intrinsics that follow a target calling 9061 /// convention or require stack pointer adjustment. Only a subset of the 9062 /// intrinsic's operands need to participate in the calling convention. 9063 void SelectionDAGBuilder::populateCallLoweringInfo( 9064 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9065 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9066 bool IsPatchPoint) { 9067 TargetLowering::ArgListTy Args; 9068 Args.reserve(NumArgs); 9069 9070 // Populate the argument list. 9071 // Attributes for args start at offset 1, after the return attribute. 9072 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9073 ArgI != ArgE; ++ArgI) { 9074 const Value *V = Call->getOperand(ArgI); 9075 9076 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9077 9078 TargetLowering::ArgListEntry Entry; 9079 Entry.Node = getValue(V); 9080 Entry.Ty = V->getType(); 9081 Entry.setAttributes(Call, ArgI); 9082 Args.push_back(Entry); 9083 } 9084 9085 CLI.setDebugLoc(getCurSDLoc()) 9086 .setChain(getRoot()) 9087 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9088 .setDiscardResult(Call->use_empty()) 9089 .setIsPatchPoint(IsPatchPoint) 9090 .setIsPreallocated( 9091 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9092 } 9093 9094 /// Add a stack map intrinsic call's live variable operands to a stackmap 9095 /// or patchpoint target node's operand list. 9096 /// 9097 /// Constants are converted to TargetConstants purely as an optimization to 9098 /// avoid constant materialization and register allocation. 9099 /// 9100 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9101 /// generate addess computation nodes, and so FinalizeISel can convert the 9102 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9103 /// address materialization and register allocation, but may also be required 9104 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9105 /// alloca in the entry block, then the runtime may assume that the alloca's 9106 /// StackMap location can be read immediately after compilation and that the 9107 /// location is valid at any point during execution (this is similar to the 9108 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9109 /// only available in a register, then the runtime would need to trap when 9110 /// execution reaches the StackMap in order to read the alloca's location. 9111 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9112 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9113 SelectionDAGBuilder &Builder) { 9114 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 9115 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 9116 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 9117 Ops.push_back( 9118 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 9119 Ops.push_back( 9120 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 9121 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 9122 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 9123 Ops.push_back(Builder.DAG.getTargetFrameIndex( 9124 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 9125 } else 9126 Ops.push_back(OpVal); 9127 } 9128 } 9129 9130 /// Lower llvm.experimental.stackmap directly to its target opcode. 9131 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9132 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 9133 // [live variables...]) 9134 9135 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9136 9137 SDValue Chain, InFlag, Callee, NullPtr; 9138 SmallVector<SDValue, 32> Ops; 9139 9140 SDLoc DL = getCurSDLoc(); 9141 Callee = getValue(CI.getCalledOperand()); 9142 NullPtr = DAG.getIntPtrConstant(0, DL, true); 9143 9144 // The stackmap intrinsic only records the live variables (the arguments 9145 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9146 // intrinsic, this won't be lowered to a function call. This means we don't 9147 // have to worry about calling conventions and target specific lowering code. 9148 // Instead we perform the call lowering right here. 9149 // 9150 // chain, flag = CALLSEQ_START(chain, 0, 0) 9151 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9152 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9153 // 9154 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9155 InFlag = Chain.getValue(1); 9156 9157 // Add the <id> and <numBytes> constants. 9158 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 9159 Ops.push_back(DAG.getTargetConstant( 9160 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 9161 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 9162 Ops.push_back(DAG.getTargetConstant( 9163 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 9164 MVT::i32)); 9165 9166 // Push live variables for the stack map. 9167 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9168 9169 // We are not pushing any register mask info here on the operands list, 9170 // because the stackmap doesn't clobber anything. 9171 9172 // Push the chain and the glue flag. 9173 Ops.push_back(Chain); 9174 Ops.push_back(InFlag); 9175 9176 // Create the STACKMAP node. 9177 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9178 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9179 Chain = SDValue(SM, 0); 9180 InFlag = Chain.getValue(1); 9181 9182 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9183 9184 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9185 9186 // Set the root to the target-lowered call chain. 9187 DAG.setRoot(Chain); 9188 9189 // Inform the Frame Information that we have a stackmap in this function. 9190 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9191 } 9192 9193 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9194 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9195 const BasicBlock *EHPadBB) { 9196 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9197 // i32 <numBytes>, 9198 // i8* <target>, 9199 // i32 <numArgs>, 9200 // [Args...], 9201 // [live variables...]) 9202 9203 CallingConv::ID CC = CB.getCallingConv(); 9204 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9205 bool HasDef = !CB.getType()->isVoidTy(); 9206 SDLoc dl = getCurSDLoc(); 9207 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9208 9209 // Handle immediate and symbolic callees. 9210 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9211 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9212 /*isTarget=*/true); 9213 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9214 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9215 SDLoc(SymbolicCallee), 9216 SymbolicCallee->getValueType(0)); 9217 9218 // Get the real number of arguments participating in the call <numArgs> 9219 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9220 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9221 9222 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9223 // Intrinsics include all meta-operands up to but not including CC. 9224 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9225 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9226 "Not enough arguments provided to the patchpoint intrinsic"); 9227 9228 // For AnyRegCC the arguments are lowered later on manually. 9229 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9230 Type *ReturnTy = 9231 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9232 9233 TargetLowering::CallLoweringInfo CLI(DAG); 9234 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9235 ReturnTy, true); 9236 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9237 9238 SDNode *CallEnd = Result.second.getNode(); 9239 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9240 CallEnd = CallEnd->getOperand(0).getNode(); 9241 9242 /// Get a call instruction from the call sequence chain. 9243 /// Tail calls are not allowed. 9244 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9245 "Expected a callseq node."); 9246 SDNode *Call = CallEnd->getOperand(0).getNode(); 9247 bool HasGlue = Call->getGluedNode(); 9248 9249 // Replace the target specific call node with the patchable intrinsic. 9250 SmallVector<SDValue, 8> Ops; 9251 9252 // Add the <id> and <numBytes> constants. 9253 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9254 Ops.push_back(DAG.getTargetConstant( 9255 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9256 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9257 Ops.push_back(DAG.getTargetConstant( 9258 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9259 MVT::i32)); 9260 9261 // Add the callee. 9262 Ops.push_back(Callee); 9263 9264 // Adjust <numArgs> to account for any arguments that have been passed on the 9265 // stack instead. 9266 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9267 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9268 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9269 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9270 9271 // Add the calling convention 9272 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9273 9274 // Add the arguments we omitted previously. The register allocator should 9275 // place these in any free register. 9276 if (IsAnyRegCC) 9277 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9278 Ops.push_back(getValue(CB.getArgOperand(i))); 9279 9280 // Push the arguments from the call instruction up to the register mask. 9281 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9282 Ops.append(Call->op_begin() + 2, e); 9283 9284 // Push live variables for the stack map. 9285 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9286 9287 // Push the register mask info. 9288 if (HasGlue) 9289 Ops.push_back(*(Call->op_end()-2)); 9290 else 9291 Ops.push_back(*(Call->op_end()-1)); 9292 9293 // Push the chain (this is originally the first operand of the call, but 9294 // becomes now the last or second to last operand). 9295 Ops.push_back(*(Call->op_begin())); 9296 9297 // Push the glue flag (last operand). 9298 if (HasGlue) 9299 Ops.push_back(*(Call->op_end()-1)); 9300 9301 SDVTList NodeTys; 9302 if (IsAnyRegCC && HasDef) { 9303 // Create the return types based on the intrinsic definition 9304 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9305 SmallVector<EVT, 3> ValueVTs; 9306 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9307 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9308 9309 // There is always a chain and a glue type at the end 9310 ValueVTs.push_back(MVT::Other); 9311 ValueVTs.push_back(MVT::Glue); 9312 NodeTys = DAG.getVTList(ValueVTs); 9313 } else 9314 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9315 9316 // Replace the target specific call node with a PATCHPOINT node. 9317 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9318 dl, NodeTys, Ops); 9319 9320 // Update the NodeMap. 9321 if (HasDef) { 9322 if (IsAnyRegCC) 9323 setValue(&CB, SDValue(MN, 0)); 9324 else 9325 setValue(&CB, Result.first); 9326 } 9327 9328 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9329 // call sequence. Furthermore the location of the chain and glue can change 9330 // when the AnyReg calling convention is used and the intrinsic returns a 9331 // value. 9332 if (IsAnyRegCC && HasDef) { 9333 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9334 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9335 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9336 } else 9337 DAG.ReplaceAllUsesWith(Call, MN); 9338 DAG.DeleteNode(Call); 9339 9340 // Inform the Frame Information that we have a patchpoint in this function. 9341 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9342 } 9343 9344 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9345 unsigned Intrinsic) { 9346 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9347 SDValue Op1 = getValue(I.getArgOperand(0)); 9348 SDValue Op2; 9349 if (I.getNumArgOperands() > 1) 9350 Op2 = getValue(I.getArgOperand(1)); 9351 SDLoc dl = getCurSDLoc(); 9352 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9353 SDValue Res; 9354 SDNodeFlags SDFlags; 9355 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9356 SDFlags.copyFMF(*FPMO); 9357 9358 switch (Intrinsic) { 9359 case Intrinsic::vector_reduce_fadd: 9360 if (SDFlags.hasAllowReassociation()) 9361 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9362 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9363 SDFlags); 9364 else 9365 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9366 break; 9367 case Intrinsic::vector_reduce_fmul: 9368 if (SDFlags.hasAllowReassociation()) 9369 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9370 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9371 SDFlags); 9372 else 9373 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9374 break; 9375 case Intrinsic::vector_reduce_add: 9376 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9377 break; 9378 case Intrinsic::vector_reduce_mul: 9379 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9380 break; 9381 case Intrinsic::vector_reduce_and: 9382 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9383 break; 9384 case Intrinsic::vector_reduce_or: 9385 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9386 break; 9387 case Intrinsic::vector_reduce_xor: 9388 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9389 break; 9390 case Intrinsic::vector_reduce_smax: 9391 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9392 break; 9393 case Intrinsic::vector_reduce_smin: 9394 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9395 break; 9396 case Intrinsic::vector_reduce_umax: 9397 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9398 break; 9399 case Intrinsic::vector_reduce_umin: 9400 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9401 break; 9402 case Intrinsic::vector_reduce_fmax: 9403 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9404 break; 9405 case Intrinsic::vector_reduce_fmin: 9406 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9407 break; 9408 default: 9409 llvm_unreachable("Unhandled vector reduce intrinsic"); 9410 } 9411 setValue(&I, Res); 9412 } 9413 9414 /// Returns an AttributeList representing the attributes applied to the return 9415 /// value of the given call. 9416 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9417 SmallVector<Attribute::AttrKind, 2> Attrs; 9418 if (CLI.RetSExt) 9419 Attrs.push_back(Attribute::SExt); 9420 if (CLI.RetZExt) 9421 Attrs.push_back(Attribute::ZExt); 9422 if (CLI.IsInReg) 9423 Attrs.push_back(Attribute::InReg); 9424 9425 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9426 Attrs); 9427 } 9428 9429 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9430 /// implementation, which just calls LowerCall. 9431 /// FIXME: When all targets are 9432 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9433 std::pair<SDValue, SDValue> 9434 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9435 // Handle the incoming return values from the call. 9436 CLI.Ins.clear(); 9437 Type *OrigRetTy = CLI.RetTy; 9438 SmallVector<EVT, 4> RetTys; 9439 SmallVector<uint64_t, 4> Offsets; 9440 auto &DL = CLI.DAG.getDataLayout(); 9441 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9442 9443 if (CLI.IsPostTypeLegalization) { 9444 // If we are lowering a libcall after legalization, split the return type. 9445 SmallVector<EVT, 4> OldRetTys; 9446 SmallVector<uint64_t, 4> OldOffsets; 9447 RetTys.swap(OldRetTys); 9448 Offsets.swap(OldOffsets); 9449 9450 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9451 EVT RetVT = OldRetTys[i]; 9452 uint64_t Offset = OldOffsets[i]; 9453 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9454 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9455 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9456 RetTys.append(NumRegs, RegisterVT); 9457 for (unsigned j = 0; j != NumRegs; ++j) 9458 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9459 } 9460 } 9461 9462 SmallVector<ISD::OutputArg, 4> Outs; 9463 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9464 9465 bool CanLowerReturn = 9466 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9467 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9468 9469 SDValue DemoteStackSlot; 9470 int DemoteStackIdx = -100; 9471 if (!CanLowerReturn) { 9472 // FIXME: equivalent assert? 9473 // assert(!CS.hasInAllocaArgument() && 9474 // "sret demotion is incompatible with inalloca"); 9475 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9476 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9477 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9478 DemoteStackIdx = 9479 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9480 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9481 DL.getAllocaAddrSpace()); 9482 9483 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9484 ArgListEntry Entry; 9485 Entry.Node = DemoteStackSlot; 9486 Entry.Ty = StackSlotPtrType; 9487 Entry.IsSExt = false; 9488 Entry.IsZExt = false; 9489 Entry.IsInReg = false; 9490 Entry.IsSRet = true; 9491 Entry.IsNest = false; 9492 Entry.IsByVal = false; 9493 Entry.IsByRef = false; 9494 Entry.IsReturned = false; 9495 Entry.IsSwiftSelf = false; 9496 Entry.IsSwiftAsync = false; 9497 Entry.IsSwiftError = false; 9498 Entry.IsCFGuardTarget = false; 9499 Entry.Alignment = Alignment; 9500 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9501 CLI.NumFixedArgs += 1; 9502 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9503 9504 // sret demotion isn't compatible with tail-calls, since the sret argument 9505 // points into the callers stack frame. 9506 CLI.IsTailCall = false; 9507 } else { 9508 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9509 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9510 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9511 ISD::ArgFlagsTy Flags; 9512 if (NeedsRegBlock) { 9513 Flags.setInConsecutiveRegs(); 9514 if (I == RetTys.size() - 1) 9515 Flags.setInConsecutiveRegsLast(); 9516 } 9517 EVT VT = RetTys[I]; 9518 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9519 CLI.CallConv, VT); 9520 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9521 CLI.CallConv, VT); 9522 for (unsigned i = 0; i != NumRegs; ++i) { 9523 ISD::InputArg MyFlags; 9524 MyFlags.Flags = Flags; 9525 MyFlags.VT = RegisterVT; 9526 MyFlags.ArgVT = VT; 9527 MyFlags.Used = CLI.IsReturnValueUsed; 9528 if (CLI.RetTy->isPointerTy()) { 9529 MyFlags.Flags.setPointer(); 9530 MyFlags.Flags.setPointerAddrSpace( 9531 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9532 } 9533 if (CLI.RetSExt) 9534 MyFlags.Flags.setSExt(); 9535 if (CLI.RetZExt) 9536 MyFlags.Flags.setZExt(); 9537 if (CLI.IsInReg) 9538 MyFlags.Flags.setInReg(); 9539 CLI.Ins.push_back(MyFlags); 9540 } 9541 } 9542 } 9543 9544 // We push in swifterror return as the last element of CLI.Ins. 9545 ArgListTy &Args = CLI.getArgs(); 9546 if (supportSwiftError()) { 9547 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9548 if (Args[i].IsSwiftError) { 9549 ISD::InputArg MyFlags; 9550 MyFlags.VT = getPointerTy(DL); 9551 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9552 MyFlags.Flags.setSwiftError(); 9553 CLI.Ins.push_back(MyFlags); 9554 } 9555 } 9556 } 9557 9558 // Handle all of the outgoing arguments. 9559 CLI.Outs.clear(); 9560 CLI.OutVals.clear(); 9561 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9562 SmallVector<EVT, 4> ValueVTs; 9563 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9564 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9565 Type *FinalType = Args[i].Ty; 9566 if (Args[i].IsByVal) 9567 FinalType = Args[i].IndirectType; 9568 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9569 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 9570 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9571 ++Value) { 9572 EVT VT = ValueVTs[Value]; 9573 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9574 SDValue Op = SDValue(Args[i].Node.getNode(), 9575 Args[i].Node.getResNo() + Value); 9576 ISD::ArgFlagsTy Flags; 9577 9578 // Certain targets (such as MIPS), may have a different ABI alignment 9579 // for a type depending on the context. Give the target a chance to 9580 // specify the alignment it wants. 9581 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9582 Flags.setOrigAlign(OriginalAlignment); 9583 9584 if (Args[i].Ty->isPointerTy()) { 9585 Flags.setPointer(); 9586 Flags.setPointerAddrSpace( 9587 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9588 } 9589 if (Args[i].IsZExt) 9590 Flags.setZExt(); 9591 if (Args[i].IsSExt) 9592 Flags.setSExt(); 9593 if (Args[i].IsInReg) { 9594 // If we are using vectorcall calling convention, a structure that is 9595 // passed InReg - is surely an HVA 9596 if (CLI.CallConv == CallingConv::X86_VectorCall && 9597 isa<StructType>(FinalType)) { 9598 // The first value of a structure is marked 9599 if (0 == Value) 9600 Flags.setHvaStart(); 9601 Flags.setHva(); 9602 } 9603 // Set InReg Flag 9604 Flags.setInReg(); 9605 } 9606 if (Args[i].IsSRet) 9607 Flags.setSRet(); 9608 if (Args[i].IsSwiftSelf) 9609 Flags.setSwiftSelf(); 9610 if (Args[i].IsSwiftAsync) 9611 Flags.setSwiftAsync(); 9612 if (Args[i].IsSwiftError) 9613 Flags.setSwiftError(); 9614 if (Args[i].IsCFGuardTarget) 9615 Flags.setCFGuardTarget(); 9616 if (Args[i].IsByVal) 9617 Flags.setByVal(); 9618 if (Args[i].IsByRef) 9619 Flags.setByRef(); 9620 if (Args[i].IsPreallocated) { 9621 Flags.setPreallocated(); 9622 // Set the byval flag for CCAssignFn callbacks that don't know about 9623 // preallocated. This way we can know how many bytes we should've 9624 // allocated and how many bytes a callee cleanup function will pop. If 9625 // we port preallocated to more targets, we'll have to add custom 9626 // preallocated handling in the various CC lowering callbacks. 9627 Flags.setByVal(); 9628 } 9629 if (Args[i].IsInAlloca) { 9630 Flags.setInAlloca(); 9631 // Set the byval flag for CCAssignFn callbacks that don't know about 9632 // inalloca. This way we can know how many bytes we should've allocated 9633 // and how many bytes a callee cleanup function will pop. If we port 9634 // inalloca to more targets, we'll have to add custom inalloca handling 9635 // in the various CC lowering callbacks. 9636 Flags.setByVal(); 9637 } 9638 Align MemAlign; 9639 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9640 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 9641 Flags.setByValSize(FrameSize); 9642 9643 // info is not there but there are cases it cannot get right. 9644 if (auto MA = Args[i].Alignment) 9645 MemAlign = *MA; 9646 else 9647 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 9648 } else if (auto MA = Args[i].Alignment) { 9649 MemAlign = *MA; 9650 } else { 9651 MemAlign = OriginalAlignment; 9652 } 9653 Flags.setMemAlign(MemAlign); 9654 if (Args[i].IsNest) 9655 Flags.setNest(); 9656 if (NeedsRegBlock) 9657 Flags.setInConsecutiveRegs(); 9658 9659 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9660 CLI.CallConv, VT); 9661 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9662 CLI.CallConv, VT); 9663 SmallVector<SDValue, 4> Parts(NumParts); 9664 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9665 9666 if (Args[i].IsSExt) 9667 ExtendKind = ISD::SIGN_EXTEND; 9668 else if (Args[i].IsZExt) 9669 ExtendKind = ISD::ZERO_EXTEND; 9670 9671 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9672 // for now. 9673 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9674 CanLowerReturn) { 9675 assert((CLI.RetTy == Args[i].Ty || 9676 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9677 CLI.RetTy->getPointerAddressSpace() == 9678 Args[i].Ty->getPointerAddressSpace())) && 9679 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9680 // Before passing 'returned' to the target lowering code, ensure that 9681 // either the register MVT and the actual EVT are the same size or that 9682 // the return value and argument are extended in the same way; in these 9683 // cases it's safe to pass the argument register value unchanged as the 9684 // return register value (although it's at the target's option whether 9685 // to do so) 9686 // TODO: allow code generation to take advantage of partially preserved 9687 // registers rather than clobbering the entire register when the 9688 // parameter extension method is not compatible with the return 9689 // extension method 9690 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9691 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9692 CLI.RetZExt == Args[i].IsZExt)) 9693 Flags.setReturned(); 9694 } 9695 9696 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9697 CLI.CallConv, ExtendKind); 9698 9699 for (unsigned j = 0; j != NumParts; ++j) { 9700 // if it isn't first piece, alignment must be 1 9701 // For scalable vectors the scalable part is currently handled 9702 // by individual targets, so we just use the known minimum size here. 9703 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9704 i < CLI.NumFixedArgs, i, 9705 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9706 if (NumParts > 1 && j == 0) 9707 MyFlags.Flags.setSplit(); 9708 else if (j != 0) { 9709 MyFlags.Flags.setOrigAlign(Align(1)); 9710 if (j == NumParts - 1) 9711 MyFlags.Flags.setSplitEnd(); 9712 } 9713 9714 CLI.Outs.push_back(MyFlags); 9715 CLI.OutVals.push_back(Parts[j]); 9716 } 9717 9718 if (NeedsRegBlock && Value == NumValues - 1) 9719 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9720 } 9721 } 9722 9723 SmallVector<SDValue, 4> InVals; 9724 CLI.Chain = LowerCall(CLI, InVals); 9725 9726 // Update CLI.InVals to use outside of this function. 9727 CLI.InVals = InVals; 9728 9729 // Verify that the target's LowerCall behaved as expected. 9730 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9731 "LowerCall didn't return a valid chain!"); 9732 assert((!CLI.IsTailCall || InVals.empty()) && 9733 "LowerCall emitted a return value for a tail call!"); 9734 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9735 "LowerCall didn't emit the correct number of values!"); 9736 9737 // For a tail call, the return value is merely live-out and there aren't 9738 // any nodes in the DAG representing it. Return a special value to 9739 // indicate that a tail call has been emitted and no more Instructions 9740 // should be processed in the current block. 9741 if (CLI.IsTailCall) { 9742 CLI.DAG.setRoot(CLI.Chain); 9743 return std::make_pair(SDValue(), SDValue()); 9744 } 9745 9746 #ifndef NDEBUG 9747 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9748 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9749 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9750 "LowerCall emitted a value with the wrong type!"); 9751 } 9752 #endif 9753 9754 SmallVector<SDValue, 4> ReturnValues; 9755 if (!CanLowerReturn) { 9756 // The instruction result is the result of loading from the 9757 // hidden sret parameter. 9758 SmallVector<EVT, 1> PVTs; 9759 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9760 9761 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9762 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9763 EVT PtrVT = PVTs[0]; 9764 9765 unsigned NumValues = RetTys.size(); 9766 ReturnValues.resize(NumValues); 9767 SmallVector<SDValue, 4> Chains(NumValues); 9768 9769 // An aggregate return value cannot wrap around the address space, so 9770 // offsets to its parts don't wrap either. 9771 SDNodeFlags Flags; 9772 Flags.setNoUnsignedWrap(true); 9773 9774 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9775 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9776 for (unsigned i = 0; i < NumValues; ++i) { 9777 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9778 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9779 PtrVT), Flags); 9780 SDValue L = CLI.DAG.getLoad( 9781 RetTys[i], CLI.DL, CLI.Chain, Add, 9782 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9783 DemoteStackIdx, Offsets[i]), 9784 HiddenSRetAlign); 9785 ReturnValues[i] = L; 9786 Chains[i] = L.getValue(1); 9787 } 9788 9789 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9790 } else { 9791 // Collect the legal value parts into potentially illegal values 9792 // that correspond to the original function's return values. 9793 Optional<ISD::NodeType> AssertOp; 9794 if (CLI.RetSExt) 9795 AssertOp = ISD::AssertSext; 9796 else if (CLI.RetZExt) 9797 AssertOp = ISD::AssertZext; 9798 unsigned CurReg = 0; 9799 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9800 EVT VT = RetTys[I]; 9801 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9802 CLI.CallConv, VT); 9803 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9804 CLI.CallConv, VT); 9805 9806 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9807 NumRegs, RegisterVT, VT, nullptr, 9808 CLI.CallConv, AssertOp)); 9809 CurReg += NumRegs; 9810 } 9811 9812 // For a function returning void, there is no return value. We can't create 9813 // such a node, so we just return a null return value in that case. In 9814 // that case, nothing will actually look at the value. 9815 if (ReturnValues.empty()) 9816 return std::make_pair(SDValue(), CLI.Chain); 9817 } 9818 9819 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9820 CLI.DAG.getVTList(RetTys), ReturnValues); 9821 return std::make_pair(Res, CLI.Chain); 9822 } 9823 9824 /// Places new result values for the node in Results (their number 9825 /// and types must exactly match those of the original return values of 9826 /// the node), or leaves Results empty, which indicates that the node is not 9827 /// to be custom lowered after all. 9828 void TargetLowering::LowerOperationWrapper(SDNode *N, 9829 SmallVectorImpl<SDValue> &Results, 9830 SelectionDAG &DAG) const { 9831 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9832 9833 if (!Res.getNode()) 9834 return; 9835 9836 // If the original node has one result, take the return value from 9837 // LowerOperation as is. It might not be result number 0. 9838 if (N->getNumValues() == 1) { 9839 Results.push_back(Res); 9840 return; 9841 } 9842 9843 // If the original node has multiple results, then the return node should 9844 // have the same number of results. 9845 assert((N->getNumValues() == Res->getNumValues()) && 9846 "Lowering returned the wrong number of results!"); 9847 9848 // Places new result values base on N result number. 9849 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9850 Results.push_back(Res.getValue(I)); 9851 } 9852 9853 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9854 llvm_unreachable("LowerOperation not implemented for this target!"); 9855 } 9856 9857 void 9858 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9859 SDValue Op = getNonRegisterValue(V); 9860 assert((Op.getOpcode() != ISD::CopyFromReg || 9861 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9862 "Copy from a reg to the same reg!"); 9863 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9864 9865 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9866 // If this is an InlineAsm we have to match the registers required, not the 9867 // notional registers required by the type. 9868 9869 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9870 None); // This is not an ABI copy. 9871 SDValue Chain = DAG.getEntryNode(); 9872 9873 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 9874 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 9875 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 9876 ExtendType = PreferredExtendIt->second; 9877 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9878 PendingExports.push_back(Chain); 9879 } 9880 9881 #include "llvm/CodeGen/SelectionDAGISel.h" 9882 9883 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9884 /// entry block, return true. This includes arguments used by switches, since 9885 /// the switch may expand into multiple basic blocks. 9886 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9887 // With FastISel active, we may be splitting blocks, so force creation 9888 // of virtual registers for all non-dead arguments. 9889 if (FastISel) 9890 return A->use_empty(); 9891 9892 const BasicBlock &Entry = A->getParent()->front(); 9893 for (const User *U : A->users()) 9894 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9895 return false; // Use not in entry block. 9896 9897 return true; 9898 } 9899 9900 using ArgCopyElisionMapTy = 9901 DenseMap<const Argument *, 9902 std::pair<const AllocaInst *, const StoreInst *>>; 9903 9904 /// Scan the entry block of the function in FuncInfo for arguments that look 9905 /// like copies into a local alloca. Record any copied arguments in 9906 /// ArgCopyElisionCandidates. 9907 static void 9908 findArgumentCopyElisionCandidates(const DataLayout &DL, 9909 FunctionLoweringInfo *FuncInfo, 9910 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9911 // Record the state of every static alloca used in the entry block. Argument 9912 // allocas are all used in the entry block, so we need approximately as many 9913 // entries as we have arguments. 9914 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9915 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9916 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9917 StaticAllocas.reserve(NumArgs * 2); 9918 9919 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9920 if (!V) 9921 return nullptr; 9922 V = V->stripPointerCasts(); 9923 const auto *AI = dyn_cast<AllocaInst>(V); 9924 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9925 return nullptr; 9926 auto Iter = StaticAllocas.insert({AI, Unknown}); 9927 return &Iter.first->second; 9928 }; 9929 9930 // Look for stores of arguments to static allocas. Look through bitcasts and 9931 // GEPs to handle type coercions, as long as the alloca is fully initialized 9932 // by the store. Any non-store use of an alloca escapes it and any subsequent 9933 // unanalyzed store might write it. 9934 // FIXME: Handle structs initialized with multiple stores. 9935 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9936 // Look for stores, and handle non-store uses conservatively. 9937 const auto *SI = dyn_cast<StoreInst>(&I); 9938 if (!SI) { 9939 // We will look through cast uses, so ignore them completely. 9940 if (I.isCast()) 9941 continue; 9942 // Ignore debug info and pseudo op intrinsics, they don't escape or store 9943 // to allocas. 9944 if (I.isDebugOrPseudoInst()) 9945 continue; 9946 // This is an unknown instruction. Assume it escapes or writes to all 9947 // static alloca operands. 9948 for (const Use &U : I.operands()) { 9949 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9950 *Info = StaticAllocaInfo::Clobbered; 9951 } 9952 continue; 9953 } 9954 9955 // If the stored value is a static alloca, mark it as escaped. 9956 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9957 *Info = StaticAllocaInfo::Clobbered; 9958 9959 // Check if the destination is a static alloca. 9960 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9961 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9962 if (!Info) 9963 continue; 9964 const AllocaInst *AI = cast<AllocaInst>(Dst); 9965 9966 // Skip allocas that have been initialized or clobbered. 9967 if (*Info != StaticAllocaInfo::Unknown) 9968 continue; 9969 9970 // Check if the stored value is an argument, and that this store fully 9971 // initializes the alloca. 9972 // If the argument type has padding bits we can't directly forward a pointer 9973 // as the upper bits may contain garbage. 9974 // Don't elide copies from the same argument twice. 9975 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9976 const auto *Arg = dyn_cast<Argument>(Val); 9977 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9978 Arg->getType()->isEmptyTy() || 9979 DL.getTypeStoreSize(Arg->getType()) != 9980 DL.getTypeAllocSize(AI->getAllocatedType()) || 9981 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 9982 ArgCopyElisionCandidates.count(Arg)) { 9983 *Info = StaticAllocaInfo::Clobbered; 9984 continue; 9985 } 9986 9987 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9988 << '\n'); 9989 9990 // Mark this alloca and store for argument copy elision. 9991 *Info = StaticAllocaInfo::Elidable; 9992 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9993 9994 // Stop scanning if we've seen all arguments. This will happen early in -O0 9995 // builds, which is useful, because -O0 builds have large entry blocks and 9996 // many allocas. 9997 if (ArgCopyElisionCandidates.size() == NumArgs) 9998 break; 9999 } 10000 } 10001 10002 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10003 /// ArgVal is a load from a suitable fixed stack object. 10004 static void tryToElideArgumentCopy( 10005 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10006 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10007 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10008 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10009 SDValue ArgVal, bool &ArgHasUses) { 10010 // Check if this is a load from a fixed stack object. 10011 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10012 if (!LNode) 10013 return; 10014 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10015 if (!FINode) 10016 return; 10017 10018 // Check that the fixed stack object is the right size and alignment. 10019 // Look at the alignment that the user wrote on the alloca instead of looking 10020 // at the stack object. 10021 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10022 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10023 const AllocaInst *AI = ArgCopyIter->second.first; 10024 int FixedIndex = FINode->getIndex(); 10025 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10026 int OldIndex = AllocaIndex; 10027 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10028 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10029 LLVM_DEBUG( 10030 dbgs() << " argument copy elision failed due to bad fixed stack " 10031 "object size\n"); 10032 return; 10033 } 10034 Align RequiredAlignment = AI->getAlign(); 10035 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10036 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10037 "greater than stack argument alignment (" 10038 << DebugStr(RequiredAlignment) << " vs " 10039 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10040 return; 10041 } 10042 10043 // Perform the elision. Delete the old stack object and replace its only use 10044 // in the variable info map. Mark the stack object as mutable. 10045 LLVM_DEBUG({ 10046 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10047 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10048 << '\n'; 10049 }); 10050 MFI.RemoveStackObject(OldIndex); 10051 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10052 AllocaIndex = FixedIndex; 10053 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10054 Chains.push_back(ArgVal.getValue(1)); 10055 10056 // Avoid emitting code for the store implementing the copy. 10057 const StoreInst *SI = ArgCopyIter->second.second; 10058 ElidedArgCopyInstrs.insert(SI); 10059 10060 // Check for uses of the argument again so that we can avoid exporting ArgVal 10061 // if it is't used by anything other than the store. 10062 for (const Value *U : Arg.users()) { 10063 if (U != SI) { 10064 ArgHasUses = true; 10065 break; 10066 } 10067 } 10068 } 10069 10070 void SelectionDAGISel::LowerArguments(const Function &F) { 10071 SelectionDAG &DAG = SDB->DAG; 10072 SDLoc dl = SDB->getCurSDLoc(); 10073 const DataLayout &DL = DAG.getDataLayout(); 10074 SmallVector<ISD::InputArg, 16> Ins; 10075 10076 // In Naked functions we aren't going to save any registers. 10077 if (F.hasFnAttribute(Attribute::Naked)) 10078 return; 10079 10080 if (!FuncInfo->CanLowerReturn) { 10081 // Put in an sret pointer parameter before all the other parameters. 10082 SmallVector<EVT, 1> ValueVTs; 10083 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10084 F.getReturnType()->getPointerTo( 10085 DAG.getDataLayout().getAllocaAddrSpace()), 10086 ValueVTs); 10087 10088 // NOTE: Assuming that a pointer will never break down to more than one VT 10089 // or one register. 10090 ISD::ArgFlagsTy Flags; 10091 Flags.setSRet(); 10092 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10093 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10094 ISD::InputArg::NoArgIndex, 0); 10095 Ins.push_back(RetArg); 10096 } 10097 10098 // Look for stores of arguments to static allocas. Mark such arguments with a 10099 // flag to ask the target to give us the memory location of that argument if 10100 // available. 10101 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10102 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10103 ArgCopyElisionCandidates); 10104 10105 // Set up the incoming argument description vector. 10106 for (const Argument &Arg : F.args()) { 10107 unsigned ArgNo = Arg.getArgNo(); 10108 SmallVector<EVT, 4> ValueVTs; 10109 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10110 bool isArgValueUsed = !Arg.use_empty(); 10111 unsigned PartBase = 0; 10112 Type *FinalType = Arg.getType(); 10113 if (Arg.hasAttribute(Attribute::ByVal)) 10114 FinalType = Arg.getParamByValType(); 10115 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10116 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10117 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10118 Value != NumValues; ++Value) { 10119 EVT VT = ValueVTs[Value]; 10120 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10121 ISD::ArgFlagsTy Flags; 10122 10123 10124 if (Arg.getType()->isPointerTy()) { 10125 Flags.setPointer(); 10126 Flags.setPointerAddrSpace( 10127 cast<PointerType>(Arg.getType())->getAddressSpace()); 10128 } 10129 if (Arg.hasAttribute(Attribute::ZExt)) 10130 Flags.setZExt(); 10131 if (Arg.hasAttribute(Attribute::SExt)) 10132 Flags.setSExt(); 10133 if (Arg.hasAttribute(Attribute::InReg)) { 10134 // If we are using vectorcall calling convention, a structure that is 10135 // passed InReg - is surely an HVA 10136 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10137 isa<StructType>(Arg.getType())) { 10138 // The first value of a structure is marked 10139 if (0 == Value) 10140 Flags.setHvaStart(); 10141 Flags.setHva(); 10142 } 10143 // Set InReg Flag 10144 Flags.setInReg(); 10145 } 10146 if (Arg.hasAttribute(Attribute::StructRet)) 10147 Flags.setSRet(); 10148 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10149 Flags.setSwiftSelf(); 10150 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10151 Flags.setSwiftAsync(); 10152 if (Arg.hasAttribute(Attribute::SwiftError)) 10153 Flags.setSwiftError(); 10154 if (Arg.hasAttribute(Attribute::ByVal)) 10155 Flags.setByVal(); 10156 if (Arg.hasAttribute(Attribute::ByRef)) 10157 Flags.setByRef(); 10158 if (Arg.hasAttribute(Attribute::InAlloca)) { 10159 Flags.setInAlloca(); 10160 // Set the byval flag for CCAssignFn callbacks that don't know about 10161 // inalloca. This way we can know how many bytes we should've allocated 10162 // and how many bytes a callee cleanup function will pop. If we port 10163 // inalloca to more targets, we'll have to add custom inalloca handling 10164 // in the various CC lowering callbacks. 10165 Flags.setByVal(); 10166 } 10167 if (Arg.hasAttribute(Attribute::Preallocated)) { 10168 Flags.setPreallocated(); 10169 // Set the byval flag for CCAssignFn callbacks that don't know about 10170 // preallocated. This way we can know how many bytes we should've 10171 // allocated and how many bytes a callee cleanup function will pop. If 10172 // we port preallocated to more targets, we'll have to add custom 10173 // preallocated handling in the various CC lowering callbacks. 10174 Flags.setByVal(); 10175 } 10176 10177 // Certain targets (such as MIPS), may have a different ABI alignment 10178 // for a type depending on the context. Give the target a chance to 10179 // specify the alignment it wants. 10180 const Align OriginalAlignment( 10181 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10182 Flags.setOrigAlign(OriginalAlignment); 10183 10184 Align MemAlign; 10185 Type *ArgMemTy = nullptr; 10186 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10187 Flags.isByRef()) { 10188 if (!ArgMemTy) 10189 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10190 10191 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10192 10193 // For in-memory arguments, size and alignment should be passed from FE. 10194 // BE will guess if this info is not there but there are cases it cannot 10195 // get right. 10196 if (auto ParamAlign = Arg.getParamStackAlign()) 10197 MemAlign = *ParamAlign; 10198 else if ((ParamAlign = Arg.getParamAlign())) 10199 MemAlign = *ParamAlign; 10200 else 10201 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10202 if (Flags.isByRef()) 10203 Flags.setByRefSize(MemSize); 10204 else 10205 Flags.setByValSize(MemSize); 10206 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10207 MemAlign = *ParamAlign; 10208 } else { 10209 MemAlign = OriginalAlignment; 10210 } 10211 Flags.setMemAlign(MemAlign); 10212 10213 if (Arg.hasAttribute(Attribute::Nest)) 10214 Flags.setNest(); 10215 if (NeedsRegBlock) 10216 Flags.setInConsecutiveRegs(); 10217 if (ArgCopyElisionCandidates.count(&Arg)) 10218 Flags.setCopyElisionCandidate(); 10219 if (Arg.hasAttribute(Attribute::Returned)) 10220 Flags.setReturned(); 10221 10222 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10223 *CurDAG->getContext(), F.getCallingConv(), VT); 10224 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10225 *CurDAG->getContext(), F.getCallingConv(), VT); 10226 for (unsigned i = 0; i != NumRegs; ++i) { 10227 // For scalable vectors, use the minimum size; individual targets 10228 // are responsible for handling scalable vector arguments and 10229 // return values. 10230 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10231 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10232 if (NumRegs > 1 && i == 0) 10233 MyFlags.Flags.setSplit(); 10234 // if it isn't first piece, alignment must be 1 10235 else if (i > 0) { 10236 MyFlags.Flags.setOrigAlign(Align(1)); 10237 if (i == NumRegs - 1) 10238 MyFlags.Flags.setSplitEnd(); 10239 } 10240 Ins.push_back(MyFlags); 10241 } 10242 if (NeedsRegBlock && Value == NumValues - 1) 10243 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10244 PartBase += VT.getStoreSize().getKnownMinSize(); 10245 } 10246 } 10247 10248 // Call the target to set up the argument values. 10249 SmallVector<SDValue, 8> InVals; 10250 SDValue NewRoot = TLI->LowerFormalArguments( 10251 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10252 10253 // Verify that the target's LowerFormalArguments behaved as expected. 10254 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10255 "LowerFormalArguments didn't return a valid chain!"); 10256 assert(InVals.size() == Ins.size() && 10257 "LowerFormalArguments didn't emit the correct number of values!"); 10258 LLVM_DEBUG({ 10259 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10260 assert(InVals[i].getNode() && 10261 "LowerFormalArguments emitted a null value!"); 10262 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10263 "LowerFormalArguments emitted a value with the wrong type!"); 10264 } 10265 }); 10266 10267 // Update the DAG with the new chain value resulting from argument lowering. 10268 DAG.setRoot(NewRoot); 10269 10270 // Set up the argument values. 10271 unsigned i = 0; 10272 if (!FuncInfo->CanLowerReturn) { 10273 // Create a virtual register for the sret pointer, and put in a copy 10274 // from the sret argument into it. 10275 SmallVector<EVT, 1> ValueVTs; 10276 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10277 F.getReturnType()->getPointerTo( 10278 DAG.getDataLayout().getAllocaAddrSpace()), 10279 ValueVTs); 10280 MVT VT = ValueVTs[0].getSimpleVT(); 10281 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10282 Optional<ISD::NodeType> AssertOp = None; 10283 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10284 nullptr, F.getCallingConv(), AssertOp); 10285 10286 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10287 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10288 Register SRetReg = 10289 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10290 FuncInfo->DemoteRegister = SRetReg; 10291 NewRoot = 10292 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10293 DAG.setRoot(NewRoot); 10294 10295 // i indexes lowered arguments. Bump it past the hidden sret argument. 10296 ++i; 10297 } 10298 10299 SmallVector<SDValue, 4> Chains; 10300 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10301 for (const Argument &Arg : F.args()) { 10302 SmallVector<SDValue, 4> ArgValues; 10303 SmallVector<EVT, 4> ValueVTs; 10304 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10305 unsigned NumValues = ValueVTs.size(); 10306 if (NumValues == 0) 10307 continue; 10308 10309 bool ArgHasUses = !Arg.use_empty(); 10310 10311 // Elide the copying store if the target loaded this argument from a 10312 // suitable fixed stack object. 10313 if (Ins[i].Flags.isCopyElisionCandidate()) { 10314 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10315 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10316 InVals[i], ArgHasUses); 10317 } 10318 10319 // If this argument is unused then remember its value. It is used to generate 10320 // debugging information. 10321 bool isSwiftErrorArg = 10322 TLI->supportSwiftError() && 10323 Arg.hasAttribute(Attribute::SwiftError); 10324 if (!ArgHasUses && !isSwiftErrorArg) { 10325 SDB->setUnusedArgValue(&Arg, InVals[i]); 10326 10327 // Also remember any frame index for use in FastISel. 10328 if (FrameIndexSDNode *FI = 10329 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10330 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10331 } 10332 10333 for (unsigned Val = 0; Val != NumValues; ++Val) { 10334 EVT VT = ValueVTs[Val]; 10335 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10336 F.getCallingConv(), VT); 10337 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10338 *CurDAG->getContext(), F.getCallingConv(), VT); 10339 10340 // Even an apparent 'unused' swifterror argument needs to be returned. So 10341 // we do generate a copy for it that can be used on return from the 10342 // function. 10343 if (ArgHasUses || isSwiftErrorArg) { 10344 Optional<ISD::NodeType> AssertOp; 10345 if (Arg.hasAttribute(Attribute::SExt)) 10346 AssertOp = ISD::AssertSext; 10347 else if (Arg.hasAttribute(Attribute::ZExt)) 10348 AssertOp = ISD::AssertZext; 10349 10350 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10351 PartVT, VT, nullptr, 10352 F.getCallingConv(), AssertOp)); 10353 } 10354 10355 i += NumParts; 10356 } 10357 10358 // We don't need to do anything else for unused arguments. 10359 if (ArgValues.empty()) 10360 continue; 10361 10362 // Note down frame index. 10363 if (FrameIndexSDNode *FI = 10364 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10365 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10366 10367 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10368 SDB->getCurSDLoc()); 10369 10370 SDB->setValue(&Arg, Res); 10371 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10372 // We want to associate the argument with the frame index, among 10373 // involved operands, that correspond to the lowest address. The 10374 // getCopyFromParts function, called earlier, is swapping the order of 10375 // the operands to BUILD_PAIR depending on endianness. The result of 10376 // that swapping is that the least significant bits of the argument will 10377 // be in the first operand of the BUILD_PAIR node, and the most 10378 // significant bits will be in the second operand. 10379 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10380 if (LoadSDNode *LNode = 10381 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10382 if (FrameIndexSDNode *FI = 10383 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10384 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10385 } 10386 10387 // Analyses past this point are naive and don't expect an assertion. 10388 if (Res.getOpcode() == ISD::AssertZext) 10389 Res = Res.getOperand(0); 10390 10391 // Update the SwiftErrorVRegDefMap. 10392 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10393 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10394 if (Register::isVirtualRegister(Reg)) 10395 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10396 Reg); 10397 } 10398 10399 // If this argument is live outside of the entry block, insert a copy from 10400 // wherever we got it to the vreg that other BB's will reference it as. 10401 if (Res.getOpcode() == ISD::CopyFromReg) { 10402 // If we can, though, try to skip creating an unnecessary vreg. 10403 // FIXME: This isn't very clean... it would be nice to make this more 10404 // general. 10405 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10406 if (Register::isVirtualRegister(Reg)) { 10407 FuncInfo->ValueMap[&Arg] = Reg; 10408 continue; 10409 } 10410 } 10411 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10412 FuncInfo->InitializeRegForValue(&Arg); 10413 SDB->CopyToExportRegsIfNeeded(&Arg); 10414 } 10415 } 10416 10417 if (!Chains.empty()) { 10418 Chains.push_back(NewRoot); 10419 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10420 } 10421 10422 DAG.setRoot(NewRoot); 10423 10424 assert(i == InVals.size() && "Argument register count mismatch!"); 10425 10426 // If any argument copy elisions occurred and we have debug info, update the 10427 // stale frame indices used in the dbg.declare variable info table. 10428 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10429 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10430 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10431 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10432 if (I != ArgCopyElisionFrameIndexMap.end()) 10433 VI.Slot = I->second; 10434 } 10435 } 10436 10437 // Finally, if the target has anything special to do, allow it to do so. 10438 emitFunctionEntryCode(); 10439 } 10440 10441 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10442 /// ensure constants are generated when needed. Remember the virtual registers 10443 /// that need to be added to the Machine PHI nodes as input. We cannot just 10444 /// directly add them, because expansion might result in multiple MBB's for one 10445 /// BB. As such, the start of the BB might correspond to a different MBB than 10446 /// the end. 10447 void 10448 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10449 const Instruction *TI = LLVMBB->getTerminator(); 10450 10451 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10452 10453 // Check PHI nodes in successors that expect a value to be available from this 10454 // block. 10455 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10456 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10457 if (!isa<PHINode>(SuccBB->begin())) continue; 10458 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10459 10460 // If this terminator has multiple identical successors (common for 10461 // switches), only handle each succ once. 10462 if (!SuccsHandled.insert(SuccMBB).second) 10463 continue; 10464 10465 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10466 10467 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10468 // nodes and Machine PHI nodes, but the incoming operands have not been 10469 // emitted yet. 10470 for (const PHINode &PN : SuccBB->phis()) { 10471 // Ignore dead phi's. 10472 if (PN.use_empty()) 10473 continue; 10474 10475 // Skip empty types 10476 if (PN.getType()->isEmptyTy()) 10477 continue; 10478 10479 unsigned Reg; 10480 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10481 10482 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10483 unsigned &RegOut = ConstantsOut[C]; 10484 if (RegOut == 0) { 10485 RegOut = FuncInfo.CreateRegs(C); 10486 CopyValueToVirtualRegister(C, RegOut); 10487 } 10488 Reg = RegOut; 10489 } else { 10490 DenseMap<const Value *, Register>::iterator I = 10491 FuncInfo.ValueMap.find(PHIOp); 10492 if (I != FuncInfo.ValueMap.end()) 10493 Reg = I->second; 10494 else { 10495 assert(isa<AllocaInst>(PHIOp) && 10496 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10497 "Didn't codegen value into a register!??"); 10498 Reg = FuncInfo.CreateRegs(PHIOp); 10499 CopyValueToVirtualRegister(PHIOp, Reg); 10500 } 10501 } 10502 10503 // Remember that this register needs to added to the machine PHI node as 10504 // the input for this MBB. 10505 SmallVector<EVT, 4> ValueVTs; 10506 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10507 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10508 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10509 EVT VT = ValueVTs[vti]; 10510 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10511 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10512 FuncInfo.PHINodesToUpdate.push_back( 10513 std::make_pair(&*MBBI++, Reg + i)); 10514 Reg += NumRegisters; 10515 } 10516 } 10517 } 10518 10519 ConstantsOut.clear(); 10520 } 10521 10522 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10523 /// is 0. 10524 MachineBasicBlock * 10525 SelectionDAGBuilder::StackProtectorDescriptor:: 10526 AddSuccessorMBB(const BasicBlock *BB, 10527 MachineBasicBlock *ParentMBB, 10528 bool IsLikely, 10529 MachineBasicBlock *SuccMBB) { 10530 // If SuccBB has not been created yet, create it. 10531 if (!SuccMBB) { 10532 MachineFunction *MF = ParentMBB->getParent(); 10533 MachineFunction::iterator BBI(ParentMBB); 10534 SuccMBB = MF->CreateMachineBasicBlock(BB); 10535 MF->insert(++BBI, SuccMBB); 10536 } 10537 // Add it as a successor of ParentMBB. 10538 ParentMBB->addSuccessor( 10539 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10540 return SuccMBB; 10541 } 10542 10543 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10544 MachineFunction::iterator I(MBB); 10545 if (++I == FuncInfo.MF->end()) 10546 return nullptr; 10547 return &*I; 10548 } 10549 10550 /// During lowering new call nodes can be created (such as memset, etc.). 10551 /// Those will become new roots of the current DAG, but complications arise 10552 /// when they are tail calls. In such cases, the call lowering will update 10553 /// the root, but the builder still needs to know that a tail call has been 10554 /// lowered in order to avoid generating an additional return. 10555 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10556 // If the node is null, we do have a tail call. 10557 if (MaybeTC.getNode() != nullptr) 10558 DAG.setRoot(MaybeTC); 10559 else 10560 HasTailCall = true; 10561 } 10562 10563 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10564 MachineBasicBlock *SwitchMBB, 10565 MachineBasicBlock *DefaultMBB) { 10566 MachineFunction *CurMF = FuncInfo.MF; 10567 MachineBasicBlock *NextMBB = nullptr; 10568 MachineFunction::iterator BBI(W.MBB); 10569 if (++BBI != FuncInfo.MF->end()) 10570 NextMBB = &*BBI; 10571 10572 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10573 10574 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10575 10576 if (Size == 2 && W.MBB == SwitchMBB) { 10577 // If any two of the cases has the same destination, and if one value 10578 // is the same as the other, but has one bit unset that the other has set, 10579 // use bit manipulation to do two compares at once. For example: 10580 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10581 // TODO: This could be extended to merge any 2 cases in switches with 3 10582 // cases. 10583 // TODO: Handle cases where W.CaseBB != SwitchBB. 10584 CaseCluster &Small = *W.FirstCluster; 10585 CaseCluster &Big = *W.LastCluster; 10586 10587 if (Small.Low == Small.High && Big.Low == Big.High && 10588 Small.MBB == Big.MBB) { 10589 const APInt &SmallValue = Small.Low->getValue(); 10590 const APInt &BigValue = Big.Low->getValue(); 10591 10592 // Check that there is only one bit different. 10593 APInt CommonBit = BigValue ^ SmallValue; 10594 if (CommonBit.isPowerOf2()) { 10595 SDValue CondLHS = getValue(Cond); 10596 EVT VT = CondLHS.getValueType(); 10597 SDLoc DL = getCurSDLoc(); 10598 10599 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10600 DAG.getConstant(CommonBit, DL, VT)); 10601 SDValue Cond = DAG.getSetCC( 10602 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10603 ISD::SETEQ); 10604 10605 // Update successor info. 10606 // Both Small and Big will jump to Small.BB, so we sum up the 10607 // probabilities. 10608 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10609 if (BPI) 10610 addSuccessorWithProb( 10611 SwitchMBB, DefaultMBB, 10612 // The default destination is the first successor in IR. 10613 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10614 else 10615 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10616 10617 // Insert the true branch. 10618 SDValue BrCond = 10619 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10620 DAG.getBasicBlock(Small.MBB)); 10621 // Insert the false branch. 10622 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10623 DAG.getBasicBlock(DefaultMBB)); 10624 10625 DAG.setRoot(BrCond); 10626 return; 10627 } 10628 } 10629 } 10630 10631 if (TM.getOptLevel() != CodeGenOpt::None) { 10632 // Here, we order cases by probability so the most likely case will be 10633 // checked first. However, two clusters can have the same probability in 10634 // which case their relative ordering is non-deterministic. So we use Low 10635 // as a tie-breaker as clusters are guaranteed to never overlap. 10636 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10637 [](const CaseCluster &a, const CaseCluster &b) { 10638 return a.Prob != b.Prob ? 10639 a.Prob > b.Prob : 10640 a.Low->getValue().slt(b.Low->getValue()); 10641 }); 10642 10643 // Rearrange the case blocks so that the last one falls through if possible 10644 // without changing the order of probabilities. 10645 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10646 --I; 10647 if (I->Prob > W.LastCluster->Prob) 10648 break; 10649 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10650 std::swap(*I, *W.LastCluster); 10651 break; 10652 } 10653 } 10654 } 10655 10656 // Compute total probability. 10657 BranchProbability DefaultProb = W.DefaultProb; 10658 BranchProbability UnhandledProbs = DefaultProb; 10659 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10660 UnhandledProbs += I->Prob; 10661 10662 MachineBasicBlock *CurMBB = W.MBB; 10663 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10664 bool FallthroughUnreachable = false; 10665 MachineBasicBlock *Fallthrough; 10666 if (I == W.LastCluster) { 10667 // For the last cluster, fall through to the default destination. 10668 Fallthrough = DefaultMBB; 10669 FallthroughUnreachable = isa<UnreachableInst>( 10670 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10671 } else { 10672 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10673 CurMF->insert(BBI, Fallthrough); 10674 // Put Cond in a virtual register to make it available from the new blocks. 10675 ExportFromCurrentBlock(Cond); 10676 } 10677 UnhandledProbs -= I->Prob; 10678 10679 switch (I->Kind) { 10680 case CC_JumpTable: { 10681 // FIXME: Optimize away range check based on pivot comparisons. 10682 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10683 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10684 10685 // The jump block hasn't been inserted yet; insert it here. 10686 MachineBasicBlock *JumpMBB = JT->MBB; 10687 CurMF->insert(BBI, JumpMBB); 10688 10689 auto JumpProb = I->Prob; 10690 auto FallthroughProb = UnhandledProbs; 10691 10692 // If the default statement is a target of the jump table, we evenly 10693 // distribute the default probability to successors of CurMBB. Also 10694 // update the probability on the edge from JumpMBB to Fallthrough. 10695 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10696 SE = JumpMBB->succ_end(); 10697 SI != SE; ++SI) { 10698 if (*SI == DefaultMBB) { 10699 JumpProb += DefaultProb / 2; 10700 FallthroughProb -= DefaultProb / 2; 10701 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10702 JumpMBB->normalizeSuccProbs(); 10703 break; 10704 } 10705 } 10706 10707 if (FallthroughUnreachable) { 10708 // Skip the range check if the fallthrough block is unreachable. 10709 JTH->OmitRangeCheck = true; 10710 } 10711 10712 if (!JTH->OmitRangeCheck) 10713 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10714 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10715 CurMBB->normalizeSuccProbs(); 10716 10717 // The jump table header will be inserted in our current block, do the 10718 // range check, and fall through to our fallthrough block. 10719 JTH->HeaderBB = CurMBB; 10720 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10721 10722 // If we're in the right place, emit the jump table header right now. 10723 if (CurMBB == SwitchMBB) { 10724 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10725 JTH->Emitted = true; 10726 } 10727 break; 10728 } 10729 case CC_BitTests: { 10730 // FIXME: Optimize away range check based on pivot comparisons. 10731 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10732 10733 // The bit test blocks haven't been inserted yet; insert them here. 10734 for (BitTestCase &BTC : BTB->Cases) 10735 CurMF->insert(BBI, BTC.ThisBB); 10736 10737 // Fill in fields of the BitTestBlock. 10738 BTB->Parent = CurMBB; 10739 BTB->Default = Fallthrough; 10740 10741 BTB->DefaultProb = UnhandledProbs; 10742 // If the cases in bit test don't form a contiguous range, we evenly 10743 // distribute the probability on the edge to Fallthrough to two 10744 // successors of CurMBB. 10745 if (!BTB->ContiguousRange) { 10746 BTB->Prob += DefaultProb / 2; 10747 BTB->DefaultProb -= DefaultProb / 2; 10748 } 10749 10750 if (FallthroughUnreachable) { 10751 // Skip the range check if the fallthrough block is unreachable. 10752 BTB->OmitRangeCheck = true; 10753 } 10754 10755 // If we're in the right place, emit the bit test header right now. 10756 if (CurMBB == SwitchMBB) { 10757 visitBitTestHeader(*BTB, SwitchMBB); 10758 BTB->Emitted = true; 10759 } 10760 break; 10761 } 10762 case CC_Range: { 10763 const Value *RHS, *LHS, *MHS; 10764 ISD::CondCode CC; 10765 if (I->Low == I->High) { 10766 // Check Cond == I->Low. 10767 CC = ISD::SETEQ; 10768 LHS = Cond; 10769 RHS=I->Low; 10770 MHS = nullptr; 10771 } else { 10772 // Check I->Low <= Cond <= I->High. 10773 CC = ISD::SETLE; 10774 LHS = I->Low; 10775 MHS = Cond; 10776 RHS = I->High; 10777 } 10778 10779 // If Fallthrough is unreachable, fold away the comparison. 10780 if (FallthroughUnreachable) 10781 CC = ISD::SETTRUE; 10782 10783 // The false probability is the sum of all unhandled cases. 10784 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10785 getCurSDLoc(), I->Prob, UnhandledProbs); 10786 10787 if (CurMBB == SwitchMBB) 10788 visitSwitchCase(CB, SwitchMBB); 10789 else 10790 SL->SwitchCases.push_back(CB); 10791 10792 break; 10793 } 10794 } 10795 CurMBB = Fallthrough; 10796 } 10797 } 10798 10799 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10800 CaseClusterIt First, 10801 CaseClusterIt Last) { 10802 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10803 if (X.Prob != CC.Prob) 10804 return X.Prob > CC.Prob; 10805 10806 // Ties are broken by comparing the case value. 10807 return X.Low->getValue().slt(CC.Low->getValue()); 10808 }); 10809 } 10810 10811 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10812 const SwitchWorkListItem &W, 10813 Value *Cond, 10814 MachineBasicBlock *SwitchMBB) { 10815 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10816 "Clusters not sorted?"); 10817 10818 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10819 10820 // Balance the tree based on branch probabilities to create a near-optimal (in 10821 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10822 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10823 CaseClusterIt LastLeft = W.FirstCluster; 10824 CaseClusterIt FirstRight = W.LastCluster; 10825 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10826 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10827 10828 // Move LastLeft and FirstRight towards each other from opposite directions to 10829 // find a partitioning of the clusters which balances the probability on both 10830 // sides. If LeftProb and RightProb are equal, alternate which side is 10831 // taken to ensure 0-probability nodes are distributed evenly. 10832 unsigned I = 0; 10833 while (LastLeft + 1 < FirstRight) { 10834 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10835 LeftProb += (++LastLeft)->Prob; 10836 else 10837 RightProb += (--FirstRight)->Prob; 10838 I++; 10839 } 10840 10841 while (true) { 10842 // Our binary search tree differs from a typical BST in that ours can have up 10843 // to three values in each leaf. The pivot selection above doesn't take that 10844 // into account, which means the tree might require more nodes and be less 10845 // efficient. We compensate for this here. 10846 10847 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10848 unsigned NumRight = W.LastCluster - FirstRight + 1; 10849 10850 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10851 // If one side has less than 3 clusters, and the other has more than 3, 10852 // consider taking a cluster from the other side. 10853 10854 if (NumLeft < NumRight) { 10855 // Consider moving the first cluster on the right to the left side. 10856 CaseCluster &CC = *FirstRight; 10857 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10858 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10859 if (LeftSideRank <= RightSideRank) { 10860 // Moving the cluster to the left does not demote it. 10861 ++LastLeft; 10862 ++FirstRight; 10863 continue; 10864 } 10865 } else { 10866 assert(NumRight < NumLeft); 10867 // Consider moving the last element on the left to the right side. 10868 CaseCluster &CC = *LastLeft; 10869 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10870 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10871 if (RightSideRank <= LeftSideRank) { 10872 // Moving the cluster to the right does not demot it. 10873 --LastLeft; 10874 --FirstRight; 10875 continue; 10876 } 10877 } 10878 } 10879 break; 10880 } 10881 10882 assert(LastLeft + 1 == FirstRight); 10883 assert(LastLeft >= W.FirstCluster); 10884 assert(FirstRight <= W.LastCluster); 10885 10886 // Use the first element on the right as pivot since we will make less-than 10887 // comparisons against it. 10888 CaseClusterIt PivotCluster = FirstRight; 10889 assert(PivotCluster > W.FirstCluster); 10890 assert(PivotCluster <= W.LastCluster); 10891 10892 CaseClusterIt FirstLeft = W.FirstCluster; 10893 CaseClusterIt LastRight = W.LastCluster; 10894 10895 const ConstantInt *Pivot = PivotCluster->Low; 10896 10897 // New blocks will be inserted immediately after the current one. 10898 MachineFunction::iterator BBI(W.MBB); 10899 ++BBI; 10900 10901 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10902 // we can branch to its destination directly if it's squeezed exactly in 10903 // between the known lower bound and Pivot - 1. 10904 MachineBasicBlock *LeftMBB; 10905 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10906 FirstLeft->Low == W.GE && 10907 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10908 LeftMBB = FirstLeft->MBB; 10909 } else { 10910 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10911 FuncInfo.MF->insert(BBI, LeftMBB); 10912 WorkList.push_back( 10913 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10914 // Put Cond in a virtual register to make it available from the new blocks. 10915 ExportFromCurrentBlock(Cond); 10916 } 10917 10918 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10919 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10920 // directly if RHS.High equals the current upper bound. 10921 MachineBasicBlock *RightMBB; 10922 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10923 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10924 RightMBB = FirstRight->MBB; 10925 } else { 10926 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10927 FuncInfo.MF->insert(BBI, RightMBB); 10928 WorkList.push_back( 10929 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10930 // Put Cond in a virtual register to make it available from the new blocks. 10931 ExportFromCurrentBlock(Cond); 10932 } 10933 10934 // Create the CaseBlock record that will be used to lower the branch. 10935 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10936 getCurSDLoc(), LeftProb, RightProb); 10937 10938 if (W.MBB == SwitchMBB) 10939 visitSwitchCase(CB, SwitchMBB); 10940 else 10941 SL->SwitchCases.push_back(CB); 10942 } 10943 10944 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10945 // from the swith statement. 10946 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10947 BranchProbability PeeledCaseProb) { 10948 if (PeeledCaseProb == BranchProbability::getOne()) 10949 return BranchProbability::getZero(); 10950 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10951 10952 uint32_t Numerator = CaseProb.getNumerator(); 10953 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10954 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10955 } 10956 10957 // Try to peel the top probability case if it exceeds the threshold. 10958 // Return current MachineBasicBlock for the switch statement if the peeling 10959 // does not occur. 10960 // If the peeling is performed, return the newly created MachineBasicBlock 10961 // for the peeled switch statement. Also update Clusters to remove the peeled 10962 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10963 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10964 const SwitchInst &SI, CaseClusterVector &Clusters, 10965 BranchProbability &PeeledCaseProb) { 10966 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10967 // Don't perform if there is only one cluster or optimizing for size. 10968 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10969 TM.getOptLevel() == CodeGenOpt::None || 10970 SwitchMBB->getParent()->getFunction().hasMinSize()) 10971 return SwitchMBB; 10972 10973 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10974 unsigned PeeledCaseIndex = 0; 10975 bool SwitchPeeled = false; 10976 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10977 CaseCluster &CC = Clusters[Index]; 10978 if (CC.Prob < TopCaseProb) 10979 continue; 10980 TopCaseProb = CC.Prob; 10981 PeeledCaseIndex = Index; 10982 SwitchPeeled = true; 10983 } 10984 if (!SwitchPeeled) 10985 return SwitchMBB; 10986 10987 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10988 << TopCaseProb << "\n"); 10989 10990 // Record the MBB for the peeled switch statement. 10991 MachineFunction::iterator BBI(SwitchMBB); 10992 ++BBI; 10993 MachineBasicBlock *PeeledSwitchMBB = 10994 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10995 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10996 10997 ExportFromCurrentBlock(SI.getCondition()); 10998 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10999 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11000 nullptr, nullptr, TopCaseProb.getCompl()}; 11001 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11002 11003 Clusters.erase(PeeledCaseIt); 11004 for (CaseCluster &CC : Clusters) { 11005 LLVM_DEBUG( 11006 dbgs() << "Scale the probablity for one cluster, before scaling: " 11007 << CC.Prob << "\n"); 11008 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11009 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11010 } 11011 PeeledCaseProb = TopCaseProb; 11012 return PeeledSwitchMBB; 11013 } 11014 11015 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11016 // Extract cases from the switch. 11017 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11018 CaseClusterVector Clusters; 11019 Clusters.reserve(SI.getNumCases()); 11020 for (auto I : SI.cases()) { 11021 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11022 const ConstantInt *CaseVal = I.getCaseValue(); 11023 BranchProbability Prob = 11024 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11025 : BranchProbability(1, SI.getNumCases() + 1); 11026 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11027 } 11028 11029 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11030 11031 // Cluster adjacent cases with the same destination. We do this at all 11032 // optimization levels because it's cheap to do and will make codegen faster 11033 // if there are many clusters. 11034 sortAndRangeify(Clusters); 11035 11036 // The branch probablity of the peeled case. 11037 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11038 MachineBasicBlock *PeeledSwitchMBB = 11039 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11040 11041 // If there is only the default destination, jump there directly. 11042 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11043 if (Clusters.empty()) { 11044 assert(PeeledSwitchMBB == SwitchMBB); 11045 SwitchMBB->addSuccessor(DefaultMBB); 11046 if (DefaultMBB != NextBlock(SwitchMBB)) { 11047 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11048 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11049 } 11050 return; 11051 } 11052 11053 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11054 SL->findBitTestClusters(Clusters, &SI); 11055 11056 LLVM_DEBUG({ 11057 dbgs() << "Case clusters: "; 11058 for (const CaseCluster &C : Clusters) { 11059 if (C.Kind == CC_JumpTable) 11060 dbgs() << "JT:"; 11061 if (C.Kind == CC_BitTests) 11062 dbgs() << "BT:"; 11063 11064 C.Low->getValue().print(dbgs(), true); 11065 if (C.Low != C.High) { 11066 dbgs() << '-'; 11067 C.High->getValue().print(dbgs(), true); 11068 } 11069 dbgs() << ' '; 11070 } 11071 dbgs() << '\n'; 11072 }); 11073 11074 assert(!Clusters.empty()); 11075 SwitchWorkList WorkList; 11076 CaseClusterIt First = Clusters.begin(); 11077 CaseClusterIt Last = Clusters.end() - 1; 11078 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11079 // Scale the branchprobability for DefaultMBB if the peel occurs and 11080 // DefaultMBB is not replaced. 11081 if (PeeledCaseProb != BranchProbability::getZero() && 11082 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11083 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11084 WorkList.push_back( 11085 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11086 11087 while (!WorkList.empty()) { 11088 SwitchWorkListItem W = WorkList.pop_back_val(); 11089 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11090 11091 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11092 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11093 // For optimized builds, lower large range as a balanced binary tree. 11094 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11095 continue; 11096 } 11097 11098 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11099 } 11100 } 11101 11102 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11103 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11104 auto DL = getCurSDLoc(); 11105 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11106 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11107 } 11108 11109 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11110 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11111 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11112 11113 SDLoc DL = getCurSDLoc(); 11114 SDValue V = getValue(I.getOperand(0)); 11115 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11116 11117 if (VT.isScalableVector()) { 11118 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11119 return; 11120 } 11121 11122 // Use VECTOR_SHUFFLE for the fixed-length vector 11123 // to maintain existing behavior. 11124 SmallVector<int, 8> Mask; 11125 unsigned NumElts = VT.getVectorMinNumElements(); 11126 for (unsigned i = 0; i != NumElts; ++i) 11127 Mask.push_back(NumElts - 1 - i); 11128 11129 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11130 } 11131 11132 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11133 SmallVector<EVT, 4> ValueVTs; 11134 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11135 ValueVTs); 11136 unsigned NumValues = ValueVTs.size(); 11137 if (NumValues == 0) return; 11138 11139 SmallVector<SDValue, 4> Values(NumValues); 11140 SDValue Op = getValue(I.getOperand(0)); 11141 11142 for (unsigned i = 0; i != NumValues; ++i) 11143 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11144 SDValue(Op.getNode(), Op.getResNo() + i)); 11145 11146 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11147 DAG.getVTList(ValueVTs), Values)); 11148 } 11149 11150 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11151 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11152 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11153 11154 SDLoc DL = getCurSDLoc(); 11155 SDValue V1 = getValue(I.getOperand(0)); 11156 SDValue V2 = getValue(I.getOperand(1)); 11157 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11158 11159 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11160 if (VT.isScalableVector()) { 11161 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11162 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11163 DAG.getConstant(Imm, DL, IdxVT))); 11164 return; 11165 } 11166 11167 unsigned NumElts = VT.getVectorNumElements(); 11168 11169 if ((-Imm > NumElts) || (Imm >= NumElts)) { 11170 // Result is undefined if immediate is out-of-bounds. 11171 setValue(&I, DAG.getUNDEF(VT)); 11172 return; 11173 } 11174 11175 uint64_t Idx = (NumElts + Imm) % NumElts; 11176 11177 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11178 SmallVector<int, 8> Mask; 11179 for (unsigned i = 0; i < NumElts; ++i) 11180 Mask.push_back(Idx + i); 11181 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11182 } 11183