1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/BlockFrequencyInfo.h" 28 #include "llvm/Analysis/BranchProbabilityInfo.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/Analysis/EHPersonalities.h" 31 #include "llvm/Analysis/Loads.h" 32 #include "llvm/Analysis/MemoryLocation.h" 33 #include "llvm/Analysis/ProfileSummaryInfo.h" 34 #include "llvm/Analysis/TargetLibraryInfo.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/Analysis/VectorUtils.h" 37 #include "llvm/CodeGen/Analysis.h" 38 #include "llvm/CodeGen/FunctionLoweringInfo.h" 39 #include "llvm/CodeGen/GCMetadata.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 53 #include "llvm/CodeGen/StackMaps.h" 54 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 55 #include "llvm/CodeGen/TargetFrameLowering.h" 56 #include "llvm/CodeGen/TargetInstrInfo.h" 57 #include "llvm/CodeGen/TargetOpcodes.h" 58 #include "llvm/CodeGen/TargetRegisterInfo.h" 59 #include "llvm/CodeGen/TargetSubtargetInfo.h" 60 #include "llvm/CodeGen/WinEHFuncInfo.h" 61 #include "llvm/IR/Argument.h" 62 #include "llvm/IR/Attributes.h" 63 #include "llvm/IR/BasicBlock.h" 64 #include "llvm/IR/CFG.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/ConstantRange.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugInfoMetadata.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GetElementPtrTypeIterator.h" 74 #include "llvm/IR/InlineAsm.h" 75 #include "llvm/IR/InstrTypes.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/IntrinsicsAArch64.h" 80 #include "llvm/IR/IntrinsicsWebAssembly.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Operator.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Statepoint.h" 87 #include "llvm/IR/Type.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/MC/MCContext.h" 91 #include "llvm/MC/MCSymbol.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/MathExtras.h" 98 #include "llvm/Support/raw_ostream.h" 99 #include "llvm/Target/TargetIntrinsicInfo.h" 100 #include "llvm/Target/TargetMachine.h" 101 #include "llvm/Target/TargetOptions.h" 102 #include "llvm/Transforms/Utils/Local.h" 103 #include <cstddef> 104 #include <cstring> 105 #include <iterator> 106 #include <limits> 107 #include <numeric> 108 #include <tuple> 109 110 using namespace llvm; 111 using namespace PatternMatch; 112 using namespace SwitchCG; 113 114 #define DEBUG_TYPE "isel" 115 116 /// LimitFloatPrecision - Generate low-precision inline sequences for 117 /// some float libcalls (6, 8 or 12 bits). 118 static unsigned LimitFloatPrecision; 119 120 static cl::opt<bool> 121 InsertAssertAlign("insert-assert-align", cl::init(true), 122 cl::desc("Insert the experimental `assertalign` node."), 123 cl::ReallyHidden); 124 125 static cl::opt<unsigned, true> 126 LimitFPPrecision("limit-float-precision", 127 cl::desc("Generate low-precision inline sequences " 128 "for some float libcalls"), 129 cl::location(LimitFloatPrecision), cl::Hidden, 130 cl::init(0)); 131 132 static cl::opt<unsigned> SwitchPeelThreshold( 133 "switch-peel-threshold", cl::Hidden, cl::init(66), 134 cl::desc("Set the case probability threshold for peeling the case from a " 135 "switch statement. A value greater than 100 will void this " 136 "optimization")); 137 138 // Limit the width of DAG chains. This is important in general to prevent 139 // DAG-based analysis from blowing up. For example, alias analysis and 140 // load clustering may not complete in reasonable time. It is difficult to 141 // recognize and avoid this situation within each individual analysis, and 142 // future analyses are likely to have the same behavior. Limiting DAG width is 143 // the safe approach and will be especially important with global DAGs. 144 // 145 // MaxParallelChains default is arbitrarily high to avoid affecting 146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 147 // sequence over this should have been converted to llvm.memcpy by the 148 // frontend. It is easy to induce this behavior with .ll code such as: 149 // %buffer = alloca [4096 x i8] 150 // %data = load [4096 x i8]* %argPtr 151 // store [4096 x i8] %data, [4096 x i8]* %buffer 152 static const unsigned MaxParallelChains = 64; 153 154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 155 const SDValue *Parts, unsigned NumParts, 156 MVT PartVT, EVT ValueVT, const Value *V, 157 Optional<CallingConv::ID> CC); 158 159 /// getCopyFromParts - Create a value that contains the specified legal parts 160 /// combined into the value they represent. If the parts combine to a type 161 /// larger than ValueVT then AssertOp can be used to specify whether the extra 162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 163 /// (ISD::AssertSext). 164 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 165 const SDValue *Parts, unsigned NumParts, 166 MVT PartVT, EVT ValueVT, const Value *V, 167 Optional<CallingConv::ID> CC = None, 168 Optional<ISD::NodeType> AssertOp = None) { 169 // Let the target assemble the parts if it wants to 170 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 171 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 172 PartVT, ValueVT, CC)) 173 return Val; 174 175 if (ValueVT.isVector()) 176 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 177 CC); 178 179 assert(NumParts > 0 && "No parts to assemble!"); 180 SDValue Val = Parts[0]; 181 182 if (NumParts > 1) { 183 // Assemble the value from multiple parts. 184 if (ValueVT.isInteger()) { 185 unsigned PartBits = PartVT.getSizeInBits(); 186 unsigned ValueBits = ValueVT.getSizeInBits(); 187 188 // Assemble the power of 2 part. 189 unsigned RoundParts = 190 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 191 unsigned RoundBits = PartBits * RoundParts; 192 EVT RoundVT = RoundBits == ValueBits ? 193 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 194 SDValue Lo, Hi; 195 196 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 197 198 if (RoundParts > 2) { 199 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 200 PartVT, HalfVT, V); 201 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 202 RoundParts / 2, PartVT, HalfVT, V); 203 } else { 204 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 205 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 206 } 207 208 if (DAG.getDataLayout().isBigEndian()) 209 std::swap(Lo, Hi); 210 211 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 212 213 if (RoundParts < NumParts) { 214 // Assemble the trailing non-power-of-2 part. 215 unsigned OddParts = NumParts - RoundParts; 216 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 217 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 218 OddVT, V, CC); 219 220 // Combine the round and odd parts. 221 Lo = Val; 222 if (DAG.getDataLayout().isBigEndian()) 223 std::swap(Lo, Hi); 224 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 225 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 226 Hi = 227 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 228 DAG.getConstant(Lo.getValueSizeInBits(), DL, 229 TLI.getPointerTy(DAG.getDataLayout()))); 230 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 231 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 232 } 233 } else if (PartVT.isFloatingPoint()) { 234 // FP split into multiple FP parts (for ppcf128) 235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 236 "Unexpected split"); 237 SDValue Lo, Hi; 238 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 239 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 240 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 241 std::swap(Lo, Hi); 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 243 } else { 244 // FP split into integer parts (soft fp) 245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 246 !PartVT.isVector() && "Unexpected split"); 247 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 249 } 250 } 251 252 // There is now one part, held in Val. Correct it to match ValueVT. 253 // PartEVT is the type of the register class that holds the value. 254 // ValueVT is the type of the inline asm operation. 255 EVT PartEVT = Val.getValueType(); 256 257 if (PartEVT == ValueVT) 258 return Val; 259 260 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 261 ValueVT.bitsLT(PartEVT)) { 262 // For an FP value in an integer part, we need to truncate to the right 263 // width first. 264 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 265 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 266 } 267 268 // Handle types that have the same size. 269 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 270 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 271 272 // Handle types with different sizes. 273 if (PartEVT.isInteger() && ValueVT.isInteger()) { 274 if (ValueVT.bitsLT(PartEVT)) { 275 // For a truncate, see if we have any information to 276 // indicate whether the truncated bits will always be 277 // zero or sign-extension. 278 if (AssertOp.hasValue()) 279 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 280 DAG.getValueType(ValueVT)); 281 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 282 } 283 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 284 } 285 286 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 287 // FP_ROUND's are always exact here. 288 if (ValueVT.bitsLT(Val.getValueType())) 289 return DAG.getNode( 290 ISD::FP_ROUND, DL, ValueVT, Val, 291 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 292 293 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 294 } 295 296 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 297 // then truncating. 298 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 299 ValueVT.bitsLT(PartEVT)) { 300 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 301 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 302 } 303 304 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 305 } 306 307 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 308 const Twine &ErrMsg) { 309 const Instruction *I = dyn_cast_or_null<Instruction>(V); 310 if (!V) 311 return Ctx.emitError(ErrMsg); 312 313 const char *AsmError = ", possible invalid constraint for vector type"; 314 if (const CallInst *CI = dyn_cast<CallInst>(I)) 315 if (CI->isInlineAsm()) 316 return Ctx.emitError(I, ErrMsg + AsmError); 317 318 return Ctx.emitError(I, ErrMsg); 319 } 320 321 /// getCopyFromPartsVector - Create a value that contains the specified legal 322 /// parts combined into the value they represent. If the parts combine to a 323 /// type larger than ValueVT then AssertOp can be used to specify whether the 324 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 325 /// ValueVT (ISD::AssertSext). 326 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 327 const SDValue *Parts, unsigned NumParts, 328 MVT PartVT, EVT ValueVT, const Value *V, 329 Optional<CallingConv::ID> CallConv) { 330 assert(ValueVT.isVector() && "Not a vector value"); 331 assert(NumParts > 0 && "No parts to assemble!"); 332 const bool IsABIRegCopy = CallConv.hasValue(); 333 334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 335 SDValue Val = Parts[0]; 336 337 // Handle a multi-element vector. 338 if (NumParts > 1) { 339 EVT IntermediateVT; 340 MVT RegisterVT; 341 unsigned NumIntermediates; 342 unsigned NumRegs; 343 344 if (IsABIRegCopy) { 345 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 346 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } else { 349 NumRegs = 350 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 351 NumIntermediates, RegisterVT); 352 } 353 354 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 355 NumParts = NumRegs; // Silence a compiler warning. 356 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 357 assert(RegisterVT.getSizeInBits() == 358 Parts[0].getSimpleValueType().getSizeInBits() && 359 "Part type sizes don't match!"); 360 361 // Assemble the parts into intermediate operands. 362 SmallVector<SDValue, 8> Ops(NumIntermediates); 363 if (NumIntermediates == NumParts) { 364 // If the register was not expanded, truncate or copy the value, 365 // as appropriate. 366 for (unsigned i = 0; i != NumParts; ++i) 367 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 368 PartVT, IntermediateVT, V, CallConv); 369 } else if (NumParts > 0) { 370 // If the intermediate type was expanded, build the intermediate 371 // operands from the parts. 372 assert(NumParts % NumIntermediates == 0 && 373 "Must expand into a divisible number of parts!"); 374 unsigned Factor = NumParts / NumIntermediates; 375 for (unsigned i = 0; i != NumIntermediates; ++i) 376 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 377 PartVT, IntermediateVT, V, CallConv); 378 } 379 380 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 381 // intermediate operands. 382 EVT BuiltVectorTy = 383 IntermediateVT.isVector() 384 ? EVT::getVectorVT( 385 *DAG.getContext(), IntermediateVT.getScalarType(), 386 IntermediateVT.getVectorElementCount() * NumParts) 387 : EVT::getVectorVT(*DAG.getContext(), 388 IntermediateVT.getScalarType(), 389 NumIntermediates); 390 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 391 : ISD::BUILD_VECTOR, 392 DL, BuiltVectorTy, Ops); 393 } 394 395 // There is now one part, held in Val. Correct it to match ValueVT. 396 EVT PartEVT = Val.getValueType(); 397 398 if (PartEVT == ValueVT) 399 return Val; 400 401 if (PartEVT.isVector()) { 402 // If the element type of the source/dest vectors are the same, but the 403 // parts vector has more elements than the value vector, then we have a 404 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 405 // elements we want. 406 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 407 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 408 ValueVT.getVectorElementCount().getKnownMinValue()) && 409 (PartEVT.getVectorElementCount().isScalable() == 410 ValueVT.getVectorElementCount().isScalable()) && 411 "Cannot narrow, it would be a lossy transformation"); 412 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 413 DAG.getVectorIdxConstant(0, DL)); 414 } 415 416 // Vector/Vector bitcast. 417 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 418 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 419 420 assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() && 421 "Cannot handle this kind of promotion"); 422 // Promoted vector extract 423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 424 425 } 426 427 // Trivial bitcast if the types are the same size and the destination 428 // vector type is legal. 429 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 430 TLI.isTypeLegal(ValueVT)) 431 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 432 433 if (ValueVT.getVectorNumElements() != 1) { 434 // Certain ABIs require that vectors are passed as integers. For vectors 435 // are the same size, this is an obvious bitcast. 436 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 437 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 438 } else if (ValueVT.bitsLT(PartEVT)) { 439 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 440 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 441 // Drop the extra bits. 442 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 443 return DAG.getBitcast(ValueVT, Val); 444 } 445 446 diagnosePossiblyInvalidConstraint( 447 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 448 return DAG.getUNDEF(ValueVT); 449 } 450 451 // Handle cases such as i8 -> <1 x i1> 452 EVT ValueSVT = ValueVT.getVectorElementType(); 453 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 454 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 455 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 456 else 457 Val = ValueVT.isFloatingPoint() 458 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 459 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 460 } 461 462 return DAG.getBuildVector(ValueVT, DL, Val); 463 } 464 465 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 466 SDValue Val, SDValue *Parts, unsigned NumParts, 467 MVT PartVT, const Value *V, 468 Optional<CallingConv::ID> CallConv); 469 470 /// getCopyToParts - Create a series of nodes that contain the specified value 471 /// split into legal parts. If the parts contain more bits than Val, then, for 472 /// integers, ExtendKind can be used to specify how to generate the extra bits. 473 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 474 SDValue *Parts, unsigned NumParts, MVT PartVT, 475 const Value *V, 476 Optional<CallingConv::ID> CallConv = None, 477 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 478 // Let the target split the parts if it wants to 479 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 480 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 481 CallConv)) 482 return; 483 EVT ValueVT = Val.getValueType(); 484 485 // Handle the vector case separately. 486 if (ValueVT.isVector()) 487 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 488 CallConv); 489 490 unsigned PartBits = PartVT.getSizeInBits(); 491 unsigned OrigNumParts = NumParts; 492 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 493 "Copying to an illegal type!"); 494 495 if (NumParts == 0) 496 return; 497 498 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 499 EVT PartEVT = PartVT; 500 if (PartEVT == ValueVT) { 501 assert(NumParts == 1 && "No-op copy with multiple parts!"); 502 Parts[0] = Val; 503 return; 504 } 505 506 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 507 // If the parts cover more bits than the value has, promote the value. 508 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 509 assert(NumParts == 1 && "Do not know what to promote to!"); 510 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 511 } else { 512 if (ValueVT.isFloatingPoint()) { 513 // FP values need to be bitcast, then extended if they are being put 514 // into a larger container. 515 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 516 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 517 } 518 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 519 ValueVT.isInteger() && 520 "Unknown mismatch!"); 521 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 522 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 523 if (PartVT == MVT::x86mmx) 524 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 525 } 526 } else if (PartBits == ValueVT.getSizeInBits()) { 527 // Different types of the same size. 528 assert(NumParts == 1 && PartEVT != ValueVT); 529 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 530 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 531 // If the parts cover less bits than value has, truncate the value. 532 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 533 ValueVT.isInteger() && 534 "Unknown mismatch!"); 535 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 536 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 537 if (PartVT == MVT::x86mmx) 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } 540 541 // The value may have changed - recompute ValueVT. 542 ValueVT = Val.getValueType(); 543 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 544 "Failed to tile the value with PartVT!"); 545 546 if (NumParts == 1) { 547 if (PartEVT != ValueVT) { 548 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 549 "scalar-to-vector conversion failed"); 550 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 551 } 552 553 Parts[0] = Val; 554 return; 555 } 556 557 // Expand the value into multiple parts. 558 if (NumParts & (NumParts - 1)) { 559 // The number of parts is not a power of 2. Split off and copy the tail. 560 assert(PartVT.isInteger() && ValueVT.isInteger() && 561 "Do not know what to expand to!"); 562 unsigned RoundParts = 1 << Log2_32(NumParts); 563 unsigned RoundBits = RoundParts * PartBits; 564 unsigned OddParts = NumParts - RoundParts; 565 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 566 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 567 568 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 569 CallConv); 570 571 if (DAG.getDataLayout().isBigEndian()) 572 // The odd parts were reversed by getCopyToParts - unreverse them. 573 std::reverse(Parts + RoundParts, Parts + NumParts); 574 575 NumParts = RoundParts; 576 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 577 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 578 } 579 580 // The number of parts is a power of 2. Repeatedly bisect the value using 581 // EXTRACT_ELEMENT. 582 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 583 EVT::getIntegerVT(*DAG.getContext(), 584 ValueVT.getSizeInBits()), 585 Val); 586 587 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 588 for (unsigned i = 0; i < NumParts; i += StepSize) { 589 unsigned ThisBits = StepSize * PartBits / 2; 590 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 591 SDValue &Part0 = Parts[i]; 592 SDValue &Part1 = Parts[i+StepSize/2]; 593 594 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 595 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 596 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 597 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 598 599 if (ThisBits == PartBits && ThisVT != PartVT) { 600 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 601 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 602 } 603 } 604 } 605 606 if (DAG.getDataLayout().isBigEndian()) 607 std::reverse(Parts, Parts + OrigNumParts); 608 } 609 610 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 611 const SDLoc &DL, EVT PartVT) { 612 if (!PartVT.isVector()) 613 return SDValue(); 614 615 EVT ValueVT = Val.getValueType(); 616 ElementCount PartNumElts = PartVT.getVectorElementCount(); 617 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 618 619 // We only support widening vectors with equivalent element types and 620 // fixed/scalable properties. If a target needs to widen a fixed-length type 621 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 622 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 623 PartNumElts.isScalable() != ValueNumElts.isScalable() || 624 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 625 return SDValue(); 626 627 // Widening a scalable vector to another scalable vector is done by inserting 628 // the vector into a larger undef one. 629 if (PartNumElts.isScalable()) 630 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 631 Val, DAG.getVectorIdxConstant(0, DL)); 632 633 EVT ElementVT = PartVT.getVectorElementType(); 634 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 635 // undef elements. 636 SmallVector<SDValue, 16> Ops; 637 DAG.ExtractVectorElements(Val, Ops); 638 SDValue EltUndef = DAG.getUNDEF(ElementVT); 639 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 640 641 // FIXME: Use CONCAT for 2x -> 4x. 642 return DAG.getBuildVector(PartVT, DL, Ops); 643 } 644 645 /// getCopyToPartsVector - Create a series of nodes that contain the specified 646 /// value split into legal parts. 647 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 648 SDValue Val, SDValue *Parts, unsigned NumParts, 649 MVT PartVT, const Value *V, 650 Optional<CallingConv::ID> CallConv) { 651 EVT ValueVT = Val.getValueType(); 652 assert(ValueVT.isVector() && "Not a vector"); 653 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 654 const bool IsABIRegCopy = CallConv.hasValue(); 655 656 if (NumParts == 1) { 657 EVT PartEVT = PartVT; 658 if (PartEVT == ValueVT) { 659 // Nothing to do. 660 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 661 // Bitconvert vector->vector case. 662 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 663 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 664 Val = Widened; 665 } else if (PartVT.isVector() && 666 PartEVT.getVectorElementType().bitsGE( 667 ValueVT.getVectorElementType()) && 668 PartEVT.getVectorElementCount() == 669 ValueVT.getVectorElementCount()) { 670 671 // Promoted vector extract 672 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 673 } else { 674 if (ValueVT.getVectorElementCount().isScalar()) { 675 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 676 DAG.getVectorIdxConstant(0, DL)); 677 } else { 678 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 679 assert(PartVT.getFixedSizeInBits() > ValueSize && 680 "lossy conversion of vector to scalar type"); 681 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 682 Val = DAG.getBitcast(IntermediateType, Val); 683 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 684 } 685 } 686 687 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 688 Parts[0] = Val; 689 return; 690 } 691 692 // Handle a multi-element vector. 693 EVT IntermediateVT; 694 MVT RegisterVT; 695 unsigned NumIntermediates; 696 unsigned NumRegs; 697 if (IsABIRegCopy) { 698 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 699 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 700 NumIntermediates, RegisterVT); 701 } else { 702 NumRegs = 703 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 704 NumIntermediates, RegisterVT); 705 } 706 707 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 708 NumParts = NumRegs; // Silence a compiler warning. 709 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 710 711 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 712 "Mixing scalable and fixed vectors when copying in parts"); 713 714 Optional<ElementCount> DestEltCnt; 715 716 if (IntermediateVT.isVector()) 717 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 718 else 719 DestEltCnt = ElementCount::getFixed(NumIntermediates); 720 721 EVT BuiltVectorTy = EVT::getVectorVT( 722 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 723 724 if (ValueVT == BuiltVectorTy) { 725 // Nothing to do. 726 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 727 // Bitconvert vector->vector case. 728 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 729 } else if (SDValue Widened = 730 widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 731 Val = Widened; 732 } else if (BuiltVectorTy.getVectorElementType().bitsGE( 733 ValueVT.getVectorElementType()) && 734 BuiltVectorTy.getVectorElementCount() == 735 ValueVT.getVectorElementCount()) { 736 // Promoted vector extract 737 Val = DAG.getAnyExtOrTrunc(Val, DL, BuiltVectorTy); 738 } 739 740 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 741 742 // Split the vector into intermediate operands. 743 SmallVector<SDValue, 8> Ops(NumIntermediates); 744 for (unsigned i = 0; i != NumIntermediates; ++i) { 745 if (IntermediateVT.isVector()) { 746 // This does something sensible for scalable vectors - see the 747 // definition of EXTRACT_SUBVECTOR for further details. 748 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 749 Ops[i] = 750 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 751 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 752 } else { 753 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 754 DAG.getVectorIdxConstant(i, DL)); 755 } 756 } 757 758 // Split the intermediate operands into legal parts. 759 if (NumParts == NumIntermediates) { 760 // If the register was not expanded, promote or copy the value, 761 // as appropriate. 762 for (unsigned i = 0; i != NumParts; ++i) 763 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 764 } else if (NumParts > 0) { 765 // If the intermediate type was expanded, split each the value into 766 // legal parts. 767 assert(NumIntermediates != 0 && "division by zero"); 768 assert(NumParts % NumIntermediates == 0 && 769 "Must expand into a divisible number of parts!"); 770 unsigned Factor = NumParts / NumIntermediates; 771 for (unsigned i = 0; i != NumIntermediates; ++i) 772 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 773 CallConv); 774 } 775 } 776 777 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 778 EVT valuevt, Optional<CallingConv::ID> CC) 779 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 780 RegCount(1, regs.size()), CallConv(CC) {} 781 782 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 783 const DataLayout &DL, unsigned Reg, Type *Ty, 784 Optional<CallingConv::ID> CC) { 785 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 786 787 CallConv = CC; 788 789 for (EVT ValueVT : ValueVTs) { 790 unsigned NumRegs = 791 isABIMangled() 792 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 793 : TLI.getNumRegisters(Context, ValueVT); 794 MVT RegisterVT = 795 isABIMangled() 796 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 797 : TLI.getRegisterType(Context, ValueVT); 798 for (unsigned i = 0; i != NumRegs; ++i) 799 Regs.push_back(Reg + i); 800 RegVTs.push_back(RegisterVT); 801 RegCount.push_back(NumRegs); 802 Reg += NumRegs; 803 } 804 } 805 806 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 807 FunctionLoweringInfo &FuncInfo, 808 const SDLoc &dl, SDValue &Chain, 809 SDValue *Flag, const Value *V) const { 810 // A Value with type {} or [0 x %t] needs no registers. 811 if (ValueVTs.empty()) 812 return SDValue(); 813 814 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 815 816 // Assemble the legal parts into the final values. 817 SmallVector<SDValue, 4> Values(ValueVTs.size()); 818 SmallVector<SDValue, 8> Parts; 819 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 820 // Copy the legal parts from the registers. 821 EVT ValueVT = ValueVTs[Value]; 822 unsigned NumRegs = RegCount[Value]; 823 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 824 *DAG.getContext(), 825 CallConv.getValue(), RegVTs[Value]) 826 : RegVTs[Value]; 827 828 Parts.resize(NumRegs); 829 for (unsigned i = 0; i != NumRegs; ++i) { 830 SDValue P; 831 if (!Flag) { 832 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 833 } else { 834 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 835 *Flag = P.getValue(2); 836 } 837 838 Chain = P.getValue(1); 839 Parts[i] = P; 840 841 // If the source register was virtual and if we know something about it, 842 // add an assert node. 843 if (!Register::isVirtualRegister(Regs[Part + i]) || 844 !RegisterVT.isInteger()) 845 continue; 846 847 const FunctionLoweringInfo::LiveOutInfo *LOI = 848 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 849 if (!LOI) 850 continue; 851 852 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 853 unsigned NumSignBits = LOI->NumSignBits; 854 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 855 856 if (NumZeroBits == RegSize) { 857 // The current value is a zero. 858 // Explicitly express that as it would be easier for 859 // optimizations to kick in. 860 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 861 continue; 862 } 863 864 // FIXME: We capture more information than the dag can represent. For 865 // now, just use the tightest assertzext/assertsext possible. 866 bool isSExt; 867 EVT FromVT(MVT::Other); 868 if (NumZeroBits) { 869 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 870 isSExt = false; 871 } else if (NumSignBits > 1) { 872 FromVT = 873 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 874 isSExt = true; 875 } else { 876 continue; 877 } 878 // Add an assertion node. 879 assert(FromVT != MVT::Other); 880 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 881 RegisterVT, P, DAG.getValueType(FromVT)); 882 } 883 884 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 885 RegisterVT, ValueVT, V, CallConv); 886 Part += NumRegs; 887 Parts.clear(); 888 } 889 890 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 891 } 892 893 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 894 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 895 const Value *V, 896 ISD::NodeType PreferredExtendType) const { 897 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 898 ISD::NodeType ExtendKind = PreferredExtendType; 899 900 // Get the list of the values's legal parts. 901 unsigned NumRegs = Regs.size(); 902 SmallVector<SDValue, 8> Parts(NumRegs); 903 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 904 unsigned NumParts = RegCount[Value]; 905 906 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 907 *DAG.getContext(), 908 CallConv.getValue(), RegVTs[Value]) 909 : RegVTs[Value]; 910 911 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 912 ExtendKind = ISD::ZERO_EXTEND; 913 914 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 915 NumParts, RegisterVT, V, CallConv, ExtendKind); 916 Part += NumParts; 917 } 918 919 // Copy the parts into the registers. 920 SmallVector<SDValue, 8> Chains(NumRegs); 921 for (unsigned i = 0; i != NumRegs; ++i) { 922 SDValue Part; 923 if (!Flag) { 924 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 925 } else { 926 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 927 *Flag = Part.getValue(1); 928 } 929 930 Chains[i] = Part.getValue(0); 931 } 932 933 if (NumRegs == 1 || Flag) 934 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 935 // flagged to it. That is the CopyToReg nodes and the user are considered 936 // a single scheduling unit. If we create a TokenFactor and return it as 937 // chain, then the TokenFactor is both a predecessor (operand) of the 938 // user as well as a successor (the TF operands are flagged to the user). 939 // c1, f1 = CopyToReg 940 // c2, f2 = CopyToReg 941 // c3 = TokenFactor c1, c2 942 // ... 943 // = op c3, ..., f2 944 Chain = Chains[NumRegs-1]; 945 else 946 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 947 } 948 949 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 950 unsigned MatchingIdx, const SDLoc &dl, 951 SelectionDAG &DAG, 952 std::vector<SDValue> &Ops) const { 953 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 954 955 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 956 if (HasMatching) 957 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 958 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 959 // Put the register class of the virtual registers in the flag word. That 960 // way, later passes can recompute register class constraints for inline 961 // assembly as well as normal instructions. 962 // Don't do this for tied operands that can use the regclass information 963 // from the def. 964 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 965 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 966 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 967 } 968 969 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 970 Ops.push_back(Res); 971 972 if (Code == InlineAsm::Kind_Clobber) { 973 // Clobbers should always have a 1:1 mapping with registers, and may 974 // reference registers that have illegal (e.g. vector) types. Hence, we 975 // shouldn't try to apply any sort of splitting logic to them. 976 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 977 "No 1:1 mapping from clobbers to regs?"); 978 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 979 (void)SP; 980 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 981 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 982 assert( 983 (Regs[I] != SP || 984 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 985 "If we clobbered the stack pointer, MFI should know about it."); 986 } 987 return; 988 } 989 990 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 991 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 992 MVT RegisterVT = RegVTs[Value]; 993 for (unsigned i = 0; i != NumRegs; ++i) { 994 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 995 unsigned TheReg = Regs[Reg++]; 996 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 997 } 998 } 999 } 1000 1001 SmallVector<std::pair<unsigned, TypeSize>, 4> 1002 RegsForValue::getRegsAndSizes() const { 1003 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1004 unsigned I = 0; 1005 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1006 unsigned RegCount = std::get<0>(CountAndVT); 1007 MVT RegisterVT = std::get<1>(CountAndVT); 1008 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1009 for (unsigned E = I + RegCount; I != E; ++I) 1010 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1011 } 1012 return OutVec; 1013 } 1014 1015 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1016 const TargetLibraryInfo *li) { 1017 AA = aa; 1018 GFI = gfi; 1019 LibInfo = li; 1020 DL = &DAG.getDataLayout(); 1021 Context = DAG.getContext(); 1022 LPadToCallSiteMap.clear(); 1023 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1024 } 1025 1026 void SelectionDAGBuilder::clear() { 1027 NodeMap.clear(); 1028 UnusedArgNodeMap.clear(); 1029 PendingLoads.clear(); 1030 PendingExports.clear(); 1031 PendingConstrainedFP.clear(); 1032 PendingConstrainedFPStrict.clear(); 1033 CurInst = nullptr; 1034 HasTailCall = false; 1035 SDNodeOrder = LowestSDNodeOrder; 1036 StatepointLowering.clear(); 1037 } 1038 1039 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1040 DanglingDebugInfoMap.clear(); 1041 } 1042 1043 // Update DAG root to include dependencies on Pending chains. 1044 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1045 SDValue Root = DAG.getRoot(); 1046 1047 if (Pending.empty()) 1048 return Root; 1049 1050 // Add current root to PendingChains, unless we already indirectly 1051 // depend on it. 1052 if (Root.getOpcode() != ISD::EntryToken) { 1053 unsigned i = 0, e = Pending.size(); 1054 for (; i != e; ++i) { 1055 assert(Pending[i].getNode()->getNumOperands() > 1); 1056 if (Pending[i].getNode()->getOperand(0) == Root) 1057 break; // Don't add the root if we already indirectly depend on it. 1058 } 1059 1060 if (i == e) 1061 Pending.push_back(Root); 1062 } 1063 1064 if (Pending.size() == 1) 1065 Root = Pending[0]; 1066 else 1067 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1068 1069 DAG.setRoot(Root); 1070 Pending.clear(); 1071 return Root; 1072 } 1073 1074 SDValue SelectionDAGBuilder::getMemoryRoot() { 1075 return updateRoot(PendingLoads); 1076 } 1077 1078 SDValue SelectionDAGBuilder::getRoot() { 1079 // Chain up all pending constrained intrinsics together with all 1080 // pending loads, by simply appending them to PendingLoads and 1081 // then calling getMemoryRoot(). 1082 PendingLoads.reserve(PendingLoads.size() + 1083 PendingConstrainedFP.size() + 1084 PendingConstrainedFPStrict.size()); 1085 PendingLoads.append(PendingConstrainedFP.begin(), 1086 PendingConstrainedFP.end()); 1087 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1088 PendingConstrainedFPStrict.end()); 1089 PendingConstrainedFP.clear(); 1090 PendingConstrainedFPStrict.clear(); 1091 return getMemoryRoot(); 1092 } 1093 1094 SDValue SelectionDAGBuilder::getControlRoot() { 1095 // We need to emit pending fpexcept.strict constrained intrinsics, 1096 // so append them to the PendingExports list. 1097 PendingExports.append(PendingConstrainedFPStrict.begin(), 1098 PendingConstrainedFPStrict.end()); 1099 PendingConstrainedFPStrict.clear(); 1100 return updateRoot(PendingExports); 1101 } 1102 1103 void SelectionDAGBuilder::visit(const Instruction &I) { 1104 // Set up outgoing PHI node register values before emitting the terminator. 1105 if (I.isTerminator()) { 1106 HandlePHINodesInSuccessorBlocks(I.getParent()); 1107 } 1108 1109 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1110 if (!isa<DbgInfoIntrinsic>(I)) 1111 ++SDNodeOrder; 1112 1113 CurInst = &I; 1114 1115 visit(I.getOpcode(), I); 1116 1117 if (!I.isTerminator() && !HasTailCall && 1118 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1119 CopyToExportRegsIfNeeded(&I); 1120 1121 CurInst = nullptr; 1122 } 1123 1124 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1125 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1126 } 1127 1128 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1129 // Note: this doesn't use InstVisitor, because it has to work with 1130 // ConstantExpr's in addition to instructions. 1131 switch (Opcode) { 1132 default: llvm_unreachable("Unknown instruction type encountered!"); 1133 // Build the switch statement using the Instruction.def file. 1134 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1135 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1136 #include "llvm/IR/Instruction.def" 1137 } 1138 } 1139 1140 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1141 DebugLoc DL, unsigned Order) { 1142 // We treat variadic dbg_values differently at this stage. 1143 if (DI->hasArgList()) { 1144 // For variadic dbg_values we will now insert an undef. 1145 // FIXME: We can potentially recover these! 1146 SmallVector<SDDbgOperand, 2> Locs; 1147 for (const Value *V : DI->getValues()) { 1148 auto Undef = UndefValue::get(V->getType()); 1149 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1150 } 1151 SDDbgValue *SDV = DAG.getDbgValueList( 1152 DI->getVariable(), DI->getExpression(), Locs, {}, 1153 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1154 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1155 } else { 1156 // TODO: Dangling debug info will eventually either be resolved or produce 1157 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1158 // between the original dbg.value location and its resolved DBG_VALUE, 1159 // which we should ideally fill with an extra Undef DBG_VALUE. 1160 assert(DI->getNumVariableLocationOps() == 1 && 1161 "DbgValueInst without an ArgList should have a single location " 1162 "operand."); 1163 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1164 } 1165 } 1166 1167 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1168 const DIExpression *Expr) { 1169 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1170 const DbgValueInst *DI = DDI.getDI(); 1171 DIVariable *DanglingVariable = DI->getVariable(); 1172 DIExpression *DanglingExpr = DI->getExpression(); 1173 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1174 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1175 return true; 1176 } 1177 return false; 1178 }; 1179 1180 for (auto &DDIMI : DanglingDebugInfoMap) { 1181 DanglingDebugInfoVector &DDIV = DDIMI.second; 1182 1183 // If debug info is to be dropped, run it through final checks to see 1184 // whether it can be salvaged. 1185 for (auto &DDI : DDIV) 1186 if (isMatchingDbgValue(DDI)) 1187 salvageUnresolvedDbgValue(DDI); 1188 1189 erase_if(DDIV, isMatchingDbgValue); 1190 } 1191 } 1192 1193 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1194 // generate the debug data structures now that we've seen its definition. 1195 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1196 SDValue Val) { 1197 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1198 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1199 return; 1200 1201 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1202 for (auto &DDI : DDIV) { 1203 const DbgValueInst *DI = DDI.getDI(); 1204 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1205 assert(DI && "Ill-formed DanglingDebugInfo"); 1206 DebugLoc dl = DDI.getdl(); 1207 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1208 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1209 DILocalVariable *Variable = DI->getVariable(); 1210 DIExpression *Expr = DI->getExpression(); 1211 assert(Variable->isValidLocationForIntrinsic(dl) && 1212 "Expected inlined-at fields to agree"); 1213 SDDbgValue *SDV; 1214 if (Val.getNode()) { 1215 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1216 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1217 // we couldn't resolve it directly when examining the DbgValue intrinsic 1218 // in the first place we should not be more successful here). Unless we 1219 // have some test case that prove this to be correct we should avoid 1220 // calling EmitFuncArgumentDbgValue here. 1221 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1222 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1223 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1224 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1225 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1226 // inserted after the definition of Val when emitting the instructions 1227 // after ISel. An alternative could be to teach 1228 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1229 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1230 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1231 << ValSDNodeOrder << "\n"); 1232 SDV = getDbgValue(Val, Variable, Expr, dl, 1233 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1234 DAG.AddDbgValue(SDV, false); 1235 } else 1236 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1237 << "in EmitFuncArgumentDbgValue\n"); 1238 } else { 1239 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1240 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1241 auto SDV = 1242 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1243 DAG.AddDbgValue(SDV, false); 1244 } 1245 } 1246 DDIV.clear(); 1247 } 1248 1249 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1250 assert(!DDI.getDI()->hasArgList() && 1251 "Not implemented for variadic dbg_values"); 1252 Value *V = DDI.getDI()->getValue(0); 1253 DILocalVariable *Var = DDI.getDI()->getVariable(); 1254 DIExpression *Expr = DDI.getDI()->getExpression(); 1255 DebugLoc DL = DDI.getdl(); 1256 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1257 unsigned SDOrder = DDI.getSDNodeOrder(); 1258 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1259 // that DW_OP_stack_value is desired. 1260 assert(isa<DbgValueInst>(DDI.getDI())); 1261 bool StackValue = true; 1262 1263 // Can this Value can be encoded without any further work? 1264 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1265 return; 1266 1267 // Attempt to salvage back through as many instructions as possible. Bail if 1268 // a non-instruction is seen, such as a constant expression or global 1269 // variable. FIXME: Further work could recover those too. 1270 while (isa<Instruction>(V)) { 1271 Instruction &VAsInst = *cast<Instruction>(V); 1272 // Temporary "0", awaiting real implementation. 1273 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue, 0); 1274 1275 // If we cannot salvage any further, and haven't yet found a suitable debug 1276 // expression, bail out. 1277 if (!NewExpr) 1278 break; 1279 1280 // New value and expr now represent this debuginfo. 1281 V = VAsInst.getOperand(0); 1282 Expr = NewExpr; 1283 1284 // Some kind of simplification occurred: check whether the operand of the 1285 // salvaged debug expression can be encoded in this DAG. 1286 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1287 /*IsVariadic=*/false)) { 1288 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1289 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1290 return; 1291 } 1292 } 1293 1294 // This was the final opportunity to salvage this debug information, and it 1295 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1296 // any earlier variable location. 1297 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1298 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1299 DAG.AddDbgValue(SDV, false); 1300 1301 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1302 << "\n"); 1303 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1304 << "\n"); 1305 } 1306 1307 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1308 DILocalVariable *Var, 1309 DIExpression *Expr, DebugLoc dl, 1310 DebugLoc InstDL, unsigned Order, 1311 bool IsVariadic) { 1312 if (Values.empty()) 1313 return true; 1314 SmallVector<SDDbgOperand> LocationOps; 1315 SmallVector<SDNode *> Dependencies; 1316 for (const Value *V : Values) { 1317 // Constant value. 1318 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1319 isa<ConstantPointerNull>(V)) { 1320 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1321 continue; 1322 } 1323 1324 // If the Value is a frame index, we can create a FrameIndex debug value 1325 // without relying on the DAG at all. 1326 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1327 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1328 if (SI != FuncInfo.StaticAllocaMap.end()) { 1329 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1330 continue; 1331 } 1332 } 1333 1334 // Do not use getValue() in here; we don't want to generate code at 1335 // this point if it hasn't been done yet. 1336 SDValue N = NodeMap[V]; 1337 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1338 N = UnusedArgNodeMap[V]; 1339 if (N.getNode()) { 1340 // Only emit func arg dbg value for non-variadic dbg.values for now. 1341 if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1342 return true; 1343 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1344 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1345 // describe stack slot locations. 1346 // 1347 // Consider "int x = 0; int *px = &x;". There are two kinds of 1348 // interesting debug values here after optimization: 1349 // 1350 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1351 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1352 // 1353 // Both describe the direct values of their associated variables. 1354 Dependencies.push_back(N.getNode()); 1355 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1356 continue; 1357 } 1358 LocationOps.emplace_back( 1359 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1360 continue; 1361 } 1362 1363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1364 // Special rules apply for the first dbg.values of parameter variables in a 1365 // function. Identify them by the fact they reference Argument Values, that 1366 // they're parameters, and they are parameters of the current function. We 1367 // need to let them dangle until they get an SDNode. 1368 bool IsParamOfFunc = 1369 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1370 if (IsParamOfFunc) 1371 return false; 1372 1373 // The value is not used in this block yet (or it would have an SDNode). 1374 // We still want the value to appear for the user if possible -- if it has 1375 // an associated VReg, we can refer to that instead. 1376 auto VMI = FuncInfo.ValueMap.find(V); 1377 if (VMI != FuncInfo.ValueMap.end()) { 1378 unsigned Reg = VMI->second; 1379 // If this is a PHI node, it may be split up into several MI PHI nodes 1380 // (in FunctionLoweringInfo::set). 1381 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1382 V->getType(), None); 1383 if (RFV.occupiesMultipleRegs()) { 1384 // FIXME: We could potentially support variadic dbg_values here. 1385 if (IsVariadic) 1386 return false; 1387 unsigned Offset = 0; 1388 unsigned BitsToDescribe = 0; 1389 if (auto VarSize = Var->getSizeInBits()) 1390 BitsToDescribe = *VarSize; 1391 if (auto Fragment = Expr->getFragmentInfo()) 1392 BitsToDescribe = Fragment->SizeInBits; 1393 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1394 // Bail out if all bits are described already. 1395 if (Offset >= BitsToDescribe) 1396 break; 1397 // TODO: handle scalable vectors. 1398 unsigned RegisterSize = RegAndSize.second; 1399 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1400 ? BitsToDescribe - Offset 1401 : RegisterSize; 1402 auto FragmentExpr = DIExpression::createFragmentExpression( 1403 Expr, Offset, FragmentSize); 1404 if (!FragmentExpr) 1405 continue; 1406 SDDbgValue *SDV = DAG.getVRegDbgValue( 1407 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1408 DAG.AddDbgValue(SDV, false); 1409 Offset += RegisterSize; 1410 } 1411 return true; 1412 } 1413 // We can use simple vreg locations for variadic dbg_values as well. 1414 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1415 continue; 1416 } 1417 // We failed to create a SDDbgOperand for V. 1418 return false; 1419 } 1420 1421 // We have created a SDDbgOperand for each Value in Values. 1422 // Should use Order instead of SDNodeOrder? 1423 assert(!LocationOps.empty()); 1424 SDDbgValue *SDV = 1425 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1426 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1427 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1428 return true; 1429 } 1430 1431 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1432 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1433 for (auto &Pair : DanglingDebugInfoMap) 1434 for (auto &DDI : Pair.second) 1435 salvageUnresolvedDbgValue(DDI); 1436 clearDanglingDebugInfo(); 1437 } 1438 1439 /// getCopyFromRegs - If there was virtual register allocated for the value V 1440 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1441 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1442 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1443 SDValue Result; 1444 1445 if (It != FuncInfo.ValueMap.end()) { 1446 Register InReg = It->second; 1447 1448 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1449 DAG.getDataLayout(), InReg, Ty, 1450 None); // This is not an ABI copy. 1451 SDValue Chain = DAG.getEntryNode(); 1452 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1453 V); 1454 resolveDanglingDebugInfo(V, Result); 1455 } 1456 1457 return Result; 1458 } 1459 1460 /// getValue - Return an SDValue for the given Value. 1461 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1462 // If we already have an SDValue for this value, use it. It's important 1463 // to do this first, so that we don't create a CopyFromReg if we already 1464 // have a regular SDValue. 1465 SDValue &N = NodeMap[V]; 1466 if (N.getNode()) return N; 1467 1468 // If there's a virtual register allocated and initialized for this 1469 // value, use it. 1470 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1471 return copyFromReg; 1472 1473 // Otherwise create a new SDValue and remember it. 1474 SDValue Val = getValueImpl(V); 1475 NodeMap[V] = Val; 1476 resolveDanglingDebugInfo(V, Val); 1477 return Val; 1478 } 1479 1480 /// getNonRegisterValue - Return an SDValue for the given Value, but 1481 /// don't look in FuncInfo.ValueMap for a virtual register. 1482 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1483 // If we already have an SDValue for this value, use it. 1484 SDValue &N = NodeMap[V]; 1485 if (N.getNode()) { 1486 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1487 // Remove the debug location from the node as the node is about to be used 1488 // in a location which may differ from the original debug location. This 1489 // is relevant to Constant and ConstantFP nodes because they can appear 1490 // as constant expressions inside PHI nodes. 1491 N->setDebugLoc(DebugLoc()); 1492 } 1493 return N; 1494 } 1495 1496 // Otherwise create a new SDValue and remember it. 1497 SDValue Val = getValueImpl(V); 1498 NodeMap[V] = Val; 1499 resolveDanglingDebugInfo(V, Val); 1500 return Val; 1501 } 1502 1503 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1504 /// Create an SDValue for the given value. 1505 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1506 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1507 1508 if (const Constant *C = dyn_cast<Constant>(V)) { 1509 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1510 1511 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1512 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1513 1514 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1515 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1516 1517 if (isa<ConstantPointerNull>(C)) { 1518 unsigned AS = V->getType()->getPointerAddressSpace(); 1519 return DAG.getConstant(0, getCurSDLoc(), 1520 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1521 } 1522 1523 if (match(C, m_VScale(DAG.getDataLayout()))) 1524 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1525 1526 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1527 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1528 1529 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1530 return DAG.getUNDEF(VT); 1531 1532 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1533 visit(CE->getOpcode(), *CE); 1534 SDValue N1 = NodeMap[V]; 1535 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1536 return N1; 1537 } 1538 1539 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1540 SmallVector<SDValue, 4> Constants; 1541 for (const Use &U : C->operands()) { 1542 SDNode *Val = getValue(U).getNode(); 1543 // If the operand is an empty aggregate, there are no values. 1544 if (!Val) continue; 1545 // Add each leaf value from the operand to the Constants list 1546 // to form a flattened list of all the values. 1547 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1548 Constants.push_back(SDValue(Val, i)); 1549 } 1550 1551 return DAG.getMergeValues(Constants, getCurSDLoc()); 1552 } 1553 1554 if (const ConstantDataSequential *CDS = 1555 dyn_cast<ConstantDataSequential>(C)) { 1556 SmallVector<SDValue, 4> Ops; 1557 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1558 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1559 // Add each leaf value from the operand to the Constants list 1560 // to form a flattened list of all the values. 1561 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1562 Ops.push_back(SDValue(Val, i)); 1563 } 1564 1565 if (isa<ArrayType>(CDS->getType())) 1566 return DAG.getMergeValues(Ops, getCurSDLoc()); 1567 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1568 } 1569 1570 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1571 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1572 "Unknown struct or array constant!"); 1573 1574 SmallVector<EVT, 4> ValueVTs; 1575 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1576 unsigned NumElts = ValueVTs.size(); 1577 if (NumElts == 0) 1578 return SDValue(); // empty struct 1579 SmallVector<SDValue, 4> Constants(NumElts); 1580 for (unsigned i = 0; i != NumElts; ++i) { 1581 EVT EltVT = ValueVTs[i]; 1582 if (isa<UndefValue>(C)) 1583 Constants[i] = DAG.getUNDEF(EltVT); 1584 else if (EltVT.isFloatingPoint()) 1585 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1586 else 1587 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1588 } 1589 1590 return DAG.getMergeValues(Constants, getCurSDLoc()); 1591 } 1592 1593 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1594 return DAG.getBlockAddress(BA, VT); 1595 1596 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1597 return getValue(Equiv->getGlobalValue()); 1598 1599 VectorType *VecTy = cast<VectorType>(V->getType()); 1600 1601 // Now that we know the number and type of the elements, get that number of 1602 // elements into the Ops array based on what kind of constant it is. 1603 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1604 SmallVector<SDValue, 16> Ops; 1605 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1606 for (unsigned i = 0; i != NumElements; ++i) 1607 Ops.push_back(getValue(CV->getOperand(i))); 1608 1609 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1610 } else if (isa<ConstantAggregateZero>(C)) { 1611 EVT EltVT = 1612 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1613 1614 SDValue Op; 1615 if (EltVT.isFloatingPoint()) 1616 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1617 else 1618 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1619 1620 if (isa<ScalableVectorType>(VecTy)) 1621 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1622 else { 1623 SmallVector<SDValue, 16> Ops; 1624 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1625 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1626 } 1627 } 1628 llvm_unreachable("Unknown vector constant"); 1629 } 1630 1631 // If this is a static alloca, generate it as the frameindex instead of 1632 // computation. 1633 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1634 DenseMap<const AllocaInst*, int>::iterator SI = 1635 FuncInfo.StaticAllocaMap.find(AI); 1636 if (SI != FuncInfo.StaticAllocaMap.end()) 1637 return DAG.getFrameIndex(SI->second, 1638 TLI.getFrameIndexTy(DAG.getDataLayout())); 1639 } 1640 1641 // If this is an instruction which fast-isel has deferred, select it now. 1642 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1643 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1644 1645 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1646 Inst->getType(), None); 1647 SDValue Chain = DAG.getEntryNode(); 1648 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1649 } 1650 1651 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1652 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1653 } 1654 llvm_unreachable("Can't get register for value!"); 1655 } 1656 1657 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1658 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1659 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1660 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1661 bool IsSEH = isAsynchronousEHPersonality(Pers); 1662 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1663 if (!IsSEH) 1664 CatchPadMBB->setIsEHScopeEntry(); 1665 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1666 if (IsMSVCCXX || IsCoreCLR) 1667 CatchPadMBB->setIsEHFuncletEntry(); 1668 } 1669 1670 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1671 // Update machine-CFG edge. 1672 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1673 FuncInfo.MBB->addSuccessor(TargetMBB); 1674 TargetMBB->setIsEHCatchretTarget(true); 1675 DAG.getMachineFunction().setHasEHCatchret(true); 1676 1677 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1678 bool IsSEH = isAsynchronousEHPersonality(Pers); 1679 if (IsSEH) { 1680 // If this is not a fall-through branch or optimizations are switched off, 1681 // emit the branch. 1682 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1683 TM.getOptLevel() == CodeGenOpt::None) 1684 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1685 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1686 return; 1687 } 1688 1689 // Figure out the funclet membership for the catchret's successor. 1690 // This will be used by the FuncletLayout pass to determine how to order the 1691 // BB's. 1692 // A 'catchret' returns to the outer scope's color. 1693 Value *ParentPad = I.getCatchSwitchParentPad(); 1694 const BasicBlock *SuccessorColor; 1695 if (isa<ConstantTokenNone>(ParentPad)) 1696 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1697 else 1698 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1699 assert(SuccessorColor && "No parent funclet for catchret!"); 1700 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1701 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1702 1703 // Create the terminator node. 1704 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1705 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1706 DAG.getBasicBlock(SuccessorColorMBB)); 1707 DAG.setRoot(Ret); 1708 } 1709 1710 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1711 // Don't emit any special code for the cleanuppad instruction. It just marks 1712 // the start of an EH scope/funclet. 1713 FuncInfo.MBB->setIsEHScopeEntry(); 1714 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1715 if (Pers != EHPersonality::Wasm_CXX) { 1716 FuncInfo.MBB->setIsEHFuncletEntry(); 1717 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1718 } 1719 } 1720 1721 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1722 // not match, it is OK to add only the first unwind destination catchpad to the 1723 // successors, because there will be at least one invoke instruction within the 1724 // catch scope that points to the next unwind destination, if one exists, so 1725 // CFGSort cannot mess up with BB sorting order. 1726 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1727 // call within them, and catchpads only consisting of 'catch (...)' have a 1728 // '__cxa_end_catch' call within them, both of which generate invokes in case 1729 // the next unwind destination exists, i.e., the next unwind destination is not 1730 // the caller.) 1731 // 1732 // Having at most one EH pad successor is also simpler and helps later 1733 // transformations. 1734 // 1735 // For example, 1736 // current: 1737 // invoke void @foo to ... unwind label %catch.dispatch 1738 // catch.dispatch: 1739 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1740 // catch.start: 1741 // ... 1742 // ... in this BB or some other child BB dominated by this BB there will be an 1743 // invoke that points to 'next' BB as an unwind destination 1744 // 1745 // next: ; We don't need to add this to 'current' BB's successor 1746 // ... 1747 static void findWasmUnwindDestinations( 1748 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1749 BranchProbability Prob, 1750 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1751 &UnwindDests) { 1752 while (EHPadBB) { 1753 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1754 if (isa<CleanupPadInst>(Pad)) { 1755 // Stop on cleanup pads. 1756 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1757 UnwindDests.back().first->setIsEHScopeEntry(); 1758 break; 1759 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1760 // Add the catchpad handlers to the possible destinations. We don't 1761 // continue to the unwind destination of the catchswitch for wasm. 1762 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1763 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1764 UnwindDests.back().first->setIsEHScopeEntry(); 1765 } 1766 break; 1767 } else { 1768 continue; 1769 } 1770 } 1771 } 1772 1773 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1774 /// many places it could ultimately go. In the IR, we have a single unwind 1775 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1776 /// This function skips over imaginary basic blocks that hold catchswitch 1777 /// instructions, and finds all the "real" machine 1778 /// basic block destinations. As those destinations may not be successors of 1779 /// EHPadBB, here we also calculate the edge probability to those destinations. 1780 /// The passed-in Prob is the edge probability to EHPadBB. 1781 static void findUnwindDestinations( 1782 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1783 BranchProbability Prob, 1784 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1785 &UnwindDests) { 1786 EHPersonality Personality = 1787 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1788 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1789 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1790 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1791 bool IsSEH = isAsynchronousEHPersonality(Personality); 1792 1793 if (IsWasmCXX) { 1794 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1795 assert(UnwindDests.size() <= 1 && 1796 "There should be at most one unwind destination for wasm"); 1797 return; 1798 } 1799 1800 while (EHPadBB) { 1801 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1802 BasicBlock *NewEHPadBB = nullptr; 1803 if (isa<LandingPadInst>(Pad)) { 1804 // Stop on landingpads. They are not funclets. 1805 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1806 break; 1807 } else if (isa<CleanupPadInst>(Pad)) { 1808 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1809 // personalities. 1810 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1811 UnwindDests.back().first->setIsEHScopeEntry(); 1812 UnwindDests.back().first->setIsEHFuncletEntry(); 1813 break; 1814 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1815 // Add the catchpad handlers to the possible destinations. 1816 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1817 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1818 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1819 if (IsMSVCCXX || IsCoreCLR) 1820 UnwindDests.back().first->setIsEHFuncletEntry(); 1821 if (!IsSEH) 1822 UnwindDests.back().first->setIsEHScopeEntry(); 1823 } 1824 NewEHPadBB = CatchSwitch->getUnwindDest(); 1825 } else { 1826 continue; 1827 } 1828 1829 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1830 if (BPI && NewEHPadBB) 1831 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1832 EHPadBB = NewEHPadBB; 1833 } 1834 } 1835 1836 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1837 // Update successor info. 1838 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1839 auto UnwindDest = I.getUnwindDest(); 1840 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1841 BranchProbability UnwindDestProb = 1842 (BPI && UnwindDest) 1843 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1844 : BranchProbability::getZero(); 1845 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1846 for (auto &UnwindDest : UnwindDests) { 1847 UnwindDest.first->setIsEHPad(); 1848 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1849 } 1850 FuncInfo.MBB->normalizeSuccProbs(); 1851 1852 // Create the terminator node. 1853 SDValue Ret = 1854 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1855 DAG.setRoot(Ret); 1856 } 1857 1858 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1859 report_fatal_error("visitCatchSwitch not yet implemented!"); 1860 } 1861 1862 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1863 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1864 auto &DL = DAG.getDataLayout(); 1865 SDValue Chain = getControlRoot(); 1866 SmallVector<ISD::OutputArg, 8> Outs; 1867 SmallVector<SDValue, 8> OutVals; 1868 1869 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1870 // lower 1871 // 1872 // %val = call <ty> @llvm.experimental.deoptimize() 1873 // ret <ty> %val 1874 // 1875 // differently. 1876 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1877 LowerDeoptimizingReturn(); 1878 return; 1879 } 1880 1881 if (!FuncInfo.CanLowerReturn) { 1882 unsigned DemoteReg = FuncInfo.DemoteRegister; 1883 const Function *F = I.getParent()->getParent(); 1884 1885 // Emit a store of the return value through the virtual register. 1886 // Leave Outs empty so that LowerReturn won't try to load return 1887 // registers the usual way. 1888 SmallVector<EVT, 1> PtrValueVTs; 1889 ComputeValueVTs(TLI, DL, 1890 F->getReturnType()->getPointerTo( 1891 DAG.getDataLayout().getAllocaAddrSpace()), 1892 PtrValueVTs); 1893 1894 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1895 DemoteReg, PtrValueVTs[0]); 1896 SDValue RetOp = getValue(I.getOperand(0)); 1897 1898 SmallVector<EVT, 4> ValueVTs, MemVTs; 1899 SmallVector<uint64_t, 4> Offsets; 1900 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1901 &Offsets); 1902 unsigned NumValues = ValueVTs.size(); 1903 1904 SmallVector<SDValue, 4> Chains(NumValues); 1905 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1906 for (unsigned i = 0; i != NumValues; ++i) { 1907 // An aggregate return value cannot wrap around the address space, so 1908 // offsets to its parts don't wrap either. 1909 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1910 TypeSize::Fixed(Offsets[i])); 1911 1912 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1913 if (MemVTs[i] != ValueVTs[i]) 1914 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1915 Chains[i] = DAG.getStore( 1916 Chain, getCurSDLoc(), Val, 1917 // FIXME: better loc info would be nice. 1918 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1919 commonAlignment(BaseAlign, Offsets[i])); 1920 } 1921 1922 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1923 MVT::Other, Chains); 1924 } else if (I.getNumOperands() != 0) { 1925 SmallVector<EVT, 4> ValueVTs; 1926 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1927 unsigned NumValues = ValueVTs.size(); 1928 if (NumValues) { 1929 SDValue RetOp = getValue(I.getOperand(0)); 1930 1931 const Function *F = I.getParent()->getParent(); 1932 1933 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1934 I.getOperand(0)->getType(), F->getCallingConv(), 1935 /*IsVarArg*/ false); 1936 1937 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1938 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1939 Attribute::SExt)) 1940 ExtendKind = ISD::SIGN_EXTEND; 1941 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1942 Attribute::ZExt)) 1943 ExtendKind = ISD::ZERO_EXTEND; 1944 1945 LLVMContext &Context = F->getContext(); 1946 bool RetInReg = F->getAttributes().hasAttribute( 1947 AttributeList::ReturnIndex, Attribute::InReg); 1948 1949 for (unsigned j = 0; j != NumValues; ++j) { 1950 EVT VT = ValueVTs[j]; 1951 1952 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1953 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1954 1955 CallingConv::ID CC = F->getCallingConv(); 1956 1957 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1958 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1959 SmallVector<SDValue, 4> Parts(NumParts); 1960 getCopyToParts(DAG, getCurSDLoc(), 1961 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1962 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1963 1964 // 'inreg' on function refers to return value 1965 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1966 if (RetInReg) 1967 Flags.setInReg(); 1968 1969 if (I.getOperand(0)->getType()->isPointerTy()) { 1970 Flags.setPointer(); 1971 Flags.setPointerAddrSpace( 1972 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1973 } 1974 1975 if (NeedsRegBlock) { 1976 Flags.setInConsecutiveRegs(); 1977 if (j == NumValues - 1) 1978 Flags.setInConsecutiveRegsLast(); 1979 } 1980 1981 // Propagate extension type if any 1982 if (ExtendKind == ISD::SIGN_EXTEND) 1983 Flags.setSExt(); 1984 else if (ExtendKind == ISD::ZERO_EXTEND) 1985 Flags.setZExt(); 1986 1987 for (unsigned i = 0; i < NumParts; ++i) { 1988 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1989 VT, /*isfixed=*/true, 0, 0)); 1990 OutVals.push_back(Parts[i]); 1991 } 1992 } 1993 } 1994 } 1995 1996 // Push in swifterror virtual register as the last element of Outs. This makes 1997 // sure swifterror virtual register will be returned in the swifterror 1998 // physical register. 1999 const Function *F = I.getParent()->getParent(); 2000 if (TLI.supportSwiftError() && 2001 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2002 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2003 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2004 Flags.setSwiftError(); 2005 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 2006 EVT(TLI.getPointerTy(DL)) /*argvt*/, 2007 true /*isfixed*/, 1 /*origidx*/, 2008 0 /*partOffs*/)); 2009 // Create SDNode for the swifterror virtual register. 2010 OutVals.push_back( 2011 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2012 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2013 EVT(TLI.getPointerTy(DL)))); 2014 } 2015 2016 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2017 CallingConv::ID CallConv = 2018 DAG.getMachineFunction().getFunction().getCallingConv(); 2019 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2020 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2021 2022 // Verify that the target's LowerReturn behaved as expected. 2023 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2024 "LowerReturn didn't return a valid chain!"); 2025 2026 // Update the DAG with the new chain value resulting from return lowering. 2027 DAG.setRoot(Chain); 2028 } 2029 2030 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2031 /// created for it, emit nodes to copy the value into the virtual 2032 /// registers. 2033 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2034 // Skip empty types 2035 if (V->getType()->isEmptyTy()) 2036 return; 2037 2038 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2039 if (VMI != FuncInfo.ValueMap.end()) { 2040 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2041 CopyValueToVirtualRegister(V, VMI->second); 2042 } 2043 } 2044 2045 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2046 /// the current basic block, add it to ValueMap now so that we'll get a 2047 /// CopyTo/FromReg. 2048 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2049 // No need to export constants. 2050 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2051 2052 // Already exported? 2053 if (FuncInfo.isExportedInst(V)) return; 2054 2055 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2056 CopyValueToVirtualRegister(V, Reg); 2057 } 2058 2059 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2060 const BasicBlock *FromBB) { 2061 // The operands of the setcc have to be in this block. We don't know 2062 // how to export them from some other block. 2063 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2064 // Can export from current BB. 2065 if (VI->getParent() == FromBB) 2066 return true; 2067 2068 // Is already exported, noop. 2069 return FuncInfo.isExportedInst(V); 2070 } 2071 2072 // If this is an argument, we can export it if the BB is the entry block or 2073 // if it is already exported. 2074 if (isa<Argument>(V)) { 2075 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2076 return true; 2077 2078 // Otherwise, can only export this if it is already exported. 2079 return FuncInfo.isExportedInst(V); 2080 } 2081 2082 // Otherwise, constants can always be exported. 2083 return true; 2084 } 2085 2086 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2087 BranchProbability 2088 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2089 const MachineBasicBlock *Dst) const { 2090 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2091 const BasicBlock *SrcBB = Src->getBasicBlock(); 2092 const BasicBlock *DstBB = Dst->getBasicBlock(); 2093 if (!BPI) { 2094 // If BPI is not available, set the default probability as 1 / N, where N is 2095 // the number of successors. 2096 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2097 return BranchProbability(1, SuccSize); 2098 } 2099 return BPI->getEdgeProbability(SrcBB, DstBB); 2100 } 2101 2102 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2103 MachineBasicBlock *Dst, 2104 BranchProbability Prob) { 2105 if (!FuncInfo.BPI) 2106 Src->addSuccessorWithoutProb(Dst); 2107 else { 2108 if (Prob.isUnknown()) 2109 Prob = getEdgeProbability(Src, Dst); 2110 Src->addSuccessor(Dst, Prob); 2111 } 2112 } 2113 2114 static bool InBlock(const Value *V, const BasicBlock *BB) { 2115 if (const Instruction *I = dyn_cast<Instruction>(V)) 2116 return I->getParent() == BB; 2117 return true; 2118 } 2119 2120 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2121 /// This function emits a branch and is used at the leaves of an OR or an 2122 /// AND operator tree. 2123 void 2124 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2125 MachineBasicBlock *TBB, 2126 MachineBasicBlock *FBB, 2127 MachineBasicBlock *CurBB, 2128 MachineBasicBlock *SwitchBB, 2129 BranchProbability TProb, 2130 BranchProbability FProb, 2131 bool InvertCond) { 2132 const BasicBlock *BB = CurBB->getBasicBlock(); 2133 2134 // If the leaf of the tree is a comparison, merge the condition into 2135 // the caseblock. 2136 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2137 // The operands of the cmp have to be in this block. We don't know 2138 // how to export them from some other block. If this is the first block 2139 // of the sequence, no exporting is needed. 2140 if (CurBB == SwitchBB || 2141 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2142 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2143 ISD::CondCode Condition; 2144 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2145 ICmpInst::Predicate Pred = 2146 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2147 Condition = getICmpCondCode(Pred); 2148 } else { 2149 const FCmpInst *FC = cast<FCmpInst>(Cond); 2150 FCmpInst::Predicate Pred = 2151 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2152 Condition = getFCmpCondCode(Pred); 2153 if (TM.Options.NoNaNsFPMath) 2154 Condition = getFCmpCodeWithoutNaN(Condition); 2155 } 2156 2157 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2158 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2159 SL->SwitchCases.push_back(CB); 2160 return; 2161 } 2162 } 2163 2164 // Create a CaseBlock record representing this branch. 2165 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2166 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2167 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2168 SL->SwitchCases.push_back(CB); 2169 } 2170 2171 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2172 MachineBasicBlock *TBB, 2173 MachineBasicBlock *FBB, 2174 MachineBasicBlock *CurBB, 2175 MachineBasicBlock *SwitchBB, 2176 Instruction::BinaryOps Opc, 2177 BranchProbability TProb, 2178 BranchProbability FProb, 2179 bool InvertCond) { 2180 // Skip over not part of the tree and remember to invert op and operands at 2181 // next level. 2182 Value *NotCond; 2183 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2184 InBlock(NotCond, CurBB->getBasicBlock())) { 2185 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2186 !InvertCond); 2187 return; 2188 } 2189 2190 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2191 const Value *BOpOp0, *BOpOp1; 2192 // Compute the effective opcode for Cond, taking into account whether it needs 2193 // to be inverted, e.g. 2194 // and (not (or A, B)), C 2195 // gets lowered as 2196 // and (and (not A, not B), C) 2197 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2198 if (BOp) { 2199 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2200 ? Instruction::And 2201 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2202 ? Instruction::Or 2203 : (Instruction::BinaryOps)0); 2204 if (InvertCond) { 2205 if (BOpc == Instruction::And) 2206 BOpc = Instruction::Or; 2207 else if (BOpc == Instruction::Or) 2208 BOpc = Instruction::And; 2209 } 2210 } 2211 2212 // If this node is not part of the or/and tree, emit it as a branch. 2213 // Note that all nodes in the tree should have same opcode. 2214 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2215 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2216 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2217 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2218 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2219 TProb, FProb, InvertCond); 2220 return; 2221 } 2222 2223 // Create TmpBB after CurBB. 2224 MachineFunction::iterator BBI(CurBB); 2225 MachineFunction &MF = DAG.getMachineFunction(); 2226 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2227 CurBB->getParent()->insert(++BBI, TmpBB); 2228 2229 if (Opc == Instruction::Or) { 2230 // Codegen X | Y as: 2231 // BB1: 2232 // jmp_if_X TBB 2233 // jmp TmpBB 2234 // TmpBB: 2235 // jmp_if_Y TBB 2236 // jmp FBB 2237 // 2238 2239 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2240 // The requirement is that 2241 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2242 // = TrueProb for original BB. 2243 // Assuming the original probabilities are A and B, one choice is to set 2244 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2245 // A/(1+B) and 2B/(1+B). This choice assumes that 2246 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2247 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2248 // TmpBB, but the math is more complicated. 2249 2250 auto NewTrueProb = TProb / 2; 2251 auto NewFalseProb = TProb / 2 + FProb; 2252 // Emit the LHS condition. 2253 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2254 NewFalseProb, InvertCond); 2255 2256 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2257 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2258 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2259 // Emit the RHS condition into TmpBB. 2260 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2261 Probs[1], InvertCond); 2262 } else { 2263 assert(Opc == Instruction::And && "Unknown merge op!"); 2264 // Codegen X & Y as: 2265 // BB1: 2266 // jmp_if_X TmpBB 2267 // jmp FBB 2268 // TmpBB: 2269 // jmp_if_Y TBB 2270 // jmp FBB 2271 // 2272 // This requires creation of TmpBB after CurBB. 2273 2274 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2275 // The requirement is that 2276 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2277 // = FalseProb for original BB. 2278 // Assuming the original probabilities are A and B, one choice is to set 2279 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2280 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2281 // TrueProb for BB1 * FalseProb for TmpBB. 2282 2283 auto NewTrueProb = TProb + FProb / 2; 2284 auto NewFalseProb = FProb / 2; 2285 // Emit the LHS condition. 2286 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2287 NewFalseProb, InvertCond); 2288 2289 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2290 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2291 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2292 // Emit the RHS condition into TmpBB. 2293 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2294 Probs[1], InvertCond); 2295 } 2296 } 2297 2298 /// If the set of cases should be emitted as a series of branches, return true. 2299 /// If we should emit this as a bunch of and/or'd together conditions, return 2300 /// false. 2301 bool 2302 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2303 if (Cases.size() != 2) return true; 2304 2305 // If this is two comparisons of the same values or'd or and'd together, they 2306 // will get folded into a single comparison, so don't emit two blocks. 2307 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2308 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2309 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2310 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2311 return false; 2312 } 2313 2314 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2315 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2316 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2317 Cases[0].CC == Cases[1].CC && 2318 isa<Constant>(Cases[0].CmpRHS) && 2319 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2320 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2321 return false; 2322 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2323 return false; 2324 } 2325 2326 return true; 2327 } 2328 2329 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2330 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2331 2332 // Update machine-CFG edges. 2333 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2334 2335 if (I.isUnconditional()) { 2336 // Update machine-CFG edges. 2337 BrMBB->addSuccessor(Succ0MBB); 2338 2339 // If this is not a fall-through branch or optimizations are switched off, 2340 // emit the branch. 2341 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2342 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2343 MVT::Other, getControlRoot(), 2344 DAG.getBasicBlock(Succ0MBB))); 2345 2346 return; 2347 } 2348 2349 // If this condition is one of the special cases we handle, do special stuff 2350 // now. 2351 const Value *CondVal = I.getCondition(); 2352 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2353 2354 // If this is a series of conditions that are or'd or and'd together, emit 2355 // this as a sequence of branches instead of setcc's with and/or operations. 2356 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2357 // unpredictable branches, and vector extracts because those jumps are likely 2358 // expensive for any target), this should improve performance. 2359 // For example, instead of something like: 2360 // cmp A, B 2361 // C = seteq 2362 // cmp D, E 2363 // F = setle 2364 // or C, F 2365 // jnz foo 2366 // Emit: 2367 // cmp A, B 2368 // je foo 2369 // cmp D, E 2370 // jle foo 2371 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2372 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2373 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2374 Value *Vec; 2375 const Value *BOp0, *BOp1; 2376 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2377 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2378 Opcode = Instruction::And; 2379 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2380 Opcode = Instruction::Or; 2381 2382 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2383 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2384 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2385 getEdgeProbability(BrMBB, Succ0MBB), 2386 getEdgeProbability(BrMBB, Succ1MBB), 2387 /*InvertCond=*/false); 2388 // If the compares in later blocks need to use values not currently 2389 // exported from this block, export them now. This block should always 2390 // be the first entry. 2391 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2392 2393 // Allow some cases to be rejected. 2394 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2395 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2396 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2397 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2398 } 2399 2400 // Emit the branch for this block. 2401 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2402 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2403 return; 2404 } 2405 2406 // Okay, we decided not to do this, remove any inserted MBB's and clear 2407 // SwitchCases. 2408 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2409 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2410 2411 SL->SwitchCases.clear(); 2412 } 2413 } 2414 2415 // Create a CaseBlock record representing this branch. 2416 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2417 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2418 2419 // Use visitSwitchCase to actually insert the fast branch sequence for this 2420 // cond branch. 2421 visitSwitchCase(CB, BrMBB); 2422 } 2423 2424 /// visitSwitchCase - Emits the necessary code to represent a single node in 2425 /// the binary search tree resulting from lowering a switch instruction. 2426 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2427 MachineBasicBlock *SwitchBB) { 2428 SDValue Cond; 2429 SDValue CondLHS = getValue(CB.CmpLHS); 2430 SDLoc dl = CB.DL; 2431 2432 if (CB.CC == ISD::SETTRUE) { 2433 // Branch or fall through to TrueBB. 2434 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2435 SwitchBB->normalizeSuccProbs(); 2436 if (CB.TrueBB != NextBlock(SwitchBB)) { 2437 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2438 DAG.getBasicBlock(CB.TrueBB))); 2439 } 2440 return; 2441 } 2442 2443 auto &TLI = DAG.getTargetLoweringInfo(); 2444 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2445 2446 // Build the setcc now. 2447 if (!CB.CmpMHS) { 2448 // Fold "(X == true)" to X and "(X == false)" to !X to 2449 // handle common cases produced by branch lowering. 2450 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2451 CB.CC == ISD::SETEQ) 2452 Cond = CondLHS; 2453 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2454 CB.CC == ISD::SETEQ) { 2455 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2456 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2457 } else { 2458 SDValue CondRHS = getValue(CB.CmpRHS); 2459 2460 // If a pointer's DAG type is larger than its memory type then the DAG 2461 // values are zero-extended. This breaks signed comparisons so truncate 2462 // back to the underlying type before doing the compare. 2463 if (CondLHS.getValueType() != MemVT) { 2464 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2465 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2466 } 2467 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2468 } 2469 } else { 2470 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2471 2472 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2473 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2474 2475 SDValue CmpOp = getValue(CB.CmpMHS); 2476 EVT VT = CmpOp.getValueType(); 2477 2478 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2479 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2480 ISD::SETLE); 2481 } else { 2482 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2483 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2484 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2485 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2486 } 2487 } 2488 2489 // Update successor info 2490 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2491 // TrueBB and FalseBB are always different unless the incoming IR is 2492 // degenerate. This only happens when running llc on weird IR. 2493 if (CB.TrueBB != CB.FalseBB) 2494 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2495 SwitchBB->normalizeSuccProbs(); 2496 2497 // If the lhs block is the next block, invert the condition so that we can 2498 // fall through to the lhs instead of the rhs block. 2499 if (CB.TrueBB == NextBlock(SwitchBB)) { 2500 std::swap(CB.TrueBB, CB.FalseBB); 2501 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2502 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2503 } 2504 2505 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2506 MVT::Other, getControlRoot(), Cond, 2507 DAG.getBasicBlock(CB.TrueBB)); 2508 2509 // Insert the false branch. Do this even if it's a fall through branch, 2510 // this makes it easier to do DAG optimizations which require inverting 2511 // the branch condition. 2512 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2513 DAG.getBasicBlock(CB.FalseBB)); 2514 2515 DAG.setRoot(BrCond); 2516 } 2517 2518 /// visitJumpTable - Emit JumpTable node in the current MBB 2519 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2520 // Emit the code for the jump table 2521 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2522 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2523 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2524 JT.Reg, PTy); 2525 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2526 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2527 MVT::Other, Index.getValue(1), 2528 Table, Index); 2529 DAG.setRoot(BrJumpTable); 2530 } 2531 2532 /// visitJumpTableHeader - This function emits necessary code to produce index 2533 /// in the JumpTable from switch case. 2534 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2535 JumpTableHeader &JTH, 2536 MachineBasicBlock *SwitchBB) { 2537 SDLoc dl = getCurSDLoc(); 2538 2539 // Subtract the lowest switch case value from the value being switched on. 2540 SDValue SwitchOp = getValue(JTH.SValue); 2541 EVT VT = SwitchOp.getValueType(); 2542 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2543 DAG.getConstant(JTH.First, dl, VT)); 2544 2545 // The SDNode we just created, which holds the value being switched on minus 2546 // the smallest case value, needs to be copied to a virtual register so it 2547 // can be used as an index into the jump table in a subsequent basic block. 2548 // This value may be smaller or larger than the target's pointer type, and 2549 // therefore require extension or truncating. 2550 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2551 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2552 2553 unsigned JumpTableReg = 2554 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2555 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2556 JumpTableReg, SwitchOp); 2557 JT.Reg = JumpTableReg; 2558 2559 if (!JTH.OmitRangeCheck) { 2560 // Emit the range check for the jump table, and branch to the default block 2561 // for the switch statement if the value being switched on exceeds the 2562 // largest case in the switch. 2563 SDValue CMP = DAG.getSetCC( 2564 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2565 Sub.getValueType()), 2566 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2567 2568 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2569 MVT::Other, CopyTo, CMP, 2570 DAG.getBasicBlock(JT.Default)); 2571 2572 // Avoid emitting unnecessary branches to the next block. 2573 if (JT.MBB != NextBlock(SwitchBB)) 2574 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2575 DAG.getBasicBlock(JT.MBB)); 2576 2577 DAG.setRoot(BrCond); 2578 } else { 2579 // Avoid emitting unnecessary branches to the next block. 2580 if (JT.MBB != NextBlock(SwitchBB)) 2581 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2582 DAG.getBasicBlock(JT.MBB))); 2583 else 2584 DAG.setRoot(CopyTo); 2585 } 2586 } 2587 2588 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2589 /// variable if there exists one. 2590 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2591 SDValue &Chain) { 2592 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2593 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2594 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2595 MachineFunction &MF = DAG.getMachineFunction(); 2596 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2597 MachineSDNode *Node = 2598 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2599 if (Global) { 2600 MachinePointerInfo MPInfo(Global); 2601 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2602 MachineMemOperand::MODereferenceable; 2603 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2604 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2605 DAG.setNodeMemRefs(Node, {MemRef}); 2606 } 2607 if (PtrTy != PtrMemTy) 2608 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2609 return SDValue(Node, 0); 2610 } 2611 2612 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2613 /// tail spliced into a stack protector check success bb. 2614 /// 2615 /// For a high level explanation of how this fits into the stack protector 2616 /// generation see the comment on the declaration of class 2617 /// StackProtectorDescriptor. 2618 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2619 MachineBasicBlock *ParentBB) { 2620 2621 // First create the loads to the guard/stack slot for the comparison. 2622 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2623 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2624 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2625 2626 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2627 int FI = MFI.getStackProtectorIndex(); 2628 2629 SDValue Guard; 2630 SDLoc dl = getCurSDLoc(); 2631 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2632 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2633 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2634 2635 // Generate code to load the content of the guard slot. 2636 SDValue GuardVal = DAG.getLoad( 2637 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2638 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2639 MachineMemOperand::MOVolatile); 2640 2641 if (TLI.useStackGuardXorFP()) 2642 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2643 2644 // Retrieve guard check function, nullptr if instrumentation is inlined. 2645 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2646 // The target provides a guard check function to validate the guard value. 2647 // Generate a call to that function with the content of the guard slot as 2648 // argument. 2649 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2650 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2651 2652 TargetLowering::ArgListTy Args; 2653 TargetLowering::ArgListEntry Entry; 2654 Entry.Node = GuardVal; 2655 Entry.Ty = FnTy->getParamType(0); 2656 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2657 Entry.IsInReg = true; 2658 Args.push_back(Entry); 2659 2660 TargetLowering::CallLoweringInfo CLI(DAG); 2661 CLI.setDebugLoc(getCurSDLoc()) 2662 .setChain(DAG.getEntryNode()) 2663 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2664 getValue(GuardCheckFn), std::move(Args)); 2665 2666 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2667 DAG.setRoot(Result.second); 2668 return; 2669 } 2670 2671 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2672 // Otherwise, emit a volatile load to retrieve the stack guard value. 2673 SDValue Chain = DAG.getEntryNode(); 2674 if (TLI.useLoadStackGuardNode()) { 2675 Guard = getLoadStackGuard(DAG, dl, Chain); 2676 } else { 2677 const Value *IRGuard = TLI.getSDagStackGuard(M); 2678 SDValue GuardPtr = getValue(IRGuard); 2679 2680 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2681 MachinePointerInfo(IRGuard, 0), Align, 2682 MachineMemOperand::MOVolatile); 2683 } 2684 2685 // Perform the comparison via a getsetcc. 2686 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2687 *DAG.getContext(), 2688 Guard.getValueType()), 2689 Guard, GuardVal, ISD::SETNE); 2690 2691 // If the guard/stackslot do not equal, branch to failure MBB. 2692 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2693 MVT::Other, GuardVal.getOperand(0), 2694 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2695 // Otherwise branch to success MBB. 2696 SDValue Br = DAG.getNode(ISD::BR, dl, 2697 MVT::Other, BrCond, 2698 DAG.getBasicBlock(SPD.getSuccessMBB())); 2699 2700 DAG.setRoot(Br); 2701 } 2702 2703 /// Codegen the failure basic block for a stack protector check. 2704 /// 2705 /// A failure stack protector machine basic block consists simply of a call to 2706 /// __stack_chk_fail(). 2707 /// 2708 /// For a high level explanation of how this fits into the stack protector 2709 /// generation see the comment on the declaration of class 2710 /// StackProtectorDescriptor. 2711 void 2712 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2713 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2714 TargetLowering::MakeLibCallOptions CallOptions; 2715 CallOptions.setDiscardResult(true); 2716 SDValue Chain = 2717 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2718 None, CallOptions, getCurSDLoc()).second; 2719 // On PS4, the "return address" must still be within the calling function, 2720 // even if it's at the very end, so emit an explicit TRAP here. 2721 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2722 if (TM.getTargetTriple().isPS4CPU()) 2723 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2724 // WebAssembly needs an unreachable instruction after a non-returning call, 2725 // because the function return type can be different from __stack_chk_fail's 2726 // return type (void). 2727 if (TM.getTargetTriple().isWasm()) 2728 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2729 2730 DAG.setRoot(Chain); 2731 } 2732 2733 /// visitBitTestHeader - This function emits necessary code to produce value 2734 /// suitable for "bit tests" 2735 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2736 MachineBasicBlock *SwitchBB) { 2737 SDLoc dl = getCurSDLoc(); 2738 2739 // Subtract the minimum value. 2740 SDValue SwitchOp = getValue(B.SValue); 2741 EVT VT = SwitchOp.getValueType(); 2742 SDValue RangeSub = 2743 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2744 2745 // Determine the type of the test operands. 2746 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2747 bool UsePtrType = false; 2748 if (!TLI.isTypeLegal(VT)) { 2749 UsePtrType = true; 2750 } else { 2751 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2752 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2753 // Switch table case range are encoded into series of masks. 2754 // Just use pointer type, it's guaranteed to fit. 2755 UsePtrType = true; 2756 break; 2757 } 2758 } 2759 SDValue Sub = RangeSub; 2760 if (UsePtrType) { 2761 VT = TLI.getPointerTy(DAG.getDataLayout()); 2762 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2763 } 2764 2765 B.RegVT = VT.getSimpleVT(); 2766 B.Reg = FuncInfo.CreateReg(B.RegVT); 2767 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2768 2769 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2770 2771 if (!B.OmitRangeCheck) 2772 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2773 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2774 SwitchBB->normalizeSuccProbs(); 2775 2776 SDValue Root = CopyTo; 2777 if (!B.OmitRangeCheck) { 2778 // Conditional branch to the default block. 2779 SDValue RangeCmp = DAG.getSetCC(dl, 2780 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2781 RangeSub.getValueType()), 2782 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2783 ISD::SETUGT); 2784 2785 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2786 DAG.getBasicBlock(B.Default)); 2787 } 2788 2789 // Avoid emitting unnecessary branches to the next block. 2790 if (MBB != NextBlock(SwitchBB)) 2791 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2792 2793 DAG.setRoot(Root); 2794 } 2795 2796 /// visitBitTestCase - this function produces one "bit test" 2797 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2798 MachineBasicBlock* NextMBB, 2799 BranchProbability BranchProbToNext, 2800 unsigned Reg, 2801 BitTestCase &B, 2802 MachineBasicBlock *SwitchBB) { 2803 SDLoc dl = getCurSDLoc(); 2804 MVT VT = BB.RegVT; 2805 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2806 SDValue Cmp; 2807 unsigned PopCount = countPopulation(B.Mask); 2808 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2809 if (PopCount == 1) { 2810 // Testing for a single bit; just compare the shift count with what it 2811 // would need to be to shift a 1 bit in that position. 2812 Cmp = DAG.getSetCC( 2813 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2814 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2815 ISD::SETEQ); 2816 } else if (PopCount == BB.Range) { 2817 // There is only one zero bit in the range, test for it directly. 2818 Cmp = DAG.getSetCC( 2819 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2820 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2821 ISD::SETNE); 2822 } else { 2823 // Make desired shift 2824 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2825 DAG.getConstant(1, dl, VT), ShiftOp); 2826 2827 // Emit bit tests and jumps 2828 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2829 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2830 Cmp = DAG.getSetCC( 2831 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2832 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2833 } 2834 2835 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2836 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2837 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2838 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2839 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2840 // one as they are relative probabilities (and thus work more like weights), 2841 // and hence we need to normalize them to let the sum of them become one. 2842 SwitchBB->normalizeSuccProbs(); 2843 2844 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2845 MVT::Other, getControlRoot(), 2846 Cmp, DAG.getBasicBlock(B.TargetBB)); 2847 2848 // Avoid emitting unnecessary branches to the next block. 2849 if (NextMBB != NextBlock(SwitchBB)) 2850 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2851 DAG.getBasicBlock(NextMBB)); 2852 2853 DAG.setRoot(BrAnd); 2854 } 2855 2856 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2857 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2858 2859 // Retrieve successors. Look through artificial IR level blocks like 2860 // catchswitch for successors. 2861 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2862 const BasicBlock *EHPadBB = I.getSuccessor(1); 2863 2864 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2865 // have to do anything here to lower funclet bundles. 2866 assert(!I.hasOperandBundlesOtherThan( 2867 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2868 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2869 LLVMContext::OB_cfguardtarget, 2870 LLVMContext::OB_clang_arc_attachedcall}) && 2871 "Cannot lower invokes with arbitrary operand bundles yet!"); 2872 2873 const Value *Callee(I.getCalledOperand()); 2874 const Function *Fn = dyn_cast<Function>(Callee); 2875 if (isa<InlineAsm>(Callee)) 2876 visitInlineAsm(I); 2877 else if (Fn && Fn->isIntrinsic()) { 2878 switch (Fn->getIntrinsicID()) { 2879 default: 2880 llvm_unreachable("Cannot invoke this intrinsic"); 2881 case Intrinsic::donothing: 2882 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2883 break; 2884 case Intrinsic::experimental_patchpoint_void: 2885 case Intrinsic::experimental_patchpoint_i64: 2886 visitPatchpoint(I, EHPadBB); 2887 break; 2888 case Intrinsic::experimental_gc_statepoint: 2889 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2890 break; 2891 case Intrinsic::wasm_rethrow: { 2892 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2893 // special because it can be invoked, so we manually lower it to a DAG 2894 // node here. 2895 SmallVector<SDValue, 8> Ops; 2896 Ops.push_back(getRoot()); // inchain 2897 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2898 Ops.push_back( 2899 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2900 TLI.getPointerTy(DAG.getDataLayout()))); 2901 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2902 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2903 break; 2904 } 2905 } 2906 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2907 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2908 // Eventually we will support lowering the @llvm.experimental.deoptimize 2909 // intrinsic, and right now there are no plans to support other intrinsics 2910 // with deopt state. 2911 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2912 } else { 2913 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2914 } 2915 2916 // If the value of the invoke is used outside of its defining block, make it 2917 // available as a virtual register. 2918 // We already took care of the exported value for the statepoint instruction 2919 // during call to the LowerStatepoint. 2920 if (!isa<GCStatepointInst>(I)) { 2921 CopyToExportRegsIfNeeded(&I); 2922 } 2923 2924 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2925 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2926 BranchProbability EHPadBBProb = 2927 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2928 : BranchProbability::getZero(); 2929 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2930 2931 // Update successor info. 2932 addSuccessorWithProb(InvokeMBB, Return); 2933 for (auto &UnwindDest : UnwindDests) { 2934 UnwindDest.first->setIsEHPad(); 2935 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2936 } 2937 InvokeMBB->normalizeSuccProbs(); 2938 2939 // Drop into normal successor. 2940 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2941 DAG.getBasicBlock(Return))); 2942 } 2943 2944 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2945 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2946 2947 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2948 // have to do anything here to lower funclet bundles. 2949 assert(!I.hasOperandBundlesOtherThan( 2950 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2951 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2952 2953 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2954 visitInlineAsm(I); 2955 CopyToExportRegsIfNeeded(&I); 2956 2957 // Retrieve successors. 2958 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2959 2960 // Update successor info. 2961 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2962 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2963 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2964 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2965 Target->setIsInlineAsmBrIndirectTarget(); 2966 } 2967 CallBrMBB->normalizeSuccProbs(); 2968 2969 // Drop into default successor. 2970 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2971 MVT::Other, getControlRoot(), 2972 DAG.getBasicBlock(Return))); 2973 } 2974 2975 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2976 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2977 } 2978 2979 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2980 assert(FuncInfo.MBB->isEHPad() && 2981 "Call to landingpad not in landing pad!"); 2982 2983 // If there aren't registers to copy the values into (e.g., during SjLj 2984 // exceptions), then don't bother to create these DAG nodes. 2985 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2986 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2987 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2988 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2989 return; 2990 2991 // If landingpad's return type is token type, we don't create DAG nodes 2992 // for its exception pointer and selector value. The extraction of exception 2993 // pointer or selector value from token type landingpads is not currently 2994 // supported. 2995 if (LP.getType()->isTokenTy()) 2996 return; 2997 2998 SmallVector<EVT, 2> ValueVTs; 2999 SDLoc dl = getCurSDLoc(); 3000 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3001 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3002 3003 // Get the two live-in registers as SDValues. The physregs have already been 3004 // copied into virtual registers. 3005 SDValue Ops[2]; 3006 if (FuncInfo.ExceptionPointerVirtReg) { 3007 Ops[0] = DAG.getZExtOrTrunc( 3008 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3009 FuncInfo.ExceptionPointerVirtReg, 3010 TLI.getPointerTy(DAG.getDataLayout())), 3011 dl, ValueVTs[0]); 3012 } else { 3013 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3014 } 3015 Ops[1] = DAG.getZExtOrTrunc( 3016 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3017 FuncInfo.ExceptionSelectorVirtReg, 3018 TLI.getPointerTy(DAG.getDataLayout())), 3019 dl, ValueVTs[1]); 3020 3021 // Merge into one. 3022 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3023 DAG.getVTList(ValueVTs), Ops); 3024 setValue(&LP, Res); 3025 } 3026 3027 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3028 MachineBasicBlock *Last) { 3029 // Update JTCases. 3030 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 3031 if (SL->JTCases[i].first.HeaderBB == First) 3032 SL->JTCases[i].first.HeaderBB = Last; 3033 3034 // Update BitTestCases. 3035 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 3036 if (SL->BitTestCases[i].Parent == First) 3037 SL->BitTestCases[i].Parent = Last; 3038 } 3039 3040 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3041 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3042 3043 // Update machine-CFG edges with unique successors. 3044 SmallSet<BasicBlock*, 32> Done; 3045 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3046 BasicBlock *BB = I.getSuccessor(i); 3047 bool Inserted = Done.insert(BB).second; 3048 if (!Inserted) 3049 continue; 3050 3051 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3052 addSuccessorWithProb(IndirectBrMBB, Succ); 3053 } 3054 IndirectBrMBB->normalizeSuccProbs(); 3055 3056 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3057 MVT::Other, getControlRoot(), 3058 getValue(I.getAddress()))); 3059 } 3060 3061 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3062 if (!DAG.getTarget().Options.TrapUnreachable) 3063 return; 3064 3065 // We may be able to ignore unreachable behind a noreturn call. 3066 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3067 const BasicBlock &BB = *I.getParent(); 3068 if (&I != &BB.front()) { 3069 BasicBlock::const_iterator PredI = 3070 std::prev(BasicBlock::const_iterator(&I)); 3071 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3072 if (Call->doesNotReturn()) 3073 return; 3074 } 3075 } 3076 } 3077 3078 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3079 } 3080 3081 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3082 SDNodeFlags Flags; 3083 3084 SDValue Op = getValue(I.getOperand(0)); 3085 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3086 Op, Flags); 3087 setValue(&I, UnNodeValue); 3088 } 3089 3090 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3091 SDNodeFlags Flags; 3092 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3093 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3094 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3095 } 3096 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3097 Flags.setExact(ExactOp->isExact()); 3098 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3099 Flags.copyFMF(*FPOp); 3100 3101 SDValue Op1 = getValue(I.getOperand(0)); 3102 SDValue Op2 = getValue(I.getOperand(1)); 3103 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3104 Op1, Op2, Flags); 3105 setValue(&I, BinNodeValue); 3106 } 3107 3108 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3109 SDValue Op1 = getValue(I.getOperand(0)); 3110 SDValue Op2 = getValue(I.getOperand(1)); 3111 3112 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3113 Op1.getValueType(), DAG.getDataLayout()); 3114 3115 // Coerce the shift amount to the right type if we can. 3116 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3117 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3118 unsigned Op2Size = Op2.getValueSizeInBits(); 3119 SDLoc DL = getCurSDLoc(); 3120 3121 // If the operand is smaller than the shift count type, promote it. 3122 if (ShiftSize > Op2Size) 3123 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3124 3125 // If the operand is larger than the shift count type but the shift 3126 // count type has enough bits to represent any shift value, truncate 3127 // it now. This is a common case and it exposes the truncate to 3128 // optimization early. 3129 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3130 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3131 // Otherwise we'll need to temporarily settle for some other convenient 3132 // type. Type legalization will make adjustments once the shiftee is split. 3133 else 3134 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3135 } 3136 3137 bool nuw = false; 3138 bool nsw = false; 3139 bool exact = false; 3140 3141 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3142 3143 if (const OverflowingBinaryOperator *OFBinOp = 3144 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3145 nuw = OFBinOp->hasNoUnsignedWrap(); 3146 nsw = OFBinOp->hasNoSignedWrap(); 3147 } 3148 if (const PossiblyExactOperator *ExactOp = 3149 dyn_cast<const PossiblyExactOperator>(&I)) 3150 exact = ExactOp->isExact(); 3151 } 3152 SDNodeFlags Flags; 3153 Flags.setExact(exact); 3154 Flags.setNoSignedWrap(nsw); 3155 Flags.setNoUnsignedWrap(nuw); 3156 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3157 Flags); 3158 setValue(&I, Res); 3159 } 3160 3161 void SelectionDAGBuilder::visitSDiv(const User &I) { 3162 SDValue Op1 = getValue(I.getOperand(0)); 3163 SDValue Op2 = getValue(I.getOperand(1)); 3164 3165 SDNodeFlags Flags; 3166 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3167 cast<PossiblyExactOperator>(&I)->isExact()); 3168 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3169 Op2, Flags)); 3170 } 3171 3172 void SelectionDAGBuilder::visitICmp(const User &I) { 3173 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3174 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3175 predicate = IC->getPredicate(); 3176 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3177 predicate = ICmpInst::Predicate(IC->getPredicate()); 3178 SDValue Op1 = getValue(I.getOperand(0)); 3179 SDValue Op2 = getValue(I.getOperand(1)); 3180 ISD::CondCode Opcode = getICmpCondCode(predicate); 3181 3182 auto &TLI = DAG.getTargetLoweringInfo(); 3183 EVT MemVT = 3184 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3185 3186 // If a pointer's DAG type is larger than its memory type then the DAG values 3187 // are zero-extended. This breaks signed comparisons so truncate back to the 3188 // underlying type before doing the compare. 3189 if (Op1.getValueType() != MemVT) { 3190 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3191 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3192 } 3193 3194 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3195 I.getType()); 3196 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3197 } 3198 3199 void SelectionDAGBuilder::visitFCmp(const User &I) { 3200 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3201 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3202 predicate = FC->getPredicate(); 3203 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3204 predicate = FCmpInst::Predicate(FC->getPredicate()); 3205 SDValue Op1 = getValue(I.getOperand(0)); 3206 SDValue Op2 = getValue(I.getOperand(1)); 3207 3208 ISD::CondCode Condition = getFCmpCondCode(predicate); 3209 auto *FPMO = cast<FPMathOperator>(&I); 3210 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3211 Condition = getFCmpCodeWithoutNaN(Condition); 3212 3213 SDNodeFlags Flags; 3214 Flags.copyFMF(*FPMO); 3215 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3216 3217 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3218 I.getType()); 3219 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3220 } 3221 3222 // Check if the condition of the select has one use or two users that are both 3223 // selects with the same condition. 3224 static bool hasOnlySelectUsers(const Value *Cond) { 3225 return llvm::all_of(Cond->users(), [](const Value *V) { 3226 return isa<SelectInst>(V); 3227 }); 3228 } 3229 3230 void SelectionDAGBuilder::visitSelect(const User &I) { 3231 SmallVector<EVT, 4> ValueVTs; 3232 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3233 ValueVTs); 3234 unsigned NumValues = ValueVTs.size(); 3235 if (NumValues == 0) return; 3236 3237 SmallVector<SDValue, 4> Values(NumValues); 3238 SDValue Cond = getValue(I.getOperand(0)); 3239 SDValue LHSVal = getValue(I.getOperand(1)); 3240 SDValue RHSVal = getValue(I.getOperand(2)); 3241 SmallVector<SDValue, 1> BaseOps(1, Cond); 3242 ISD::NodeType OpCode = 3243 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3244 3245 bool IsUnaryAbs = false; 3246 bool Negate = false; 3247 3248 SDNodeFlags Flags; 3249 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3250 Flags.copyFMF(*FPOp); 3251 3252 // Min/max matching is only viable if all output VTs are the same. 3253 if (is_splat(ValueVTs)) { 3254 EVT VT = ValueVTs[0]; 3255 LLVMContext &Ctx = *DAG.getContext(); 3256 auto &TLI = DAG.getTargetLoweringInfo(); 3257 3258 // We care about the legality of the operation after it has been type 3259 // legalized. 3260 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3261 VT = TLI.getTypeToTransformTo(Ctx, VT); 3262 3263 // If the vselect is legal, assume we want to leave this as a vector setcc + 3264 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3265 // min/max is legal on the scalar type. 3266 bool UseScalarMinMax = VT.isVector() && 3267 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3268 3269 Value *LHS, *RHS; 3270 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3271 ISD::NodeType Opc = ISD::DELETED_NODE; 3272 switch (SPR.Flavor) { 3273 case SPF_UMAX: Opc = ISD::UMAX; break; 3274 case SPF_UMIN: Opc = ISD::UMIN; break; 3275 case SPF_SMAX: Opc = ISD::SMAX; break; 3276 case SPF_SMIN: Opc = ISD::SMIN; break; 3277 case SPF_FMINNUM: 3278 switch (SPR.NaNBehavior) { 3279 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3280 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3281 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3282 case SPNB_RETURNS_ANY: { 3283 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3284 Opc = ISD::FMINNUM; 3285 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3286 Opc = ISD::FMINIMUM; 3287 else if (UseScalarMinMax) 3288 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3289 ISD::FMINNUM : ISD::FMINIMUM; 3290 break; 3291 } 3292 } 3293 break; 3294 case SPF_FMAXNUM: 3295 switch (SPR.NaNBehavior) { 3296 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3297 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3298 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3299 case SPNB_RETURNS_ANY: 3300 3301 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3302 Opc = ISD::FMAXNUM; 3303 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3304 Opc = ISD::FMAXIMUM; 3305 else if (UseScalarMinMax) 3306 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3307 ISD::FMAXNUM : ISD::FMAXIMUM; 3308 break; 3309 } 3310 break; 3311 case SPF_NABS: 3312 Negate = true; 3313 LLVM_FALLTHROUGH; 3314 case SPF_ABS: 3315 IsUnaryAbs = true; 3316 Opc = ISD::ABS; 3317 break; 3318 default: break; 3319 } 3320 3321 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3322 (TLI.isOperationLegalOrCustom(Opc, VT) || 3323 (UseScalarMinMax && 3324 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3325 // If the underlying comparison instruction is used by any other 3326 // instruction, the consumed instructions won't be destroyed, so it is 3327 // not profitable to convert to a min/max. 3328 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3329 OpCode = Opc; 3330 LHSVal = getValue(LHS); 3331 RHSVal = getValue(RHS); 3332 BaseOps.clear(); 3333 } 3334 3335 if (IsUnaryAbs) { 3336 OpCode = Opc; 3337 LHSVal = getValue(LHS); 3338 BaseOps.clear(); 3339 } 3340 } 3341 3342 if (IsUnaryAbs) { 3343 for (unsigned i = 0; i != NumValues; ++i) { 3344 SDLoc dl = getCurSDLoc(); 3345 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3346 Values[i] = 3347 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3348 if (Negate) 3349 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3350 Values[i]); 3351 } 3352 } else { 3353 for (unsigned i = 0; i != NumValues; ++i) { 3354 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3355 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3356 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3357 Values[i] = DAG.getNode( 3358 OpCode, getCurSDLoc(), 3359 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3360 } 3361 } 3362 3363 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3364 DAG.getVTList(ValueVTs), Values)); 3365 } 3366 3367 void SelectionDAGBuilder::visitTrunc(const User &I) { 3368 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3369 SDValue N = getValue(I.getOperand(0)); 3370 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3371 I.getType()); 3372 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3373 } 3374 3375 void SelectionDAGBuilder::visitZExt(const User &I) { 3376 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3377 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3378 SDValue N = getValue(I.getOperand(0)); 3379 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3380 I.getType()); 3381 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3382 } 3383 3384 void SelectionDAGBuilder::visitSExt(const User &I) { 3385 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3386 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3387 SDValue N = getValue(I.getOperand(0)); 3388 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3389 I.getType()); 3390 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3391 } 3392 3393 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3394 // FPTrunc is never a no-op cast, no need to check 3395 SDValue N = getValue(I.getOperand(0)); 3396 SDLoc dl = getCurSDLoc(); 3397 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3398 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3399 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3400 DAG.getTargetConstant( 3401 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3402 } 3403 3404 void SelectionDAGBuilder::visitFPExt(const User &I) { 3405 // FPExt is never a no-op cast, no need to check 3406 SDValue N = getValue(I.getOperand(0)); 3407 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3408 I.getType()); 3409 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3410 } 3411 3412 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3413 // FPToUI is never a no-op cast, no need to check 3414 SDValue N = getValue(I.getOperand(0)); 3415 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3416 I.getType()); 3417 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3418 } 3419 3420 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3421 // FPToSI is never a no-op cast, no need to check 3422 SDValue N = getValue(I.getOperand(0)); 3423 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3424 I.getType()); 3425 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3426 } 3427 3428 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3429 // UIToFP is never a no-op cast, no need to check 3430 SDValue N = getValue(I.getOperand(0)); 3431 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3432 I.getType()); 3433 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3434 } 3435 3436 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3437 // SIToFP is never a no-op cast, no need to check 3438 SDValue N = getValue(I.getOperand(0)); 3439 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3440 I.getType()); 3441 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3442 } 3443 3444 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3445 // What to do depends on the size of the integer and the size of the pointer. 3446 // We can either truncate, zero extend, or no-op, accordingly. 3447 SDValue N = getValue(I.getOperand(0)); 3448 auto &TLI = DAG.getTargetLoweringInfo(); 3449 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3450 I.getType()); 3451 EVT PtrMemVT = 3452 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3453 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3454 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3455 setValue(&I, N); 3456 } 3457 3458 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3459 // What to do depends on the size of the integer and the size of the pointer. 3460 // We can either truncate, zero extend, or no-op, accordingly. 3461 SDValue N = getValue(I.getOperand(0)); 3462 auto &TLI = DAG.getTargetLoweringInfo(); 3463 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3464 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3465 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3466 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3467 setValue(&I, N); 3468 } 3469 3470 void SelectionDAGBuilder::visitBitCast(const User &I) { 3471 SDValue N = getValue(I.getOperand(0)); 3472 SDLoc dl = getCurSDLoc(); 3473 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3474 I.getType()); 3475 3476 // BitCast assures us that source and destination are the same size so this is 3477 // either a BITCAST or a no-op. 3478 if (DestVT != N.getValueType()) 3479 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3480 DestVT, N)); // convert types. 3481 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3482 // might fold any kind of constant expression to an integer constant and that 3483 // is not what we are looking for. Only recognize a bitcast of a genuine 3484 // constant integer as an opaque constant. 3485 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3486 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3487 /*isOpaque*/true)); 3488 else 3489 setValue(&I, N); // noop cast. 3490 } 3491 3492 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3493 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3494 const Value *SV = I.getOperand(0); 3495 SDValue N = getValue(SV); 3496 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3497 3498 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3499 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3500 3501 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3502 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3503 3504 setValue(&I, N); 3505 } 3506 3507 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3509 SDValue InVec = getValue(I.getOperand(0)); 3510 SDValue InVal = getValue(I.getOperand(1)); 3511 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3512 TLI.getVectorIdxTy(DAG.getDataLayout())); 3513 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3514 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3515 InVec, InVal, InIdx)); 3516 } 3517 3518 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3519 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3520 SDValue InVec = getValue(I.getOperand(0)); 3521 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3522 TLI.getVectorIdxTy(DAG.getDataLayout())); 3523 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3524 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3525 InVec, InIdx)); 3526 } 3527 3528 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3529 SDValue Src1 = getValue(I.getOperand(0)); 3530 SDValue Src2 = getValue(I.getOperand(1)); 3531 ArrayRef<int> Mask; 3532 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3533 Mask = SVI->getShuffleMask(); 3534 else 3535 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3536 SDLoc DL = getCurSDLoc(); 3537 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3538 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3539 EVT SrcVT = Src1.getValueType(); 3540 3541 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3542 VT.isScalableVector()) { 3543 // Canonical splat form of first element of first input vector. 3544 SDValue FirstElt = 3545 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3546 DAG.getVectorIdxConstant(0, DL)); 3547 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3548 return; 3549 } 3550 3551 // For now, we only handle splats for scalable vectors. 3552 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3553 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3554 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3555 3556 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3557 unsigned MaskNumElts = Mask.size(); 3558 3559 if (SrcNumElts == MaskNumElts) { 3560 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3561 return; 3562 } 3563 3564 // Normalize the shuffle vector since mask and vector length don't match. 3565 if (SrcNumElts < MaskNumElts) { 3566 // Mask is longer than the source vectors. We can use concatenate vector to 3567 // make the mask and vectors lengths match. 3568 3569 if (MaskNumElts % SrcNumElts == 0) { 3570 // Mask length is a multiple of the source vector length. 3571 // Check if the shuffle is some kind of concatenation of the input 3572 // vectors. 3573 unsigned NumConcat = MaskNumElts / SrcNumElts; 3574 bool IsConcat = true; 3575 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3576 for (unsigned i = 0; i != MaskNumElts; ++i) { 3577 int Idx = Mask[i]; 3578 if (Idx < 0) 3579 continue; 3580 // Ensure the indices in each SrcVT sized piece are sequential and that 3581 // the same source is used for the whole piece. 3582 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3583 (ConcatSrcs[i / SrcNumElts] >= 0 && 3584 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3585 IsConcat = false; 3586 break; 3587 } 3588 // Remember which source this index came from. 3589 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3590 } 3591 3592 // The shuffle is concatenating multiple vectors together. Just emit 3593 // a CONCAT_VECTORS operation. 3594 if (IsConcat) { 3595 SmallVector<SDValue, 8> ConcatOps; 3596 for (auto Src : ConcatSrcs) { 3597 if (Src < 0) 3598 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3599 else if (Src == 0) 3600 ConcatOps.push_back(Src1); 3601 else 3602 ConcatOps.push_back(Src2); 3603 } 3604 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3605 return; 3606 } 3607 } 3608 3609 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3610 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3611 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3612 PaddedMaskNumElts); 3613 3614 // Pad both vectors with undefs to make them the same length as the mask. 3615 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3616 3617 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3618 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3619 MOps1[0] = Src1; 3620 MOps2[0] = Src2; 3621 3622 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3623 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3624 3625 // Readjust mask for new input vector length. 3626 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3627 for (unsigned i = 0; i != MaskNumElts; ++i) { 3628 int Idx = Mask[i]; 3629 if (Idx >= (int)SrcNumElts) 3630 Idx -= SrcNumElts - PaddedMaskNumElts; 3631 MappedOps[i] = Idx; 3632 } 3633 3634 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3635 3636 // If the concatenated vector was padded, extract a subvector with the 3637 // correct number of elements. 3638 if (MaskNumElts != PaddedMaskNumElts) 3639 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3640 DAG.getVectorIdxConstant(0, DL)); 3641 3642 setValue(&I, Result); 3643 return; 3644 } 3645 3646 if (SrcNumElts > MaskNumElts) { 3647 // Analyze the access pattern of the vector to see if we can extract 3648 // two subvectors and do the shuffle. 3649 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3650 bool CanExtract = true; 3651 for (int Idx : Mask) { 3652 unsigned Input = 0; 3653 if (Idx < 0) 3654 continue; 3655 3656 if (Idx >= (int)SrcNumElts) { 3657 Input = 1; 3658 Idx -= SrcNumElts; 3659 } 3660 3661 // If all the indices come from the same MaskNumElts sized portion of 3662 // the sources we can use extract. Also make sure the extract wouldn't 3663 // extract past the end of the source. 3664 int NewStartIdx = alignDown(Idx, MaskNumElts); 3665 if (NewStartIdx + MaskNumElts > SrcNumElts || 3666 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3667 CanExtract = false; 3668 // Make sure we always update StartIdx as we use it to track if all 3669 // elements are undef. 3670 StartIdx[Input] = NewStartIdx; 3671 } 3672 3673 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3674 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3675 return; 3676 } 3677 if (CanExtract) { 3678 // Extract appropriate subvector and generate a vector shuffle 3679 for (unsigned Input = 0; Input < 2; ++Input) { 3680 SDValue &Src = Input == 0 ? Src1 : Src2; 3681 if (StartIdx[Input] < 0) 3682 Src = DAG.getUNDEF(VT); 3683 else { 3684 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3685 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3686 } 3687 } 3688 3689 // Calculate new mask. 3690 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3691 for (int &Idx : MappedOps) { 3692 if (Idx >= (int)SrcNumElts) 3693 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3694 else if (Idx >= 0) 3695 Idx -= StartIdx[0]; 3696 } 3697 3698 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3699 return; 3700 } 3701 } 3702 3703 // We can't use either concat vectors or extract subvectors so fall back to 3704 // replacing the shuffle with extract and build vector. 3705 // to insert and build vector. 3706 EVT EltVT = VT.getVectorElementType(); 3707 SmallVector<SDValue,8> Ops; 3708 for (int Idx : Mask) { 3709 SDValue Res; 3710 3711 if (Idx < 0) { 3712 Res = DAG.getUNDEF(EltVT); 3713 } else { 3714 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3715 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3716 3717 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3718 DAG.getVectorIdxConstant(Idx, DL)); 3719 } 3720 3721 Ops.push_back(Res); 3722 } 3723 3724 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3725 } 3726 3727 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3728 ArrayRef<unsigned> Indices; 3729 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3730 Indices = IV->getIndices(); 3731 else 3732 Indices = cast<ConstantExpr>(&I)->getIndices(); 3733 3734 const Value *Op0 = I.getOperand(0); 3735 const Value *Op1 = I.getOperand(1); 3736 Type *AggTy = I.getType(); 3737 Type *ValTy = Op1->getType(); 3738 bool IntoUndef = isa<UndefValue>(Op0); 3739 bool FromUndef = isa<UndefValue>(Op1); 3740 3741 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3742 3743 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3744 SmallVector<EVT, 4> AggValueVTs; 3745 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3746 SmallVector<EVT, 4> ValValueVTs; 3747 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3748 3749 unsigned NumAggValues = AggValueVTs.size(); 3750 unsigned NumValValues = ValValueVTs.size(); 3751 SmallVector<SDValue, 4> Values(NumAggValues); 3752 3753 // Ignore an insertvalue that produces an empty object 3754 if (!NumAggValues) { 3755 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3756 return; 3757 } 3758 3759 SDValue Agg = getValue(Op0); 3760 unsigned i = 0; 3761 // Copy the beginning value(s) from the original aggregate. 3762 for (; i != LinearIndex; ++i) 3763 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3764 SDValue(Agg.getNode(), Agg.getResNo() + i); 3765 // Copy values from the inserted value(s). 3766 if (NumValValues) { 3767 SDValue Val = getValue(Op1); 3768 for (; i != LinearIndex + NumValValues; ++i) 3769 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3770 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3771 } 3772 // Copy remaining value(s) from the original aggregate. 3773 for (; i != NumAggValues; ++i) 3774 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3775 SDValue(Agg.getNode(), Agg.getResNo() + i); 3776 3777 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3778 DAG.getVTList(AggValueVTs), Values)); 3779 } 3780 3781 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3782 ArrayRef<unsigned> Indices; 3783 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3784 Indices = EV->getIndices(); 3785 else 3786 Indices = cast<ConstantExpr>(&I)->getIndices(); 3787 3788 const Value *Op0 = I.getOperand(0); 3789 Type *AggTy = Op0->getType(); 3790 Type *ValTy = I.getType(); 3791 bool OutOfUndef = isa<UndefValue>(Op0); 3792 3793 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3794 3795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3796 SmallVector<EVT, 4> ValValueVTs; 3797 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3798 3799 unsigned NumValValues = ValValueVTs.size(); 3800 3801 // Ignore a extractvalue that produces an empty object 3802 if (!NumValValues) { 3803 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3804 return; 3805 } 3806 3807 SmallVector<SDValue, 4> Values(NumValValues); 3808 3809 SDValue Agg = getValue(Op0); 3810 // Copy out the selected value(s). 3811 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3812 Values[i - LinearIndex] = 3813 OutOfUndef ? 3814 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3815 SDValue(Agg.getNode(), Agg.getResNo() + i); 3816 3817 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3818 DAG.getVTList(ValValueVTs), Values)); 3819 } 3820 3821 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3822 Value *Op0 = I.getOperand(0); 3823 // Note that the pointer operand may be a vector of pointers. Take the scalar 3824 // element which holds a pointer. 3825 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3826 SDValue N = getValue(Op0); 3827 SDLoc dl = getCurSDLoc(); 3828 auto &TLI = DAG.getTargetLoweringInfo(); 3829 3830 // Normalize Vector GEP - all scalar operands should be converted to the 3831 // splat vector. 3832 bool IsVectorGEP = I.getType()->isVectorTy(); 3833 ElementCount VectorElementCount = 3834 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3835 : ElementCount::getFixed(0); 3836 3837 if (IsVectorGEP && !N.getValueType().isVector()) { 3838 LLVMContext &Context = *DAG.getContext(); 3839 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3840 if (VectorElementCount.isScalable()) 3841 N = DAG.getSplatVector(VT, dl, N); 3842 else 3843 N = DAG.getSplatBuildVector(VT, dl, N); 3844 } 3845 3846 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3847 GTI != E; ++GTI) { 3848 const Value *Idx = GTI.getOperand(); 3849 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3850 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3851 if (Field) { 3852 // N = N + Offset 3853 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3854 3855 // In an inbounds GEP with an offset that is nonnegative even when 3856 // interpreted as signed, assume there is no unsigned overflow. 3857 SDNodeFlags Flags; 3858 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3859 Flags.setNoUnsignedWrap(true); 3860 3861 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3862 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3863 } 3864 } else { 3865 // IdxSize is the width of the arithmetic according to IR semantics. 3866 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3867 // (and fix up the result later). 3868 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3869 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3870 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3871 // We intentionally mask away the high bits here; ElementSize may not 3872 // fit in IdxTy. 3873 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3874 bool ElementScalable = ElementSize.isScalable(); 3875 3876 // If this is a scalar constant or a splat vector of constants, 3877 // handle it quickly. 3878 const auto *C = dyn_cast<Constant>(Idx); 3879 if (C && isa<VectorType>(C->getType())) 3880 C = C->getSplatValue(); 3881 3882 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3883 if (CI && CI->isZero()) 3884 continue; 3885 if (CI && !ElementScalable) { 3886 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3887 LLVMContext &Context = *DAG.getContext(); 3888 SDValue OffsVal; 3889 if (IsVectorGEP) 3890 OffsVal = DAG.getConstant( 3891 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3892 else 3893 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3894 3895 // In an inbounds GEP with an offset that is nonnegative even when 3896 // interpreted as signed, assume there is no unsigned overflow. 3897 SDNodeFlags Flags; 3898 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3899 Flags.setNoUnsignedWrap(true); 3900 3901 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3902 3903 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3904 continue; 3905 } 3906 3907 // N = N + Idx * ElementMul; 3908 SDValue IdxN = getValue(Idx); 3909 3910 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3911 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3912 VectorElementCount); 3913 if (VectorElementCount.isScalable()) 3914 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3915 else 3916 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3917 } 3918 3919 // If the index is smaller or larger than intptr_t, truncate or extend 3920 // it. 3921 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3922 3923 if (ElementScalable) { 3924 EVT VScaleTy = N.getValueType().getScalarType(); 3925 SDValue VScale = DAG.getNode( 3926 ISD::VSCALE, dl, VScaleTy, 3927 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3928 if (IsVectorGEP) 3929 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3930 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3931 } else { 3932 // If this is a multiply by a power of two, turn it into a shl 3933 // immediately. This is a very common case. 3934 if (ElementMul != 1) { 3935 if (ElementMul.isPowerOf2()) { 3936 unsigned Amt = ElementMul.logBase2(); 3937 IdxN = DAG.getNode(ISD::SHL, dl, 3938 N.getValueType(), IdxN, 3939 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3940 } else { 3941 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3942 IdxN.getValueType()); 3943 IdxN = DAG.getNode(ISD::MUL, dl, 3944 N.getValueType(), IdxN, Scale); 3945 } 3946 } 3947 } 3948 3949 N = DAG.getNode(ISD::ADD, dl, 3950 N.getValueType(), N, IdxN); 3951 } 3952 } 3953 3954 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3955 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3956 if (IsVectorGEP) { 3957 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3958 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3959 } 3960 3961 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3962 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3963 3964 setValue(&I, N); 3965 } 3966 3967 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3968 // If this is a fixed sized alloca in the entry block of the function, 3969 // allocate it statically on the stack. 3970 if (FuncInfo.StaticAllocaMap.count(&I)) 3971 return; // getValue will auto-populate this. 3972 3973 SDLoc dl = getCurSDLoc(); 3974 Type *Ty = I.getAllocatedType(); 3975 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3976 auto &DL = DAG.getDataLayout(); 3977 uint64_t TySize = DL.getTypeAllocSize(Ty); 3978 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3979 3980 SDValue AllocSize = getValue(I.getArraySize()); 3981 3982 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3983 if (AllocSize.getValueType() != IntPtr) 3984 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3985 3986 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3987 AllocSize, 3988 DAG.getConstant(TySize, dl, IntPtr)); 3989 3990 // Handle alignment. If the requested alignment is less than or equal to 3991 // the stack alignment, ignore it. If the size is greater than or equal to 3992 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3993 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3994 if (*Alignment <= StackAlign) 3995 Alignment = None; 3996 3997 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3998 // Round the size of the allocation up to the stack alignment size 3999 // by add SA-1 to the size. This doesn't overflow because we're computing 4000 // an address inside an alloca. 4001 SDNodeFlags Flags; 4002 Flags.setNoUnsignedWrap(true); 4003 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4004 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4005 4006 // Mask out the low bits for alignment purposes. 4007 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4008 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4009 4010 SDValue Ops[] = { 4011 getRoot(), AllocSize, 4012 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4013 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4014 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4015 setValue(&I, DSA); 4016 DAG.setRoot(DSA.getValue(1)); 4017 4018 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4019 } 4020 4021 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4022 if (I.isAtomic()) 4023 return visitAtomicLoad(I); 4024 4025 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4026 const Value *SV = I.getOperand(0); 4027 if (TLI.supportSwiftError()) { 4028 // Swifterror values can come from either a function parameter with 4029 // swifterror attribute or an alloca with swifterror attribute. 4030 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4031 if (Arg->hasSwiftErrorAttr()) 4032 return visitLoadFromSwiftError(I); 4033 } 4034 4035 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4036 if (Alloca->isSwiftError()) 4037 return visitLoadFromSwiftError(I); 4038 } 4039 } 4040 4041 SDValue Ptr = getValue(SV); 4042 4043 Type *Ty = I.getType(); 4044 Align Alignment = I.getAlign(); 4045 4046 AAMDNodes AAInfo; 4047 I.getAAMetadata(AAInfo); 4048 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4049 4050 SmallVector<EVT, 4> ValueVTs, MemVTs; 4051 SmallVector<uint64_t, 4> Offsets; 4052 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4053 unsigned NumValues = ValueVTs.size(); 4054 if (NumValues == 0) 4055 return; 4056 4057 bool isVolatile = I.isVolatile(); 4058 4059 SDValue Root; 4060 bool ConstantMemory = false; 4061 if (isVolatile) 4062 // Serialize volatile loads with other side effects. 4063 Root = getRoot(); 4064 else if (NumValues > MaxParallelChains) 4065 Root = getMemoryRoot(); 4066 else if (AA && 4067 AA->pointsToConstantMemory(MemoryLocation( 4068 SV, 4069 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4070 AAInfo))) { 4071 // Do not serialize (non-volatile) loads of constant memory with anything. 4072 Root = DAG.getEntryNode(); 4073 ConstantMemory = true; 4074 } else { 4075 // Do not serialize non-volatile loads against each other. 4076 Root = DAG.getRoot(); 4077 } 4078 4079 SDLoc dl = getCurSDLoc(); 4080 4081 if (isVolatile) 4082 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4083 4084 // An aggregate load cannot wrap around the address space, so offsets to its 4085 // parts don't wrap either. 4086 SDNodeFlags Flags; 4087 Flags.setNoUnsignedWrap(true); 4088 4089 SmallVector<SDValue, 4> Values(NumValues); 4090 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4091 EVT PtrVT = Ptr.getValueType(); 4092 4093 MachineMemOperand::Flags MMOFlags 4094 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4095 4096 unsigned ChainI = 0; 4097 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4098 // Serializing loads here may result in excessive register pressure, and 4099 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4100 // could recover a bit by hoisting nodes upward in the chain by recognizing 4101 // they are side-effect free or do not alias. The optimizer should really 4102 // avoid this case by converting large object/array copies to llvm.memcpy 4103 // (MaxParallelChains should always remain as failsafe). 4104 if (ChainI == MaxParallelChains) { 4105 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4106 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4107 makeArrayRef(Chains.data(), ChainI)); 4108 Root = Chain; 4109 ChainI = 0; 4110 } 4111 SDValue A = DAG.getNode(ISD::ADD, dl, 4112 PtrVT, Ptr, 4113 DAG.getConstant(Offsets[i], dl, PtrVT), 4114 Flags); 4115 4116 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4117 MachinePointerInfo(SV, Offsets[i]), Alignment, 4118 MMOFlags, AAInfo, Ranges); 4119 Chains[ChainI] = L.getValue(1); 4120 4121 if (MemVTs[i] != ValueVTs[i]) 4122 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4123 4124 Values[i] = L; 4125 } 4126 4127 if (!ConstantMemory) { 4128 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4129 makeArrayRef(Chains.data(), ChainI)); 4130 if (isVolatile) 4131 DAG.setRoot(Chain); 4132 else 4133 PendingLoads.push_back(Chain); 4134 } 4135 4136 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4137 DAG.getVTList(ValueVTs), Values)); 4138 } 4139 4140 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4141 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4142 "call visitStoreToSwiftError when backend supports swifterror"); 4143 4144 SmallVector<EVT, 4> ValueVTs; 4145 SmallVector<uint64_t, 4> Offsets; 4146 const Value *SrcV = I.getOperand(0); 4147 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4148 SrcV->getType(), ValueVTs, &Offsets); 4149 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4150 "expect a single EVT for swifterror"); 4151 4152 SDValue Src = getValue(SrcV); 4153 // Create a virtual register, then update the virtual register. 4154 Register VReg = 4155 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4156 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4157 // Chain can be getRoot or getControlRoot. 4158 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4159 SDValue(Src.getNode(), Src.getResNo())); 4160 DAG.setRoot(CopyNode); 4161 } 4162 4163 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4164 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4165 "call visitLoadFromSwiftError when backend supports swifterror"); 4166 4167 assert(!I.isVolatile() && 4168 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4169 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4170 "Support volatile, non temporal, invariant for load_from_swift_error"); 4171 4172 const Value *SV = I.getOperand(0); 4173 Type *Ty = I.getType(); 4174 AAMDNodes AAInfo; 4175 I.getAAMetadata(AAInfo); 4176 assert( 4177 (!AA || 4178 !AA->pointsToConstantMemory(MemoryLocation( 4179 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4180 AAInfo))) && 4181 "load_from_swift_error should not be constant memory"); 4182 4183 SmallVector<EVT, 4> ValueVTs; 4184 SmallVector<uint64_t, 4> Offsets; 4185 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4186 ValueVTs, &Offsets); 4187 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4188 "expect a single EVT for swifterror"); 4189 4190 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4191 SDValue L = DAG.getCopyFromReg( 4192 getRoot(), getCurSDLoc(), 4193 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4194 4195 setValue(&I, L); 4196 } 4197 4198 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4199 if (I.isAtomic()) 4200 return visitAtomicStore(I); 4201 4202 const Value *SrcV = I.getOperand(0); 4203 const Value *PtrV = I.getOperand(1); 4204 4205 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4206 if (TLI.supportSwiftError()) { 4207 // Swifterror values can come from either a function parameter with 4208 // swifterror attribute or an alloca with swifterror attribute. 4209 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4210 if (Arg->hasSwiftErrorAttr()) 4211 return visitStoreToSwiftError(I); 4212 } 4213 4214 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4215 if (Alloca->isSwiftError()) 4216 return visitStoreToSwiftError(I); 4217 } 4218 } 4219 4220 SmallVector<EVT, 4> ValueVTs, MemVTs; 4221 SmallVector<uint64_t, 4> Offsets; 4222 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4223 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4224 unsigned NumValues = ValueVTs.size(); 4225 if (NumValues == 0) 4226 return; 4227 4228 // Get the lowered operands. Note that we do this after 4229 // checking if NumResults is zero, because with zero results 4230 // the operands won't have values in the map. 4231 SDValue Src = getValue(SrcV); 4232 SDValue Ptr = getValue(PtrV); 4233 4234 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4235 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4236 SDLoc dl = getCurSDLoc(); 4237 Align Alignment = I.getAlign(); 4238 AAMDNodes AAInfo; 4239 I.getAAMetadata(AAInfo); 4240 4241 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4242 4243 // An aggregate load cannot wrap around the address space, so offsets to its 4244 // parts don't wrap either. 4245 SDNodeFlags Flags; 4246 Flags.setNoUnsignedWrap(true); 4247 4248 unsigned ChainI = 0; 4249 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4250 // See visitLoad comments. 4251 if (ChainI == MaxParallelChains) { 4252 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4253 makeArrayRef(Chains.data(), ChainI)); 4254 Root = Chain; 4255 ChainI = 0; 4256 } 4257 SDValue Add = 4258 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4259 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4260 if (MemVTs[i] != ValueVTs[i]) 4261 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4262 SDValue St = 4263 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4264 Alignment, MMOFlags, AAInfo); 4265 Chains[ChainI] = St; 4266 } 4267 4268 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4269 makeArrayRef(Chains.data(), ChainI)); 4270 DAG.setRoot(StoreNode); 4271 } 4272 4273 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4274 bool IsCompressing) { 4275 SDLoc sdl = getCurSDLoc(); 4276 4277 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4278 MaybeAlign &Alignment) { 4279 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4280 Src0 = I.getArgOperand(0); 4281 Ptr = I.getArgOperand(1); 4282 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4283 Mask = I.getArgOperand(3); 4284 }; 4285 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4286 MaybeAlign &Alignment) { 4287 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4288 Src0 = I.getArgOperand(0); 4289 Ptr = I.getArgOperand(1); 4290 Mask = I.getArgOperand(2); 4291 Alignment = None; 4292 }; 4293 4294 Value *PtrOperand, *MaskOperand, *Src0Operand; 4295 MaybeAlign Alignment; 4296 if (IsCompressing) 4297 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4298 else 4299 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4300 4301 SDValue Ptr = getValue(PtrOperand); 4302 SDValue Src0 = getValue(Src0Operand); 4303 SDValue Mask = getValue(MaskOperand); 4304 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4305 4306 EVT VT = Src0.getValueType(); 4307 if (!Alignment) 4308 Alignment = DAG.getEVTAlign(VT); 4309 4310 AAMDNodes AAInfo; 4311 I.getAAMetadata(AAInfo); 4312 4313 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4314 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4315 // TODO: Make MachineMemOperands aware of scalable 4316 // vectors. 4317 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4318 SDValue StoreNode = 4319 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4320 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4321 DAG.setRoot(StoreNode); 4322 setValue(&I, StoreNode); 4323 } 4324 4325 // Get a uniform base for the Gather/Scatter intrinsic. 4326 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4327 // We try to represent it as a base pointer + vector of indices. 4328 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4329 // The first operand of the GEP may be a single pointer or a vector of pointers 4330 // Example: 4331 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4332 // or 4333 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4334 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4335 // 4336 // When the first GEP operand is a single pointer - it is the uniform base we 4337 // are looking for. If first operand of the GEP is a splat vector - we 4338 // extract the splat value and use it as a uniform base. 4339 // In all other cases the function returns 'false'. 4340 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4341 ISD::MemIndexType &IndexType, SDValue &Scale, 4342 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4343 SelectionDAG& DAG = SDB->DAG; 4344 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4345 const DataLayout &DL = DAG.getDataLayout(); 4346 4347 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4348 4349 // Handle splat constant pointer. 4350 if (auto *C = dyn_cast<Constant>(Ptr)) { 4351 C = C->getSplatValue(); 4352 if (!C) 4353 return false; 4354 4355 Base = SDB->getValue(C); 4356 4357 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4358 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4359 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4360 IndexType = ISD::SIGNED_SCALED; 4361 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4362 return true; 4363 } 4364 4365 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4366 if (!GEP || GEP->getParent() != CurBB) 4367 return false; 4368 4369 if (GEP->getNumOperands() != 2) 4370 return false; 4371 4372 const Value *BasePtr = GEP->getPointerOperand(); 4373 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4374 4375 // Make sure the base is scalar and the index is a vector. 4376 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4377 return false; 4378 4379 Base = SDB->getValue(BasePtr); 4380 Index = SDB->getValue(IndexVal); 4381 IndexType = ISD::SIGNED_SCALED; 4382 Scale = DAG.getTargetConstant( 4383 DL.getTypeAllocSize(GEP->getResultElementType()), 4384 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4385 return true; 4386 } 4387 4388 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4389 SDLoc sdl = getCurSDLoc(); 4390 4391 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4392 const Value *Ptr = I.getArgOperand(1); 4393 SDValue Src0 = getValue(I.getArgOperand(0)); 4394 SDValue Mask = getValue(I.getArgOperand(3)); 4395 EVT VT = Src0.getValueType(); 4396 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4397 ->getMaybeAlignValue() 4398 .getValueOr(DAG.getEVTAlign(VT)); 4399 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4400 4401 AAMDNodes AAInfo; 4402 I.getAAMetadata(AAInfo); 4403 4404 SDValue Base; 4405 SDValue Index; 4406 ISD::MemIndexType IndexType; 4407 SDValue Scale; 4408 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4409 I.getParent()); 4410 4411 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4412 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4413 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4414 // TODO: Make MachineMemOperands aware of scalable 4415 // vectors. 4416 MemoryLocation::UnknownSize, Alignment, AAInfo); 4417 if (!UniformBase) { 4418 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4419 Index = getValue(Ptr); 4420 IndexType = ISD::SIGNED_UNSCALED; 4421 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4422 } 4423 4424 EVT IdxVT = Index.getValueType(); 4425 EVT EltTy = IdxVT.getVectorElementType(); 4426 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4427 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4428 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4429 } 4430 4431 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4432 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4433 Ops, MMO, IndexType, false); 4434 DAG.setRoot(Scatter); 4435 setValue(&I, Scatter); 4436 } 4437 4438 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4439 SDLoc sdl = getCurSDLoc(); 4440 4441 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4442 MaybeAlign &Alignment) { 4443 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4444 Ptr = I.getArgOperand(0); 4445 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4446 Mask = I.getArgOperand(2); 4447 Src0 = I.getArgOperand(3); 4448 }; 4449 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4450 MaybeAlign &Alignment) { 4451 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4452 Ptr = I.getArgOperand(0); 4453 Alignment = None; 4454 Mask = I.getArgOperand(1); 4455 Src0 = I.getArgOperand(2); 4456 }; 4457 4458 Value *PtrOperand, *MaskOperand, *Src0Operand; 4459 MaybeAlign Alignment; 4460 if (IsExpanding) 4461 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4462 else 4463 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4464 4465 SDValue Ptr = getValue(PtrOperand); 4466 SDValue Src0 = getValue(Src0Operand); 4467 SDValue Mask = getValue(MaskOperand); 4468 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4469 4470 EVT VT = Src0.getValueType(); 4471 if (!Alignment) 4472 Alignment = DAG.getEVTAlign(VT); 4473 4474 AAMDNodes AAInfo; 4475 I.getAAMetadata(AAInfo); 4476 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4477 4478 // Do not serialize masked loads of constant memory with anything. 4479 MemoryLocation ML; 4480 if (VT.isScalableVector()) 4481 ML = MemoryLocation::getAfter(PtrOperand); 4482 else 4483 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4484 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4485 AAInfo); 4486 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4487 4488 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4489 4490 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4491 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4492 // TODO: Make MachineMemOperands aware of scalable 4493 // vectors. 4494 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4495 4496 SDValue Load = 4497 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4498 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4499 if (AddToChain) 4500 PendingLoads.push_back(Load.getValue(1)); 4501 setValue(&I, Load); 4502 } 4503 4504 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4505 SDLoc sdl = getCurSDLoc(); 4506 4507 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4508 const Value *Ptr = I.getArgOperand(0); 4509 SDValue Src0 = getValue(I.getArgOperand(3)); 4510 SDValue Mask = getValue(I.getArgOperand(2)); 4511 4512 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4513 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4514 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4515 ->getMaybeAlignValue() 4516 .getValueOr(DAG.getEVTAlign(VT)); 4517 4518 AAMDNodes AAInfo; 4519 I.getAAMetadata(AAInfo); 4520 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4521 4522 SDValue Root = DAG.getRoot(); 4523 SDValue Base; 4524 SDValue Index; 4525 ISD::MemIndexType IndexType; 4526 SDValue Scale; 4527 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4528 I.getParent()); 4529 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4530 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4531 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4532 // TODO: Make MachineMemOperands aware of scalable 4533 // vectors. 4534 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4535 4536 if (!UniformBase) { 4537 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4538 Index = getValue(Ptr); 4539 IndexType = ISD::SIGNED_UNSCALED; 4540 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4541 } 4542 4543 EVT IdxVT = Index.getValueType(); 4544 EVT EltTy = IdxVT.getVectorElementType(); 4545 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4546 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4547 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4548 } 4549 4550 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4551 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4552 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4553 4554 PendingLoads.push_back(Gather.getValue(1)); 4555 setValue(&I, Gather); 4556 } 4557 4558 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4559 SDLoc dl = getCurSDLoc(); 4560 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4561 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4562 SyncScope::ID SSID = I.getSyncScopeID(); 4563 4564 SDValue InChain = getRoot(); 4565 4566 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4567 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4568 4569 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4570 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4571 4572 MachineFunction &MF = DAG.getMachineFunction(); 4573 MachineMemOperand *MMO = MF.getMachineMemOperand( 4574 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4575 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4576 FailureOrdering); 4577 4578 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4579 dl, MemVT, VTs, InChain, 4580 getValue(I.getPointerOperand()), 4581 getValue(I.getCompareOperand()), 4582 getValue(I.getNewValOperand()), MMO); 4583 4584 SDValue OutChain = L.getValue(2); 4585 4586 setValue(&I, L); 4587 DAG.setRoot(OutChain); 4588 } 4589 4590 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4591 SDLoc dl = getCurSDLoc(); 4592 ISD::NodeType NT; 4593 switch (I.getOperation()) { 4594 default: llvm_unreachable("Unknown atomicrmw operation"); 4595 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4596 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4597 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4598 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4599 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4600 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4601 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4602 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4603 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4604 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4605 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4606 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4607 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4608 } 4609 AtomicOrdering Ordering = I.getOrdering(); 4610 SyncScope::ID SSID = I.getSyncScopeID(); 4611 4612 SDValue InChain = getRoot(); 4613 4614 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4615 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4616 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4617 4618 MachineFunction &MF = DAG.getMachineFunction(); 4619 MachineMemOperand *MMO = MF.getMachineMemOperand( 4620 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4621 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4622 4623 SDValue L = 4624 DAG.getAtomic(NT, dl, MemVT, InChain, 4625 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4626 MMO); 4627 4628 SDValue OutChain = L.getValue(1); 4629 4630 setValue(&I, L); 4631 DAG.setRoot(OutChain); 4632 } 4633 4634 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4635 SDLoc dl = getCurSDLoc(); 4636 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4637 SDValue Ops[3]; 4638 Ops[0] = getRoot(); 4639 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4640 TLI.getFenceOperandTy(DAG.getDataLayout())); 4641 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4642 TLI.getFenceOperandTy(DAG.getDataLayout())); 4643 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4644 } 4645 4646 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4647 SDLoc dl = getCurSDLoc(); 4648 AtomicOrdering Order = I.getOrdering(); 4649 SyncScope::ID SSID = I.getSyncScopeID(); 4650 4651 SDValue InChain = getRoot(); 4652 4653 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4654 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4655 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4656 4657 if (!TLI.supportsUnalignedAtomics() && 4658 I.getAlignment() < MemVT.getSizeInBits() / 8) 4659 report_fatal_error("Cannot generate unaligned atomic load"); 4660 4661 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4662 4663 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4664 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4665 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4666 4667 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4668 4669 SDValue Ptr = getValue(I.getPointerOperand()); 4670 4671 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4672 // TODO: Once this is better exercised by tests, it should be merged with 4673 // the normal path for loads to prevent future divergence. 4674 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4675 if (MemVT != VT) 4676 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4677 4678 setValue(&I, L); 4679 SDValue OutChain = L.getValue(1); 4680 if (!I.isUnordered()) 4681 DAG.setRoot(OutChain); 4682 else 4683 PendingLoads.push_back(OutChain); 4684 return; 4685 } 4686 4687 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4688 Ptr, MMO); 4689 4690 SDValue OutChain = L.getValue(1); 4691 if (MemVT != VT) 4692 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4693 4694 setValue(&I, L); 4695 DAG.setRoot(OutChain); 4696 } 4697 4698 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4699 SDLoc dl = getCurSDLoc(); 4700 4701 AtomicOrdering Ordering = I.getOrdering(); 4702 SyncScope::ID SSID = I.getSyncScopeID(); 4703 4704 SDValue InChain = getRoot(); 4705 4706 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4707 EVT MemVT = 4708 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4709 4710 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4711 report_fatal_error("Cannot generate unaligned atomic store"); 4712 4713 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4714 4715 MachineFunction &MF = DAG.getMachineFunction(); 4716 MachineMemOperand *MMO = MF.getMachineMemOperand( 4717 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4718 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4719 4720 SDValue Val = getValue(I.getValueOperand()); 4721 if (Val.getValueType() != MemVT) 4722 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4723 SDValue Ptr = getValue(I.getPointerOperand()); 4724 4725 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4726 // TODO: Once this is better exercised by tests, it should be merged with 4727 // the normal path for stores to prevent future divergence. 4728 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4729 DAG.setRoot(S); 4730 return; 4731 } 4732 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4733 Ptr, Val, MMO); 4734 4735 4736 DAG.setRoot(OutChain); 4737 } 4738 4739 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4740 /// node. 4741 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4742 unsigned Intrinsic) { 4743 // Ignore the callsite's attributes. A specific call site may be marked with 4744 // readnone, but the lowering code will expect the chain based on the 4745 // definition. 4746 const Function *F = I.getCalledFunction(); 4747 bool HasChain = !F->doesNotAccessMemory(); 4748 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4749 4750 // Build the operand list. 4751 SmallVector<SDValue, 8> Ops; 4752 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4753 if (OnlyLoad) { 4754 // We don't need to serialize loads against other loads. 4755 Ops.push_back(DAG.getRoot()); 4756 } else { 4757 Ops.push_back(getRoot()); 4758 } 4759 } 4760 4761 // Info is set by getTgtMemInstrinsic 4762 TargetLowering::IntrinsicInfo Info; 4763 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4764 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4765 DAG.getMachineFunction(), 4766 Intrinsic); 4767 4768 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4769 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4770 Info.opc == ISD::INTRINSIC_W_CHAIN) 4771 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4772 TLI.getPointerTy(DAG.getDataLayout()))); 4773 4774 // Add all operands of the call to the operand list. 4775 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4776 const Value *Arg = I.getArgOperand(i); 4777 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4778 Ops.push_back(getValue(Arg)); 4779 continue; 4780 } 4781 4782 // Use TargetConstant instead of a regular constant for immarg. 4783 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4784 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4785 assert(CI->getBitWidth() <= 64 && 4786 "large intrinsic immediates not handled"); 4787 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4788 } else { 4789 Ops.push_back( 4790 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4791 } 4792 } 4793 4794 SmallVector<EVT, 4> ValueVTs; 4795 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4796 4797 if (HasChain) 4798 ValueVTs.push_back(MVT::Other); 4799 4800 SDVTList VTs = DAG.getVTList(ValueVTs); 4801 4802 // Create the node. 4803 SDValue Result; 4804 if (IsTgtIntrinsic) { 4805 // This is target intrinsic that touches memory 4806 AAMDNodes AAInfo; 4807 I.getAAMetadata(AAInfo); 4808 Result = 4809 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4810 MachinePointerInfo(Info.ptrVal, Info.offset), 4811 Info.align, Info.flags, Info.size, AAInfo); 4812 } else if (!HasChain) { 4813 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4814 } else if (!I.getType()->isVoidTy()) { 4815 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4816 } else { 4817 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4818 } 4819 4820 if (HasChain) { 4821 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4822 if (OnlyLoad) 4823 PendingLoads.push_back(Chain); 4824 else 4825 DAG.setRoot(Chain); 4826 } 4827 4828 if (!I.getType()->isVoidTy()) { 4829 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4830 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4831 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4832 } else 4833 Result = lowerRangeToAssertZExt(DAG, I, Result); 4834 4835 MaybeAlign Alignment = I.getRetAlign(); 4836 if (!Alignment) 4837 Alignment = F->getAttributes().getRetAlignment(); 4838 // Insert `assertalign` node if there's an alignment. 4839 if (InsertAssertAlign && Alignment) { 4840 Result = 4841 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4842 } 4843 4844 setValue(&I, Result); 4845 } 4846 } 4847 4848 /// GetSignificand - Get the significand and build it into a floating-point 4849 /// number with exponent of 1: 4850 /// 4851 /// Op = (Op & 0x007fffff) | 0x3f800000; 4852 /// 4853 /// where Op is the hexadecimal representation of floating point value. 4854 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4855 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4856 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4857 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4858 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4859 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4860 } 4861 4862 /// GetExponent - Get the exponent: 4863 /// 4864 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4865 /// 4866 /// where Op is the hexadecimal representation of floating point value. 4867 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4868 const TargetLowering &TLI, const SDLoc &dl) { 4869 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4870 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4871 SDValue t1 = DAG.getNode( 4872 ISD::SRL, dl, MVT::i32, t0, 4873 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4874 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4875 DAG.getConstant(127, dl, MVT::i32)); 4876 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4877 } 4878 4879 /// getF32Constant - Get 32-bit floating point constant. 4880 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4881 const SDLoc &dl) { 4882 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4883 MVT::f32); 4884 } 4885 4886 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4887 SelectionDAG &DAG) { 4888 // TODO: What fast-math-flags should be set on the floating-point nodes? 4889 4890 // IntegerPartOfX = ((int32_t)(t0); 4891 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4892 4893 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4894 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4895 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4896 4897 // IntegerPartOfX <<= 23; 4898 IntegerPartOfX = DAG.getNode( 4899 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4900 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4901 DAG.getDataLayout()))); 4902 4903 SDValue TwoToFractionalPartOfX; 4904 if (LimitFloatPrecision <= 6) { 4905 // For floating-point precision of 6: 4906 // 4907 // TwoToFractionalPartOfX = 4908 // 0.997535578f + 4909 // (0.735607626f + 0.252464424f * x) * x; 4910 // 4911 // error 0.0144103317, which is 6 bits 4912 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4913 getF32Constant(DAG, 0x3e814304, dl)); 4914 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4915 getF32Constant(DAG, 0x3f3c50c8, dl)); 4916 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4917 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4918 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4919 } else if (LimitFloatPrecision <= 12) { 4920 // For floating-point precision of 12: 4921 // 4922 // TwoToFractionalPartOfX = 4923 // 0.999892986f + 4924 // (0.696457318f + 4925 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4926 // 4927 // error 0.000107046256, which is 13 to 14 bits 4928 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4929 getF32Constant(DAG, 0x3da235e3, dl)); 4930 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4931 getF32Constant(DAG, 0x3e65b8f3, dl)); 4932 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4933 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4934 getF32Constant(DAG, 0x3f324b07, dl)); 4935 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4936 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4937 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4938 } else { // LimitFloatPrecision <= 18 4939 // For floating-point precision of 18: 4940 // 4941 // TwoToFractionalPartOfX = 4942 // 0.999999982f + 4943 // (0.693148872f + 4944 // (0.240227044f + 4945 // (0.554906021e-1f + 4946 // (0.961591928e-2f + 4947 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4948 // error 2.47208000*10^(-7), which is better than 18 bits 4949 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4950 getF32Constant(DAG, 0x3924b03e, dl)); 4951 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4952 getF32Constant(DAG, 0x3ab24b87, dl)); 4953 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4954 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4955 getF32Constant(DAG, 0x3c1d8c17, dl)); 4956 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4957 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4958 getF32Constant(DAG, 0x3d634a1d, dl)); 4959 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4960 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4961 getF32Constant(DAG, 0x3e75fe14, dl)); 4962 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4963 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4964 getF32Constant(DAG, 0x3f317234, dl)); 4965 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4966 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4967 getF32Constant(DAG, 0x3f800000, dl)); 4968 } 4969 4970 // Add the exponent into the result in integer domain. 4971 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4972 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4973 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4974 } 4975 4976 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4977 /// limited-precision mode. 4978 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4979 const TargetLowering &TLI, SDNodeFlags Flags) { 4980 if (Op.getValueType() == MVT::f32 && 4981 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4982 4983 // Put the exponent in the right bit position for later addition to the 4984 // final result: 4985 // 4986 // t0 = Op * log2(e) 4987 4988 // TODO: What fast-math-flags should be set here? 4989 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4990 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4991 return getLimitedPrecisionExp2(t0, dl, DAG); 4992 } 4993 4994 // No special expansion. 4995 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 4996 } 4997 4998 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4999 /// limited-precision mode. 5000 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5001 const TargetLowering &TLI, SDNodeFlags Flags) { 5002 // TODO: What fast-math-flags should be set on the floating-point nodes? 5003 5004 if (Op.getValueType() == MVT::f32 && 5005 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5006 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5007 5008 // Scale the exponent by log(2). 5009 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5010 SDValue LogOfExponent = 5011 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5012 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5013 5014 // Get the significand and build it into a floating-point number with 5015 // exponent of 1. 5016 SDValue X = GetSignificand(DAG, Op1, dl); 5017 5018 SDValue LogOfMantissa; 5019 if (LimitFloatPrecision <= 6) { 5020 // For floating-point precision of 6: 5021 // 5022 // LogofMantissa = 5023 // -1.1609546f + 5024 // (1.4034025f - 0.23903021f * x) * x; 5025 // 5026 // error 0.0034276066, which is better than 8 bits 5027 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5028 getF32Constant(DAG, 0xbe74c456, dl)); 5029 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5030 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5031 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5032 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5033 getF32Constant(DAG, 0x3f949a29, dl)); 5034 } else if (LimitFloatPrecision <= 12) { 5035 // For floating-point precision of 12: 5036 // 5037 // LogOfMantissa = 5038 // -1.7417939f + 5039 // (2.8212026f + 5040 // (-1.4699568f + 5041 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5042 // 5043 // error 0.000061011436, which is 14 bits 5044 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5045 getF32Constant(DAG, 0xbd67b6d6, dl)); 5046 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5047 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5048 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5049 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5050 getF32Constant(DAG, 0x3fbc278b, dl)); 5051 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5052 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5053 getF32Constant(DAG, 0x40348e95, dl)); 5054 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5055 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5056 getF32Constant(DAG, 0x3fdef31a, dl)); 5057 } else { // LimitFloatPrecision <= 18 5058 // For floating-point precision of 18: 5059 // 5060 // LogOfMantissa = 5061 // -2.1072184f + 5062 // (4.2372794f + 5063 // (-3.7029485f + 5064 // (2.2781945f + 5065 // (-0.87823314f + 5066 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5067 // 5068 // error 0.0000023660568, which is better than 18 bits 5069 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5070 getF32Constant(DAG, 0xbc91e5ac, dl)); 5071 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5072 getF32Constant(DAG, 0x3e4350aa, dl)); 5073 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5074 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5075 getF32Constant(DAG, 0x3f60d3e3, dl)); 5076 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5077 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5078 getF32Constant(DAG, 0x4011cdf0, dl)); 5079 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5080 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5081 getF32Constant(DAG, 0x406cfd1c, dl)); 5082 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5083 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5084 getF32Constant(DAG, 0x408797cb, dl)); 5085 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5086 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5087 getF32Constant(DAG, 0x4006dcab, dl)); 5088 } 5089 5090 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5091 } 5092 5093 // No special expansion. 5094 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5095 } 5096 5097 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5098 /// limited-precision mode. 5099 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5100 const TargetLowering &TLI, SDNodeFlags Flags) { 5101 // TODO: What fast-math-flags should be set on the floating-point nodes? 5102 5103 if (Op.getValueType() == MVT::f32 && 5104 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5105 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5106 5107 // Get the exponent. 5108 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5109 5110 // Get the significand and build it into a floating-point number with 5111 // exponent of 1. 5112 SDValue X = GetSignificand(DAG, Op1, dl); 5113 5114 // Different possible minimax approximations of significand in 5115 // floating-point for various degrees of accuracy over [1,2]. 5116 SDValue Log2ofMantissa; 5117 if (LimitFloatPrecision <= 6) { 5118 // For floating-point precision of 6: 5119 // 5120 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5121 // 5122 // error 0.0049451742, which is more than 7 bits 5123 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5124 getF32Constant(DAG, 0xbeb08fe0, dl)); 5125 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5126 getF32Constant(DAG, 0x40019463, dl)); 5127 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5128 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5129 getF32Constant(DAG, 0x3fd6633d, dl)); 5130 } else if (LimitFloatPrecision <= 12) { 5131 // For floating-point precision of 12: 5132 // 5133 // Log2ofMantissa = 5134 // -2.51285454f + 5135 // (4.07009056f + 5136 // (-2.12067489f + 5137 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5138 // 5139 // error 0.0000876136000, which is better than 13 bits 5140 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5141 getF32Constant(DAG, 0xbda7262e, dl)); 5142 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5143 getF32Constant(DAG, 0x3f25280b, dl)); 5144 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5145 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5146 getF32Constant(DAG, 0x4007b923, dl)); 5147 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5148 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5149 getF32Constant(DAG, 0x40823e2f, dl)); 5150 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5151 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5152 getF32Constant(DAG, 0x4020d29c, dl)); 5153 } else { // LimitFloatPrecision <= 18 5154 // For floating-point precision of 18: 5155 // 5156 // Log2ofMantissa = 5157 // -3.0400495f + 5158 // (6.1129976f + 5159 // (-5.3420409f + 5160 // (3.2865683f + 5161 // (-1.2669343f + 5162 // (0.27515199f - 5163 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5164 // 5165 // error 0.0000018516, which is better than 18 bits 5166 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5167 getF32Constant(DAG, 0xbcd2769e, dl)); 5168 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5169 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5170 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5171 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5172 getF32Constant(DAG, 0x3fa22ae7, dl)); 5173 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5174 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5175 getF32Constant(DAG, 0x40525723, dl)); 5176 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5177 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5178 getF32Constant(DAG, 0x40aaf200, dl)); 5179 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5180 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5181 getF32Constant(DAG, 0x40c39dad, dl)); 5182 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5183 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5184 getF32Constant(DAG, 0x4042902c, dl)); 5185 } 5186 5187 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5188 } 5189 5190 // No special expansion. 5191 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5192 } 5193 5194 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5195 /// limited-precision mode. 5196 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5197 const TargetLowering &TLI, SDNodeFlags Flags) { 5198 // TODO: What fast-math-flags should be set on the floating-point nodes? 5199 5200 if (Op.getValueType() == MVT::f32 && 5201 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5202 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5203 5204 // Scale the exponent by log10(2) [0.30102999f]. 5205 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5206 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5207 getF32Constant(DAG, 0x3e9a209a, dl)); 5208 5209 // Get the significand and build it into a floating-point number with 5210 // exponent of 1. 5211 SDValue X = GetSignificand(DAG, Op1, dl); 5212 5213 SDValue Log10ofMantissa; 5214 if (LimitFloatPrecision <= 6) { 5215 // For floating-point precision of 6: 5216 // 5217 // Log10ofMantissa = 5218 // -0.50419619f + 5219 // (0.60948995f - 0.10380950f * x) * x; 5220 // 5221 // error 0.0014886165, which is 6 bits 5222 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5223 getF32Constant(DAG, 0xbdd49a13, dl)); 5224 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5225 getF32Constant(DAG, 0x3f1c0789, dl)); 5226 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5227 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5228 getF32Constant(DAG, 0x3f011300, dl)); 5229 } else if (LimitFloatPrecision <= 12) { 5230 // For floating-point precision of 12: 5231 // 5232 // Log10ofMantissa = 5233 // -0.64831180f + 5234 // (0.91751397f + 5235 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5236 // 5237 // error 0.00019228036, which is better than 12 bits 5238 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5239 getF32Constant(DAG, 0x3d431f31, dl)); 5240 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5241 getF32Constant(DAG, 0x3ea21fb2, dl)); 5242 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5243 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5244 getF32Constant(DAG, 0x3f6ae232, dl)); 5245 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5246 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5247 getF32Constant(DAG, 0x3f25f7c3, dl)); 5248 } else { // LimitFloatPrecision <= 18 5249 // For floating-point precision of 18: 5250 // 5251 // Log10ofMantissa = 5252 // -0.84299375f + 5253 // (1.5327582f + 5254 // (-1.0688956f + 5255 // (0.49102474f + 5256 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5257 // 5258 // error 0.0000037995730, which is better than 18 bits 5259 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5260 getF32Constant(DAG, 0x3c5d51ce, dl)); 5261 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5262 getF32Constant(DAG, 0x3e00685a, dl)); 5263 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5264 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5265 getF32Constant(DAG, 0x3efb6798, dl)); 5266 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5267 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5268 getF32Constant(DAG, 0x3f88d192, dl)); 5269 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5270 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5271 getF32Constant(DAG, 0x3fc4316c, dl)); 5272 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5273 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5274 getF32Constant(DAG, 0x3f57ce70, dl)); 5275 } 5276 5277 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5278 } 5279 5280 // No special expansion. 5281 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5282 } 5283 5284 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5285 /// limited-precision mode. 5286 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5287 const TargetLowering &TLI, SDNodeFlags Flags) { 5288 if (Op.getValueType() == MVT::f32 && 5289 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5290 return getLimitedPrecisionExp2(Op, dl, DAG); 5291 5292 // No special expansion. 5293 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5294 } 5295 5296 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5297 /// limited-precision mode with x == 10.0f. 5298 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5299 SelectionDAG &DAG, const TargetLowering &TLI, 5300 SDNodeFlags Flags) { 5301 bool IsExp10 = false; 5302 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5303 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5304 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5305 APFloat Ten(10.0f); 5306 IsExp10 = LHSC->isExactlyValue(Ten); 5307 } 5308 } 5309 5310 // TODO: What fast-math-flags should be set on the FMUL node? 5311 if (IsExp10) { 5312 // Put the exponent in the right bit position for later addition to the 5313 // final result: 5314 // 5315 // #define LOG2OF10 3.3219281f 5316 // t0 = Op * LOG2OF10; 5317 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5318 getF32Constant(DAG, 0x40549a78, dl)); 5319 return getLimitedPrecisionExp2(t0, dl, DAG); 5320 } 5321 5322 // No special expansion. 5323 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5324 } 5325 5326 /// ExpandPowI - Expand a llvm.powi intrinsic. 5327 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5328 SelectionDAG &DAG) { 5329 // If RHS is a constant, we can expand this out to a multiplication tree, 5330 // otherwise we end up lowering to a call to __powidf2 (for example). When 5331 // optimizing for size, we only want to do this if the expansion would produce 5332 // a small number of multiplies, otherwise we do the full expansion. 5333 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5334 // Get the exponent as a positive value. 5335 unsigned Val = RHSC->getSExtValue(); 5336 if ((int)Val < 0) Val = -Val; 5337 5338 // powi(x, 0) -> 1.0 5339 if (Val == 0) 5340 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5341 5342 bool OptForSize = DAG.shouldOptForSize(); 5343 if (!OptForSize || 5344 // If optimizing for size, don't insert too many multiplies. 5345 // This inserts up to 5 multiplies. 5346 countPopulation(Val) + Log2_32(Val) < 7) { 5347 // We use the simple binary decomposition method to generate the multiply 5348 // sequence. There are more optimal ways to do this (for example, 5349 // powi(x,15) generates one more multiply than it should), but this has 5350 // the benefit of being both really simple and much better than a libcall. 5351 SDValue Res; // Logically starts equal to 1.0 5352 SDValue CurSquare = LHS; 5353 // TODO: Intrinsics should have fast-math-flags that propagate to these 5354 // nodes. 5355 while (Val) { 5356 if (Val & 1) { 5357 if (Res.getNode()) 5358 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5359 else 5360 Res = CurSquare; // 1.0*CurSquare. 5361 } 5362 5363 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5364 CurSquare, CurSquare); 5365 Val >>= 1; 5366 } 5367 5368 // If the original was negative, invert the result, producing 1/(x*x*x). 5369 if (RHSC->getSExtValue() < 0) 5370 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5371 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5372 return Res; 5373 } 5374 } 5375 5376 // Otherwise, expand to a libcall. 5377 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5378 } 5379 5380 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5381 SDValue LHS, SDValue RHS, SDValue Scale, 5382 SelectionDAG &DAG, const TargetLowering &TLI) { 5383 EVT VT = LHS.getValueType(); 5384 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5385 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5386 LLVMContext &Ctx = *DAG.getContext(); 5387 5388 // If the type is legal but the operation isn't, this node might survive all 5389 // the way to operation legalization. If we end up there and we do not have 5390 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5391 // node. 5392 5393 // Coax the legalizer into expanding the node during type legalization instead 5394 // by bumping the size by one bit. This will force it to Promote, enabling the 5395 // early expansion and avoiding the need to expand later. 5396 5397 // We don't have to do this if Scale is 0; that can always be expanded, unless 5398 // it's a saturating signed operation. Those can experience true integer 5399 // division overflow, a case which we must avoid. 5400 5401 // FIXME: We wouldn't have to do this (or any of the early 5402 // expansion/promotion) if it was possible to expand a libcall of an 5403 // illegal type during operation legalization. But it's not, so things 5404 // get a bit hacky. 5405 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5406 if ((ScaleInt > 0 || (Saturating && Signed)) && 5407 (TLI.isTypeLegal(VT) || 5408 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5409 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5410 Opcode, VT, ScaleInt); 5411 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5412 EVT PromVT; 5413 if (VT.isScalarInteger()) 5414 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5415 else if (VT.isVector()) { 5416 PromVT = VT.getVectorElementType(); 5417 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5418 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5419 } else 5420 llvm_unreachable("Wrong VT for DIVFIX?"); 5421 if (Signed) { 5422 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5423 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5424 } else { 5425 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5426 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5427 } 5428 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5429 // For saturating operations, we need to shift up the LHS to get the 5430 // proper saturation width, and then shift down again afterwards. 5431 if (Saturating) 5432 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5433 DAG.getConstant(1, DL, ShiftTy)); 5434 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5435 if (Saturating) 5436 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5437 DAG.getConstant(1, DL, ShiftTy)); 5438 return DAG.getZExtOrTrunc(Res, DL, VT); 5439 } 5440 } 5441 5442 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5443 } 5444 5445 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5446 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5447 static void 5448 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5449 const SDValue &N) { 5450 switch (N.getOpcode()) { 5451 case ISD::CopyFromReg: { 5452 SDValue Op = N.getOperand(1); 5453 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5454 Op.getValueType().getSizeInBits()); 5455 return; 5456 } 5457 case ISD::BITCAST: 5458 case ISD::AssertZext: 5459 case ISD::AssertSext: 5460 case ISD::TRUNCATE: 5461 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5462 return; 5463 case ISD::BUILD_PAIR: 5464 case ISD::BUILD_VECTOR: 5465 case ISD::CONCAT_VECTORS: 5466 for (SDValue Op : N->op_values()) 5467 getUnderlyingArgRegs(Regs, Op); 5468 return; 5469 default: 5470 return; 5471 } 5472 } 5473 5474 /// If the DbgValueInst is a dbg_value of a function argument, create the 5475 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5476 /// instruction selection, they will be inserted to the entry BB. 5477 /// We don't currently support this for variadic dbg_values, as they shouldn't 5478 /// appear for function arguments or in the prologue. 5479 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5480 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5481 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5482 const Argument *Arg = dyn_cast<Argument>(V); 5483 if (!Arg) 5484 return false; 5485 5486 if (!IsDbgDeclare) { 5487 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5488 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5489 // the entry block. 5490 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5491 if (!IsInEntryBlock) 5492 return false; 5493 5494 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5495 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5496 // variable that also is a param. 5497 // 5498 // Although, if we are at the top of the entry block already, we can still 5499 // emit using ArgDbgValue. This might catch some situations when the 5500 // dbg.value refers to an argument that isn't used in the entry block, so 5501 // any CopyToReg node would be optimized out and the only way to express 5502 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5503 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5504 // we should only emit as ArgDbgValue if the Variable is an argument to the 5505 // current function, and the dbg.value intrinsic is found in the entry 5506 // block. 5507 bool VariableIsFunctionInputArg = Variable->isParameter() && 5508 !DL->getInlinedAt(); 5509 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5510 if (!IsInPrologue && !VariableIsFunctionInputArg) 5511 return false; 5512 5513 // Here we assume that a function argument on IR level only can be used to 5514 // describe one input parameter on source level. If we for example have 5515 // source code like this 5516 // 5517 // struct A { long x, y; }; 5518 // void foo(struct A a, long b) { 5519 // ... 5520 // b = a.x; 5521 // ... 5522 // } 5523 // 5524 // and IR like this 5525 // 5526 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5527 // entry: 5528 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5529 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5530 // call void @llvm.dbg.value(metadata i32 %b, "b", 5531 // ... 5532 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5533 // ... 5534 // 5535 // then the last dbg.value is describing a parameter "b" using a value that 5536 // is an argument. But since we already has used %a1 to describe a parameter 5537 // we should not handle that last dbg.value here (that would result in an 5538 // incorrect hoisting of the DBG_VALUE to the function entry). 5539 // Notice that we allow one dbg.value per IR level argument, to accommodate 5540 // for the situation with fragments above. 5541 if (VariableIsFunctionInputArg) { 5542 unsigned ArgNo = Arg->getArgNo(); 5543 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5544 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5545 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5546 return false; 5547 FuncInfo.DescribedArgs.set(ArgNo); 5548 } 5549 } 5550 5551 MachineFunction &MF = DAG.getMachineFunction(); 5552 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5553 5554 bool IsIndirect = false; 5555 Optional<MachineOperand> Op; 5556 // Some arguments' frame index is recorded during argument lowering. 5557 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5558 if (FI != std::numeric_limits<int>::max()) 5559 Op = MachineOperand::CreateFI(FI); 5560 5561 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5562 if (!Op && N.getNode()) { 5563 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5564 Register Reg; 5565 if (ArgRegsAndSizes.size() == 1) 5566 Reg = ArgRegsAndSizes.front().first; 5567 5568 if (Reg && Reg.isVirtual()) { 5569 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5570 Register PR = RegInfo.getLiveInPhysReg(Reg); 5571 if (PR) 5572 Reg = PR; 5573 } 5574 if (Reg) { 5575 Op = MachineOperand::CreateReg(Reg, false); 5576 IsIndirect = IsDbgDeclare; 5577 } 5578 } 5579 5580 if (!Op && N.getNode()) { 5581 // Check if frame index is available. 5582 SDValue LCandidate = peekThroughBitcasts(N); 5583 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5584 if (FrameIndexSDNode *FINode = 5585 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5586 Op = MachineOperand::CreateFI(FINode->getIndex()); 5587 } 5588 5589 if (!Op) { 5590 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5591 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5592 SplitRegs) { 5593 unsigned Offset = 0; 5594 for (auto RegAndSize : SplitRegs) { 5595 // If the expression is already a fragment, the current register 5596 // offset+size might extend beyond the fragment. In this case, only 5597 // the register bits that are inside the fragment are relevant. 5598 int RegFragmentSizeInBits = RegAndSize.second; 5599 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5600 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5601 // The register is entirely outside the expression fragment, 5602 // so is irrelevant for debug info. 5603 if (Offset >= ExprFragmentSizeInBits) 5604 break; 5605 // The register is partially outside the expression fragment, only 5606 // the low bits within the fragment are relevant for debug info. 5607 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5608 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5609 } 5610 } 5611 5612 auto FragmentExpr = DIExpression::createFragmentExpression( 5613 Expr, Offset, RegFragmentSizeInBits); 5614 Offset += RegAndSize.second; 5615 // If a valid fragment expression cannot be created, the variable's 5616 // correct value cannot be determined and so it is set as Undef. 5617 if (!FragmentExpr) { 5618 SDDbgValue *SDV = DAG.getConstantDbgValue( 5619 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5620 DAG.AddDbgValue(SDV, false); 5621 continue; 5622 } 5623 FuncInfo.ArgDbgValues.push_back( 5624 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5625 RegAndSize.first, Variable, *FragmentExpr)); 5626 } 5627 }; 5628 5629 // Check if ValueMap has reg number. 5630 DenseMap<const Value *, Register>::const_iterator 5631 VMI = FuncInfo.ValueMap.find(V); 5632 if (VMI != FuncInfo.ValueMap.end()) { 5633 const auto &TLI = DAG.getTargetLoweringInfo(); 5634 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5635 V->getType(), None); 5636 if (RFV.occupiesMultipleRegs()) { 5637 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5638 return true; 5639 } 5640 5641 Op = MachineOperand::CreateReg(VMI->second, false); 5642 IsIndirect = IsDbgDeclare; 5643 } else if (ArgRegsAndSizes.size() > 1) { 5644 // This was split due to the calling convention, and no virtual register 5645 // mapping exists for the value. 5646 splitMultiRegDbgValue(ArgRegsAndSizes); 5647 return true; 5648 } 5649 } 5650 5651 if (!Op) 5652 return false; 5653 5654 assert(Variable->isValidLocationForIntrinsic(DL) && 5655 "Expected inlined-at fields to agree"); 5656 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5657 FuncInfo.ArgDbgValues.push_back( 5658 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5659 *Op, Variable, Expr)); 5660 5661 return true; 5662 } 5663 5664 /// Return the appropriate SDDbgValue based on N. 5665 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5666 DILocalVariable *Variable, 5667 DIExpression *Expr, 5668 const DebugLoc &dl, 5669 unsigned DbgSDNodeOrder) { 5670 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5671 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5672 // stack slot locations. 5673 // 5674 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5675 // debug values here after optimization: 5676 // 5677 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5678 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5679 // 5680 // Both describe the direct values of their associated variables. 5681 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5682 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5683 } 5684 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5685 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5686 } 5687 5688 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5689 switch (Intrinsic) { 5690 case Intrinsic::smul_fix: 5691 return ISD::SMULFIX; 5692 case Intrinsic::umul_fix: 5693 return ISD::UMULFIX; 5694 case Intrinsic::smul_fix_sat: 5695 return ISD::SMULFIXSAT; 5696 case Intrinsic::umul_fix_sat: 5697 return ISD::UMULFIXSAT; 5698 case Intrinsic::sdiv_fix: 5699 return ISD::SDIVFIX; 5700 case Intrinsic::udiv_fix: 5701 return ISD::UDIVFIX; 5702 case Intrinsic::sdiv_fix_sat: 5703 return ISD::SDIVFIXSAT; 5704 case Intrinsic::udiv_fix_sat: 5705 return ISD::UDIVFIXSAT; 5706 default: 5707 llvm_unreachable("Unhandled fixed point intrinsic"); 5708 } 5709 } 5710 5711 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5712 const char *FunctionName) { 5713 assert(FunctionName && "FunctionName must not be nullptr"); 5714 SDValue Callee = DAG.getExternalSymbol( 5715 FunctionName, 5716 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5717 LowerCallTo(I, Callee, I.isTailCall()); 5718 } 5719 5720 /// Given a @llvm.call.preallocated.setup, return the corresponding 5721 /// preallocated call. 5722 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5723 assert(cast<CallBase>(PreallocatedSetup) 5724 ->getCalledFunction() 5725 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5726 "expected call_preallocated_setup Value"); 5727 for (auto *U : PreallocatedSetup->users()) { 5728 auto *UseCall = cast<CallBase>(U); 5729 const Function *Fn = UseCall->getCalledFunction(); 5730 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5731 return UseCall; 5732 } 5733 } 5734 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5735 } 5736 5737 /// Lower the call to the specified intrinsic function. 5738 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5739 unsigned Intrinsic) { 5740 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5741 SDLoc sdl = getCurSDLoc(); 5742 DebugLoc dl = getCurDebugLoc(); 5743 SDValue Res; 5744 5745 SDNodeFlags Flags; 5746 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5747 Flags.copyFMF(*FPOp); 5748 5749 switch (Intrinsic) { 5750 default: 5751 // By default, turn this into a target intrinsic node. 5752 visitTargetIntrinsic(I, Intrinsic); 5753 return; 5754 case Intrinsic::vscale: { 5755 match(&I, m_VScale(DAG.getDataLayout())); 5756 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5757 setValue(&I, 5758 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5759 return; 5760 } 5761 case Intrinsic::vastart: visitVAStart(I); return; 5762 case Intrinsic::vaend: visitVAEnd(I); return; 5763 case Intrinsic::vacopy: visitVACopy(I); return; 5764 case Intrinsic::returnaddress: 5765 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5766 TLI.getPointerTy(DAG.getDataLayout()), 5767 getValue(I.getArgOperand(0)))); 5768 return; 5769 case Intrinsic::addressofreturnaddress: 5770 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5771 TLI.getPointerTy(DAG.getDataLayout()))); 5772 return; 5773 case Intrinsic::sponentry: 5774 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5775 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5776 return; 5777 case Intrinsic::frameaddress: 5778 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5779 TLI.getFrameIndexTy(DAG.getDataLayout()), 5780 getValue(I.getArgOperand(0)))); 5781 return; 5782 case Intrinsic::read_volatile_register: 5783 case Intrinsic::read_register: { 5784 Value *Reg = I.getArgOperand(0); 5785 SDValue Chain = getRoot(); 5786 SDValue RegName = 5787 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5788 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5789 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5790 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5791 setValue(&I, Res); 5792 DAG.setRoot(Res.getValue(1)); 5793 return; 5794 } 5795 case Intrinsic::write_register: { 5796 Value *Reg = I.getArgOperand(0); 5797 Value *RegValue = I.getArgOperand(1); 5798 SDValue Chain = getRoot(); 5799 SDValue RegName = 5800 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5801 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5802 RegName, getValue(RegValue))); 5803 return; 5804 } 5805 case Intrinsic::memcpy: { 5806 const auto &MCI = cast<MemCpyInst>(I); 5807 SDValue Op1 = getValue(I.getArgOperand(0)); 5808 SDValue Op2 = getValue(I.getArgOperand(1)); 5809 SDValue Op3 = getValue(I.getArgOperand(2)); 5810 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5811 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5812 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5813 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5814 bool isVol = MCI.isVolatile(); 5815 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5816 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5817 // node. 5818 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5819 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5820 /* AlwaysInline */ false, isTC, 5821 MachinePointerInfo(I.getArgOperand(0)), 5822 MachinePointerInfo(I.getArgOperand(1))); 5823 updateDAGForMaybeTailCall(MC); 5824 return; 5825 } 5826 case Intrinsic::memcpy_inline: { 5827 const auto &MCI = cast<MemCpyInlineInst>(I); 5828 SDValue Dst = getValue(I.getArgOperand(0)); 5829 SDValue Src = getValue(I.getArgOperand(1)); 5830 SDValue Size = getValue(I.getArgOperand(2)); 5831 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5832 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5833 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5834 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5835 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5836 bool isVol = MCI.isVolatile(); 5837 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5838 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5839 // node. 5840 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5841 /* AlwaysInline */ true, isTC, 5842 MachinePointerInfo(I.getArgOperand(0)), 5843 MachinePointerInfo(I.getArgOperand(1))); 5844 updateDAGForMaybeTailCall(MC); 5845 return; 5846 } 5847 case Intrinsic::memset: { 5848 const auto &MSI = cast<MemSetInst>(I); 5849 SDValue Op1 = getValue(I.getArgOperand(0)); 5850 SDValue Op2 = getValue(I.getArgOperand(1)); 5851 SDValue Op3 = getValue(I.getArgOperand(2)); 5852 // @llvm.memset defines 0 and 1 to both mean no alignment. 5853 Align Alignment = MSI.getDestAlign().valueOrOne(); 5854 bool isVol = MSI.isVolatile(); 5855 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5856 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5857 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5858 MachinePointerInfo(I.getArgOperand(0))); 5859 updateDAGForMaybeTailCall(MS); 5860 return; 5861 } 5862 case Intrinsic::memmove: { 5863 const auto &MMI = cast<MemMoveInst>(I); 5864 SDValue Op1 = getValue(I.getArgOperand(0)); 5865 SDValue Op2 = getValue(I.getArgOperand(1)); 5866 SDValue Op3 = getValue(I.getArgOperand(2)); 5867 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5868 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5869 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5870 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5871 bool isVol = MMI.isVolatile(); 5872 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5873 // FIXME: Support passing different dest/src alignments to the memmove DAG 5874 // node. 5875 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5876 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5877 isTC, MachinePointerInfo(I.getArgOperand(0)), 5878 MachinePointerInfo(I.getArgOperand(1))); 5879 updateDAGForMaybeTailCall(MM); 5880 return; 5881 } 5882 case Intrinsic::memcpy_element_unordered_atomic: { 5883 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5884 SDValue Dst = getValue(MI.getRawDest()); 5885 SDValue Src = getValue(MI.getRawSource()); 5886 SDValue Length = getValue(MI.getLength()); 5887 5888 unsigned DstAlign = MI.getDestAlignment(); 5889 unsigned SrcAlign = MI.getSourceAlignment(); 5890 Type *LengthTy = MI.getLength()->getType(); 5891 unsigned ElemSz = MI.getElementSizeInBytes(); 5892 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5893 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5894 SrcAlign, Length, LengthTy, ElemSz, isTC, 5895 MachinePointerInfo(MI.getRawDest()), 5896 MachinePointerInfo(MI.getRawSource())); 5897 updateDAGForMaybeTailCall(MC); 5898 return; 5899 } 5900 case Intrinsic::memmove_element_unordered_atomic: { 5901 auto &MI = cast<AtomicMemMoveInst>(I); 5902 SDValue Dst = getValue(MI.getRawDest()); 5903 SDValue Src = getValue(MI.getRawSource()); 5904 SDValue Length = getValue(MI.getLength()); 5905 5906 unsigned DstAlign = MI.getDestAlignment(); 5907 unsigned SrcAlign = MI.getSourceAlignment(); 5908 Type *LengthTy = MI.getLength()->getType(); 5909 unsigned ElemSz = MI.getElementSizeInBytes(); 5910 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5911 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5912 SrcAlign, Length, LengthTy, ElemSz, isTC, 5913 MachinePointerInfo(MI.getRawDest()), 5914 MachinePointerInfo(MI.getRawSource())); 5915 updateDAGForMaybeTailCall(MC); 5916 return; 5917 } 5918 case Intrinsic::memset_element_unordered_atomic: { 5919 auto &MI = cast<AtomicMemSetInst>(I); 5920 SDValue Dst = getValue(MI.getRawDest()); 5921 SDValue Val = getValue(MI.getValue()); 5922 SDValue Length = getValue(MI.getLength()); 5923 5924 unsigned DstAlign = MI.getDestAlignment(); 5925 Type *LengthTy = MI.getLength()->getType(); 5926 unsigned ElemSz = MI.getElementSizeInBytes(); 5927 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5928 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5929 LengthTy, ElemSz, isTC, 5930 MachinePointerInfo(MI.getRawDest())); 5931 updateDAGForMaybeTailCall(MC); 5932 return; 5933 } 5934 case Intrinsic::call_preallocated_setup: { 5935 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5936 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5937 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5938 getRoot(), SrcValue); 5939 setValue(&I, Res); 5940 DAG.setRoot(Res); 5941 return; 5942 } 5943 case Intrinsic::call_preallocated_arg: { 5944 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5945 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5946 SDValue Ops[3]; 5947 Ops[0] = getRoot(); 5948 Ops[1] = SrcValue; 5949 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5950 MVT::i32); // arg index 5951 SDValue Res = DAG.getNode( 5952 ISD::PREALLOCATED_ARG, sdl, 5953 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5954 setValue(&I, Res); 5955 DAG.setRoot(Res.getValue(1)); 5956 return; 5957 } 5958 case Intrinsic::dbg_addr: 5959 case Intrinsic::dbg_declare: { 5960 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 5961 // they are non-variadic. 5962 const auto &DI = cast<DbgVariableIntrinsic>(I); 5963 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 5964 DILocalVariable *Variable = DI.getVariable(); 5965 DIExpression *Expression = DI.getExpression(); 5966 dropDanglingDebugInfo(Variable, Expression); 5967 assert(Variable && "Missing variable"); 5968 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5969 << "\n"); 5970 // Check if address has undef value. 5971 const Value *Address = DI.getVariableLocationOp(0); 5972 if (!Address || isa<UndefValue>(Address) || 5973 (Address->use_empty() && !isa<Argument>(Address))) { 5974 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5975 << " (bad/undef/unused-arg address)\n"); 5976 return; 5977 } 5978 5979 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5980 5981 // Check if this variable can be described by a frame index, typically 5982 // either as a static alloca or a byval parameter. 5983 int FI = std::numeric_limits<int>::max(); 5984 if (const auto *AI = 5985 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5986 if (AI->isStaticAlloca()) { 5987 auto I = FuncInfo.StaticAllocaMap.find(AI); 5988 if (I != FuncInfo.StaticAllocaMap.end()) 5989 FI = I->second; 5990 } 5991 } else if (const auto *Arg = dyn_cast<Argument>( 5992 Address->stripInBoundsConstantOffsets())) { 5993 FI = FuncInfo.getArgumentFrameIndex(Arg); 5994 } 5995 5996 // llvm.dbg.addr is control dependent and always generates indirect 5997 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5998 // the MachineFunction variable table. 5999 if (FI != std::numeric_limits<int>::max()) { 6000 if (Intrinsic == Intrinsic::dbg_addr) { 6001 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6002 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6003 dl, SDNodeOrder); 6004 DAG.AddDbgValue(SDV, isParameter); 6005 } else { 6006 LLVM_DEBUG(dbgs() << "Skipping " << DI 6007 << " (variable info stashed in MF side table)\n"); 6008 } 6009 return; 6010 } 6011 6012 SDValue &N = NodeMap[Address]; 6013 if (!N.getNode() && isa<Argument>(Address)) 6014 // Check unused arguments map. 6015 N = UnusedArgNodeMap[Address]; 6016 SDDbgValue *SDV; 6017 if (N.getNode()) { 6018 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6019 Address = BCI->getOperand(0); 6020 // Parameters are handled specially. 6021 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6022 if (isParameter && FINode) { 6023 // Byval parameter. We have a frame index at this point. 6024 SDV = 6025 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6026 /*IsIndirect*/ true, dl, SDNodeOrder); 6027 } else if (isa<Argument>(Address)) { 6028 // Address is an argument, so try to emit its dbg value using 6029 // virtual register info from the FuncInfo.ValueMap. 6030 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6031 return; 6032 } else { 6033 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6034 true, dl, SDNodeOrder); 6035 } 6036 DAG.AddDbgValue(SDV, isParameter); 6037 } else { 6038 // If Address is an argument then try to emit its dbg value using 6039 // virtual register info from the FuncInfo.ValueMap. 6040 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6041 N)) { 6042 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6043 << " (could not emit func-arg dbg_value)\n"); 6044 } 6045 } 6046 return; 6047 } 6048 case Intrinsic::dbg_label: { 6049 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6050 DILabel *Label = DI.getLabel(); 6051 assert(Label && "Missing label"); 6052 6053 SDDbgLabel *SDV; 6054 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6055 DAG.AddDbgLabel(SDV); 6056 return; 6057 } 6058 case Intrinsic::dbg_value: { 6059 const DbgValueInst &DI = cast<DbgValueInst>(I); 6060 assert(DI.getVariable() && "Missing variable"); 6061 6062 DILocalVariable *Variable = DI.getVariable(); 6063 DIExpression *Expression = DI.getExpression(); 6064 dropDanglingDebugInfo(Variable, Expression); 6065 SmallVector<Value *, 4> Values(DI.getValues()); 6066 if (Values.empty()) 6067 return; 6068 6069 if (std::count(Values.begin(), Values.end(), nullptr)) 6070 return; 6071 6072 bool IsVariadic = DI.hasArgList(); 6073 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6074 SDNodeOrder, IsVariadic)) 6075 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6076 return; 6077 } 6078 6079 case Intrinsic::eh_typeid_for: { 6080 // Find the type id for the given typeinfo. 6081 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6082 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6083 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6084 setValue(&I, Res); 6085 return; 6086 } 6087 6088 case Intrinsic::eh_return_i32: 6089 case Intrinsic::eh_return_i64: 6090 DAG.getMachineFunction().setCallsEHReturn(true); 6091 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6092 MVT::Other, 6093 getControlRoot(), 6094 getValue(I.getArgOperand(0)), 6095 getValue(I.getArgOperand(1)))); 6096 return; 6097 case Intrinsic::eh_unwind_init: 6098 DAG.getMachineFunction().setCallsUnwindInit(true); 6099 return; 6100 case Intrinsic::eh_dwarf_cfa: 6101 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6102 TLI.getPointerTy(DAG.getDataLayout()), 6103 getValue(I.getArgOperand(0)))); 6104 return; 6105 case Intrinsic::eh_sjlj_callsite: { 6106 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6107 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6108 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6109 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6110 6111 MMI.setCurrentCallSite(CI->getZExtValue()); 6112 return; 6113 } 6114 case Intrinsic::eh_sjlj_functioncontext: { 6115 // Get and store the index of the function context. 6116 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6117 AllocaInst *FnCtx = 6118 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6119 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6120 MFI.setFunctionContextIndex(FI); 6121 return; 6122 } 6123 case Intrinsic::eh_sjlj_setjmp: { 6124 SDValue Ops[2]; 6125 Ops[0] = getRoot(); 6126 Ops[1] = getValue(I.getArgOperand(0)); 6127 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6128 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6129 setValue(&I, Op.getValue(0)); 6130 DAG.setRoot(Op.getValue(1)); 6131 return; 6132 } 6133 case Intrinsic::eh_sjlj_longjmp: 6134 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6135 getRoot(), getValue(I.getArgOperand(0)))); 6136 return; 6137 case Intrinsic::eh_sjlj_setup_dispatch: 6138 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6139 getRoot())); 6140 return; 6141 case Intrinsic::masked_gather: 6142 visitMaskedGather(I); 6143 return; 6144 case Intrinsic::masked_load: 6145 visitMaskedLoad(I); 6146 return; 6147 case Intrinsic::masked_scatter: 6148 visitMaskedScatter(I); 6149 return; 6150 case Intrinsic::masked_store: 6151 visitMaskedStore(I); 6152 return; 6153 case Intrinsic::masked_expandload: 6154 visitMaskedLoad(I, true /* IsExpanding */); 6155 return; 6156 case Intrinsic::masked_compressstore: 6157 visitMaskedStore(I, true /* IsCompressing */); 6158 return; 6159 case Intrinsic::powi: 6160 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6161 getValue(I.getArgOperand(1)), DAG)); 6162 return; 6163 case Intrinsic::log: 6164 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6165 return; 6166 case Intrinsic::log2: 6167 setValue(&I, 6168 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6169 return; 6170 case Intrinsic::log10: 6171 setValue(&I, 6172 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6173 return; 6174 case Intrinsic::exp: 6175 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6176 return; 6177 case Intrinsic::exp2: 6178 setValue(&I, 6179 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6180 return; 6181 case Intrinsic::pow: 6182 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6183 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6184 return; 6185 case Intrinsic::sqrt: 6186 case Intrinsic::fabs: 6187 case Intrinsic::sin: 6188 case Intrinsic::cos: 6189 case Intrinsic::floor: 6190 case Intrinsic::ceil: 6191 case Intrinsic::trunc: 6192 case Intrinsic::rint: 6193 case Intrinsic::nearbyint: 6194 case Intrinsic::round: 6195 case Intrinsic::roundeven: 6196 case Intrinsic::canonicalize: { 6197 unsigned Opcode; 6198 switch (Intrinsic) { 6199 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6200 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6201 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6202 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6203 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6204 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6205 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6206 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6207 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6208 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6209 case Intrinsic::round: Opcode = ISD::FROUND; break; 6210 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6211 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6212 } 6213 6214 setValue(&I, DAG.getNode(Opcode, sdl, 6215 getValue(I.getArgOperand(0)).getValueType(), 6216 getValue(I.getArgOperand(0)), Flags)); 6217 return; 6218 } 6219 case Intrinsic::lround: 6220 case Intrinsic::llround: 6221 case Intrinsic::lrint: 6222 case Intrinsic::llrint: { 6223 unsigned Opcode; 6224 switch (Intrinsic) { 6225 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6226 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6227 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6228 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6229 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6230 } 6231 6232 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6233 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6234 getValue(I.getArgOperand(0)))); 6235 return; 6236 } 6237 case Intrinsic::minnum: 6238 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6239 getValue(I.getArgOperand(0)).getValueType(), 6240 getValue(I.getArgOperand(0)), 6241 getValue(I.getArgOperand(1)), Flags)); 6242 return; 6243 case Intrinsic::maxnum: 6244 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6245 getValue(I.getArgOperand(0)).getValueType(), 6246 getValue(I.getArgOperand(0)), 6247 getValue(I.getArgOperand(1)), Flags)); 6248 return; 6249 case Intrinsic::minimum: 6250 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6251 getValue(I.getArgOperand(0)).getValueType(), 6252 getValue(I.getArgOperand(0)), 6253 getValue(I.getArgOperand(1)), Flags)); 6254 return; 6255 case Intrinsic::maximum: 6256 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6257 getValue(I.getArgOperand(0)).getValueType(), 6258 getValue(I.getArgOperand(0)), 6259 getValue(I.getArgOperand(1)), Flags)); 6260 return; 6261 case Intrinsic::copysign: 6262 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6263 getValue(I.getArgOperand(0)).getValueType(), 6264 getValue(I.getArgOperand(0)), 6265 getValue(I.getArgOperand(1)), Flags)); 6266 return; 6267 case Intrinsic::fma: 6268 setValue(&I, DAG.getNode( 6269 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6270 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6271 getValue(I.getArgOperand(2)), Flags)); 6272 return; 6273 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6274 case Intrinsic::INTRINSIC: 6275 #include "llvm/IR/ConstrainedOps.def" 6276 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6277 return; 6278 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6279 #include "llvm/IR/VPIntrinsics.def" 6280 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6281 return; 6282 case Intrinsic::fmuladd: { 6283 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6284 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6285 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6286 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6287 getValue(I.getArgOperand(0)).getValueType(), 6288 getValue(I.getArgOperand(0)), 6289 getValue(I.getArgOperand(1)), 6290 getValue(I.getArgOperand(2)), Flags)); 6291 } else { 6292 // TODO: Intrinsic calls should have fast-math-flags. 6293 SDValue Mul = DAG.getNode( 6294 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6295 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6296 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6297 getValue(I.getArgOperand(0)).getValueType(), 6298 Mul, getValue(I.getArgOperand(2)), Flags); 6299 setValue(&I, Add); 6300 } 6301 return; 6302 } 6303 case Intrinsic::convert_to_fp16: 6304 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6305 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6306 getValue(I.getArgOperand(0)), 6307 DAG.getTargetConstant(0, sdl, 6308 MVT::i32)))); 6309 return; 6310 case Intrinsic::convert_from_fp16: 6311 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6312 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6313 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6314 getValue(I.getArgOperand(0))))); 6315 return; 6316 case Intrinsic::fptosi_sat: { 6317 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6318 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6319 getValue(I.getArgOperand(0)), 6320 DAG.getValueType(VT.getScalarType()))); 6321 return; 6322 } 6323 case Intrinsic::fptoui_sat: { 6324 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6325 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6326 getValue(I.getArgOperand(0)), 6327 DAG.getValueType(VT.getScalarType()))); 6328 return; 6329 } 6330 case Intrinsic::set_rounding: 6331 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6332 {getRoot(), getValue(I.getArgOperand(0))}); 6333 setValue(&I, Res); 6334 DAG.setRoot(Res.getValue(0)); 6335 return; 6336 case Intrinsic::pcmarker: { 6337 SDValue Tmp = getValue(I.getArgOperand(0)); 6338 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6339 return; 6340 } 6341 case Intrinsic::readcyclecounter: { 6342 SDValue Op = getRoot(); 6343 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6344 DAG.getVTList(MVT::i64, MVT::Other), Op); 6345 setValue(&I, Res); 6346 DAG.setRoot(Res.getValue(1)); 6347 return; 6348 } 6349 case Intrinsic::bitreverse: 6350 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6351 getValue(I.getArgOperand(0)).getValueType(), 6352 getValue(I.getArgOperand(0)))); 6353 return; 6354 case Intrinsic::bswap: 6355 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6356 getValue(I.getArgOperand(0)).getValueType(), 6357 getValue(I.getArgOperand(0)))); 6358 return; 6359 case Intrinsic::cttz: { 6360 SDValue Arg = getValue(I.getArgOperand(0)); 6361 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6362 EVT Ty = Arg.getValueType(); 6363 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6364 sdl, Ty, Arg)); 6365 return; 6366 } 6367 case Intrinsic::ctlz: { 6368 SDValue Arg = getValue(I.getArgOperand(0)); 6369 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6370 EVT Ty = Arg.getValueType(); 6371 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6372 sdl, Ty, Arg)); 6373 return; 6374 } 6375 case Intrinsic::ctpop: { 6376 SDValue Arg = getValue(I.getArgOperand(0)); 6377 EVT Ty = Arg.getValueType(); 6378 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6379 return; 6380 } 6381 case Intrinsic::fshl: 6382 case Intrinsic::fshr: { 6383 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6384 SDValue X = getValue(I.getArgOperand(0)); 6385 SDValue Y = getValue(I.getArgOperand(1)); 6386 SDValue Z = getValue(I.getArgOperand(2)); 6387 EVT VT = X.getValueType(); 6388 6389 if (X == Y) { 6390 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6391 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6392 } else { 6393 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6394 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6395 } 6396 return; 6397 } 6398 case Intrinsic::sadd_sat: { 6399 SDValue Op1 = getValue(I.getArgOperand(0)); 6400 SDValue Op2 = getValue(I.getArgOperand(1)); 6401 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6402 return; 6403 } 6404 case Intrinsic::uadd_sat: { 6405 SDValue Op1 = getValue(I.getArgOperand(0)); 6406 SDValue Op2 = getValue(I.getArgOperand(1)); 6407 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6408 return; 6409 } 6410 case Intrinsic::ssub_sat: { 6411 SDValue Op1 = getValue(I.getArgOperand(0)); 6412 SDValue Op2 = getValue(I.getArgOperand(1)); 6413 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6414 return; 6415 } 6416 case Intrinsic::usub_sat: { 6417 SDValue Op1 = getValue(I.getArgOperand(0)); 6418 SDValue Op2 = getValue(I.getArgOperand(1)); 6419 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6420 return; 6421 } 6422 case Intrinsic::sshl_sat: { 6423 SDValue Op1 = getValue(I.getArgOperand(0)); 6424 SDValue Op2 = getValue(I.getArgOperand(1)); 6425 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6426 return; 6427 } 6428 case Intrinsic::ushl_sat: { 6429 SDValue Op1 = getValue(I.getArgOperand(0)); 6430 SDValue Op2 = getValue(I.getArgOperand(1)); 6431 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6432 return; 6433 } 6434 case Intrinsic::smul_fix: 6435 case Intrinsic::umul_fix: 6436 case Intrinsic::smul_fix_sat: 6437 case Intrinsic::umul_fix_sat: { 6438 SDValue Op1 = getValue(I.getArgOperand(0)); 6439 SDValue Op2 = getValue(I.getArgOperand(1)); 6440 SDValue Op3 = getValue(I.getArgOperand(2)); 6441 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6442 Op1.getValueType(), Op1, Op2, Op3)); 6443 return; 6444 } 6445 case Intrinsic::sdiv_fix: 6446 case Intrinsic::udiv_fix: 6447 case Intrinsic::sdiv_fix_sat: 6448 case Intrinsic::udiv_fix_sat: { 6449 SDValue Op1 = getValue(I.getArgOperand(0)); 6450 SDValue Op2 = getValue(I.getArgOperand(1)); 6451 SDValue Op3 = getValue(I.getArgOperand(2)); 6452 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6453 Op1, Op2, Op3, DAG, TLI)); 6454 return; 6455 } 6456 case Intrinsic::smax: { 6457 SDValue Op1 = getValue(I.getArgOperand(0)); 6458 SDValue Op2 = getValue(I.getArgOperand(1)); 6459 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6460 return; 6461 } 6462 case Intrinsic::smin: { 6463 SDValue Op1 = getValue(I.getArgOperand(0)); 6464 SDValue Op2 = getValue(I.getArgOperand(1)); 6465 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6466 return; 6467 } 6468 case Intrinsic::umax: { 6469 SDValue Op1 = getValue(I.getArgOperand(0)); 6470 SDValue Op2 = getValue(I.getArgOperand(1)); 6471 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6472 return; 6473 } 6474 case Intrinsic::umin: { 6475 SDValue Op1 = getValue(I.getArgOperand(0)); 6476 SDValue Op2 = getValue(I.getArgOperand(1)); 6477 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6478 return; 6479 } 6480 case Intrinsic::abs: { 6481 // TODO: Preserve "int min is poison" arg in SDAG? 6482 SDValue Op1 = getValue(I.getArgOperand(0)); 6483 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6484 return; 6485 } 6486 case Intrinsic::stacksave: { 6487 SDValue Op = getRoot(); 6488 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6489 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6490 setValue(&I, Res); 6491 DAG.setRoot(Res.getValue(1)); 6492 return; 6493 } 6494 case Intrinsic::stackrestore: 6495 Res = getValue(I.getArgOperand(0)); 6496 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6497 return; 6498 case Intrinsic::get_dynamic_area_offset: { 6499 SDValue Op = getRoot(); 6500 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6501 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6502 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6503 // target. 6504 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6505 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6506 " intrinsic!"); 6507 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6508 Op); 6509 DAG.setRoot(Op); 6510 setValue(&I, Res); 6511 return; 6512 } 6513 case Intrinsic::stackguard: { 6514 MachineFunction &MF = DAG.getMachineFunction(); 6515 const Module &M = *MF.getFunction().getParent(); 6516 SDValue Chain = getRoot(); 6517 if (TLI.useLoadStackGuardNode()) { 6518 Res = getLoadStackGuard(DAG, sdl, Chain); 6519 } else { 6520 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6521 const Value *Global = TLI.getSDagStackGuard(M); 6522 Align Align = DL->getPrefTypeAlign(Global->getType()); 6523 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6524 MachinePointerInfo(Global, 0), Align, 6525 MachineMemOperand::MOVolatile); 6526 } 6527 if (TLI.useStackGuardXorFP()) 6528 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6529 DAG.setRoot(Chain); 6530 setValue(&I, Res); 6531 return; 6532 } 6533 case Intrinsic::stackprotector: { 6534 // Emit code into the DAG to store the stack guard onto the stack. 6535 MachineFunction &MF = DAG.getMachineFunction(); 6536 MachineFrameInfo &MFI = MF.getFrameInfo(); 6537 SDValue Src, Chain = getRoot(); 6538 6539 if (TLI.useLoadStackGuardNode()) 6540 Src = getLoadStackGuard(DAG, sdl, Chain); 6541 else 6542 Src = getValue(I.getArgOperand(0)); // The guard's value. 6543 6544 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6545 6546 int FI = FuncInfo.StaticAllocaMap[Slot]; 6547 MFI.setStackProtectorIndex(FI); 6548 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6549 6550 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6551 6552 // Store the stack protector onto the stack. 6553 Res = DAG.getStore( 6554 Chain, sdl, Src, FIN, 6555 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6556 MaybeAlign(), MachineMemOperand::MOVolatile); 6557 setValue(&I, Res); 6558 DAG.setRoot(Res); 6559 return; 6560 } 6561 case Intrinsic::objectsize: 6562 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6563 6564 case Intrinsic::is_constant: 6565 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6566 6567 case Intrinsic::annotation: 6568 case Intrinsic::ptr_annotation: 6569 case Intrinsic::launder_invariant_group: 6570 case Intrinsic::strip_invariant_group: 6571 // Drop the intrinsic, but forward the value 6572 setValue(&I, getValue(I.getOperand(0))); 6573 return; 6574 6575 case Intrinsic::assume: 6576 case Intrinsic::experimental_noalias_scope_decl: 6577 case Intrinsic::var_annotation: 6578 case Intrinsic::sideeffect: 6579 // Discard annotate attributes, noalias scope declarations, assumptions, and 6580 // artificial side-effects. 6581 return; 6582 6583 case Intrinsic::codeview_annotation: { 6584 // Emit a label associated with this metadata. 6585 MachineFunction &MF = DAG.getMachineFunction(); 6586 MCSymbol *Label = 6587 MF.getMMI().getContext().createTempSymbol("annotation", true); 6588 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6589 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6590 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6591 DAG.setRoot(Res); 6592 return; 6593 } 6594 6595 case Intrinsic::init_trampoline: { 6596 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6597 6598 SDValue Ops[6]; 6599 Ops[0] = getRoot(); 6600 Ops[1] = getValue(I.getArgOperand(0)); 6601 Ops[2] = getValue(I.getArgOperand(1)); 6602 Ops[3] = getValue(I.getArgOperand(2)); 6603 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6604 Ops[5] = DAG.getSrcValue(F); 6605 6606 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6607 6608 DAG.setRoot(Res); 6609 return; 6610 } 6611 case Intrinsic::adjust_trampoline: 6612 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6613 TLI.getPointerTy(DAG.getDataLayout()), 6614 getValue(I.getArgOperand(0)))); 6615 return; 6616 case Intrinsic::gcroot: { 6617 assert(DAG.getMachineFunction().getFunction().hasGC() && 6618 "only valid in functions with gc specified, enforced by Verifier"); 6619 assert(GFI && "implied by previous"); 6620 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6621 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6622 6623 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6624 GFI->addStackRoot(FI->getIndex(), TypeMap); 6625 return; 6626 } 6627 case Intrinsic::gcread: 6628 case Intrinsic::gcwrite: 6629 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6630 case Intrinsic::flt_rounds: 6631 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6632 setValue(&I, Res); 6633 DAG.setRoot(Res.getValue(1)); 6634 return; 6635 6636 case Intrinsic::expect: 6637 // Just replace __builtin_expect(exp, c) with EXP. 6638 setValue(&I, getValue(I.getArgOperand(0))); 6639 return; 6640 6641 case Intrinsic::ubsantrap: 6642 case Intrinsic::debugtrap: 6643 case Intrinsic::trap: { 6644 StringRef TrapFuncName = 6645 I.getAttributes() 6646 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6647 .getValueAsString(); 6648 if (TrapFuncName.empty()) { 6649 switch (Intrinsic) { 6650 case Intrinsic::trap: 6651 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6652 break; 6653 case Intrinsic::debugtrap: 6654 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6655 break; 6656 case Intrinsic::ubsantrap: 6657 DAG.setRoot(DAG.getNode( 6658 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6659 DAG.getTargetConstant( 6660 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6661 MVT::i32))); 6662 break; 6663 default: llvm_unreachable("unknown trap intrinsic"); 6664 } 6665 return; 6666 } 6667 TargetLowering::ArgListTy Args; 6668 if (Intrinsic == Intrinsic::ubsantrap) { 6669 Args.push_back(TargetLoweringBase::ArgListEntry()); 6670 Args[0].Val = I.getArgOperand(0); 6671 Args[0].Node = getValue(Args[0].Val); 6672 Args[0].Ty = Args[0].Val->getType(); 6673 } 6674 6675 TargetLowering::CallLoweringInfo CLI(DAG); 6676 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6677 CallingConv::C, I.getType(), 6678 DAG.getExternalSymbol(TrapFuncName.data(), 6679 TLI.getPointerTy(DAG.getDataLayout())), 6680 std::move(Args)); 6681 6682 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6683 DAG.setRoot(Result.second); 6684 return; 6685 } 6686 6687 case Intrinsic::uadd_with_overflow: 6688 case Intrinsic::sadd_with_overflow: 6689 case Intrinsic::usub_with_overflow: 6690 case Intrinsic::ssub_with_overflow: 6691 case Intrinsic::umul_with_overflow: 6692 case Intrinsic::smul_with_overflow: { 6693 ISD::NodeType Op; 6694 switch (Intrinsic) { 6695 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6696 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6697 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6698 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6699 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6700 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6701 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6702 } 6703 SDValue Op1 = getValue(I.getArgOperand(0)); 6704 SDValue Op2 = getValue(I.getArgOperand(1)); 6705 6706 EVT ResultVT = Op1.getValueType(); 6707 EVT OverflowVT = MVT::i1; 6708 if (ResultVT.isVector()) 6709 OverflowVT = EVT::getVectorVT( 6710 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6711 6712 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6713 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6714 return; 6715 } 6716 case Intrinsic::prefetch: { 6717 SDValue Ops[5]; 6718 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6719 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6720 Ops[0] = DAG.getRoot(); 6721 Ops[1] = getValue(I.getArgOperand(0)); 6722 Ops[2] = getValue(I.getArgOperand(1)); 6723 Ops[3] = getValue(I.getArgOperand(2)); 6724 Ops[4] = getValue(I.getArgOperand(3)); 6725 SDValue Result = DAG.getMemIntrinsicNode( 6726 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6727 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6728 /* align */ None, Flags); 6729 6730 // Chain the prefetch in parallell with any pending loads, to stay out of 6731 // the way of later optimizations. 6732 PendingLoads.push_back(Result); 6733 Result = getRoot(); 6734 DAG.setRoot(Result); 6735 return; 6736 } 6737 case Intrinsic::lifetime_start: 6738 case Intrinsic::lifetime_end: { 6739 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6740 // Stack coloring is not enabled in O0, discard region information. 6741 if (TM.getOptLevel() == CodeGenOpt::None) 6742 return; 6743 6744 const int64_t ObjectSize = 6745 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6746 Value *const ObjectPtr = I.getArgOperand(1); 6747 SmallVector<const Value *, 4> Allocas; 6748 getUnderlyingObjects(ObjectPtr, Allocas); 6749 6750 for (const Value *Alloca : Allocas) { 6751 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6752 6753 // Could not find an Alloca. 6754 if (!LifetimeObject) 6755 continue; 6756 6757 // First check that the Alloca is static, otherwise it won't have a 6758 // valid frame index. 6759 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6760 if (SI == FuncInfo.StaticAllocaMap.end()) 6761 return; 6762 6763 const int FrameIndex = SI->second; 6764 int64_t Offset; 6765 if (GetPointerBaseWithConstantOffset( 6766 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6767 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6768 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6769 Offset); 6770 DAG.setRoot(Res); 6771 } 6772 return; 6773 } 6774 case Intrinsic::pseudoprobe: { 6775 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6776 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6777 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6778 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6779 DAG.setRoot(Res); 6780 return; 6781 } 6782 case Intrinsic::invariant_start: 6783 // Discard region information. 6784 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6785 return; 6786 case Intrinsic::invariant_end: 6787 // Discard region information. 6788 return; 6789 case Intrinsic::clear_cache: 6790 /// FunctionName may be null. 6791 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6792 lowerCallToExternalSymbol(I, FunctionName); 6793 return; 6794 case Intrinsic::donothing: 6795 // ignore 6796 return; 6797 case Intrinsic::experimental_stackmap: 6798 visitStackmap(I); 6799 return; 6800 case Intrinsic::experimental_patchpoint_void: 6801 case Intrinsic::experimental_patchpoint_i64: 6802 visitPatchpoint(I); 6803 return; 6804 case Intrinsic::experimental_gc_statepoint: 6805 LowerStatepoint(cast<GCStatepointInst>(I)); 6806 return; 6807 case Intrinsic::experimental_gc_result: 6808 visitGCResult(cast<GCResultInst>(I)); 6809 return; 6810 case Intrinsic::experimental_gc_relocate: 6811 visitGCRelocate(cast<GCRelocateInst>(I)); 6812 return; 6813 case Intrinsic::instrprof_increment: 6814 llvm_unreachable("instrprof failed to lower an increment"); 6815 case Intrinsic::instrprof_value_profile: 6816 llvm_unreachable("instrprof failed to lower a value profiling call"); 6817 case Intrinsic::localescape: { 6818 MachineFunction &MF = DAG.getMachineFunction(); 6819 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6820 6821 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6822 // is the same on all targets. 6823 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6824 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6825 if (isa<ConstantPointerNull>(Arg)) 6826 continue; // Skip null pointers. They represent a hole in index space. 6827 AllocaInst *Slot = cast<AllocaInst>(Arg); 6828 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6829 "can only escape static allocas"); 6830 int FI = FuncInfo.StaticAllocaMap[Slot]; 6831 MCSymbol *FrameAllocSym = 6832 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6833 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6834 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6835 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6836 .addSym(FrameAllocSym) 6837 .addFrameIndex(FI); 6838 } 6839 6840 return; 6841 } 6842 6843 case Intrinsic::localrecover: { 6844 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6845 MachineFunction &MF = DAG.getMachineFunction(); 6846 6847 // Get the symbol that defines the frame offset. 6848 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6849 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6850 unsigned IdxVal = 6851 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6852 MCSymbol *FrameAllocSym = 6853 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6854 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6855 6856 Value *FP = I.getArgOperand(1); 6857 SDValue FPVal = getValue(FP); 6858 EVT PtrVT = FPVal.getValueType(); 6859 6860 // Create a MCSymbol for the label to avoid any target lowering 6861 // that would make this PC relative. 6862 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6863 SDValue OffsetVal = 6864 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6865 6866 // Add the offset to the FP. 6867 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6868 setValue(&I, Add); 6869 6870 return; 6871 } 6872 6873 case Intrinsic::eh_exceptionpointer: 6874 case Intrinsic::eh_exceptioncode: { 6875 // Get the exception pointer vreg, copy from it, and resize it to fit. 6876 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6877 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6878 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6879 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6880 SDValue N = 6881 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6882 if (Intrinsic == Intrinsic::eh_exceptioncode) 6883 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6884 setValue(&I, N); 6885 return; 6886 } 6887 case Intrinsic::xray_customevent: { 6888 // Here we want to make sure that the intrinsic behaves as if it has a 6889 // specific calling convention, and only for x86_64. 6890 // FIXME: Support other platforms later. 6891 const auto &Triple = DAG.getTarget().getTargetTriple(); 6892 if (Triple.getArch() != Triple::x86_64) 6893 return; 6894 6895 SDLoc DL = getCurSDLoc(); 6896 SmallVector<SDValue, 8> Ops; 6897 6898 // We want to say that we always want the arguments in registers. 6899 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6900 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6901 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6902 SDValue Chain = getRoot(); 6903 Ops.push_back(LogEntryVal); 6904 Ops.push_back(StrSizeVal); 6905 Ops.push_back(Chain); 6906 6907 // We need to enforce the calling convention for the callsite, so that 6908 // argument ordering is enforced correctly, and that register allocation can 6909 // see that some registers may be assumed clobbered and have to preserve 6910 // them across calls to the intrinsic. 6911 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6912 DL, NodeTys, Ops); 6913 SDValue patchableNode = SDValue(MN, 0); 6914 DAG.setRoot(patchableNode); 6915 setValue(&I, patchableNode); 6916 return; 6917 } 6918 case Intrinsic::xray_typedevent: { 6919 // Here we want to make sure that the intrinsic behaves as if it has a 6920 // specific calling convention, and only for x86_64. 6921 // FIXME: Support other platforms later. 6922 const auto &Triple = DAG.getTarget().getTargetTriple(); 6923 if (Triple.getArch() != Triple::x86_64) 6924 return; 6925 6926 SDLoc DL = getCurSDLoc(); 6927 SmallVector<SDValue, 8> Ops; 6928 6929 // We want to say that we always want the arguments in registers. 6930 // It's unclear to me how manipulating the selection DAG here forces callers 6931 // to provide arguments in registers instead of on the stack. 6932 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6933 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6934 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6935 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6936 SDValue Chain = getRoot(); 6937 Ops.push_back(LogTypeId); 6938 Ops.push_back(LogEntryVal); 6939 Ops.push_back(StrSizeVal); 6940 Ops.push_back(Chain); 6941 6942 // We need to enforce the calling convention for the callsite, so that 6943 // argument ordering is enforced correctly, and that register allocation can 6944 // see that some registers may be assumed clobbered and have to preserve 6945 // them across calls to the intrinsic. 6946 MachineSDNode *MN = DAG.getMachineNode( 6947 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6948 SDValue patchableNode = SDValue(MN, 0); 6949 DAG.setRoot(patchableNode); 6950 setValue(&I, patchableNode); 6951 return; 6952 } 6953 case Intrinsic::experimental_deoptimize: 6954 LowerDeoptimizeCall(&I); 6955 return; 6956 case Intrinsic::experimental_stepvector: 6957 visitStepVector(I); 6958 return; 6959 case Intrinsic::vector_reduce_fadd: 6960 case Intrinsic::vector_reduce_fmul: 6961 case Intrinsic::vector_reduce_add: 6962 case Intrinsic::vector_reduce_mul: 6963 case Intrinsic::vector_reduce_and: 6964 case Intrinsic::vector_reduce_or: 6965 case Intrinsic::vector_reduce_xor: 6966 case Intrinsic::vector_reduce_smax: 6967 case Intrinsic::vector_reduce_smin: 6968 case Intrinsic::vector_reduce_umax: 6969 case Intrinsic::vector_reduce_umin: 6970 case Intrinsic::vector_reduce_fmax: 6971 case Intrinsic::vector_reduce_fmin: 6972 visitVectorReduce(I, Intrinsic); 6973 return; 6974 6975 case Intrinsic::icall_branch_funnel: { 6976 SmallVector<SDValue, 16> Ops; 6977 Ops.push_back(getValue(I.getArgOperand(0))); 6978 6979 int64_t Offset; 6980 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6981 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6982 if (!Base) 6983 report_fatal_error( 6984 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6985 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6986 6987 struct BranchFunnelTarget { 6988 int64_t Offset; 6989 SDValue Target; 6990 }; 6991 SmallVector<BranchFunnelTarget, 8> Targets; 6992 6993 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6994 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6995 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6996 if (ElemBase != Base) 6997 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6998 "to the same GlobalValue"); 6999 7000 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7001 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7002 if (!GA) 7003 report_fatal_error( 7004 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7005 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7006 GA->getGlobal(), getCurSDLoc(), 7007 Val.getValueType(), GA->getOffset())}); 7008 } 7009 llvm::sort(Targets, 7010 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7011 return T1.Offset < T2.Offset; 7012 }); 7013 7014 for (auto &T : Targets) { 7015 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 7016 Ops.push_back(T.Target); 7017 } 7018 7019 Ops.push_back(DAG.getRoot()); // Chain 7020 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 7021 getCurSDLoc(), MVT::Other, Ops), 7022 0); 7023 DAG.setRoot(N); 7024 setValue(&I, N); 7025 HasTailCall = true; 7026 return; 7027 } 7028 7029 case Intrinsic::wasm_landingpad_index: 7030 // Information this intrinsic contained has been transferred to 7031 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7032 // delete it now. 7033 return; 7034 7035 case Intrinsic::aarch64_settag: 7036 case Intrinsic::aarch64_settag_zero: { 7037 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7038 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7039 SDValue Val = TSI.EmitTargetCodeForSetTag( 7040 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 7041 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7042 ZeroMemory); 7043 DAG.setRoot(Val); 7044 setValue(&I, Val); 7045 return; 7046 } 7047 case Intrinsic::ptrmask: { 7048 SDValue Ptr = getValue(I.getOperand(0)); 7049 SDValue Const = getValue(I.getOperand(1)); 7050 7051 EVT PtrVT = Ptr.getValueType(); 7052 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 7053 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 7054 return; 7055 } 7056 case Intrinsic::get_active_lane_mask: { 7057 auto DL = getCurSDLoc(); 7058 SDValue Index = getValue(I.getOperand(0)); 7059 SDValue TripCount = getValue(I.getOperand(1)); 7060 Type *ElementTy = I.getOperand(0)->getType(); 7061 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7062 unsigned VecWidth = VT.getVectorNumElements(); 7063 7064 SmallVector<SDValue, 16> OpsTripCount; 7065 SmallVector<SDValue, 16> OpsIndex; 7066 SmallVector<SDValue, 16> OpsStepConstants; 7067 for (unsigned i = 0; i < VecWidth; i++) { 7068 OpsTripCount.push_back(TripCount); 7069 OpsIndex.push_back(Index); 7070 OpsStepConstants.push_back( 7071 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 7072 } 7073 7074 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 7075 7076 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 7077 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 7078 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 7079 SDValue VectorInduction = DAG.getNode( 7080 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 7081 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 7082 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 7083 VectorTripCount, ISD::CondCode::SETULT); 7084 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 7085 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 7086 SetCC)); 7087 return; 7088 } 7089 case Intrinsic::experimental_vector_insert: { 7090 auto DL = getCurSDLoc(); 7091 7092 SDValue Vec = getValue(I.getOperand(0)); 7093 SDValue SubVec = getValue(I.getOperand(1)); 7094 SDValue Index = getValue(I.getOperand(2)); 7095 7096 // The intrinsic's index type is i64, but the SDNode requires an index type 7097 // suitable for the target. Convert the index as required. 7098 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7099 if (Index.getValueType() != VectorIdxTy) 7100 Index = DAG.getVectorIdxConstant( 7101 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7102 7103 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7104 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec, 7105 Index)); 7106 return; 7107 } 7108 case Intrinsic::experimental_vector_extract: { 7109 auto DL = getCurSDLoc(); 7110 7111 SDValue Vec = getValue(I.getOperand(0)); 7112 SDValue Index = getValue(I.getOperand(1)); 7113 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7114 7115 // The intrinsic's index type is i64, but the SDNode requires an index type 7116 // suitable for the target. Convert the index as required. 7117 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7118 if (Index.getValueType() != VectorIdxTy) 7119 Index = DAG.getVectorIdxConstant( 7120 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7121 7122 setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index)); 7123 return; 7124 } 7125 case Intrinsic::experimental_vector_reverse: 7126 visitVectorReverse(I); 7127 return; 7128 case Intrinsic::experimental_vector_splice: 7129 visitVectorSplice(I); 7130 return; 7131 } 7132 } 7133 7134 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7135 const ConstrainedFPIntrinsic &FPI) { 7136 SDLoc sdl = getCurSDLoc(); 7137 7138 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7139 SmallVector<EVT, 4> ValueVTs; 7140 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7141 ValueVTs.push_back(MVT::Other); // Out chain 7142 7143 // We do not need to serialize constrained FP intrinsics against 7144 // each other or against (nonvolatile) loads, so they can be 7145 // chained like loads. 7146 SDValue Chain = DAG.getRoot(); 7147 SmallVector<SDValue, 4> Opers; 7148 Opers.push_back(Chain); 7149 if (FPI.isUnaryOp()) { 7150 Opers.push_back(getValue(FPI.getArgOperand(0))); 7151 } else if (FPI.isTernaryOp()) { 7152 Opers.push_back(getValue(FPI.getArgOperand(0))); 7153 Opers.push_back(getValue(FPI.getArgOperand(1))); 7154 Opers.push_back(getValue(FPI.getArgOperand(2))); 7155 } else { 7156 Opers.push_back(getValue(FPI.getArgOperand(0))); 7157 Opers.push_back(getValue(FPI.getArgOperand(1))); 7158 } 7159 7160 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7161 assert(Result.getNode()->getNumValues() == 2); 7162 7163 // Push node to the appropriate list so that future instructions can be 7164 // chained up correctly. 7165 SDValue OutChain = Result.getValue(1); 7166 switch (EB) { 7167 case fp::ExceptionBehavior::ebIgnore: 7168 // The only reason why ebIgnore nodes still need to be chained is that 7169 // they might depend on the current rounding mode, and therefore must 7170 // not be moved across instruction that may change that mode. 7171 LLVM_FALLTHROUGH; 7172 case fp::ExceptionBehavior::ebMayTrap: 7173 // These must not be moved across calls or instructions that may change 7174 // floating-point exception masks. 7175 PendingConstrainedFP.push_back(OutChain); 7176 break; 7177 case fp::ExceptionBehavior::ebStrict: 7178 // These must not be moved across calls or instructions that may change 7179 // floating-point exception masks or read floating-point exception flags. 7180 // In addition, they cannot be optimized out even if unused. 7181 PendingConstrainedFPStrict.push_back(OutChain); 7182 break; 7183 } 7184 }; 7185 7186 SDVTList VTs = DAG.getVTList(ValueVTs); 7187 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7188 7189 SDNodeFlags Flags; 7190 if (EB == fp::ExceptionBehavior::ebIgnore) 7191 Flags.setNoFPExcept(true); 7192 7193 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7194 Flags.copyFMF(*FPOp); 7195 7196 unsigned Opcode; 7197 switch (FPI.getIntrinsicID()) { 7198 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7199 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7200 case Intrinsic::INTRINSIC: \ 7201 Opcode = ISD::STRICT_##DAGN; \ 7202 break; 7203 #include "llvm/IR/ConstrainedOps.def" 7204 case Intrinsic::experimental_constrained_fmuladd: { 7205 Opcode = ISD::STRICT_FMA; 7206 // Break fmuladd into fmul and fadd. 7207 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7208 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7209 ValueVTs[0])) { 7210 Opers.pop_back(); 7211 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7212 pushOutChain(Mul, EB); 7213 Opcode = ISD::STRICT_FADD; 7214 Opers.clear(); 7215 Opers.push_back(Mul.getValue(1)); 7216 Opers.push_back(Mul.getValue(0)); 7217 Opers.push_back(getValue(FPI.getArgOperand(2))); 7218 } 7219 break; 7220 } 7221 } 7222 7223 // A few strict DAG nodes carry additional operands that are not 7224 // set up by the default code above. 7225 switch (Opcode) { 7226 default: break; 7227 case ISD::STRICT_FP_ROUND: 7228 Opers.push_back( 7229 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7230 break; 7231 case ISD::STRICT_FSETCC: 7232 case ISD::STRICT_FSETCCS: { 7233 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7234 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7235 if (TM.Options.NoNaNsFPMath) 7236 Condition = getFCmpCodeWithoutNaN(Condition); 7237 Opers.push_back(DAG.getCondCode(Condition)); 7238 break; 7239 } 7240 } 7241 7242 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7243 pushOutChain(Result, EB); 7244 7245 SDValue FPResult = Result.getValue(0); 7246 setValue(&FPI, FPResult); 7247 } 7248 7249 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7250 Optional<unsigned> ResOPC; 7251 switch (VPIntrin.getIntrinsicID()) { 7252 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN: 7253 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID; 7254 #define END_REGISTER_VP_INTRINSIC(...) break; 7255 #include "llvm/IR/VPIntrinsics.def" 7256 } 7257 7258 if (!ResOPC.hasValue()) 7259 llvm_unreachable( 7260 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7261 7262 return ResOPC.getValue(); 7263 } 7264 7265 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7266 const VPIntrinsic &VPIntrin) { 7267 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7268 7269 SmallVector<EVT, 4> ValueVTs; 7270 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7271 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7272 SDVTList VTs = DAG.getVTList(ValueVTs); 7273 7274 // Request operands. 7275 SmallVector<SDValue, 7> OpValues; 7276 for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i) 7277 OpValues.push_back(getValue(VPIntrin.getArgOperand(i))); 7278 7279 SDLoc DL = getCurSDLoc(); 7280 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7281 setValue(&VPIntrin, Result); 7282 } 7283 7284 std::pair<SDValue, SDValue> 7285 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7286 const BasicBlock *EHPadBB) { 7287 MachineFunction &MF = DAG.getMachineFunction(); 7288 MachineModuleInfo &MMI = MF.getMMI(); 7289 MCSymbol *BeginLabel = nullptr; 7290 7291 if (EHPadBB) { 7292 // Insert a label before the invoke call to mark the try range. This can be 7293 // used to detect deletion of the invoke via the MachineModuleInfo. 7294 BeginLabel = MMI.getContext().createTempSymbol(); 7295 7296 // For SjLj, keep track of which landing pads go with which invokes 7297 // so as to maintain the ordering of pads in the LSDA. 7298 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7299 if (CallSiteIndex) { 7300 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7301 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7302 7303 // Now that the call site is handled, stop tracking it. 7304 MMI.setCurrentCallSite(0); 7305 } 7306 7307 // Both PendingLoads and PendingExports must be flushed here; 7308 // this call might not return. 7309 (void)getRoot(); 7310 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7311 7312 CLI.setChain(getRoot()); 7313 } 7314 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7315 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7316 7317 assert((CLI.IsTailCall || Result.second.getNode()) && 7318 "Non-null chain expected with non-tail call!"); 7319 assert((Result.second.getNode() || !Result.first.getNode()) && 7320 "Null value expected with tail call!"); 7321 7322 if (!Result.second.getNode()) { 7323 // As a special case, a null chain means that a tail call has been emitted 7324 // and the DAG root is already updated. 7325 HasTailCall = true; 7326 7327 // Since there's no actual continuation from this block, nothing can be 7328 // relying on us setting vregs for them. 7329 PendingExports.clear(); 7330 } else { 7331 DAG.setRoot(Result.second); 7332 } 7333 7334 if (EHPadBB) { 7335 // Insert a label at the end of the invoke call to mark the try range. This 7336 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7337 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7338 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7339 7340 // Inform MachineModuleInfo of range. 7341 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7342 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7343 // actually use outlined funclets and their LSDA info style. 7344 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7345 assert(CLI.CB); 7346 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7347 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel); 7348 } else if (!isScopedEHPersonality(Pers)) { 7349 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7350 } 7351 } 7352 7353 return Result; 7354 } 7355 7356 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7357 bool isTailCall, 7358 const BasicBlock *EHPadBB) { 7359 auto &DL = DAG.getDataLayout(); 7360 FunctionType *FTy = CB.getFunctionType(); 7361 Type *RetTy = CB.getType(); 7362 7363 TargetLowering::ArgListTy Args; 7364 Args.reserve(CB.arg_size()); 7365 7366 const Value *SwiftErrorVal = nullptr; 7367 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7368 7369 if (isTailCall) { 7370 // Avoid emitting tail calls in functions with the disable-tail-calls 7371 // attribute. 7372 auto *Caller = CB.getParent()->getParent(); 7373 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7374 "true") 7375 isTailCall = false; 7376 7377 // We can't tail call inside a function with a swifterror argument. Lowering 7378 // does not support this yet. It would have to move into the swifterror 7379 // register before the call. 7380 if (TLI.supportSwiftError() && 7381 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7382 isTailCall = false; 7383 } 7384 7385 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7386 TargetLowering::ArgListEntry Entry; 7387 const Value *V = *I; 7388 7389 // Skip empty types 7390 if (V->getType()->isEmptyTy()) 7391 continue; 7392 7393 SDValue ArgNode = getValue(V); 7394 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7395 7396 Entry.setAttributes(&CB, I - CB.arg_begin()); 7397 7398 // Use swifterror virtual register as input to the call. 7399 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7400 SwiftErrorVal = V; 7401 // We find the virtual register for the actual swifterror argument. 7402 // Instead of using the Value, we use the virtual register instead. 7403 Entry.Node = 7404 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7405 EVT(TLI.getPointerTy(DL))); 7406 } 7407 7408 Args.push_back(Entry); 7409 7410 // If we have an explicit sret argument that is an Instruction, (i.e., it 7411 // might point to function-local memory), we can't meaningfully tail-call. 7412 if (Entry.IsSRet && isa<Instruction>(V)) 7413 isTailCall = false; 7414 } 7415 7416 // If call site has a cfguardtarget operand bundle, create and add an 7417 // additional ArgListEntry. 7418 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7419 TargetLowering::ArgListEntry Entry; 7420 Value *V = Bundle->Inputs[0]; 7421 SDValue ArgNode = getValue(V); 7422 Entry.Node = ArgNode; 7423 Entry.Ty = V->getType(); 7424 Entry.IsCFGuardTarget = true; 7425 Args.push_back(Entry); 7426 } 7427 7428 // Check if target-independent constraints permit a tail call here. 7429 // Target-dependent constraints are checked within TLI->LowerCallTo. 7430 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7431 isTailCall = false; 7432 7433 // Disable tail calls if there is an swifterror argument. Targets have not 7434 // been updated to support tail calls. 7435 if (TLI.supportSwiftError() && SwiftErrorVal) 7436 isTailCall = false; 7437 7438 TargetLowering::CallLoweringInfo CLI(DAG); 7439 CLI.setDebugLoc(getCurSDLoc()) 7440 .setChain(getRoot()) 7441 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7442 .setTailCall(isTailCall) 7443 .setConvergent(CB.isConvergent()) 7444 .setIsPreallocated( 7445 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7446 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7447 7448 if (Result.first.getNode()) { 7449 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7450 setValue(&CB, Result.first); 7451 } 7452 7453 // The last element of CLI.InVals has the SDValue for swifterror return. 7454 // Here we copy it to a virtual register and update SwiftErrorMap for 7455 // book-keeping. 7456 if (SwiftErrorVal && TLI.supportSwiftError()) { 7457 // Get the last element of InVals. 7458 SDValue Src = CLI.InVals.back(); 7459 Register VReg = 7460 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7461 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7462 DAG.setRoot(CopyNode); 7463 } 7464 } 7465 7466 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7467 SelectionDAGBuilder &Builder) { 7468 // Check to see if this load can be trivially constant folded, e.g. if the 7469 // input is from a string literal. 7470 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7471 // Cast pointer to the type we really want to load. 7472 Type *LoadTy = 7473 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7474 if (LoadVT.isVector()) 7475 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7476 7477 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7478 PointerType::getUnqual(LoadTy)); 7479 7480 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7481 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7482 return Builder.getValue(LoadCst); 7483 } 7484 7485 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7486 // still constant memory, the input chain can be the entry node. 7487 SDValue Root; 7488 bool ConstantMemory = false; 7489 7490 // Do not serialize (non-volatile) loads of constant memory with anything. 7491 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7492 Root = Builder.DAG.getEntryNode(); 7493 ConstantMemory = true; 7494 } else { 7495 // Do not serialize non-volatile loads against each other. 7496 Root = Builder.DAG.getRoot(); 7497 } 7498 7499 SDValue Ptr = Builder.getValue(PtrVal); 7500 SDValue LoadVal = 7501 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7502 MachinePointerInfo(PtrVal), Align(1)); 7503 7504 if (!ConstantMemory) 7505 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7506 return LoadVal; 7507 } 7508 7509 /// Record the value for an instruction that produces an integer result, 7510 /// converting the type where necessary. 7511 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7512 SDValue Value, 7513 bool IsSigned) { 7514 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7515 I.getType(), true); 7516 if (IsSigned) 7517 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7518 else 7519 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7520 setValue(&I, Value); 7521 } 7522 7523 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7524 /// true and lower it. Otherwise return false, and it will be lowered like a 7525 /// normal call. 7526 /// The caller already checked that \p I calls the appropriate LibFunc with a 7527 /// correct prototype. 7528 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7529 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7530 const Value *Size = I.getArgOperand(2); 7531 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7532 if (CSize && CSize->getZExtValue() == 0) { 7533 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7534 I.getType(), true); 7535 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7536 return true; 7537 } 7538 7539 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7540 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7541 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7542 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7543 if (Res.first.getNode()) { 7544 processIntegerCallValue(I, Res.first, true); 7545 PendingLoads.push_back(Res.second); 7546 return true; 7547 } 7548 7549 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7550 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7551 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7552 return false; 7553 7554 // If the target has a fast compare for the given size, it will return a 7555 // preferred load type for that size. Require that the load VT is legal and 7556 // that the target supports unaligned loads of that type. Otherwise, return 7557 // INVALID. 7558 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7559 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7560 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7561 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7562 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7563 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7564 // TODO: Check alignment of src and dest ptrs. 7565 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7566 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7567 if (!TLI.isTypeLegal(LVT) || 7568 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7569 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7570 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7571 } 7572 7573 return LVT; 7574 }; 7575 7576 // This turns into unaligned loads. We only do this if the target natively 7577 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7578 // we'll only produce a small number of byte loads. 7579 MVT LoadVT; 7580 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7581 switch (NumBitsToCompare) { 7582 default: 7583 return false; 7584 case 16: 7585 LoadVT = MVT::i16; 7586 break; 7587 case 32: 7588 LoadVT = MVT::i32; 7589 break; 7590 case 64: 7591 case 128: 7592 case 256: 7593 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7594 break; 7595 } 7596 7597 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7598 return false; 7599 7600 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7601 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7602 7603 // Bitcast to a wide integer type if the loads are vectors. 7604 if (LoadVT.isVector()) { 7605 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7606 LoadL = DAG.getBitcast(CmpVT, LoadL); 7607 LoadR = DAG.getBitcast(CmpVT, LoadR); 7608 } 7609 7610 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7611 processIntegerCallValue(I, Cmp, false); 7612 return true; 7613 } 7614 7615 /// See if we can lower a memchr call into an optimized form. If so, return 7616 /// true and lower it. Otherwise return false, and it will be lowered like a 7617 /// normal call. 7618 /// The caller already checked that \p I calls the appropriate LibFunc with a 7619 /// correct prototype. 7620 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7621 const Value *Src = I.getArgOperand(0); 7622 const Value *Char = I.getArgOperand(1); 7623 const Value *Length = I.getArgOperand(2); 7624 7625 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7626 std::pair<SDValue, SDValue> Res = 7627 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7628 getValue(Src), getValue(Char), getValue(Length), 7629 MachinePointerInfo(Src)); 7630 if (Res.first.getNode()) { 7631 setValue(&I, Res.first); 7632 PendingLoads.push_back(Res.second); 7633 return true; 7634 } 7635 7636 return false; 7637 } 7638 7639 /// See if we can lower a mempcpy call into an optimized form. If so, return 7640 /// true and lower it. Otherwise return false, and it will be lowered like a 7641 /// normal call. 7642 /// The caller already checked that \p I calls the appropriate LibFunc with a 7643 /// correct prototype. 7644 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7645 SDValue Dst = getValue(I.getArgOperand(0)); 7646 SDValue Src = getValue(I.getArgOperand(1)); 7647 SDValue Size = getValue(I.getArgOperand(2)); 7648 7649 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7650 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7651 // DAG::getMemcpy needs Alignment to be defined. 7652 Align Alignment = std::min(DstAlign, SrcAlign); 7653 7654 bool isVol = false; 7655 SDLoc sdl = getCurSDLoc(); 7656 7657 // In the mempcpy context we need to pass in a false value for isTailCall 7658 // because the return pointer needs to be adjusted by the size of 7659 // the copied memory. 7660 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7661 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7662 /*isTailCall=*/false, 7663 MachinePointerInfo(I.getArgOperand(0)), 7664 MachinePointerInfo(I.getArgOperand(1))); 7665 assert(MC.getNode() != nullptr && 7666 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7667 DAG.setRoot(MC); 7668 7669 // Check if Size needs to be truncated or extended. 7670 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7671 7672 // Adjust return pointer to point just past the last dst byte. 7673 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7674 Dst, Size); 7675 setValue(&I, DstPlusSize); 7676 return true; 7677 } 7678 7679 /// See if we can lower a strcpy call into an optimized form. If so, return 7680 /// true and lower it, otherwise return false and it will be lowered like a 7681 /// normal call. 7682 /// The caller already checked that \p I calls the appropriate LibFunc with a 7683 /// correct prototype. 7684 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7685 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7686 7687 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7688 std::pair<SDValue, SDValue> Res = 7689 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7690 getValue(Arg0), getValue(Arg1), 7691 MachinePointerInfo(Arg0), 7692 MachinePointerInfo(Arg1), isStpcpy); 7693 if (Res.first.getNode()) { 7694 setValue(&I, Res.first); 7695 DAG.setRoot(Res.second); 7696 return true; 7697 } 7698 7699 return false; 7700 } 7701 7702 /// See if we can lower a strcmp call into an optimized form. If so, return 7703 /// true and lower it, otherwise return false and it will be lowered like a 7704 /// normal call. 7705 /// The caller already checked that \p I calls the appropriate LibFunc with a 7706 /// correct prototype. 7707 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7708 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7709 7710 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7711 std::pair<SDValue, SDValue> Res = 7712 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7713 getValue(Arg0), getValue(Arg1), 7714 MachinePointerInfo(Arg0), 7715 MachinePointerInfo(Arg1)); 7716 if (Res.first.getNode()) { 7717 processIntegerCallValue(I, Res.first, true); 7718 PendingLoads.push_back(Res.second); 7719 return true; 7720 } 7721 7722 return false; 7723 } 7724 7725 /// See if we can lower a strlen call into an optimized form. If so, return 7726 /// true and lower it, otherwise return false and it will be lowered like a 7727 /// normal call. 7728 /// The caller already checked that \p I calls the appropriate LibFunc with a 7729 /// correct prototype. 7730 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7731 const Value *Arg0 = I.getArgOperand(0); 7732 7733 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7734 std::pair<SDValue, SDValue> Res = 7735 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7736 getValue(Arg0), MachinePointerInfo(Arg0)); 7737 if (Res.first.getNode()) { 7738 processIntegerCallValue(I, Res.first, false); 7739 PendingLoads.push_back(Res.second); 7740 return true; 7741 } 7742 7743 return false; 7744 } 7745 7746 /// See if we can lower a strnlen 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::visitStrNLenCall(const CallInst &I) { 7752 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7753 7754 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7755 std::pair<SDValue, SDValue> Res = 7756 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7757 getValue(Arg0), getValue(Arg1), 7758 MachinePointerInfo(Arg0)); 7759 if (Res.first.getNode()) { 7760 processIntegerCallValue(I, Res.first, false); 7761 PendingLoads.push_back(Res.second); 7762 return true; 7763 } 7764 7765 return false; 7766 } 7767 7768 /// See if we can lower a unary floating-point operation into an SDNode with 7769 /// the specified Opcode. If so, return true and lower it, otherwise return 7770 /// false and it will be lowered like a normal call. 7771 /// The caller already checked that \p I calls the appropriate LibFunc with a 7772 /// correct prototype. 7773 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7774 unsigned Opcode) { 7775 // We already checked this call's prototype; verify it doesn't modify errno. 7776 if (!I.onlyReadsMemory()) 7777 return false; 7778 7779 SDNodeFlags Flags; 7780 Flags.copyFMF(cast<FPMathOperator>(I)); 7781 7782 SDValue Tmp = getValue(I.getArgOperand(0)); 7783 setValue(&I, 7784 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7785 return true; 7786 } 7787 7788 /// See if we can lower a binary floating-point operation into an SDNode with 7789 /// the specified Opcode. If so, return true and lower it. Otherwise return 7790 /// false, and it will be lowered like a normal call. 7791 /// The caller already checked that \p I calls the appropriate LibFunc with a 7792 /// correct prototype. 7793 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7794 unsigned Opcode) { 7795 // We already checked this call's prototype; verify it doesn't modify errno. 7796 if (!I.onlyReadsMemory()) 7797 return false; 7798 7799 SDNodeFlags Flags; 7800 Flags.copyFMF(cast<FPMathOperator>(I)); 7801 7802 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7803 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7804 EVT VT = Tmp0.getValueType(); 7805 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7806 return true; 7807 } 7808 7809 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7810 // Handle inline assembly differently. 7811 if (I.isInlineAsm()) { 7812 visitInlineAsm(I); 7813 return; 7814 } 7815 7816 if (Function *F = I.getCalledFunction()) { 7817 if (F->isDeclaration()) { 7818 // Is this an LLVM intrinsic or a target-specific intrinsic? 7819 unsigned IID = F->getIntrinsicID(); 7820 if (!IID) 7821 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7822 IID = II->getIntrinsicID(F); 7823 7824 if (IID) { 7825 visitIntrinsicCall(I, IID); 7826 return; 7827 } 7828 } 7829 7830 // Check for well-known libc/libm calls. If the function is internal, it 7831 // can't be a library call. Don't do the check if marked as nobuiltin for 7832 // some reason or the call site requires strict floating point semantics. 7833 LibFunc Func; 7834 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7835 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7836 LibInfo->hasOptimizedCodeGen(Func)) { 7837 switch (Func) { 7838 default: break; 7839 case LibFunc_bcmp: 7840 if (visitMemCmpBCmpCall(I)) 7841 return; 7842 break; 7843 case LibFunc_copysign: 7844 case LibFunc_copysignf: 7845 case LibFunc_copysignl: 7846 // We already checked this call's prototype; verify it doesn't modify 7847 // errno. 7848 if (I.onlyReadsMemory()) { 7849 SDValue LHS = getValue(I.getArgOperand(0)); 7850 SDValue RHS = getValue(I.getArgOperand(1)); 7851 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7852 LHS.getValueType(), LHS, RHS)); 7853 return; 7854 } 7855 break; 7856 case LibFunc_fabs: 7857 case LibFunc_fabsf: 7858 case LibFunc_fabsl: 7859 if (visitUnaryFloatCall(I, ISD::FABS)) 7860 return; 7861 break; 7862 case LibFunc_fmin: 7863 case LibFunc_fminf: 7864 case LibFunc_fminl: 7865 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7866 return; 7867 break; 7868 case LibFunc_fmax: 7869 case LibFunc_fmaxf: 7870 case LibFunc_fmaxl: 7871 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7872 return; 7873 break; 7874 case LibFunc_sin: 7875 case LibFunc_sinf: 7876 case LibFunc_sinl: 7877 if (visitUnaryFloatCall(I, ISD::FSIN)) 7878 return; 7879 break; 7880 case LibFunc_cos: 7881 case LibFunc_cosf: 7882 case LibFunc_cosl: 7883 if (visitUnaryFloatCall(I, ISD::FCOS)) 7884 return; 7885 break; 7886 case LibFunc_sqrt: 7887 case LibFunc_sqrtf: 7888 case LibFunc_sqrtl: 7889 case LibFunc_sqrt_finite: 7890 case LibFunc_sqrtf_finite: 7891 case LibFunc_sqrtl_finite: 7892 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7893 return; 7894 break; 7895 case LibFunc_floor: 7896 case LibFunc_floorf: 7897 case LibFunc_floorl: 7898 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7899 return; 7900 break; 7901 case LibFunc_nearbyint: 7902 case LibFunc_nearbyintf: 7903 case LibFunc_nearbyintl: 7904 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7905 return; 7906 break; 7907 case LibFunc_ceil: 7908 case LibFunc_ceilf: 7909 case LibFunc_ceill: 7910 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7911 return; 7912 break; 7913 case LibFunc_rint: 7914 case LibFunc_rintf: 7915 case LibFunc_rintl: 7916 if (visitUnaryFloatCall(I, ISD::FRINT)) 7917 return; 7918 break; 7919 case LibFunc_round: 7920 case LibFunc_roundf: 7921 case LibFunc_roundl: 7922 if (visitUnaryFloatCall(I, ISD::FROUND)) 7923 return; 7924 break; 7925 case LibFunc_trunc: 7926 case LibFunc_truncf: 7927 case LibFunc_truncl: 7928 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7929 return; 7930 break; 7931 case LibFunc_log2: 7932 case LibFunc_log2f: 7933 case LibFunc_log2l: 7934 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7935 return; 7936 break; 7937 case LibFunc_exp2: 7938 case LibFunc_exp2f: 7939 case LibFunc_exp2l: 7940 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7941 return; 7942 break; 7943 case LibFunc_memcmp: 7944 if (visitMemCmpBCmpCall(I)) 7945 return; 7946 break; 7947 case LibFunc_mempcpy: 7948 if (visitMemPCpyCall(I)) 7949 return; 7950 break; 7951 case LibFunc_memchr: 7952 if (visitMemChrCall(I)) 7953 return; 7954 break; 7955 case LibFunc_strcpy: 7956 if (visitStrCpyCall(I, false)) 7957 return; 7958 break; 7959 case LibFunc_stpcpy: 7960 if (visitStrCpyCall(I, true)) 7961 return; 7962 break; 7963 case LibFunc_strcmp: 7964 if (visitStrCmpCall(I)) 7965 return; 7966 break; 7967 case LibFunc_strlen: 7968 if (visitStrLenCall(I)) 7969 return; 7970 break; 7971 case LibFunc_strnlen: 7972 if (visitStrNLenCall(I)) 7973 return; 7974 break; 7975 } 7976 } 7977 } 7978 7979 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7980 // have to do anything here to lower funclet bundles. 7981 // CFGuardTarget bundles are lowered in LowerCallTo. 7982 assert(!I.hasOperandBundlesOtherThan( 7983 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 7984 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 7985 LLVMContext::OB_clang_arc_attachedcall}) && 7986 "Cannot lower calls with arbitrary operand bundles!"); 7987 7988 SDValue Callee = getValue(I.getCalledOperand()); 7989 7990 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7991 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7992 else 7993 // Check if we can potentially perform a tail call. More detailed checking 7994 // is be done within LowerCallTo, after more information about the call is 7995 // known. 7996 LowerCallTo(I, Callee, I.isTailCall()); 7997 } 7998 7999 namespace { 8000 8001 /// AsmOperandInfo - This contains information for each constraint that we are 8002 /// lowering. 8003 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8004 public: 8005 /// CallOperand - If this is the result output operand or a clobber 8006 /// this is null, otherwise it is the incoming operand to the CallInst. 8007 /// This gets modified as the asm is processed. 8008 SDValue CallOperand; 8009 8010 /// AssignedRegs - If this is a register or register class operand, this 8011 /// contains the set of register corresponding to the operand. 8012 RegsForValue AssignedRegs; 8013 8014 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8015 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8016 } 8017 8018 /// Whether or not this operand accesses memory 8019 bool hasMemory(const TargetLowering &TLI) const { 8020 // Indirect operand accesses access memory. 8021 if (isIndirect) 8022 return true; 8023 8024 for (const auto &Code : Codes) 8025 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8026 return true; 8027 8028 return false; 8029 } 8030 8031 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8032 /// corresponds to. If there is no Value* for this operand, it returns 8033 /// MVT::Other. 8034 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8035 const DataLayout &DL) const { 8036 if (!CallOperandVal) return MVT::Other; 8037 8038 if (isa<BasicBlock>(CallOperandVal)) 8039 return TLI.getProgramPointerTy(DL); 8040 8041 llvm::Type *OpTy = CallOperandVal->getType(); 8042 8043 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8044 // If this is an indirect operand, the operand is a pointer to the 8045 // accessed type. 8046 if (isIndirect) { 8047 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 8048 if (!PtrTy) 8049 report_fatal_error("Indirect operand for inline asm not a pointer!"); 8050 OpTy = PtrTy->getElementType(); 8051 } 8052 8053 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8054 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8055 if (STy->getNumElements() == 1) 8056 OpTy = STy->getElementType(0); 8057 8058 // If OpTy is not a single value, it may be a struct/union that we 8059 // can tile with integers. 8060 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8061 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8062 switch (BitSize) { 8063 default: break; 8064 case 1: 8065 case 8: 8066 case 16: 8067 case 32: 8068 case 64: 8069 case 128: 8070 OpTy = IntegerType::get(Context, BitSize); 8071 break; 8072 } 8073 } 8074 8075 return TLI.getValueType(DL, OpTy, true); 8076 } 8077 }; 8078 8079 8080 } // end anonymous namespace 8081 8082 /// Make sure that the output operand \p OpInfo and its corresponding input 8083 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8084 /// out). 8085 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8086 SDISelAsmOperandInfo &MatchingOpInfo, 8087 SelectionDAG &DAG) { 8088 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8089 return; 8090 8091 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8092 const auto &TLI = DAG.getTargetLoweringInfo(); 8093 8094 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8095 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8096 OpInfo.ConstraintVT); 8097 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8098 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8099 MatchingOpInfo.ConstraintVT); 8100 if ((OpInfo.ConstraintVT.isInteger() != 8101 MatchingOpInfo.ConstraintVT.isInteger()) || 8102 (MatchRC.second != InputRC.second)) { 8103 // FIXME: error out in a more elegant fashion 8104 report_fatal_error("Unsupported asm: input constraint" 8105 " with a matching output constraint of" 8106 " incompatible type!"); 8107 } 8108 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8109 } 8110 8111 /// Get a direct memory input to behave well as an indirect operand. 8112 /// This may introduce stores, hence the need for a \p Chain. 8113 /// \return The (possibly updated) chain. 8114 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8115 SDISelAsmOperandInfo &OpInfo, 8116 SelectionDAG &DAG) { 8117 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8118 8119 // If we don't have an indirect input, put it in the constpool if we can, 8120 // otherwise spill it to a stack slot. 8121 // TODO: This isn't quite right. We need to handle these according to 8122 // the addressing mode that the constraint wants. Also, this may take 8123 // an additional register for the computation and we don't want that 8124 // either. 8125 8126 // If the operand is a float, integer, or vector constant, spill to a 8127 // constant pool entry to get its address. 8128 const Value *OpVal = OpInfo.CallOperandVal; 8129 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8130 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8131 OpInfo.CallOperand = DAG.getConstantPool( 8132 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8133 return Chain; 8134 } 8135 8136 // Otherwise, create a stack slot and emit a store to it before the asm. 8137 Type *Ty = OpVal->getType(); 8138 auto &DL = DAG.getDataLayout(); 8139 uint64_t TySize = DL.getTypeAllocSize(Ty); 8140 MachineFunction &MF = DAG.getMachineFunction(); 8141 int SSFI = MF.getFrameInfo().CreateStackObject( 8142 TySize, DL.getPrefTypeAlign(Ty), false); 8143 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8144 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8145 MachinePointerInfo::getFixedStack(MF, SSFI), 8146 TLI.getMemValueType(DL, Ty)); 8147 OpInfo.CallOperand = StackSlot; 8148 8149 return Chain; 8150 } 8151 8152 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8153 /// specified operand. We prefer to assign virtual registers, to allow the 8154 /// register allocator to handle the assignment process. However, if the asm 8155 /// uses features that we can't model on machineinstrs, we have SDISel do the 8156 /// allocation. This produces generally horrible, but correct, code. 8157 /// 8158 /// OpInfo describes the operand 8159 /// RefOpInfo describes the matching operand if any, the operand otherwise 8160 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8161 SDISelAsmOperandInfo &OpInfo, 8162 SDISelAsmOperandInfo &RefOpInfo) { 8163 LLVMContext &Context = *DAG.getContext(); 8164 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8165 8166 MachineFunction &MF = DAG.getMachineFunction(); 8167 SmallVector<unsigned, 4> Regs; 8168 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8169 8170 // No work to do for memory operations. 8171 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8172 return; 8173 8174 // If this is a constraint for a single physreg, or a constraint for a 8175 // register class, find it. 8176 unsigned AssignedReg; 8177 const TargetRegisterClass *RC; 8178 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8179 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8180 // RC is unset only on failure. Return immediately. 8181 if (!RC) 8182 return; 8183 8184 // Get the actual register value type. This is important, because the user 8185 // may have asked for (e.g.) the AX register in i32 type. We need to 8186 // remember that AX is actually i16 to get the right extension. 8187 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8188 8189 if (OpInfo.ConstraintVT != MVT::Other) { 8190 // If this is an FP operand in an integer register (or visa versa), or more 8191 // generally if the operand value disagrees with the register class we plan 8192 // to stick it in, fix the operand type. 8193 // 8194 // If this is an input value, the bitcast to the new type is done now. 8195 // Bitcast for output value is done at the end of visitInlineAsm(). 8196 if ((OpInfo.Type == InlineAsm::isOutput || 8197 OpInfo.Type == InlineAsm::isInput) && 8198 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8199 // Try to convert to the first EVT that the reg class contains. If the 8200 // types are identical size, use a bitcast to convert (e.g. two differing 8201 // vector types). Note: output bitcast is done at the end of 8202 // visitInlineAsm(). 8203 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8204 // Exclude indirect inputs while they are unsupported because the code 8205 // to perform the load is missing and thus OpInfo.CallOperand still 8206 // refers to the input address rather than the pointed-to value. 8207 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8208 OpInfo.CallOperand = 8209 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8210 OpInfo.ConstraintVT = RegVT; 8211 // If the operand is an FP value and we want it in integer registers, 8212 // use the corresponding integer type. This turns an f64 value into 8213 // i64, which can be passed with two i32 values on a 32-bit machine. 8214 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8215 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8216 if (OpInfo.Type == InlineAsm::isInput) 8217 OpInfo.CallOperand = 8218 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8219 OpInfo.ConstraintVT = VT; 8220 } 8221 } 8222 } 8223 8224 // No need to allocate a matching input constraint since the constraint it's 8225 // matching to has already been allocated. 8226 if (OpInfo.isMatchingInputConstraint()) 8227 return; 8228 8229 EVT ValueVT = OpInfo.ConstraintVT; 8230 if (OpInfo.ConstraintVT == MVT::Other) 8231 ValueVT = RegVT; 8232 8233 // Initialize NumRegs. 8234 unsigned NumRegs = 1; 8235 if (OpInfo.ConstraintVT != MVT::Other) 8236 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8237 8238 // If this is a constraint for a specific physical register, like {r17}, 8239 // assign it now. 8240 8241 // If this associated to a specific register, initialize iterator to correct 8242 // place. If virtual, make sure we have enough registers 8243 8244 // Initialize iterator if necessary 8245 TargetRegisterClass::iterator I = RC->begin(); 8246 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8247 8248 // Do not check for single registers. 8249 if (AssignedReg) { 8250 for (; *I != AssignedReg; ++I) 8251 assert(I != RC->end() && "AssignedReg should be member of RC"); 8252 } 8253 8254 for (; NumRegs; --NumRegs, ++I) { 8255 assert(I != RC->end() && "Ran out of registers to allocate!"); 8256 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8257 Regs.push_back(R); 8258 } 8259 8260 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8261 } 8262 8263 static unsigned 8264 findMatchingInlineAsmOperand(unsigned OperandNo, 8265 const std::vector<SDValue> &AsmNodeOperands) { 8266 // Scan until we find the definition we already emitted of this operand. 8267 unsigned CurOp = InlineAsm::Op_FirstOperand; 8268 for (; OperandNo; --OperandNo) { 8269 // Advance to the next operand. 8270 unsigned OpFlag = 8271 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8272 assert((InlineAsm::isRegDefKind(OpFlag) || 8273 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8274 InlineAsm::isMemKind(OpFlag)) && 8275 "Skipped past definitions?"); 8276 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8277 } 8278 return CurOp; 8279 } 8280 8281 namespace { 8282 8283 class ExtraFlags { 8284 unsigned Flags = 0; 8285 8286 public: 8287 explicit ExtraFlags(const CallBase &Call) { 8288 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8289 if (IA->hasSideEffects()) 8290 Flags |= InlineAsm::Extra_HasSideEffects; 8291 if (IA->isAlignStack()) 8292 Flags |= InlineAsm::Extra_IsAlignStack; 8293 if (Call.isConvergent()) 8294 Flags |= InlineAsm::Extra_IsConvergent; 8295 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8296 } 8297 8298 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8299 // Ideally, we would only check against memory constraints. However, the 8300 // meaning of an Other constraint can be target-specific and we can't easily 8301 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8302 // for Other constraints as well. 8303 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8304 OpInfo.ConstraintType == TargetLowering::C_Other) { 8305 if (OpInfo.Type == InlineAsm::isInput) 8306 Flags |= InlineAsm::Extra_MayLoad; 8307 else if (OpInfo.Type == InlineAsm::isOutput) 8308 Flags |= InlineAsm::Extra_MayStore; 8309 else if (OpInfo.Type == InlineAsm::isClobber) 8310 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8311 } 8312 } 8313 8314 unsigned get() const { return Flags; } 8315 }; 8316 8317 } // end anonymous namespace 8318 8319 /// visitInlineAsm - Handle a call to an InlineAsm object. 8320 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 8321 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8322 8323 /// ConstraintOperands - Information about all of the constraints. 8324 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8325 8326 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8327 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8328 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8329 8330 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8331 // AsmDialect, MayLoad, MayStore). 8332 bool HasSideEffect = IA->hasSideEffects(); 8333 ExtraFlags ExtraInfo(Call); 8334 8335 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8336 unsigned ResNo = 0; // ResNo - The result number of the next output. 8337 unsigned NumMatchingOps = 0; 8338 for (auto &T : TargetConstraints) { 8339 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8340 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8341 8342 // Compute the value type for each operand. 8343 if (OpInfo.Type == InlineAsm::isInput || 8344 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8345 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8346 8347 // Process the call argument. BasicBlocks are labels, currently appearing 8348 // only in asm's. 8349 if (isa<CallBrInst>(Call) && 8350 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8351 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8352 NumMatchingOps) && 8353 (NumMatchingOps == 0 || 8354 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8355 NumMatchingOps))) { 8356 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8357 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8358 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8359 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8360 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8361 } else { 8362 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8363 } 8364 8365 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8366 DAG.getDataLayout()); 8367 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8368 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8369 // The return value of the call is this value. As such, there is no 8370 // corresponding argument. 8371 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8372 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8373 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8374 DAG.getDataLayout(), STy->getElementType(ResNo)); 8375 } else { 8376 assert(ResNo == 0 && "Asm only has one result!"); 8377 OpInfo.ConstraintVT = 8378 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8379 } 8380 ++ResNo; 8381 } else { 8382 OpInfo.ConstraintVT = MVT::Other; 8383 } 8384 8385 if (OpInfo.hasMatchingInput()) 8386 ++NumMatchingOps; 8387 8388 if (!HasSideEffect) 8389 HasSideEffect = OpInfo.hasMemory(TLI); 8390 8391 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8392 // FIXME: Could we compute this on OpInfo rather than T? 8393 8394 // Compute the constraint code and ConstraintType to use. 8395 TLI.ComputeConstraintToUse(T, SDValue()); 8396 8397 if (T.ConstraintType == TargetLowering::C_Immediate && 8398 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8399 // We've delayed emitting a diagnostic like the "n" constraint because 8400 // inlining could cause an integer showing up. 8401 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8402 "' expects an integer constant " 8403 "expression"); 8404 8405 ExtraInfo.update(T); 8406 } 8407 8408 8409 // We won't need to flush pending loads if this asm doesn't touch 8410 // memory and is nonvolatile. 8411 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8412 8413 bool IsCallBr = isa<CallBrInst>(Call); 8414 if (IsCallBr) { 8415 // If this is a callbr we need to flush pending exports since inlineasm_br 8416 // is a terminator. We need to do this before nodes are glued to 8417 // the inlineasm_br node. 8418 Chain = getControlRoot(); 8419 } 8420 8421 // Second pass over the constraints: compute which constraint option to use. 8422 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8423 // If this is an output operand with a matching input operand, look up the 8424 // matching input. If their types mismatch, e.g. one is an integer, the 8425 // other is floating point, or their sizes are different, flag it as an 8426 // error. 8427 if (OpInfo.hasMatchingInput()) { 8428 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8429 patchMatchingInput(OpInfo, Input, DAG); 8430 } 8431 8432 // Compute the constraint code and ConstraintType to use. 8433 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8434 8435 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8436 OpInfo.Type == InlineAsm::isClobber) 8437 continue; 8438 8439 // If this is a memory input, and if the operand is not indirect, do what we 8440 // need to provide an address for the memory input. 8441 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8442 !OpInfo.isIndirect) { 8443 assert((OpInfo.isMultipleAlternative || 8444 (OpInfo.Type == InlineAsm::isInput)) && 8445 "Can only indirectify direct input operands!"); 8446 8447 // Memory operands really want the address of the value. 8448 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8449 8450 // There is no longer a Value* corresponding to this operand. 8451 OpInfo.CallOperandVal = nullptr; 8452 8453 // It is now an indirect operand. 8454 OpInfo.isIndirect = true; 8455 } 8456 8457 } 8458 8459 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8460 std::vector<SDValue> AsmNodeOperands; 8461 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8462 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8463 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8464 8465 // If we have a !srcloc metadata node associated with it, we want to attach 8466 // this to the ultimately generated inline asm machineinstr. To do this, we 8467 // pass in the third operand as this (potentially null) inline asm MDNode. 8468 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8469 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8470 8471 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8472 // bits as operand 3. 8473 AsmNodeOperands.push_back(DAG.getTargetConstant( 8474 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8475 8476 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8477 // this, assign virtual and physical registers for inputs and otput. 8478 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8479 // Assign Registers. 8480 SDISelAsmOperandInfo &RefOpInfo = 8481 OpInfo.isMatchingInputConstraint() 8482 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8483 : OpInfo; 8484 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8485 8486 auto DetectWriteToReservedRegister = [&]() { 8487 const MachineFunction &MF = DAG.getMachineFunction(); 8488 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8489 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8490 if (Register::isPhysicalRegister(Reg) && 8491 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8492 const char *RegName = TRI.getName(Reg); 8493 emitInlineAsmError(Call, "write to reserved register '" + 8494 Twine(RegName) + "'"); 8495 return true; 8496 } 8497 } 8498 return false; 8499 }; 8500 8501 switch (OpInfo.Type) { 8502 case InlineAsm::isOutput: 8503 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8504 unsigned ConstraintID = 8505 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8506 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8507 "Failed to convert memory constraint code to constraint id."); 8508 8509 // Add information to the INLINEASM node to know about this output. 8510 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8511 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8512 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8513 MVT::i32)); 8514 AsmNodeOperands.push_back(OpInfo.CallOperand); 8515 } else { 8516 // Otherwise, this outputs to a register (directly for C_Register / 8517 // C_RegisterClass, and a target-defined fashion for 8518 // C_Immediate/C_Other). Find a register that we can use. 8519 if (OpInfo.AssignedRegs.Regs.empty()) { 8520 emitInlineAsmError( 8521 Call, "couldn't allocate output register for constraint '" + 8522 Twine(OpInfo.ConstraintCode) + "'"); 8523 return; 8524 } 8525 8526 if (DetectWriteToReservedRegister()) 8527 return; 8528 8529 // Add information to the INLINEASM node to know that this register is 8530 // set. 8531 OpInfo.AssignedRegs.AddInlineAsmOperands( 8532 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8533 : InlineAsm::Kind_RegDef, 8534 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8535 } 8536 break; 8537 8538 case InlineAsm::isInput: { 8539 SDValue InOperandVal = OpInfo.CallOperand; 8540 8541 if (OpInfo.isMatchingInputConstraint()) { 8542 // If this is required to match an output register we have already set, 8543 // just use its register. 8544 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8545 AsmNodeOperands); 8546 unsigned OpFlag = 8547 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8548 if (InlineAsm::isRegDefKind(OpFlag) || 8549 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8550 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8551 if (OpInfo.isIndirect) { 8552 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8553 emitInlineAsmError(Call, "inline asm not supported yet: " 8554 "don't know how to handle tied " 8555 "indirect register inputs"); 8556 return; 8557 } 8558 8559 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8560 SmallVector<unsigned, 4> Regs; 8561 8562 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8563 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8564 MachineRegisterInfo &RegInfo = 8565 DAG.getMachineFunction().getRegInfo(); 8566 for (unsigned i = 0; i != NumRegs; ++i) 8567 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8568 } else { 8569 emitInlineAsmError(Call, 8570 "inline asm error: This value type register " 8571 "class is not natively supported!"); 8572 return; 8573 } 8574 8575 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8576 8577 SDLoc dl = getCurSDLoc(); 8578 // Use the produced MatchedRegs object to 8579 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8580 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8581 true, OpInfo.getMatchedOperand(), dl, 8582 DAG, AsmNodeOperands); 8583 break; 8584 } 8585 8586 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8587 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8588 "Unexpected number of operands"); 8589 // Add information to the INLINEASM node to know about this input. 8590 // See InlineAsm.h isUseOperandTiedToDef. 8591 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8592 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8593 OpInfo.getMatchedOperand()); 8594 AsmNodeOperands.push_back(DAG.getTargetConstant( 8595 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8596 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8597 break; 8598 } 8599 8600 // Treat indirect 'X' constraint as memory. 8601 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8602 OpInfo.isIndirect) 8603 OpInfo.ConstraintType = TargetLowering::C_Memory; 8604 8605 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8606 OpInfo.ConstraintType == TargetLowering::C_Other) { 8607 std::vector<SDValue> Ops; 8608 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8609 Ops, DAG); 8610 if (Ops.empty()) { 8611 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8612 if (isa<ConstantSDNode>(InOperandVal)) { 8613 emitInlineAsmError(Call, "value out of range for constraint '" + 8614 Twine(OpInfo.ConstraintCode) + "'"); 8615 return; 8616 } 8617 8618 emitInlineAsmError(Call, 8619 "invalid operand for inline asm constraint '" + 8620 Twine(OpInfo.ConstraintCode) + "'"); 8621 return; 8622 } 8623 8624 // Add information to the INLINEASM node to know about this input. 8625 unsigned ResOpType = 8626 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8627 AsmNodeOperands.push_back(DAG.getTargetConstant( 8628 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8629 llvm::append_range(AsmNodeOperands, Ops); 8630 break; 8631 } 8632 8633 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8634 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8635 assert(InOperandVal.getValueType() == 8636 TLI.getPointerTy(DAG.getDataLayout()) && 8637 "Memory operands expect pointer values"); 8638 8639 unsigned ConstraintID = 8640 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8641 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8642 "Failed to convert memory constraint code to constraint id."); 8643 8644 // Add information to the INLINEASM node to know about this input. 8645 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8646 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8647 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8648 getCurSDLoc(), 8649 MVT::i32)); 8650 AsmNodeOperands.push_back(InOperandVal); 8651 break; 8652 } 8653 8654 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8655 OpInfo.ConstraintType == TargetLowering::C_Register) && 8656 "Unknown constraint type!"); 8657 8658 // TODO: Support this. 8659 if (OpInfo.isIndirect) { 8660 emitInlineAsmError( 8661 Call, "Don't know how to handle indirect register inputs yet " 8662 "for constraint '" + 8663 Twine(OpInfo.ConstraintCode) + "'"); 8664 return; 8665 } 8666 8667 // Copy the input into the appropriate registers. 8668 if (OpInfo.AssignedRegs.Regs.empty()) { 8669 emitInlineAsmError(Call, 8670 "couldn't allocate input reg for constraint '" + 8671 Twine(OpInfo.ConstraintCode) + "'"); 8672 return; 8673 } 8674 8675 if (DetectWriteToReservedRegister()) 8676 return; 8677 8678 SDLoc dl = getCurSDLoc(); 8679 8680 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8681 &Call); 8682 8683 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8684 dl, DAG, AsmNodeOperands); 8685 break; 8686 } 8687 case InlineAsm::isClobber: 8688 // Add the clobbered value to the operand list, so that the register 8689 // allocator is aware that the physreg got clobbered. 8690 if (!OpInfo.AssignedRegs.Regs.empty()) 8691 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8692 false, 0, getCurSDLoc(), DAG, 8693 AsmNodeOperands); 8694 break; 8695 } 8696 } 8697 8698 // Finish up input operands. Set the input chain and add the flag last. 8699 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8700 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8701 8702 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8703 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8704 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8705 Flag = Chain.getValue(1); 8706 8707 // Do additional work to generate outputs. 8708 8709 SmallVector<EVT, 1> ResultVTs; 8710 SmallVector<SDValue, 1> ResultValues; 8711 SmallVector<SDValue, 8> OutChains; 8712 8713 llvm::Type *CallResultType = Call.getType(); 8714 ArrayRef<Type *> ResultTypes; 8715 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8716 ResultTypes = StructResult->elements(); 8717 else if (!CallResultType->isVoidTy()) 8718 ResultTypes = makeArrayRef(CallResultType); 8719 8720 auto CurResultType = ResultTypes.begin(); 8721 auto handleRegAssign = [&](SDValue V) { 8722 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8723 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8724 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8725 ++CurResultType; 8726 // If the type of the inline asm call site return value is different but has 8727 // same size as the type of the asm output bitcast it. One example of this 8728 // is for vectors with different width / number of elements. This can 8729 // happen for register classes that can contain multiple different value 8730 // types. The preg or vreg allocated may not have the same VT as was 8731 // expected. 8732 // 8733 // This can also happen for a return value that disagrees with the register 8734 // class it is put in, eg. a double in a general-purpose register on a 8735 // 32-bit machine. 8736 if (ResultVT != V.getValueType() && 8737 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8738 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8739 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8740 V.getValueType().isInteger()) { 8741 // If a result value was tied to an input value, the computed result 8742 // may have a wider width than the expected result. Extract the 8743 // relevant portion. 8744 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8745 } 8746 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8747 ResultVTs.push_back(ResultVT); 8748 ResultValues.push_back(V); 8749 }; 8750 8751 // Deal with output operands. 8752 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8753 if (OpInfo.Type == InlineAsm::isOutput) { 8754 SDValue Val; 8755 // Skip trivial output operands. 8756 if (OpInfo.AssignedRegs.Regs.empty()) 8757 continue; 8758 8759 switch (OpInfo.ConstraintType) { 8760 case TargetLowering::C_Register: 8761 case TargetLowering::C_RegisterClass: 8762 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8763 Chain, &Flag, &Call); 8764 break; 8765 case TargetLowering::C_Immediate: 8766 case TargetLowering::C_Other: 8767 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8768 OpInfo, DAG); 8769 break; 8770 case TargetLowering::C_Memory: 8771 break; // Already handled. 8772 case TargetLowering::C_Unknown: 8773 assert(false && "Unexpected unknown constraint"); 8774 } 8775 8776 // Indirect output manifest as stores. Record output chains. 8777 if (OpInfo.isIndirect) { 8778 const Value *Ptr = OpInfo.CallOperandVal; 8779 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8780 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8781 MachinePointerInfo(Ptr)); 8782 OutChains.push_back(Store); 8783 } else { 8784 // generate CopyFromRegs to associated registers. 8785 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8786 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8787 for (const SDValue &V : Val->op_values()) 8788 handleRegAssign(V); 8789 } else 8790 handleRegAssign(Val); 8791 } 8792 } 8793 } 8794 8795 // Set results. 8796 if (!ResultValues.empty()) { 8797 assert(CurResultType == ResultTypes.end() && 8798 "Mismatch in number of ResultTypes"); 8799 assert(ResultValues.size() == ResultTypes.size() && 8800 "Mismatch in number of output operands in asm result"); 8801 8802 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8803 DAG.getVTList(ResultVTs), ResultValues); 8804 setValue(&Call, V); 8805 } 8806 8807 // Collect store chains. 8808 if (!OutChains.empty()) 8809 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8810 8811 // Only Update Root if inline assembly has a memory effect. 8812 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8813 DAG.setRoot(Chain); 8814 } 8815 8816 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8817 const Twine &Message) { 8818 LLVMContext &Ctx = *DAG.getContext(); 8819 Ctx.emitError(&Call, Message); 8820 8821 // Make sure we leave the DAG in a valid state 8822 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8823 SmallVector<EVT, 1> ValueVTs; 8824 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8825 8826 if (ValueVTs.empty()) 8827 return; 8828 8829 SmallVector<SDValue, 1> Ops; 8830 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8831 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8832 8833 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8834 } 8835 8836 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8837 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8838 MVT::Other, getRoot(), 8839 getValue(I.getArgOperand(0)), 8840 DAG.getSrcValue(I.getArgOperand(0)))); 8841 } 8842 8843 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8844 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8845 const DataLayout &DL = DAG.getDataLayout(); 8846 SDValue V = DAG.getVAArg( 8847 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8848 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8849 DL.getABITypeAlign(I.getType()).value()); 8850 DAG.setRoot(V.getValue(1)); 8851 8852 if (I.getType()->isPointerTy()) 8853 V = DAG.getPtrExtOrTrunc( 8854 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8855 setValue(&I, V); 8856 } 8857 8858 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8859 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8860 MVT::Other, getRoot(), 8861 getValue(I.getArgOperand(0)), 8862 DAG.getSrcValue(I.getArgOperand(0)))); 8863 } 8864 8865 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8866 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8867 MVT::Other, getRoot(), 8868 getValue(I.getArgOperand(0)), 8869 getValue(I.getArgOperand(1)), 8870 DAG.getSrcValue(I.getArgOperand(0)), 8871 DAG.getSrcValue(I.getArgOperand(1)))); 8872 } 8873 8874 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8875 const Instruction &I, 8876 SDValue Op) { 8877 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8878 if (!Range) 8879 return Op; 8880 8881 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8882 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8883 return Op; 8884 8885 APInt Lo = CR.getUnsignedMin(); 8886 if (!Lo.isMinValue()) 8887 return Op; 8888 8889 APInt Hi = CR.getUnsignedMax(); 8890 unsigned Bits = std::max(Hi.getActiveBits(), 8891 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8892 8893 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8894 8895 SDLoc SL = getCurSDLoc(); 8896 8897 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8898 DAG.getValueType(SmallVT)); 8899 unsigned NumVals = Op.getNode()->getNumValues(); 8900 if (NumVals == 1) 8901 return ZExt; 8902 8903 SmallVector<SDValue, 4> Ops; 8904 8905 Ops.push_back(ZExt); 8906 for (unsigned I = 1; I != NumVals; ++I) 8907 Ops.push_back(Op.getValue(I)); 8908 8909 return DAG.getMergeValues(Ops, SL); 8910 } 8911 8912 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8913 /// the call being lowered. 8914 /// 8915 /// This is a helper for lowering intrinsics that follow a target calling 8916 /// convention or require stack pointer adjustment. Only a subset of the 8917 /// intrinsic's operands need to participate in the calling convention. 8918 void SelectionDAGBuilder::populateCallLoweringInfo( 8919 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8920 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8921 bool IsPatchPoint) { 8922 TargetLowering::ArgListTy Args; 8923 Args.reserve(NumArgs); 8924 8925 // Populate the argument list. 8926 // Attributes for args start at offset 1, after the return attribute. 8927 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8928 ArgI != ArgE; ++ArgI) { 8929 const Value *V = Call->getOperand(ArgI); 8930 8931 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8932 8933 TargetLowering::ArgListEntry Entry; 8934 Entry.Node = getValue(V); 8935 Entry.Ty = V->getType(); 8936 Entry.setAttributes(Call, ArgI); 8937 Args.push_back(Entry); 8938 } 8939 8940 CLI.setDebugLoc(getCurSDLoc()) 8941 .setChain(getRoot()) 8942 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8943 .setDiscardResult(Call->use_empty()) 8944 .setIsPatchPoint(IsPatchPoint) 8945 .setIsPreallocated( 8946 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8947 } 8948 8949 /// Add a stack map intrinsic call's live variable operands to a stackmap 8950 /// or patchpoint target node's operand list. 8951 /// 8952 /// Constants are converted to TargetConstants purely as an optimization to 8953 /// avoid constant materialization and register allocation. 8954 /// 8955 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8956 /// generate addess computation nodes, and so FinalizeISel can convert the 8957 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8958 /// address materialization and register allocation, but may also be required 8959 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8960 /// alloca in the entry block, then the runtime may assume that the alloca's 8961 /// StackMap location can be read immediately after compilation and that the 8962 /// location is valid at any point during execution (this is similar to the 8963 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8964 /// only available in a register, then the runtime would need to trap when 8965 /// execution reaches the StackMap in order to read the alloca's location. 8966 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8967 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8968 SelectionDAGBuilder &Builder) { 8969 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8970 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8971 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8972 Ops.push_back( 8973 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8974 Ops.push_back( 8975 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8976 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8977 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8978 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8979 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8980 } else 8981 Ops.push_back(OpVal); 8982 } 8983 } 8984 8985 /// Lower llvm.experimental.stackmap directly to its target opcode. 8986 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8987 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8988 // [live variables...]) 8989 8990 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8991 8992 SDValue Chain, InFlag, Callee, NullPtr; 8993 SmallVector<SDValue, 32> Ops; 8994 8995 SDLoc DL = getCurSDLoc(); 8996 Callee = getValue(CI.getCalledOperand()); 8997 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8998 8999 // The stackmap intrinsic only records the live variables (the arguments 9000 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9001 // intrinsic, this won't be lowered to a function call. This means we don't 9002 // have to worry about calling conventions and target specific lowering code. 9003 // Instead we perform the call lowering right here. 9004 // 9005 // chain, flag = CALLSEQ_START(chain, 0, 0) 9006 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9007 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9008 // 9009 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9010 InFlag = Chain.getValue(1); 9011 9012 // Add the <id> and <numBytes> constants. 9013 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 9014 Ops.push_back(DAG.getTargetConstant( 9015 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 9016 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 9017 Ops.push_back(DAG.getTargetConstant( 9018 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 9019 MVT::i32)); 9020 9021 // Push live variables for the stack map. 9022 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9023 9024 // We are not pushing any register mask info here on the operands list, 9025 // because the stackmap doesn't clobber anything. 9026 9027 // Push the chain and the glue flag. 9028 Ops.push_back(Chain); 9029 Ops.push_back(InFlag); 9030 9031 // Create the STACKMAP node. 9032 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9033 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9034 Chain = SDValue(SM, 0); 9035 InFlag = Chain.getValue(1); 9036 9037 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9038 9039 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9040 9041 // Set the root to the target-lowered call chain. 9042 DAG.setRoot(Chain); 9043 9044 // Inform the Frame Information that we have a stackmap in this function. 9045 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9046 } 9047 9048 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9049 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9050 const BasicBlock *EHPadBB) { 9051 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9052 // i32 <numBytes>, 9053 // i8* <target>, 9054 // i32 <numArgs>, 9055 // [Args...], 9056 // [live variables...]) 9057 9058 CallingConv::ID CC = CB.getCallingConv(); 9059 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9060 bool HasDef = !CB.getType()->isVoidTy(); 9061 SDLoc dl = getCurSDLoc(); 9062 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9063 9064 // Handle immediate and symbolic callees. 9065 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9066 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9067 /*isTarget=*/true); 9068 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9069 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9070 SDLoc(SymbolicCallee), 9071 SymbolicCallee->getValueType(0)); 9072 9073 // Get the real number of arguments participating in the call <numArgs> 9074 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9075 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9076 9077 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9078 // Intrinsics include all meta-operands up to but not including CC. 9079 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9080 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9081 "Not enough arguments provided to the patchpoint intrinsic"); 9082 9083 // For AnyRegCC the arguments are lowered later on manually. 9084 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9085 Type *ReturnTy = 9086 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9087 9088 TargetLowering::CallLoweringInfo CLI(DAG); 9089 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9090 ReturnTy, true); 9091 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9092 9093 SDNode *CallEnd = Result.second.getNode(); 9094 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9095 CallEnd = CallEnd->getOperand(0).getNode(); 9096 9097 /// Get a call instruction from the call sequence chain. 9098 /// Tail calls are not allowed. 9099 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9100 "Expected a callseq node."); 9101 SDNode *Call = CallEnd->getOperand(0).getNode(); 9102 bool HasGlue = Call->getGluedNode(); 9103 9104 // Replace the target specific call node with the patchable intrinsic. 9105 SmallVector<SDValue, 8> Ops; 9106 9107 // Add the <id> and <numBytes> constants. 9108 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9109 Ops.push_back(DAG.getTargetConstant( 9110 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9111 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9112 Ops.push_back(DAG.getTargetConstant( 9113 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9114 MVT::i32)); 9115 9116 // Add the callee. 9117 Ops.push_back(Callee); 9118 9119 // Adjust <numArgs> to account for any arguments that have been passed on the 9120 // stack instead. 9121 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9122 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9123 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9124 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9125 9126 // Add the calling convention 9127 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9128 9129 // Add the arguments we omitted previously. The register allocator should 9130 // place these in any free register. 9131 if (IsAnyRegCC) 9132 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9133 Ops.push_back(getValue(CB.getArgOperand(i))); 9134 9135 // Push the arguments from the call instruction up to the register mask. 9136 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9137 Ops.append(Call->op_begin() + 2, e); 9138 9139 // Push live variables for the stack map. 9140 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9141 9142 // Push the register mask info. 9143 if (HasGlue) 9144 Ops.push_back(*(Call->op_end()-2)); 9145 else 9146 Ops.push_back(*(Call->op_end()-1)); 9147 9148 // Push the chain (this is originally the first operand of the call, but 9149 // becomes now the last or second to last operand). 9150 Ops.push_back(*(Call->op_begin())); 9151 9152 // Push the glue flag (last operand). 9153 if (HasGlue) 9154 Ops.push_back(*(Call->op_end()-1)); 9155 9156 SDVTList NodeTys; 9157 if (IsAnyRegCC && HasDef) { 9158 // Create the return types based on the intrinsic definition 9159 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9160 SmallVector<EVT, 3> ValueVTs; 9161 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9162 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9163 9164 // There is always a chain and a glue type at the end 9165 ValueVTs.push_back(MVT::Other); 9166 ValueVTs.push_back(MVT::Glue); 9167 NodeTys = DAG.getVTList(ValueVTs); 9168 } else 9169 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9170 9171 // Replace the target specific call node with a PATCHPOINT node. 9172 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9173 dl, NodeTys, Ops); 9174 9175 // Update the NodeMap. 9176 if (HasDef) { 9177 if (IsAnyRegCC) 9178 setValue(&CB, SDValue(MN, 0)); 9179 else 9180 setValue(&CB, Result.first); 9181 } 9182 9183 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9184 // call sequence. Furthermore the location of the chain and glue can change 9185 // when the AnyReg calling convention is used and the intrinsic returns a 9186 // value. 9187 if (IsAnyRegCC && HasDef) { 9188 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9189 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9190 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9191 } else 9192 DAG.ReplaceAllUsesWith(Call, MN); 9193 DAG.DeleteNode(Call); 9194 9195 // Inform the Frame Information that we have a patchpoint in this function. 9196 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9197 } 9198 9199 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9200 unsigned Intrinsic) { 9201 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9202 SDValue Op1 = getValue(I.getArgOperand(0)); 9203 SDValue Op2; 9204 if (I.getNumArgOperands() > 1) 9205 Op2 = getValue(I.getArgOperand(1)); 9206 SDLoc dl = getCurSDLoc(); 9207 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9208 SDValue Res; 9209 SDNodeFlags SDFlags; 9210 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9211 SDFlags.copyFMF(*FPMO); 9212 9213 switch (Intrinsic) { 9214 case Intrinsic::vector_reduce_fadd: 9215 if (SDFlags.hasAllowReassociation()) 9216 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9217 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9218 SDFlags); 9219 else 9220 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9221 break; 9222 case Intrinsic::vector_reduce_fmul: 9223 if (SDFlags.hasAllowReassociation()) 9224 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9225 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9226 SDFlags); 9227 else 9228 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9229 break; 9230 case Intrinsic::vector_reduce_add: 9231 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9232 break; 9233 case Intrinsic::vector_reduce_mul: 9234 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9235 break; 9236 case Intrinsic::vector_reduce_and: 9237 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9238 break; 9239 case Intrinsic::vector_reduce_or: 9240 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9241 break; 9242 case Intrinsic::vector_reduce_xor: 9243 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9244 break; 9245 case Intrinsic::vector_reduce_smax: 9246 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9247 break; 9248 case Intrinsic::vector_reduce_smin: 9249 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9250 break; 9251 case Intrinsic::vector_reduce_umax: 9252 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9253 break; 9254 case Intrinsic::vector_reduce_umin: 9255 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9256 break; 9257 case Intrinsic::vector_reduce_fmax: 9258 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9259 break; 9260 case Intrinsic::vector_reduce_fmin: 9261 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9262 break; 9263 default: 9264 llvm_unreachable("Unhandled vector reduce intrinsic"); 9265 } 9266 setValue(&I, Res); 9267 } 9268 9269 /// Returns an AttributeList representing the attributes applied to the return 9270 /// value of the given call. 9271 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9272 SmallVector<Attribute::AttrKind, 2> Attrs; 9273 if (CLI.RetSExt) 9274 Attrs.push_back(Attribute::SExt); 9275 if (CLI.RetZExt) 9276 Attrs.push_back(Attribute::ZExt); 9277 if (CLI.IsInReg) 9278 Attrs.push_back(Attribute::InReg); 9279 9280 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9281 Attrs); 9282 } 9283 9284 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9285 /// implementation, which just calls LowerCall. 9286 /// FIXME: When all targets are 9287 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9288 std::pair<SDValue, SDValue> 9289 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9290 // Handle the incoming return values from the call. 9291 CLI.Ins.clear(); 9292 Type *OrigRetTy = CLI.RetTy; 9293 SmallVector<EVT, 4> RetTys; 9294 SmallVector<uint64_t, 4> Offsets; 9295 auto &DL = CLI.DAG.getDataLayout(); 9296 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9297 9298 if (CLI.IsPostTypeLegalization) { 9299 // If we are lowering a libcall after legalization, split the return type. 9300 SmallVector<EVT, 4> OldRetTys; 9301 SmallVector<uint64_t, 4> OldOffsets; 9302 RetTys.swap(OldRetTys); 9303 Offsets.swap(OldOffsets); 9304 9305 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9306 EVT RetVT = OldRetTys[i]; 9307 uint64_t Offset = OldOffsets[i]; 9308 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9309 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9310 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9311 RetTys.append(NumRegs, RegisterVT); 9312 for (unsigned j = 0; j != NumRegs; ++j) 9313 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9314 } 9315 } 9316 9317 SmallVector<ISD::OutputArg, 4> Outs; 9318 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9319 9320 bool CanLowerReturn = 9321 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9322 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9323 9324 SDValue DemoteStackSlot; 9325 int DemoteStackIdx = -100; 9326 if (!CanLowerReturn) { 9327 // FIXME: equivalent assert? 9328 // assert(!CS.hasInAllocaArgument() && 9329 // "sret demotion is incompatible with inalloca"); 9330 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9331 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9332 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9333 DemoteStackIdx = 9334 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9335 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9336 DL.getAllocaAddrSpace()); 9337 9338 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9339 ArgListEntry Entry; 9340 Entry.Node = DemoteStackSlot; 9341 Entry.Ty = StackSlotPtrType; 9342 Entry.IsSExt = false; 9343 Entry.IsZExt = false; 9344 Entry.IsInReg = false; 9345 Entry.IsSRet = true; 9346 Entry.IsNest = false; 9347 Entry.IsByVal = false; 9348 Entry.IsByRef = false; 9349 Entry.IsReturned = false; 9350 Entry.IsSwiftSelf = false; 9351 Entry.IsSwiftError = false; 9352 Entry.IsCFGuardTarget = false; 9353 Entry.Alignment = Alignment; 9354 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9355 CLI.NumFixedArgs += 1; 9356 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9357 9358 // sret demotion isn't compatible with tail-calls, since the sret argument 9359 // points into the callers stack frame. 9360 CLI.IsTailCall = false; 9361 } else { 9362 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9363 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9364 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9365 ISD::ArgFlagsTy Flags; 9366 if (NeedsRegBlock) { 9367 Flags.setInConsecutiveRegs(); 9368 if (I == RetTys.size() - 1) 9369 Flags.setInConsecutiveRegsLast(); 9370 } 9371 EVT VT = RetTys[I]; 9372 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9373 CLI.CallConv, VT); 9374 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9375 CLI.CallConv, VT); 9376 for (unsigned i = 0; i != NumRegs; ++i) { 9377 ISD::InputArg MyFlags; 9378 MyFlags.Flags = Flags; 9379 MyFlags.VT = RegisterVT; 9380 MyFlags.ArgVT = VT; 9381 MyFlags.Used = CLI.IsReturnValueUsed; 9382 if (CLI.RetTy->isPointerTy()) { 9383 MyFlags.Flags.setPointer(); 9384 MyFlags.Flags.setPointerAddrSpace( 9385 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9386 } 9387 if (CLI.RetSExt) 9388 MyFlags.Flags.setSExt(); 9389 if (CLI.RetZExt) 9390 MyFlags.Flags.setZExt(); 9391 if (CLI.IsInReg) 9392 MyFlags.Flags.setInReg(); 9393 CLI.Ins.push_back(MyFlags); 9394 } 9395 } 9396 } 9397 9398 // We push in swifterror return as the last element of CLI.Ins. 9399 ArgListTy &Args = CLI.getArgs(); 9400 if (supportSwiftError()) { 9401 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9402 if (Args[i].IsSwiftError) { 9403 ISD::InputArg MyFlags; 9404 MyFlags.VT = getPointerTy(DL); 9405 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9406 MyFlags.Flags.setSwiftError(); 9407 CLI.Ins.push_back(MyFlags); 9408 } 9409 } 9410 } 9411 9412 // Handle all of the outgoing arguments. 9413 CLI.Outs.clear(); 9414 CLI.OutVals.clear(); 9415 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9416 SmallVector<EVT, 4> ValueVTs; 9417 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9418 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9419 Type *FinalType = Args[i].Ty; 9420 if (Args[i].IsByVal) 9421 FinalType = Args[i].IndirectType; 9422 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9423 FinalType, CLI.CallConv, CLI.IsVarArg); 9424 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9425 ++Value) { 9426 EVT VT = ValueVTs[Value]; 9427 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9428 SDValue Op = SDValue(Args[i].Node.getNode(), 9429 Args[i].Node.getResNo() + Value); 9430 ISD::ArgFlagsTy Flags; 9431 9432 // Certain targets (such as MIPS), may have a different ABI alignment 9433 // for a type depending on the context. Give the target a chance to 9434 // specify the alignment it wants. 9435 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9436 Flags.setOrigAlign(OriginalAlignment); 9437 9438 if (Args[i].Ty->isPointerTy()) { 9439 Flags.setPointer(); 9440 Flags.setPointerAddrSpace( 9441 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9442 } 9443 if (Args[i].IsZExt) 9444 Flags.setZExt(); 9445 if (Args[i].IsSExt) 9446 Flags.setSExt(); 9447 if (Args[i].IsInReg) { 9448 // If we are using vectorcall calling convention, a structure that is 9449 // passed InReg - is surely an HVA 9450 if (CLI.CallConv == CallingConv::X86_VectorCall && 9451 isa<StructType>(FinalType)) { 9452 // The first value of a structure is marked 9453 if (0 == Value) 9454 Flags.setHvaStart(); 9455 Flags.setHva(); 9456 } 9457 // Set InReg Flag 9458 Flags.setInReg(); 9459 } 9460 if (Args[i].IsSRet) 9461 Flags.setSRet(); 9462 if (Args[i].IsSwiftSelf) 9463 Flags.setSwiftSelf(); 9464 if (Args[i].IsSwiftError) 9465 Flags.setSwiftError(); 9466 if (Args[i].IsCFGuardTarget) 9467 Flags.setCFGuardTarget(); 9468 if (Args[i].IsByVal) 9469 Flags.setByVal(); 9470 if (Args[i].IsByRef) 9471 Flags.setByRef(); 9472 if (Args[i].IsPreallocated) { 9473 Flags.setPreallocated(); 9474 // Set the byval flag for CCAssignFn callbacks that don't know about 9475 // preallocated. This way we can know how many bytes we should've 9476 // allocated and how many bytes a callee cleanup function will pop. If 9477 // we port preallocated to more targets, we'll have to add custom 9478 // preallocated handling in the various CC lowering callbacks. 9479 Flags.setByVal(); 9480 } 9481 if (Args[i].IsInAlloca) { 9482 Flags.setInAlloca(); 9483 // Set the byval flag for CCAssignFn callbacks that don't know about 9484 // inalloca. This way we can know how many bytes we should've allocated 9485 // and how many bytes a callee cleanup function will pop. If we port 9486 // inalloca to more targets, we'll have to add custom inalloca handling 9487 // in the various CC lowering callbacks. 9488 Flags.setByVal(); 9489 } 9490 Align MemAlign; 9491 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9492 Type *ElementTy = Args[i].IndirectType; 9493 assert(ElementTy && "Indirect type not set in ArgListEntry"); 9494 9495 unsigned FrameSize = DL.getTypeAllocSize(ElementTy); 9496 Flags.setByValSize(FrameSize); 9497 9498 // info is not there but there are cases it cannot get right. 9499 if (auto MA = Args[i].Alignment) 9500 MemAlign = *MA; 9501 else 9502 MemAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9503 } else if (auto MA = Args[i].Alignment) { 9504 MemAlign = *MA; 9505 } else { 9506 MemAlign = OriginalAlignment; 9507 } 9508 Flags.setMemAlign(MemAlign); 9509 if (Args[i].IsNest) 9510 Flags.setNest(); 9511 if (NeedsRegBlock) 9512 Flags.setInConsecutiveRegs(); 9513 9514 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9515 CLI.CallConv, VT); 9516 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9517 CLI.CallConv, VT); 9518 SmallVector<SDValue, 4> Parts(NumParts); 9519 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9520 9521 if (Args[i].IsSExt) 9522 ExtendKind = ISD::SIGN_EXTEND; 9523 else if (Args[i].IsZExt) 9524 ExtendKind = ISD::ZERO_EXTEND; 9525 9526 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9527 // for now. 9528 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9529 CanLowerReturn) { 9530 assert((CLI.RetTy == Args[i].Ty || 9531 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9532 CLI.RetTy->getPointerAddressSpace() == 9533 Args[i].Ty->getPointerAddressSpace())) && 9534 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9535 // Before passing 'returned' to the target lowering code, ensure that 9536 // either the register MVT and the actual EVT are the same size or that 9537 // the return value and argument are extended in the same way; in these 9538 // cases it's safe to pass the argument register value unchanged as the 9539 // return register value (although it's at the target's option whether 9540 // to do so) 9541 // TODO: allow code generation to take advantage of partially preserved 9542 // registers rather than clobbering the entire register when the 9543 // parameter extension method is not compatible with the return 9544 // extension method 9545 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9546 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9547 CLI.RetZExt == Args[i].IsZExt)) 9548 Flags.setReturned(); 9549 } 9550 9551 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9552 CLI.CallConv, ExtendKind); 9553 9554 for (unsigned j = 0; j != NumParts; ++j) { 9555 // if it isn't first piece, alignment must be 1 9556 // For scalable vectors the scalable part is currently handled 9557 // by individual targets, so we just use the known minimum size here. 9558 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9559 i < CLI.NumFixedArgs, i, 9560 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9561 if (NumParts > 1 && j == 0) 9562 MyFlags.Flags.setSplit(); 9563 else if (j != 0) { 9564 MyFlags.Flags.setOrigAlign(Align(1)); 9565 if (j == NumParts - 1) 9566 MyFlags.Flags.setSplitEnd(); 9567 } 9568 9569 CLI.Outs.push_back(MyFlags); 9570 CLI.OutVals.push_back(Parts[j]); 9571 } 9572 9573 if (NeedsRegBlock && Value == NumValues - 1) 9574 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9575 } 9576 } 9577 9578 SmallVector<SDValue, 4> InVals; 9579 CLI.Chain = LowerCall(CLI, InVals); 9580 9581 // Update CLI.InVals to use outside of this function. 9582 CLI.InVals = InVals; 9583 9584 // Verify that the target's LowerCall behaved as expected. 9585 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9586 "LowerCall didn't return a valid chain!"); 9587 assert((!CLI.IsTailCall || InVals.empty()) && 9588 "LowerCall emitted a return value for a tail call!"); 9589 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9590 "LowerCall didn't emit the correct number of values!"); 9591 9592 // For a tail call, the return value is merely live-out and there aren't 9593 // any nodes in the DAG representing it. Return a special value to 9594 // indicate that a tail call has been emitted and no more Instructions 9595 // should be processed in the current block. 9596 if (CLI.IsTailCall) { 9597 CLI.DAG.setRoot(CLI.Chain); 9598 return std::make_pair(SDValue(), SDValue()); 9599 } 9600 9601 #ifndef NDEBUG 9602 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9603 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9604 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9605 "LowerCall emitted a value with the wrong type!"); 9606 } 9607 #endif 9608 9609 SmallVector<SDValue, 4> ReturnValues; 9610 if (!CanLowerReturn) { 9611 // The instruction result is the result of loading from the 9612 // hidden sret parameter. 9613 SmallVector<EVT, 1> PVTs; 9614 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9615 9616 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9617 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9618 EVT PtrVT = PVTs[0]; 9619 9620 unsigned NumValues = RetTys.size(); 9621 ReturnValues.resize(NumValues); 9622 SmallVector<SDValue, 4> Chains(NumValues); 9623 9624 // An aggregate return value cannot wrap around the address space, so 9625 // offsets to its parts don't wrap either. 9626 SDNodeFlags Flags; 9627 Flags.setNoUnsignedWrap(true); 9628 9629 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9630 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9631 for (unsigned i = 0; i < NumValues; ++i) { 9632 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9633 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9634 PtrVT), Flags); 9635 SDValue L = CLI.DAG.getLoad( 9636 RetTys[i], CLI.DL, CLI.Chain, Add, 9637 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9638 DemoteStackIdx, Offsets[i]), 9639 HiddenSRetAlign); 9640 ReturnValues[i] = L; 9641 Chains[i] = L.getValue(1); 9642 } 9643 9644 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9645 } else { 9646 // Collect the legal value parts into potentially illegal values 9647 // that correspond to the original function's return values. 9648 Optional<ISD::NodeType> AssertOp; 9649 if (CLI.RetSExt) 9650 AssertOp = ISD::AssertSext; 9651 else if (CLI.RetZExt) 9652 AssertOp = ISD::AssertZext; 9653 unsigned CurReg = 0; 9654 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9655 EVT VT = RetTys[I]; 9656 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9657 CLI.CallConv, VT); 9658 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9659 CLI.CallConv, VT); 9660 9661 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9662 NumRegs, RegisterVT, VT, nullptr, 9663 CLI.CallConv, AssertOp)); 9664 CurReg += NumRegs; 9665 } 9666 9667 // For a function returning void, there is no return value. We can't create 9668 // such a node, so we just return a null return value in that case. In 9669 // that case, nothing will actually look at the value. 9670 if (ReturnValues.empty()) 9671 return std::make_pair(SDValue(), CLI.Chain); 9672 } 9673 9674 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9675 CLI.DAG.getVTList(RetTys), ReturnValues); 9676 return std::make_pair(Res, CLI.Chain); 9677 } 9678 9679 /// Places new result values for the node in Results (their number 9680 /// and types must exactly match those of the original return values of 9681 /// the node), or leaves Results empty, which indicates that the node is not 9682 /// to be custom lowered after all. 9683 void TargetLowering::LowerOperationWrapper(SDNode *N, 9684 SmallVectorImpl<SDValue> &Results, 9685 SelectionDAG &DAG) const { 9686 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9687 9688 if (!Res.getNode()) 9689 return; 9690 9691 // If the original node has one result, take the return value from 9692 // LowerOperation as is. It might not be result number 0. 9693 if (N->getNumValues() == 1) { 9694 Results.push_back(Res); 9695 return; 9696 } 9697 9698 // If the original node has multiple results, then the return node should 9699 // have the same number of results. 9700 assert((N->getNumValues() == Res->getNumValues()) && 9701 "Lowering returned the wrong number of results!"); 9702 9703 // Places new result values base on N result number. 9704 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9705 Results.push_back(Res.getValue(I)); 9706 } 9707 9708 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9709 llvm_unreachable("LowerOperation not implemented for this target!"); 9710 } 9711 9712 void 9713 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9714 SDValue Op = getNonRegisterValue(V); 9715 assert((Op.getOpcode() != ISD::CopyFromReg || 9716 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9717 "Copy from a reg to the same reg!"); 9718 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9719 9720 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9721 // If this is an InlineAsm we have to match the registers required, not the 9722 // notional registers required by the type. 9723 9724 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9725 None); // This is not an ABI copy. 9726 SDValue Chain = DAG.getEntryNode(); 9727 9728 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9729 FuncInfo.PreferredExtendType.end()) 9730 ? ISD::ANY_EXTEND 9731 : FuncInfo.PreferredExtendType[V]; 9732 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9733 PendingExports.push_back(Chain); 9734 } 9735 9736 #include "llvm/CodeGen/SelectionDAGISel.h" 9737 9738 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9739 /// entry block, return true. This includes arguments used by switches, since 9740 /// the switch may expand into multiple basic blocks. 9741 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9742 // With FastISel active, we may be splitting blocks, so force creation 9743 // of virtual registers for all non-dead arguments. 9744 if (FastISel) 9745 return A->use_empty(); 9746 9747 const BasicBlock &Entry = A->getParent()->front(); 9748 for (const User *U : A->users()) 9749 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9750 return false; // Use not in entry block. 9751 9752 return true; 9753 } 9754 9755 using ArgCopyElisionMapTy = 9756 DenseMap<const Argument *, 9757 std::pair<const AllocaInst *, const StoreInst *>>; 9758 9759 /// Scan the entry block of the function in FuncInfo for arguments that look 9760 /// like copies into a local alloca. Record any copied arguments in 9761 /// ArgCopyElisionCandidates. 9762 static void 9763 findArgumentCopyElisionCandidates(const DataLayout &DL, 9764 FunctionLoweringInfo *FuncInfo, 9765 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9766 // Record the state of every static alloca used in the entry block. Argument 9767 // allocas are all used in the entry block, so we need approximately as many 9768 // entries as we have arguments. 9769 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9770 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9771 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9772 StaticAllocas.reserve(NumArgs * 2); 9773 9774 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9775 if (!V) 9776 return nullptr; 9777 V = V->stripPointerCasts(); 9778 const auto *AI = dyn_cast<AllocaInst>(V); 9779 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9780 return nullptr; 9781 auto Iter = StaticAllocas.insert({AI, Unknown}); 9782 return &Iter.first->second; 9783 }; 9784 9785 // Look for stores of arguments to static allocas. Look through bitcasts and 9786 // GEPs to handle type coercions, as long as the alloca is fully initialized 9787 // by the store. Any non-store use of an alloca escapes it and any subsequent 9788 // unanalyzed store might write it. 9789 // FIXME: Handle structs initialized with multiple stores. 9790 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9791 // Look for stores, and handle non-store uses conservatively. 9792 const auto *SI = dyn_cast<StoreInst>(&I); 9793 if (!SI) { 9794 // We will look through cast uses, so ignore them completely. 9795 if (I.isCast()) 9796 continue; 9797 // Ignore debug info and pseudo op intrinsics, they don't escape or store 9798 // to allocas. 9799 if (I.isDebugOrPseudoInst()) 9800 continue; 9801 // This is an unknown instruction. Assume it escapes or writes to all 9802 // static alloca operands. 9803 for (const Use &U : I.operands()) { 9804 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9805 *Info = StaticAllocaInfo::Clobbered; 9806 } 9807 continue; 9808 } 9809 9810 // If the stored value is a static alloca, mark it as escaped. 9811 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9812 *Info = StaticAllocaInfo::Clobbered; 9813 9814 // Check if the destination is a static alloca. 9815 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9816 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9817 if (!Info) 9818 continue; 9819 const AllocaInst *AI = cast<AllocaInst>(Dst); 9820 9821 // Skip allocas that have been initialized or clobbered. 9822 if (*Info != StaticAllocaInfo::Unknown) 9823 continue; 9824 9825 // Check if the stored value is an argument, and that this store fully 9826 // initializes the alloca. Don't elide copies from the same argument twice. 9827 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9828 const auto *Arg = dyn_cast<Argument>(Val); 9829 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9830 Arg->getType()->isEmptyTy() || 9831 DL.getTypeStoreSize(Arg->getType()) != 9832 DL.getTypeAllocSize(AI->getAllocatedType()) || 9833 ArgCopyElisionCandidates.count(Arg)) { 9834 *Info = StaticAllocaInfo::Clobbered; 9835 continue; 9836 } 9837 9838 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9839 << '\n'); 9840 9841 // Mark this alloca and store for argument copy elision. 9842 *Info = StaticAllocaInfo::Elidable; 9843 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9844 9845 // Stop scanning if we've seen all arguments. This will happen early in -O0 9846 // builds, which is useful, because -O0 builds have large entry blocks and 9847 // many allocas. 9848 if (ArgCopyElisionCandidates.size() == NumArgs) 9849 break; 9850 } 9851 } 9852 9853 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9854 /// ArgVal is a load from a suitable fixed stack object. 9855 static void tryToElideArgumentCopy( 9856 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9857 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9858 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9859 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9860 SDValue ArgVal, bool &ArgHasUses) { 9861 // Check if this is a load from a fixed stack object. 9862 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9863 if (!LNode) 9864 return; 9865 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9866 if (!FINode) 9867 return; 9868 9869 // Check that the fixed stack object is the right size and alignment. 9870 // Look at the alignment that the user wrote on the alloca instead of looking 9871 // at the stack object. 9872 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9873 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9874 const AllocaInst *AI = ArgCopyIter->second.first; 9875 int FixedIndex = FINode->getIndex(); 9876 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9877 int OldIndex = AllocaIndex; 9878 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9879 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9880 LLVM_DEBUG( 9881 dbgs() << " argument copy elision failed due to bad fixed stack " 9882 "object size\n"); 9883 return; 9884 } 9885 Align RequiredAlignment = AI->getAlign(); 9886 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9887 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9888 "greater than stack argument alignment (" 9889 << DebugStr(RequiredAlignment) << " vs " 9890 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9891 return; 9892 } 9893 9894 // Perform the elision. Delete the old stack object and replace its only use 9895 // in the variable info map. Mark the stack object as mutable. 9896 LLVM_DEBUG({ 9897 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9898 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9899 << '\n'; 9900 }); 9901 MFI.RemoveStackObject(OldIndex); 9902 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9903 AllocaIndex = FixedIndex; 9904 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9905 Chains.push_back(ArgVal.getValue(1)); 9906 9907 // Avoid emitting code for the store implementing the copy. 9908 const StoreInst *SI = ArgCopyIter->second.second; 9909 ElidedArgCopyInstrs.insert(SI); 9910 9911 // Check for uses of the argument again so that we can avoid exporting ArgVal 9912 // if it is't used by anything other than the store. 9913 for (const Value *U : Arg.users()) { 9914 if (U != SI) { 9915 ArgHasUses = true; 9916 break; 9917 } 9918 } 9919 } 9920 9921 void SelectionDAGISel::LowerArguments(const Function &F) { 9922 SelectionDAG &DAG = SDB->DAG; 9923 SDLoc dl = SDB->getCurSDLoc(); 9924 const DataLayout &DL = DAG.getDataLayout(); 9925 SmallVector<ISD::InputArg, 16> Ins; 9926 9927 // In Naked functions we aren't going to save any registers. 9928 if (F.hasFnAttribute(Attribute::Naked)) 9929 return; 9930 9931 if (!FuncInfo->CanLowerReturn) { 9932 // Put in an sret pointer parameter before all the other parameters. 9933 SmallVector<EVT, 1> ValueVTs; 9934 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9935 F.getReturnType()->getPointerTo( 9936 DAG.getDataLayout().getAllocaAddrSpace()), 9937 ValueVTs); 9938 9939 // NOTE: Assuming that a pointer will never break down to more than one VT 9940 // or one register. 9941 ISD::ArgFlagsTy Flags; 9942 Flags.setSRet(); 9943 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9944 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9945 ISD::InputArg::NoArgIndex, 0); 9946 Ins.push_back(RetArg); 9947 } 9948 9949 // Look for stores of arguments to static allocas. Mark such arguments with a 9950 // flag to ask the target to give us the memory location of that argument if 9951 // available. 9952 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9953 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9954 ArgCopyElisionCandidates); 9955 9956 // Set up the incoming argument description vector. 9957 for (const Argument &Arg : F.args()) { 9958 unsigned ArgNo = Arg.getArgNo(); 9959 SmallVector<EVT, 4> ValueVTs; 9960 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9961 bool isArgValueUsed = !Arg.use_empty(); 9962 unsigned PartBase = 0; 9963 Type *FinalType = Arg.getType(); 9964 if (Arg.hasAttribute(Attribute::ByVal)) 9965 FinalType = Arg.getParamByValType(); 9966 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9967 FinalType, F.getCallingConv(), F.isVarArg()); 9968 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9969 Value != NumValues; ++Value) { 9970 EVT VT = ValueVTs[Value]; 9971 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9972 ISD::ArgFlagsTy Flags; 9973 9974 9975 if (Arg.getType()->isPointerTy()) { 9976 Flags.setPointer(); 9977 Flags.setPointerAddrSpace( 9978 cast<PointerType>(Arg.getType())->getAddressSpace()); 9979 } 9980 if (Arg.hasAttribute(Attribute::ZExt)) 9981 Flags.setZExt(); 9982 if (Arg.hasAttribute(Attribute::SExt)) 9983 Flags.setSExt(); 9984 if (Arg.hasAttribute(Attribute::InReg)) { 9985 // If we are using vectorcall calling convention, a structure that is 9986 // passed InReg - is surely an HVA 9987 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9988 isa<StructType>(Arg.getType())) { 9989 // The first value of a structure is marked 9990 if (0 == Value) 9991 Flags.setHvaStart(); 9992 Flags.setHva(); 9993 } 9994 // Set InReg Flag 9995 Flags.setInReg(); 9996 } 9997 if (Arg.hasAttribute(Attribute::StructRet)) 9998 Flags.setSRet(); 9999 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10000 Flags.setSwiftSelf(); 10001 if (Arg.hasAttribute(Attribute::SwiftError)) 10002 Flags.setSwiftError(); 10003 if (Arg.hasAttribute(Attribute::ByVal)) 10004 Flags.setByVal(); 10005 if (Arg.hasAttribute(Attribute::ByRef)) 10006 Flags.setByRef(); 10007 if (Arg.hasAttribute(Attribute::InAlloca)) { 10008 Flags.setInAlloca(); 10009 // Set the byval flag for CCAssignFn callbacks that don't know about 10010 // inalloca. This way we can know how many bytes we should've allocated 10011 // and how many bytes a callee cleanup function will pop. If we port 10012 // inalloca to more targets, we'll have to add custom inalloca handling 10013 // in the various CC lowering callbacks. 10014 Flags.setByVal(); 10015 } 10016 if (Arg.hasAttribute(Attribute::Preallocated)) { 10017 Flags.setPreallocated(); 10018 // Set the byval flag for CCAssignFn callbacks that don't know about 10019 // preallocated. This way we can know how many bytes we should've 10020 // allocated and how many bytes a callee cleanup function will pop. If 10021 // we port preallocated to more targets, we'll have to add custom 10022 // preallocated handling in the various CC lowering callbacks. 10023 Flags.setByVal(); 10024 } 10025 10026 // Certain targets (such as MIPS), may have a different ABI alignment 10027 // for a type depending on the context. Give the target a chance to 10028 // specify the alignment it wants. 10029 const Align OriginalAlignment( 10030 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10031 Flags.setOrigAlign(OriginalAlignment); 10032 10033 Align MemAlign; 10034 Type *ArgMemTy = nullptr; 10035 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10036 Flags.isByRef()) { 10037 if (!ArgMemTy) 10038 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10039 10040 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10041 10042 // For in-memory arguments, size and alignment should be passed from FE. 10043 // BE will guess if this info is not there but there are cases it cannot 10044 // get right. 10045 if (auto ParamAlign = Arg.getParamStackAlign()) 10046 MemAlign = *ParamAlign; 10047 else if ((ParamAlign = Arg.getParamAlign())) 10048 MemAlign = *ParamAlign; 10049 else 10050 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10051 if (Flags.isByRef()) 10052 Flags.setByRefSize(MemSize); 10053 else 10054 Flags.setByValSize(MemSize); 10055 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10056 MemAlign = *ParamAlign; 10057 } else { 10058 MemAlign = OriginalAlignment; 10059 } 10060 Flags.setMemAlign(MemAlign); 10061 10062 if (Arg.hasAttribute(Attribute::Nest)) 10063 Flags.setNest(); 10064 if (NeedsRegBlock) 10065 Flags.setInConsecutiveRegs(); 10066 if (ArgCopyElisionCandidates.count(&Arg)) 10067 Flags.setCopyElisionCandidate(); 10068 if (Arg.hasAttribute(Attribute::Returned)) 10069 Flags.setReturned(); 10070 10071 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10072 *CurDAG->getContext(), F.getCallingConv(), VT); 10073 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10074 *CurDAG->getContext(), F.getCallingConv(), VT); 10075 for (unsigned i = 0; i != NumRegs; ++i) { 10076 // For scalable vectors, use the minimum size; individual targets 10077 // are responsible for handling scalable vector arguments and 10078 // return values. 10079 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10080 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10081 if (NumRegs > 1 && i == 0) 10082 MyFlags.Flags.setSplit(); 10083 // if it isn't first piece, alignment must be 1 10084 else if (i > 0) { 10085 MyFlags.Flags.setOrigAlign(Align(1)); 10086 if (i == NumRegs - 1) 10087 MyFlags.Flags.setSplitEnd(); 10088 } 10089 Ins.push_back(MyFlags); 10090 } 10091 if (NeedsRegBlock && Value == NumValues - 1) 10092 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10093 PartBase += VT.getStoreSize().getKnownMinSize(); 10094 } 10095 } 10096 10097 // Call the target to set up the argument values. 10098 SmallVector<SDValue, 8> InVals; 10099 SDValue NewRoot = TLI->LowerFormalArguments( 10100 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10101 10102 // Verify that the target's LowerFormalArguments behaved as expected. 10103 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10104 "LowerFormalArguments didn't return a valid chain!"); 10105 assert(InVals.size() == Ins.size() && 10106 "LowerFormalArguments didn't emit the correct number of values!"); 10107 LLVM_DEBUG({ 10108 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10109 assert(InVals[i].getNode() && 10110 "LowerFormalArguments emitted a null value!"); 10111 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10112 "LowerFormalArguments emitted a value with the wrong type!"); 10113 } 10114 }); 10115 10116 // Update the DAG with the new chain value resulting from argument lowering. 10117 DAG.setRoot(NewRoot); 10118 10119 // Set up the argument values. 10120 unsigned i = 0; 10121 if (!FuncInfo->CanLowerReturn) { 10122 // Create a virtual register for the sret pointer, and put in a copy 10123 // from the sret argument into it. 10124 SmallVector<EVT, 1> ValueVTs; 10125 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10126 F.getReturnType()->getPointerTo( 10127 DAG.getDataLayout().getAllocaAddrSpace()), 10128 ValueVTs); 10129 MVT VT = ValueVTs[0].getSimpleVT(); 10130 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10131 Optional<ISD::NodeType> AssertOp = None; 10132 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10133 nullptr, F.getCallingConv(), AssertOp); 10134 10135 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10136 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10137 Register SRetReg = 10138 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10139 FuncInfo->DemoteRegister = SRetReg; 10140 NewRoot = 10141 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10142 DAG.setRoot(NewRoot); 10143 10144 // i indexes lowered arguments. Bump it past the hidden sret argument. 10145 ++i; 10146 } 10147 10148 SmallVector<SDValue, 4> Chains; 10149 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10150 for (const Argument &Arg : F.args()) { 10151 SmallVector<SDValue, 4> ArgValues; 10152 SmallVector<EVT, 4> ValueVTs; 10153 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10154 unsigned NumValues = ValueVTs.size(); 10155 if (NumValues == 0) 10156 continue; 10157 10158 bool ArgHasUses = !Arg.use_empty(); 10159 10160 // Elide the copying store if the target loaded this argument from a 10161 // suitable fixed stack object. 10162 if (Ins[i].Flags.isCopyElisionCandidate()) { 10163 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10164 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10165 InVals[i], ArgHasUses); 10166 } 10167 10168 // If this argument is unused then remember its value. It is used to generate 10169 // debugging information. 10170 bool isSwiftErrorArg = 10171 TLI->supportSwiftError() && 10172 Arg.hasAttribute(Attribute::SwiftError); 10173 if (!ArgHasUses && !isSwiftErrorArg) { 10174 SDB->setUnusedArgValue(&Arg, InVals[i]); 10175 10176 // Also remember any frame index for use in FastISel. 10177 if (FrameIndexSDNode *FI = 10178 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10179 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10180 } 10181 10182 for (unsigned Val = 0; Val != NumValues; ++Val) { 10183 EVT VT = ValueVTs[Val]; 10184 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10185 F.getCallingConv(), VT); 10186 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10187 *CurDAG->getContext(), F.getCallingConv(), VT); 10188 10189 // Even an apparent 'unused' swifterror argument needs to be returned. So 10190 // we do generate a copy for it that can be used on return from the 10191 // function. 10192 if (ArgHasUses || isSwiftErrorArg) { 10193 Optional<ISD::NodeType> AssertOp; 10194 if (Arg.hasAttribute(Attribute::SExt)) 10195 AssertOp = ISD::AssertSext; 10196 else if (Arg.hasAttribute(Attribute::ZExt)) 10197 AssertOp = ISD::AssertZext; 10198 10199 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10200 PartVT, VT, nullptr, 10201 F.getCallingConv(), AssertOp)); 10202 } 10203 10204 i += NumParts; 10205 } 10206 10207 // We don't need to do anything else for unused arguments. 10208 if (ArgValues.empty()) 10209 continue; 10210 10211 // Note down frame index. 10212 if (FrameIndexSDNode *FI = 10213 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10214 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10215 10216 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10217 SDB->getCurSDLoc()); 10218 10219 SDB->setValue(&Arg, Res); 10220 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10221 // We want to associate the argument with the frame index, among 10222 // involved operands, that correspond to the lowest address. The 10223 // getCopyFromParts function, called earlier, is swapping the order of 10224 // the operands to BUILD_PAIR depending on endianness. The result of 10225 // that swapping is that the least significant bits of the argument will 10226 // be in the first operand of the BUILD_PAIR node, and the most 10227 // significant bits will be in the second operand. 10228 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10229 if (LoadSDNode *LNode = 10230 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10231 if (FrameIndexSDNode *FI = 10232 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10233 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10234 } 10235 10236 // Analyses past this point are naive and don't expect an assertion. 10237 if (Res.getOpcode() == ISD::AssertZext) 10238 Res = Res.getOperand(0); 10239 10240 // Update the SwiftErrorVRegDefMap. 10241 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10242 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10243 if (Register::isVirtualRegister(Reg)) 10244 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10245 Reg); 10246 } 10247 10248 // If this argument is live outside of the entry block, insert a copy from 10249 // wherever we got it to the vreg that other BB's will reference it as. 10250 if (Res.getOpcode() == ISD::CopyFromReg) { 10251 // If we can, though, try to skip creating an unnecessary vreg. 10252 // FIXME: This isn't very clean... it would be nice to make this more 10253 // general. 10254 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10255 if (Register::isVirtualRegister(Reg)) { 10256 FuncInfo->ValueMap[&Arg] = Reg; 10257 continue; 10258 } 10259 } 10260 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10261 FuncInfo->InitializeRegForValue(&Arg); 10262 SDB->CopyToExportRegsIfNeeded(&Arg); 10263 } 10264 } 10265 10266 if (!Chains.empty()) { 10267 Chains.push_back(NewRoot); 10268 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10269 } 10270 10271 DAG.setRoot(NewRoot); 10272 10273 assert(i == InVals.size() && "Argument register count mismatch!"); 10274 10275 // If any argument copy elisions occurred and we have debug info, update the 10276 // stale frame indices used in the dbg.declare variable info table. 10277 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10278 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10279 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10280 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10281 if (I != ArgCopyElisionFrameIndexMap.end()) 10282 VI.Slot = I->second; 10283 } 10284 } 10285 10286 // Finally, if the target has anything special to do, allow it to do so. 10287 emitFunctionEntryCode(); 10288 } 10289 10290 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10291 /// ensure constants are generated when needed. Remember the virtual registers 10292 /// that need to be added to the Machine PHI nodes as input. We cannot just 10293 /// directly add them, because expansion might result in multiple MBB's for one 10294 /// BB. As such, the start of the BB might correspond to a different MBB than 10295 /// the end. 10296 void 10297 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10298 const Instruction *TI = LLVMBB->getTerminator(); 10299 10300 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10301 10302 // Check PHI nodes in successors that expect a value to be available from this 10303 // block. 10304 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10305 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10306 if (!isa<PHINode>(SuccBB->begin())) continue; 10307 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10308 10309 // If this terminator has multiple identical successors (common for 10310 // switches), only handle each succ once. 10311 if (!SuccsHandled.insert(SuccMBB).second) 10312 continue; 10313 10314 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10315 10316 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10317 // nodes and Machine PHI nodes, but the incoming operands have not been 10318 // emitted yet. 10319 for (const PHINode &PN : SuccBB->phis()) { 10320 // Ignore dead phi's. 10321 if (PN.use_empty()) 10322 continue; 10323 10324 // Skip empty types 10325 if (PN.getType()->isEmptyTy()) 10326 continue; 10327 10328 unsigned Reg; 10329 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10330 10331 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10332 unsigned &RegOut = ConstantsOut[C]; 10333 if (RegOut == 0) { 10334 RegOut = FuncInfo.CreateRegs(C); 10335 CopyValueToVirtualRegister(C, RegOut); 10336 } 10337 Reg = RegOut; 10338 } else { 10339 DenseMap<const Value *, Register>::iterator I = 10340 FuncInfo.ValueMap.find(PHIOp); 10341 if (I != FuncInfo.ValueMap.end()) 10342 Reg = I->second; 10343 else { 10344 assert(isa<AllocaInst>(PHIOp) && 10345 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10346 "Didn't codegen value into a register!??"); 10347 Reg = FuncInfo.CreateRegs(PHIOp); 10348 CopyValueToVirtualRegister(PHIOp, Reg); 10349 } 10350 } 10351 10352 // Remember that this register needs to added to the machine PHI node as 10353 // the input for this MBB. 10354 SmallVector<EVT, 4> ValueVTs; 10355 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10356 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10357 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10358 EVT VT = ValueVTs[vti]; 10359 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10360 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10361 FuncInfo.PHINodesToUpdate.push_back( 10362 std::make_pair(&*MBBI++, Reg + i)); 10363 Reg += NumRegisters; 10364 } 10365 } 10366 } 10367 10368 ConstantsOut.clear(); 10369 } 10370 10371 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10372 /// is 0. 10373 MachineBasicBlock * 10374 SelectionDAGBuilder::StackProtectorDescriptor:: 10375 AddSuccessorMBB(const BasicBlock *BB, 10376 MachineBasicBlock *ParentMBB, 10377 bool IsLikely, 10378 MachineBasicBlock *SuccMBB) { 10379 // If SuccBB has not been created yet, create it. 10380 if (!SuccMBB) { 10381 MachineFunction *MF = ParentMBB->getParent(); 10382 MachineFunction::iterator BBI(ParentMBB); 10383 SuccMBB = MF->CreateMachineBasicBlock(BB); 10384 MF->insert(++BBI, SuccMBB); 10385 } 10386 // Add it as a successor of ParentMBB. 10387 ParentMBB->addSuccessor( 10388 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10389 return SuccMBB; 10390 } 10391 10392 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10393 MachineFunction::iterator I(MBB); 10394 if (++I == FuncInfo.MF->end()) 10395 return nullptr; 10396 return &*I; 10397 } 10398 10399 /// During lowering new call nodes can be created (such as memset, etc.). 10400 /// Those will become new roots of the current DAG, but complications arise 10401 /// when they are tail calls. In such cases, the call lowering will update 10402 /// the root, but the builder still needs to know that a tail call has been 10403 /// lowered in order to avoid generating an additional return. 10404 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10405 // If the node is null, we do have a tail call. 10406 if (MaybeTC.getNode() != nullptr) 10407 DAG.setRoot(MaybeTC); 10408 else 10409 HasTailCall = true; 10410 } 10411 10412 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10413 MachineBasicBlock *SwitchMBB, 10414 MachineBasicBlock *DefaultMBB) { 10415 MachineFunction *CurMF = FuncInfo.MF; 10416 MachineBasicBlock *NextMBB = nullptr; 10417 MachineFunction::iterator BBI(W.MBB); 10418 if (++BBI != FuncInfo.MF->end()) 10419 NextMBB = &*BBI; 10420 10421 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10422 10423 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10424 10425 if (Size == 2 && W.MBB == SwitchMBB) { 10426 // If any two of the cases has the same destination, and if one value 10427 // is the same as the other, but has one bit unset that the other has set, 10428 // use bit manipulation to do two compares at once. For example: 10429 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10430 // TODO: This could be extended to merge any 2 cases in switches with 3 10431 // cases. 10432 // TODO: Handle cases where W.CaseBB != SwitchBB. 10433 CaseCluster &Small = *W.FirstCluster; 10434 CaseCluster &Big = *W.LastCluster; 10435 10436 if (Small.Low == Small.High && Big.Low == Big.High && 10437 Small.MBB == Big.MBB) { 10438 const APInt &SmallValue = Small.Low->getValue(); 10439 const APInt &BigValue = Big.Low->getValue(); 10440 10441 // Check that there is only one bit different. 10442 APInt CommonBit = BigValue ^ SmallValue; 10443 if (CommonBit.isPowerOf2()) { 10444 SDValue CondLHS = getValue(Cond); 10445 EVT VT = CondLHS.getValueType(); 10446 SDLoc DL = getCurSDLoc(); 10447 10448 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10449 DAG.getConstant(CommonBit, DL, VT)); 10450 SDValue Cond = DAG.getSetCC( 10451 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10452 ISD::SETEQ); 10453 10454 // Update successor info. 10455 // Both Small and Big will jump to Small.BB, so we sum up the 10456 // probabilities. 10457 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10458 if (BPI) 10459 addSuccessorWithProb( 10460 SwitchMBB, DefaultMBB, 10461 // The default destination is the first successor in IR. 10462 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10463 else 10464 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10465 10466 // Insert the true branch. 10467 SDValue BrCond = 10468 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10469 DAG.getBasicBlock(Small.MBB)); 10470 // Insert the false branch. 10471 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10472 DAG.getBasicBlock(DefaultMBB)); 10473 10474 DAG.setRoot(BrCond); 10475 return; 10476 } 10477 } 10478 } 10479 10480 if (TM.getOptLevel() != CodeGenOpt::None) { 10481 // Here, we order cases by probability so the most likely case will be 10482 // checked first. However, two clusters can have the same probability in 10483 // which case their relative ordering is non-deterministic. So we use Low 10484 // as a tie-breaker as clusters are guaranteed to never overlap. 10485 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10486 [](const CaseCluster &a, const CaseCluster &b) { 10487 return a.Prob != b.Prob ? 10488 a.Prob > b.Prob : 10489 a.Low->getValue().slt(b.Low->getValue()); 10490 }); 10491 10492 // Rearrange the case blocks so that the last one falls through if possible 10493 // without changing the order of probabilities. 10494 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10495 --I; 10496 if (I->Prob > W.LastCluster->Prob) 10497 break; 10498 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10499 std::swap(*I, *W.LastCluster); 10500 break; 10501 } 10502 } 10503 } 10504 10505 // Compute total probability. 10506 BranchProbability DefaultProb = W.DefaultProb; 10507 BranchProbability UnhandledProbs = DefaultProb; 10508 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10509 UnhandledProbs += I->Prob; 10510 10511 MachineBasicBlock *CurMBB = W.MBB; 10512 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10513 bool FallthroughUnreachable = false; 10514 MachineBasicBlock *Fallthrough; 10515 if (I == W.LastCluster) { 10516 // For the last cluster, fall through to the default destination. 10517 Fallthrough = DefaultMBB; 10518 FallthroughUnreachable = isa<UnreachableInst>( 10519 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10520 } else { 10521 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10522 CurMF->insert(BBI, Fallthrough); 10523 // Put Cond in a virtual register to make it available from the new blocks. 10524 ExportFromCurrentBlock(Cond); 10525 } 10526 UnhandledProbs -= I->Prob; 10527 10528 switch (I->Kind) { 10529 case CC_JumpTable: { 10530 // FIXME: Optimize away range check based on pivot comparisons. 10531 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10532 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10533 10534 // The jump block hasn't been inserted yet; insert it here. 10535 MachineBasicBlock *JumpMBB = JT->MBB; 10536 CurMF->insert(BBI, JumpMBB); 10537 10538 auto JumpProb = I->Prob; 10539 auto FallthroughProb = UnhandledProbs; 10540 10541 // If the default statement is a target of the jump table, we evenly 10542 // distribute the default probability to successors of CurMBB. Also 10543 // update the probability on the edge from JumpMBB to Fallthrough. 10544 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10545 SE = JumpMBB->succ_end(); 10546 SI != SE; ++SI) { 10547 if (*SI == DefaultMBB) { 10548 JumpProb += DefaultProb / 2; 10549 FallthroughProb -= DefaultProb / 2; 10550 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10551 JumpMBB->normalizeSuccProbs(); 10552 break; 10553 } 10554 } 10555 10556 if (FallthroughUnreachable) { 10557 // Skip the range check if the fallthrough block is unreachable. 10558 JTH->OmitRangeCheck = true; 10559 } 10560 10561 if (!JTH->OmitRangeCheck) 10562 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10563 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10564 CurMBB->normalizeSuccProbs(); 10565 10566 // The jump table header will be inserted in our current block, do the 10567 // range check, and fall through to our fallthrough block. 10568 JTH->HeaderBB = CurMBB; 10569 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10570 10571 // If we're in the right place, emit the jump table header right now. 10572 if (CurMBB == SwitchMBB) { 10573 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10574 JTH->Emitted = true; 10575 } 10576 break; 10577 } 10578 case CC_BitTests: { 10579 // FIXME: Optimize away range check based on pivot comparisons. 10580 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10581 10582 // The bit test blocks haven't been inserted yet; insert them here. 10583 for (BitTestCase &BTC : BTB->Cases) 10584 CurMF->insert(BBI, BTC.ThisBB); 10585 10586 // Fill in fields of the BitTestBlock. 10587 BTB->Parent = CurMBB; 10588 BTB->Default = Fallthrough; 10589 10590 BTB->DefaultProb = UnhandledProbs; 10591 // If the cases in bit test don't form a contiguous range, we evenly 10592 // distribute the probability on the edge to Fallthrough to two 10593 // successors of CurMBB. 10594 if (!BTB->ContiguousRange) { 10595 BTB->Prob += DefaultProb / 2; 10596 BTB->DefaultProb -= DefaultProb / 2; 10597 } 10598 10599 if (FallthroughUnreachable) { 10600 // Skip the range check if the fallthrough block is unreachable. 10601 BTB->OmitRangeCheck = true; 10602 } 10603 10604 // If we're in the right place, emit the bit test header right now. 10605 if (CurMBB == SwitchMBB) { 10606 visitBitTestHeader(*BTB, SwitchMBB); 10607 BTB->Emitted = true; 10608 } 10609 break; 10610 } 10611 case CC_Range: { 10612 const Value *RHS, *LHS, *MHS; 10613 ISD::CondCode CC; 10614 if (I->Low == I->High) { 10615 // Check Cond == I->Low. 10616 CC = ISD::SETEQ; 10617 LHS = Cond; 10618 RHS=I->Low; 10619 MHS = nullptr; 10620 } else { 10621 // Check I->Low <= Cond <= I->High. 10622 CC = ISD::SETLE; 10623 LHS = I->Low; 10624 MHS = Cond; 10625 RHS = I->High; 10626 } 10627 10628 // If Fallthrough is unreachable, fold away the comparison. 10629 if (FallthroughUnreachable) 10630 CC = ISD::SETTRUE; 10631 10632 // The false probability is the sum of all unhandled cases. 10633 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10634 getCurSDLoc(), I->Prob, UnhandledProbs); 10635 10636 if (CurMBB == SwitchMBB) 10637 visitSwitchCase(CB, SwitchMBB); 10638 else 10639 SL->SwitchCases.push_back(CB); 10640 10641 break; 10642 } 10643 } 10644 CurMBB = Fallthrough; 10645 } 10646 } 10647 10648 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10649 CaseClusterIt First, 10650 CaseClusterIt Last) { 10651 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10652 if (X.Prob != CC.Prob) 10653 return X.Prob > CC.Prob; 10654 10655 // Ties are broken by comparing the case value. 10656 return X.Low->getValue().slt(CC.Low->getValue()); 10657 }); 10658 } 10659 10660 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10661 const SwitchWorkListItem &W, 10662 Value *Cond, 10663 MachineBasicBlock *SwitchMBB) { 10664 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10665 "Clusters not sorted?"); 10666 10667 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10668 10669 // Balance the tree based on branch probabilities to create a near-optimal (in 10670 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10671 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10672 CaseClusterIt LastLeft = W.FirstCluster; 10673 CaseClusterIt FirstRight = W.LastCluster; 10674 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10675 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10676 10677 // Move LastLeft and FirstRight towards each other from opposite directions to 10678 // find a partitioning of the clusters which balances the probability on both 10679 // sides. If LeftProb and RightProb are equal, alternate which side is 10680 // taken to ensure 0-probability nodes are distributed evenly. 10681 unsigned I = 0; 10682 while (LastLeft + 1 < FirstRight) { 10683 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10684 LeftProb += (++LastLeft)->Prob; 10685 else 10686 RightProb += (--FirstRight)->Prob; 10687 I++; 10688 } 10689 10690 while (true) { 10691 // Our binary search tree differs from a typical BST in that ours can have up 10692 // to three values in each leaf. The pivot selection above doesn't take that 10693 // into account, which means the tree might require more nodes and be less 10694 // efficient. We compensate for this here. 10695 10696 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10697 unsigned NumRight = W.LastCluster - FirstRight + 1; 10698 10699 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10700 // If one side has less than 3 clusters, and the other has more than 3, 10701 // consider taking a cluster from the other side. 10702 10703 if (NumLeft < NumRight) { 10704 // Consider moving the first cluster on the right to the left side. 10705 CaseCluster &CC = *FirstRight; 10706 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10707 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10708 if (LeftSideRank <= RightSideRank) { 10709 // Moving the cluster to the left does not demote it. 10710 ++LastLeft; 10711 ++FirstRight; 10712 continue; 10713 } 10714 } else { 10715 assert(NumRight < NumLeft); 10716 // Consider moving the last element on the left to the right side. 10717 CaseCluster &CC = *LastLeft; 10718 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10719 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10720 if (RightSideRank <= LeftSideRank) { 10721 // Moving the cluster to the right does not demot it. 10722 --LastLeft; 10723 --FirstRight; 10724 continue; 10725 } 10726 } 10727 } 10728 break; 10729 } 10730 10731 assert(LastLeft + 1 == FirstRight); 10732 assert(LastLeft >= W.FirstCluster); 10733 assert(FirstRight <= W.LastCluster); 10734 10735 // Use the first element on the right as pivot since we will make less-than 10736 // comparisons against it. 10737 CaseClusterIt PivotCluster = FirstRight; 10738 assert(PivotCluster > W.FirstCluster); 10739 assert(PivotCluster <= W.LastCluster); 10740 10741 CaseClusterIt FirstLeft = W.FirstCluster; 10742 CaseClusterIt LastRight = W.LastCluster; 10743 10744 const ConstantInt *Pivot = PivotCluster->Low; 10745 10746 // New blocks will be inserted immediately after the current one. 10747 MachineFunction::iterator BBI(W.MBB); 10748 ++BBI; 10749 10750 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10751 // we can branch to its destination directly if it's squeezed exactly in 10752 // between the known lower bound and Pivot - 1. 10753 MachineBasicBlock *LeftMBB; 10754 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10755 FirstLeft->Low == W.GE && 10756 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10757 LeftMBB = FirstLeft->MBB; 10758 } else { 10759 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10760 FuncInfo.MF->insert(BBI, LeftMBB); 10761 WorkList.push_back( 10762 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10763 // Put Cond in a virtual register to make it available from the new blocks. 10764 ExportFromCurrentBlock(Cond); 10765 } 10766 10767 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10768 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10769 // directly if RHS.High equals the current upper bound. 10770 MachineBasicBlock *RightMBB; 10771 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10772 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10773 RightMBB = FirstRight->MBB; 10774 } else { 10775 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10776 FuncInfo.MF->insert(BBI, RightMBB); 10777 WorkList.push_back( 10778 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10779 // Put Cond in a virtual register to make it available from the new blocks. 10780 ExportFromCurrentBlock(Cond); 10781 } 10782 10783 // Create the CaseBlock record that will be used to lower the branch. 10784 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10785 getCurSDLoc(), LeftProb, RightProb); 10786 10787 if (W.MBB == SwitchMBB) 10788 visitSwitchCase(CB, SwitchMBB); 10789 else 10790 SL->SwitchCases.push_back(CB); 10791 } 10792 10793 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10794 // from the swith statement. 10795 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10796 BranchProbability PeeledCaseProb) { 10797 if (PeeledCaseProb == BranchProbability::getOne()) 10798 return BranchProbability::getZero(); 10799 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10800 10801 uint32_t Numerator = CaseProb.getNumerator(); 10802 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10803 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10804 } 10805 10806 // Try to peel the top probability case if it exceeds the threshold. 10807 // Return current MachineBasicBlock for the switch statement if the peeling 10808 // does not occur. 10809 // If the peeling is performed, return the newly created MachineBasicBlock 10810 // for the peeled switch statement. Also update Clusters to remove the peeled 10811 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10812 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10813 const SwitchInst &SI, CaseClusterVector &Clusters, 10814 BranchProbability &PeeledCaseProb) { 10815 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10816 // Don't perform if there is only one cluster or optimizing for size. 10817 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10818 TM.getOptLevel() == CodeGenOpt::None || 10819 SwitchMBB->getParent()->getFunction().hasMinSize()) 10820 return SwitchMBB; 10821 10822 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10823 unsigned PeeledCaseIndex = 0; 10824 bool SwitchPeeled = false; 10825 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10826 CaseCluster &CC = Clusters[Index]; 10827 if (CC.Prob < TopCaseProb) 10828 continue; 10829 TopCaseProb = CC.Prob; 10830 PeeledCaseIndex = Index; 10831 SwitchPeeled = true; 10832 } 10833 if (!SwitchPeeled) 10834 return SwitchMBB; 10835 10836 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10837 << TopCaseProb << "\n"); 10838 10839 // Record the MBB for the peeled switch statement. 10840 MachineFunction::iterator BBI(SwitchMBB); 10841 ++BBI; 10842 MachineBasicBlock *PeeledSwitchMBB = 10843 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10844 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10845 10846 ExportFromCurrentBlock(SI.getCondition()); 10847 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10848 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10849 nullptr, nullptr, TopCaseProb.getCompl()}; 10850 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10851 10852 Clusters.erase(PeeledCaseIt); 10853 for (CaseCluster &CC : Clusters) { 10854 LLVM_DEBUG( 10855 dbgs() << "Scale the probablity for one cluster, before scaling: " 10856 << CC.Prob << "\n"); 10857 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10858 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10859 } 10860 PeeledCaseProb = TopCaseProb; 10861 return PeeledSwitchMBB; 10862 } 10863 10864 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10865 // Extract cases from the switch. 10866 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10867 CaseClusterVector Clusters; 10868 Clusters.reserve(SI.getNumCases()); 10869 for (auto I : SI.cases()) { 10870 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10871 const ConstantInt *CaseVal = I.getCaseValue(); 10872 BranchProbability Prob = 10873 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10874 : BranchProbability(1, SI.getNumCases() + 1); 10875 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10876 } 10877 10878 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10879 10880 // Cluster adjacent cases with the same destination. We do this at all 10881 // optimization levels because it's cheap to do and will make codegen faster 10882 // if there are many clusters. 10883 sortAndRangeify(Clusters); 10884 10885 // The branch probablity of the peeled case. 10886 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10887 MachineBasicBlock *PeeledSwitchMBB = 10888 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10889 10890 // If there is only the default destination, jump there directly. 10891 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10892 if (Clusters.empty()) { 10893 assert(PeeledSwitchMBB == SwitchMBB); 10894 SwitchMBB->addSuccessor(DefaultMBB); 10895 if (DefaultMBB != NextBlock(SwitchMBB)) { 10896 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10897 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10898 } 10899 return; 10900 } 10901 10902 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10903 SL->findBitTestClusters(Clusters, &SI); 10904 10905 LLVM_DEBUG({ 10906 dbgs() << "Case clusters: "; 10907 for (const CaseCluster &C : Clusters) { 10908 if (C.Kind == CC_JumpTable) 10909 dbgs() << "JT:"; 10910 if (C.Kind == CC_BitTests) 10911 dbgs() << "BT:"; 10912 10913 C.Low->getValue().print(dbgs(), true); 10914 if (C.Low != C.High) { 10915 dbgs() << '-'; 10916 C.High->getValue().print(dbgs(), true); 10917 } 10918 dbgs() << ' '; 10919 } 10920 dbgs() << '\n'; 10921 }); 10922 10923 assert(!Clusters.empty()); 10924 SwitchWorkList WorkList; 10925 CaseClusterIt First = Clusters.begin(); 10926 CaseClusterIt Last = Clusters.end() - 1; 10927 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10928 // Scale the branchprobability for DefaultMBB if the peel occurs and 10929 // DefaultMBB is not replaced. 10930 if (PeeledCaseProb != BranchProbability::getZero() && 10931 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10932 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10933 WorkList.push_back( 10934 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10935 10936 while (!WorkList.empty()) { 10937 SwitchWorkListItem W = WorkList.pop_back_val(); 10938 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10939 10940 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10941 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10942 // For optimized builds, lower large range as a balanced binary tree. 10943 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10944 continue; 10945 } 10946 10947 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10948 } 10949 } 10950 10951 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 10952 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10953 auto DL = getCurSDLoc(); 10954 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10955 EVT OpVT = 10956 TLI.getTypeToTransformTo(*DAG.getContext(), ResultVT.getScalarType()); 10957 SDValue Step = DAG.getConstant(1, DL, OpVT); 10958 setValue(&I, DAG.getStepVector(DL, ResultVT, Step)); 10959 } 10960 10961 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 10962 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10963 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10964 10965 SDLoc DL = getCurSDLoc(); 10966 SDValue V = getValue(I.getOperand(0)); 10967 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 10968 10969 if (VT.isScalableVector()) { 10970 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 10971 return; 10972 } 10973 10974 // Use VECTOR_SHUFFLE for the fixed-length vector 10975 // to maintain existing behavior. 10976 SmallVector<int, 8> Mask; 10977 unsigned NumElts = VT.getVectorMinNumElements(); 10978 for (unsigned i = 0; i != NumElts; ++i) 10979 Mask.push_back(NumElts - 1 - i); 10980 10981 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 10982 } 10983 10984 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10985 SmallVector<EVT, 4> ValueVTs; 10986 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10987 ValueVTs); 10988 unsigned NumValues = ValueVTs.size(); 10989 if (NumValues == 0) return; 10990 10991 SmallVector<SDValue, 4> Values(NumValues); 10992 SDValue Op = getValue(I.getOperand(0)); 10993 10994 for (unsigned i = 0; i != NumValues; ++i) 10995 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10996 SDValue(Op.getNode(), Op.getResNo() + i)); 10997 10998 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10999 DAG.getVTList(ValueVTs), Values)); 11000 } 11001 11002 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11003 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11004 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11005 11006 SDLoc DL = getCurSDLoc(); 11007 SDValue V1 = getValue(I.getOperand(0)); 11008 SDValue V2 = getValue(I.getOperand(1)); 11009 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11010 11011 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11012 if (VT.isScalableVector()) { 11013 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11014 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11015 DAG.getConstant(Imm, DL, IdxVT))); 11016 return; 11017 } 11018 11019 unsigned NumElts = VT.getVectorNumElements(); 11020 11021 if ((-Imm > NumElts) || (Imm >= NumElts)) { 11022 // Result is undefined if immediate is out-of-bounds. 11023 setValue(&I, DAG.getUNDEF(VT)); 11024 return; 11025 } 11026 11027 uint64_t Idx = (NumElts + Imm) % NumElts; 11028 11029 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11030 SmallVector<int, 8> Mask; 11031 for (unsigned i = 0; i < NumElts; ++i) 11032 Mask.push_back(Idx + i); 11033 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11034 } 11035