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, 611 SDValue Val, const SDLoc &DL, EVT PartVT) { 612 if (!PartVT.isFixedLengthVector()) 613 return SDValue(); 614 615 EVT ValueVT = Val.getValueType(); 616 unsigned PartNumElts = PartVT.getVectorNumElements(); 617 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 618 if (PartNumElts > ValueNumElts && 619 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 620 EVT ElementVT = PartVT.getVectorElementType(); 621 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 622 // undef elements. 623 SmallVector<SDValue, 16> Ops; 624 DAG.ExtractVectorElements(Val, Ops); 625 SDValue EltUndef = DAG.getUNDEF(ElementVT); 626 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 627 Ops.push_back(EltUndef); 628 629 // FIXME: Use CONCAT for 2x -> 4x. 630 return DAG.getBuildVector(PartVT, DL, Ops); 631 } 632 633 return SDValue(); 634 } 635 636 /// getCopyToPartsVector - Create a series of nodes that contain the specified 637 /// value split into legal parts. 638 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 639 SDValue Val, SDValue *Parts, unsigned NumParts, 640 MVT PartVT, const Value *V, 641 Optional<CallingConv::ID> CallConv) { 642 EVT ValueVT = Val.getValueType(); 643 assert(ValueVT.isVector() && "Not a vector"); 644 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 645 const bool IsABIRegCopy = CallConv.hasValue(); 646 647 if (NumParts == 1) { 648 EVT PartEVT = PartVT; 649 if (PartEVT == ValueVT) { 650 // Nothing to do. 651 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 652 // Bitconvert vector->vector case. 653 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 654 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 655 Val = Widened; 656 } else if (PartVT.isVector() && 657 PartEVT.getVectorElementType().bitsGE( 658 ValueVT.getVectorElementType()) && 659 PartEVT.getVectorElementCount() == 660 ValueVT.getVectorElementCount()) { 661 662 // Promoted vector extract 663 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 664 } else { 665 if (ValueVT.getVectorElementCount().isScalar()) { 666 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 667 DAG.getVectorIdxConstant(0, DL)); 668 } else { 669 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 670 assert(PartVT.getFixedSizeInBits() > ValueSize && 671 "lossy conversion of vector to scalar type"); 672 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 673 Val = DAG.getBitcast(IntermediateType, Val); 674 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 675 } 676 } 677 678 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 679 Parts[0] = Val; 680 return; 681 } 682 683 // Handle a multi-element vector. 684 EVT IntermediateVT; 685 MVT RegisterVT; 686 unsigned NumIntermediates; 687 unsigned NumRegs; 688 if (IsABIRegCopy) { 689 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 690 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 691 NumIntermediates, RegisterVT); 692 } else { 693 NumRegs = 694 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 695 NumIntermediates, RegisterVT); 696 } 697 698 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 699 NumParts = NumRegs; // Silence a compiler warning. 700 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 701 702 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 703 "Mixing scalable and fixed vectors when copying in parts"); 704 705 Optional<ElementCount> DestEltCnt; 706 707 if (IntermediateVT.isVector()) 708 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 709 else 710 DestEltCnt = ElementCount::getFixed(NumIntermediates); 711 712 EVT BuiltVectorTy = EVT::getVectorVT( 713 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 714 715 if (ValueVT == BuiltVectorTy) { 716 // Nothing to do. 717 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 718 // Bitconvert vector->vector case. 719 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 720 } else if (SDValue Widened = 721 widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 722 Val = Widened; 723 } else if (BuiltVectorTy.getVectorElementType().bitsGE( 724 ValueVT.getVectorElementType()) && 725 BuiltVectorTy.getVectorElementCount() == 726 ValueVT.getVectorElementCount()) { 727 // Promoted vector extract 728 Val = DAG.getAnyExtOrTrunc(Val, DL, BuiltVectorTy); 729 } 730 731 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 732 733 // Split the vector into intermediate operands. 734 SmallVector<SDValue, 8> Ops(NumIntermediates); 735 for (unsigned i = 0; i != NumIntermediates; ++i) { 736 if (IntermediateVT.isVector()) { 737 // This does something sensible for scalable vectors - see the 738 // definition of EXTRACT_SUBVECTOR for further details. 739 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 740 Ops[i] = 741 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 742 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 743 } else { 744 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 745 DAG.getVectorIdxConstant(i, DL)); 746 } 747 } 748 749 // Split the intermediate operands into legal parts. 750 if (NumParts == NumIntermediates) { 751 // If the register was not expanded, promote or copy the value, 752 // as appropriate. 753 for (unsigned i = 0; i != NumParts; ++i) 754 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 755 } else if (NumParts > 0) { 756 // If the intermediate type was expanded, split each the value into 757 // legal parts. 758 assert(NumIntermediates != 0 && "division by zero"); 759 assert(NumParts % NumIntermediates == 0 && 760 "Must expand into a divisible number of parts!"); 761 unsigned Factor = NumParts / NumIntermediates; 762 for (unsigned i = 0; i != NumIntermediates; ++i) 763 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 764 CallConv); 765 } 766 } 767 768 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 769 EVT valuevt, Optional<CallingConv::ID> CC) 770 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 771 RegCount(1, regs.size()), CallConv(CC) {} 772 773 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 774 const DataLayout &DL, unsigned Reg, Type *Ty, 775 Optional<CallingConv::ID> CC) { 776 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 777 778 CallConv = CC; 779 780 for (EVT ValueVT : ValueVTs) { 781 unsigned NumRegs = 782 isABIMangled() 783 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 784 : TLI.getNumRegisters(Context, ValueVT); 785 MVT RegisterVT = 786 isABIMangled() 787 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 788 : TLI.getRegisterType(Context, ValueVT); 789 for (unsigned i = 0; i != NumRegs; ++i) 790 Regs.push_back(Reg + i); 791 RegVTs.push_back(RegisterVT); 792 RegCount.push_back(NumRegs); 793 Reg += NumRegs; 794 } 795 } 796 797 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 798 FunctionLoweringInfo &FuncInfo, 799 const SDLoc &dl, SDValue &Chain, 800 SDValue *Flag, const Value *V) const { 801 // A Value with type {} or [0 x %t] needs no registers. 802 if (ValueVTs.empty()) 803 return SDValue(); 804 805 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 806 807 // Assemble the legal parts into the final values. 808 SmallVector<SDValue, 4> Values(ValueVTs.size()); 809 SmallVector<SDValue, 8> Parts; 810 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 811 // Copy the legal parts from the registers. 812 EVT ValueVT = ValueVTs[Value]; 813 unsigned NumRegs = RegCount[Value]; 814 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 815 *DAG.getContext(), 816 CallConv.getValue(), RegVTs[Value]) 817 : RegVTs[Value]; 818 819 Parts.resize(NumRegs); 820 for (unsigned i = 0; i != NumRegs; ++i) { 821 SDValue P; 822 if (!Flag) { 823 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 824 } else { 825 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 826 *Flag = P.getValue(2); 827 } 828 829 Chain = P.getValue(1); 830 Parts[i] = P; 831 832 // If the source register was virtual and if we know something about it, 833 // add an assert node. 834 if (!Register::isVirtualRegister(Regs[Part + i]) || 835 !RegisterVT.isInteger()) 836 continue; 837 838 const FunctionLoweringInfo::LiveOutInfo *LOI = 839 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 840 if (!LOI) 841 continue; 842 843 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 844 unsigned NumSignBits = LOI->NumSignBits; 845 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 846 847 if (NumZeroBits == RegSize) { 848 // The current value is a zero. 849 // Explicitly express that as it would be easier for 850 // optimizations to kick in. 851 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 852 continue; 853 } 854 855 // FIXME: We capture more information than the dag can represent. For 856 // now, just use the tightest assertzext/assertsext possible. 857 bool isSExt; 858 EVT FromVT(MVT::Other); 859 if (NumZeroBits) { 860 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 861 isSExt = false; 862 } else if (NumSignBits > 1) { 863 FromVT = 864 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 865 isSExt = true; 866 } else { 867 continue; 868 } 869 // Add an assertion node. 870 assert(FromVT != MVT::Other); 871 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 872 RegisterVT, P, DAG.getValueType(FromVT)); 873 } 874 875 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 876 RegisterVT, ValueVT, V, CallConv); 877 Part += NumRegs; 878 Parts.clear(); 879 } 880 881 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 882 } 883 884 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 885 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 886 const Value *V, 887 ISD::NodeType PreferredExtendType) const { 888 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 889 ISD::NodeType ExtendKind = PreferredExtendType; 890 891 // Get the list of the values's legal parts. 892 unsigned NumRegs = Regs.size(); 893 SmallVector<SDValue, 8> Parts(NumRegs); 894 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 895 unsigned NumParts = RegCount[Value]; 896 897 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 898 *DAG.getContext(), 899 CallConv.getValue(), RegVTs[Value]) 900 : RegVTs[Value]; 901 902 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 903 ExtendKind = ISD::ZERO_EXTEND; 904 905 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 906 NumParts, RegisterVT, V, CallConv, ExtendKind); 907 Part += NumParts; 908 } 909 910 // Copy the parts into the registers. 911 SmallVector<SDValue, 8> Chains(NumRegs); 912 for (unsigned i = 0; i != NumRegs; ++i) { 913 SDValue Part; 914 if (!Flag) { 915 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 916 } else { 917 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 918 *Flag = Part.getValue(1); 919 } 920 921 Chains[i] = Part.getValue(0); 922 } 923 924 if (NumRegs == 1 || Flag) 925 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 926 // flagged to it. That is the CopyToReg nodes and the user are considered 927 // a single scheduling unit. If we create a TokenFactor and return it as 928 // chain, then the TokenFactor is both a predecessor (operand) of the 929 // user as well as a successor (the TF operands are flagged to the user). 930 // c1, f1 = CopyToReg 931 // c2, f2 = CopyToReg 932 // c3 = TokenFactor c1, c2 933 // ... 934 // = op c3, ..., f2 935 Chain = Chains[NumRegs-1]; 936 else 937 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 938 } 939 940 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 941 unsigned MatchingIdx, const SDLoc &dl, 942 SelectionDAG &DAG, 943 std::vector<SDValue> &Ops) const { 944 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 945 946 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 947 if (HasMatching) 948 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 949 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 950 // Put the register class of the virtual registers in the flag word. That 951 // way, later passes can recompute register class constraints for inline 952 // assembly as well as normal instructions. 953 // Don't do this for tied operands that can use the regclass information 954 // from the def. 955 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 956 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 957 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 958 } 959 960 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 961 Ops.push_back(Res); 962 963 if (Code == InlineAsm::Kind_Clobber) { 964 // Clobbers should always have a 1:1 mapping with registers, and may 965 // reference registers that have illegal (e.g. vector) types. Hence, we 966 // shouldn't try to apply any sort of splitting logic to them. 967 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 968 "No 1:1 mapping from clobbers to regs?"); 969 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 970 (void)SP; 971 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 972 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 973 assert( 974 (Regs[I] != SP || 975 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 976 "If we clobbered the stack pointer, MFI should know about it."); 977 } 978 return; 979 } 980 981 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 982 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 983 MVT RegisterVT = RegVTs[Value]; 984 for (unsigned i = 0; i != NumRegs; ++i) { 985 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 986 unsigned TheReg = Regs[Reg++]; 987 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 988 } 989 } 990 } 991 992 SmallVector<std::pair<unsigned, TypeSize>, 4> 993 RegsForValue::getRegsAndSizes() const { 994 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 995 unsigned I = 0; 996 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 997 unsigned RegCount = std::get<0>(CountAndVT); 998 MVT RegisterVT = std::get<1>(CountAndVT); 999 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1000 for (unsigned E = I + RegCount; I != E; ++I) 1001 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1002 } 1003 return OutVec; 1004 } 1005 1006 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1007 const TargetLibraryInfo *li) { 1008 AA = aa; 1009 GFI = gfi; 1010 LibInfo = li; 1011 DL = &DAG.getDataLayout(); 1012 Context = DAG.getContext(); 1013 LPadToCallSiteMap.clear(); 1014 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1015 } 1016 1017 void SelectionDAGBuilder::clear() { 1018 NodeMap.clear(); 1019 UnusedArgNodeMap.clear(); 1020 PendingLoads.clear(); 1021 PendingExports.clear(); 1022 PendingConstrainedFP.clear(); 1023 PendingConstrainedFPStrict.clear(); 1024 CurInst = nullptr; 1025 HasTailCall = false; 1026 SDNodeOrder = LowestSDNodeOrder; 1027 StatepointLowering.clear(); 1028 } 1029 1030 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1031 DanglingDebugInfoMap.clear(); 1032 } 1033 1034 // Update DAG root to include dependencies on Pending chains. 1035 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1036 SDValue Root = DAG.getRoot(); 1037 1038 if (Pending.empty()) 1039 return Root; 1040 1041 // Add current root to PendingChains, unless we already indirectly 1042 // depend on it. 1043 if (Root.getOpcode() != ISD::EntryToken) { 1044 unsigned i = 0, e = Pending.size(); 1045 for (; i != e; ++i) { 1046 assert(Pending[i].getNode()->getNumOperands() > 1); 1047 if (Pending[i].getNode()->getOperand(0) == Root) 1048 break; // Don't add the root if we already indirectly depend on it. 1049 } 1050 1051 if (i == e) 1052 Pending.push_back(Root); 1053 } 1054 1055 if (Pending.size() == 1) 1056 Root = Pending[0]; 1057 else 1058 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1059 1060 DAG.setRoot(Root); 1061 Pending.clear(); 1062 return Root; 1063 } 1064 1065 SDValue SelectionDAGBuilder::getMemoryRoot() { 1066 return updateRoot(PendingLoads); 1067 } 1068 1069 SDValue SelectionDAGBuilder::getRoot() { 1070 // Chain up all pending constrained intrinsics together with all 1071 // pending loads, by simply appending them to PendingLoads and 1072 // then calling getMemoryRoot(). 1073 PendingLoads.reserve(PendingLoads.size() + 1074 PendingConstrainedFP.size() + 1075 PendingConstrainedFPStrict.size()); 1076 PendingLoads.append(PendingConstrainedFP.begin(), 1077 PendingConstrainedFP.end()); 1078 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1079 PendingConstrainedFPStrict.end()); 1080 PendingConstrainedFP.clear(); 1081 PendingConstrainedFPStrict.clear(); 1082 return getMemoryRoot(); 1083 } 1084 1085 SDValue SelectionDAGBuilder::getControlRoot() { 1086 // We need to emit pending fpexcept.strict constrained intrinsics, 1087 // so append them to the PendingExports list. 1088 PendingExports.append(PendingConstrainedFPStrict.begin(), 1089 PendingConstrainedFPStrict.end()); 1090 PendingConstrainedFPStrict.clear(); 1091 return updateRoot(PendingExports); 1092 } 1093 1094 void SelectionDAGBuilder::visit(const Instruction &I) { 1095 // Set up outgoing PHI node register values before emitting the terminator. 1096 if (I.isTerminator()) { 1097 HandlePHINodesInSuccessorBlocks(I.getParent()); 1098 } 1099 1100 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1101 if (!isa<DbgInfoIntrinsic>(I)) 1102 ++SDNodeOrder; 1103 1104 CurInst = &I; 1105 1106 visit(I.getOpcode(), I); 1107 1108 if (!I.isTerminator() && !HasTailCall && 1109 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1110 CopyToExportRegsIfNeeded(&I); 1111 1112 CurInst = nullptr; 1113 } 1114 1115 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1116 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1117 } 1118 1119 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1120 // Note: this doesn't use InstVisitor, because it has to work with 1121 // ConstantExpr's in addition to instructions. 1122 switch (Opcode) { 1123 default: llvm_unreachable("Unknown instruction type encountered!"); 1124 // Build the switch statement using the Instruction.def file. 1125 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1126 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1127 #include "llvm/IR/Instruction.def" 1128 } 1129 } 1130 1131 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1132 DebugLoc DL, unsigned Order) { 1133 // We treat variadic dbg_values differently at this stage. 1134 if (DI->hasArgList()) { 1135 // For variadic dbg_values we will now insert an undef. 1136 // FIXME: We can potentially recover these! 1137 SmallVector<SDDbgOperand, 2> Locs; 1138 for (const Value *V : DI->getValues()) { 1139 auto Undef = UndefValue::get(V->getType()); 1140 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1141 } 1142 SDDbgValue *SDV = DAG.getDbgValueList( 1143 DI->getVariable(), DI->getExpression(), Locs, {}, 1144 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1145 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1146 } else { 1147 // TODO: Dangling debug info will eventually either be resolved or produce 1148 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1149 // between the original dbg.value location and its resolved DBG_VALUE, 1150 // which we should ideally fill with an extra Undef DBG_VALUE. 1151 assert(DI->getNumVariableLocationOps() == 1 && 1152 "DbgValueInst without an ArgList should have a single location " 1153 "operand."); 1154 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1155 } 1156 } 1157 1158 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1159 const DIExpression *Expr) { 1160 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1161 const DbgValueInst *DI = DDI.getDI(); 1162 DIVariable *DanglingVariable = DI->getVariable(); 1163 DIExpression *DanglingExpr = DI->getExpression(); 1164 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1165 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1166 return true; 1167 } 1168 return false; 1169 }; 1170 1171 for (auto &DDIMI : DanglingDebugInfoMap) { 1172 DanglingDebugInfoVector &DDIV = DDIMI.second; 1173 1174 // If debug info is to be dropped, run it through final checks to see 1175 // whether it can be salvaged. 1176 for (auto &DDI : DDIV) 1177 if (isMatchingDbgValue(DDI)) 1178 salvageUnresolvedDbgValue(DDI); 1179 1180 erase_if(DDIV, isMatchingDbgValue); 1181 } 1182 } 1183 1184 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1185 // generate the debug data structures now that we've seen its definition. 1186 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1187 SDValue Val) { 1188 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1189 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1190 return; 1191 1192 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1193 for (auto &DDI : DDIV) { 1194 const DbgValueInst *DI = DDI.getDI(); 1195 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1196 assert(DI && "Ill-formed DanglingDebugInfo"); 1197 DebugLoc dl = DDI.getdl(); 1198 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1199 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1200 DILocalVariable *Variable = DI->getVariable(); 1201 DIExpression *Expr = DI->getExpression(); 1202 assert(Variable->isValidLocationForIntrinsic(dl) && 1203 "Expected inlined-at fields to agree"); 1204 SDDbgValue *SDV; 1205 if (Val.getNode()) { 1206 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1207 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1208 // we couldn't resolve it directly when examining the DbgValue intrinsic 1209 // in the first place we should not be more successful here). Unless we 1210 // have some test case that prove this to be correct we should avoid 1211 // calling EmitFuncArgumentDbgValue here. 1212 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1213 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1214 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1215 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1216 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1217 // inserted after the definition of Val when emitting the instructions 1218 // after ISel. An alternative could be to teach 1219 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1220 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1221 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1222 << ValSDNodeOrder << "\n"); 1223 SDV = getDbgValue(Val, Variable, Expr, dl, 1224 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1225 DAG.AddDbgValue(SDV, false); 1226 } else 1227 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1228 << "in EmitFuncArgumentDbgValue\n"); 1229 } else { 1230 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1231 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1232 auto SDV = 1233 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1234 DAG.AddDbgValue(SDV, false); 1235 } 1236 } 1237 DDIV.clear(); 1238 } 1239 1240 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1241 assert(!DDI.getDI()->hasArgList() && 1242 "Not implemented for variadic dbg_values"); 1243 Value *V = DDI.getDI()->getValue(0); 1244 DILocalVariable *Var = DDI.getDI()->getVariable(); 1245 DIExpression *Expr = DDI.getDI()->getExpression(); 1246 DebugLoc DL = DDI.getdl(); 1247 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1248 unsigned SDOrder = DDI.getSDNodeOrder(); 1249 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1250 // that DW_OP_stack_value is desired. 1251 assert(isa<DbgValueInst>(DDI.getDI())); 1252 bool StackValue = true; 1253 1254 // Can this Value can be encoded without any further work? 1255 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1256 return; 1257 1258 // Attempt to salvage back through as many instructions as possible. Bail if 1259 // a non-instruction is seen, such as a constant expression or global 1260 // variable. FIXME: Further work could recover those too. 1261 while (isa<Instruction>(V)) { 1262 Instruction &VAsInst = *cast<Instruction>(V); 1263 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1264 1265 // If we cannot salvage any further, and haven't yet found a suitable debug 1266 // expression, bail out. 1267 if (!NewExpr) 1268 break; 1269 1270 // New value and expr now represent this debuginfo. 1271 V = VAsInst.getOperand(0); 1272 Expr = NewExpr; 1273 1274 // Some kind of simplification occurred: check whether the operand of the 1275 // salvaged debug expression can be encoded in this DAG. 1276 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1277 /*IsVariadic=*/false)) { 1278 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1279 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1280 return; 1281 } 1282 } 1283 1284 // This was the final opportunity to salvage this debug information, and it 1285 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1286 // any earlier variable location. 1287 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1288 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1289 DAG.AddDbgValue(SDV, false); 1290 1291 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1292 << "\n"); 1293 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1294 << "\n"); 1295 } 1296 1297 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1298 DILocalVariable *Var, 1299 DIExpression *Expr, DebugLoc dl, 1300 DebugLoc InstDL, unsigned Order, 1301 bool IsVariadic) { 1302 if (Values.empty()) 1303 return true; 1304 SDDbgValue::LocOpVector LocationOps; 1305 SDDbgValue::SDNodeVector Dependencies; 1306 for (const Value *V : Values) { 1307 // Constant value. 1308 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1309 isa<ConstantPointerNull>(V)) { 1310 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1311 continue; 1312 } 1313 1314 // If the Value is a frame index, we can create a FrameIndex debug value 1315 // without relying on the DAG at all. 1316 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1317 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1318 if (SI != FuncInfo.StaticAllocaMap.end()) { 1319 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1320 continue; 1321 } 1322 } 1323 1324 // Do not use getValue() in here; we don't want to generate code at 1325 // this point if it hasn't been done yet. 1326 SDValue N = NodeMap[V]; 1327 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1328 N = UnusedArgNodeMap[V]; 1329 if (N.getNode()) { 1330 // Only emit func arg dbg value for non-variadic dbg.values for now. 1331 if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1332 return true; 1333 Dependencies.push_back(N.getNode()); 1334 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1335 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1336 // describe stack slot locations. 1337 // 1338 // Consider "int x = 0; int *px = &x;". There are two kinds of 1339 // interesting debug values here after optimization: 1340 // 1341 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1342 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1343 // 1344 // Both describe the direct values of their associated variables. 1345 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1346 continue; 1347 } 1348 LocationOps.emplace_back( 1349 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1350 continue; 1351 } 1352 1353 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1354 // Special rules apply for the first dbg.values of parameter variables in a 1355 // function. Identify them by the fact they reference Argument Values, that 1356 // they're parameters, and they are parameters of the current function. We 1357 // need to let them dangle until they get an SDNode. 1358 bool IsParamOfFunc = 1359 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1360 if (IsParamOfFunc) 1361 return false; 1362 1363 // The value is not used in this block yet (or it would have an SDNode). 1364 // We still want the value to appear for the user if possible -- if it has 1365 // an associated VReg, we can refer to that instead. 1366 auto VMI = FuncInfo.ValueMap.find(V); 1367 if (VMI != FuncInfo.ValueMap.end()) { 1368 unsigned Reg = VMI->second; 1369 // If this is a PHI node, it may be split up into several MI PHI nodes 1370 // (in FunctionLoweringInfo::set). 1371 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1372 V->getType(), None); 1373 if (RFV.occupiesMultipleRegs()) { 1374 // FIXME: We could potentially support variadic dbg_values here. 1375 if (IsVariadic) 1376 return false; 1377 unsigned Offset = 0; 1378 unsigned BitsToDescribe = 0; 1379 if (auto VarSize = Var->getSizeInBits()) 1380 BitsToDescribe = *VarSize; 1381 if (auto Fragment = Expr->getFragmentInfo()) 1382 BitsToDescribe = Fragment->SizeInBits; 1383 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1384 // Bail out if all bits are described already. 1385 if (Offset >= BitsToDescribe) 1386 break; 1387 // TODO: handle scalable vectors. 1388 unsigned RegisterSize = RegAndSize.second; 1389 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1390 ? BitsToDescribe - Offset 1391 : RegisterSize; 1392 auto FragmentExpr = DIExpression::createFragmentExpression( 1393 Expr, Offset, FragmentSize); 1394 if (!FragmentExpr) 1395 continue; 1396 SDDbgValue *SDV = DAG.getVRegDbgValue( 1397 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1398 DAG.AddDbgValue(SDV, false); 1399 Offset += RegisterSize; 1400 } 1401 return true; 1402 } 1403 // We can use simple vreg locations for variadic dbg_values as well. 1404 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1405 continue; 1406 } 1407 // We failed to create a SDDbgOperand for V. 1408 return false; 1409 } 1410 1411 // We have created a SDDbgOperand for each Value in Values. 1412 // Should use Order instead of SDNodeOrder? 1413 assert(!LocationOps.empty()); 1414 SDDbgValue *SDV = 1415 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1416 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1417 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1418 return true; 1419 } 1420 1421 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1422 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1423 for (auto &Pair : DanglingDebugInfoMap) 1424 for (auto &DDI : Pair.second) 1425 salvageUnresolvedDbgValue(DDI); 1426 clearDanglingDebugInfo(); 1427 } 1428 1429 /// getCopyFromRegs - If there was virtual register allocated for the value V 1430 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1431 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1432 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1433 SDValue Result; 1434 1435 if (It != FuncInfo.ValueMap.end()) { 1436 Register InReg = It->second; 1437 1438 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1439 DAG.getDataLayout(), InReg, Ty, 1440 None); // This is not an ABI copy. 1441 SDValue Chain = DAG.getEntryNode(); 1442 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1443 V); 1444 resolveDanglingDebugInfo(V, Result); 1445 } 1446 1447 return Result; 1448 } 1449 1450 /// getValue - Return an SDValue for the given Value. 1451 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1452 // If we already have an SDValue for this value, use it. It's important 1453 // to do this first, so that we don't create a CopyFromReg if we already 1454 // have a regular SDValue. 1455 SDValue &N = NodeMap[V]; 1456 if (N.getNode()) return N; 1457 1458 // If there's a virtual register allocated and initialized for this 1459 // value, use it. 1460 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1461 return copyFromReg; 1462 1463 // Otherwise create a new SDValue and remember it. 1464 SDValue Val = getValueImpl(V); 1465 NodeMap[V] = Val; 1466 resolveDanglingDebugInfo(V, Val); 1467 return Val; 1468 } 1469 1470 /// getNonRegisterValue - Return an SDValue for the given Value, but 1471 /// don't look in FuncInfo.ValueMap for a virtual register. 1472 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1473 // If we already have an SDValue for this value, use it. 1474 SDValue &N = NodeMap[V]; 1475 if (N.getNode()) { 1476 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1477 // Remove the debug location from the node as the node is about to be used 1478 // in a location which may differ from the original debug location. This 1479 // is relevant to Constant and ConstantFP nodes because they can appear 1480 // as constant expressions inside PHI nodes. 1481 N->setDebugLoc(DebugLoc()); 1482 } 1483 return N; 1484 } 1485 1486 // Otherwise create a new SDValue and remember it. 1487 SDValue Val = getValueImpl(V); 1488 NodeMap[V] = Val; 1489 resolveDanglingDebugInfo(V, Val); 1490 return Val; 1491 } 1492 1493 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1494 /// Create an SDValue for the given value. 1495 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1496 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1497 1498 if (const Constant *C = dyn_cast<Constant>(V)) { 1499 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1500 1501 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1502 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1503 1504 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1505 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1506 1507 if (isa<ConstantPointerNull>(C)) { 1508 unsigned AS = V->getType()->getPointerAddressSpace(); 1509 return DAG.getConstant(0, getCurSDLoc(), 1510 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1511 } 1512 1513 if (match(C, m_VScale(DAG.getDataLayout()))) 1514 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1515 1516 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1517 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1518 1519 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1520 return DAG.getUNDEF(VT); 1521 1522 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1523 visit(CE->getOpcode(), *CE); 1524 SDValue N1 = NodeMap[V]; 1525 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1526 return N1; 1527 } 1528 1529 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1530 SmallVector<SDValue, 4> Constants; 1531 for (const Use &U : C->operands()) { 1532 SDNode *Val = getValue(U).getNode(); 1533 // If the operand is an empty aggregate, there are no values. 1534 if (!Val) continue; 1535 // Add each leaf value from the operand to the Constants list 1536 // to form a flattened list of all the values. 1537 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1538 Constants.push_back(SDValue(Val, i)); 1539 } 1540 1541 return DAG.getMergeValues(Constants, getCurSDLoc()); 1542 } 1543 1544 if (const ConstantDataSequential *CDS = 1545 dyn_cast<ConstantDataSequential>(C)) { 1546 SmallVector<SDValue, 4> Ops; 1547 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1548 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1549 // Add each leaf value from the operand to the Constants list 1550 // to form a flattened list of all the values. 1551 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1552 Ops.push_back(SDValue(Val, i)); 1553 } 1554 1555 if (isa<ArrayType>(CDS->getType())) 1556 return DAG.getMergeValues(Ops, getCurSDLoc()); 1557 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1558 } 1559 1560 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1561 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1562 "Unknown struct or array constant!"); 1563 1564 SmallVector<EVT, 4> ValueVTs; 1565 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1566 unsigned NumElts = ValueVTs.size(); 1567 if (NumElts == 0) 1568 return SDValue(); // empty struct 1569 SmallVector<SDValue, 4> Constants(NumElts); 1570 for (unsigned i = 0; i != NumElts; ++i) { 1571 EVT EltVT = ValueVTs[i]; 1572 if (isa<UndefValue>(C)) 1573 Constants[i] = DAG.getUNDEF(EltVT); 1574 else if (EltVT.isFloatingPoint()) 1575 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1576 else 1577 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1578 } 1579 1580 return DAG.getMergeValues(Constants, getCurSDLoc()); 1581 } 1582 1583 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1584 return DAG.getBlockAddress(BA, VT); 1585 1586 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1587 return getValue(Equiv->getGlobalValue()); 1588 1589 VectorType *VecTy = cast<VectorType>(V->getType()); 1590 1591 // Now that we know the number and type of the elements, get that number of 1592 // elements into the Ops array based on what kind of constant it is. 1593 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1594 SmallVector<SDValue, 16> Ops; 1595 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1596 for (unsigned i = 0; i != NumElements; ++i) 1597 Ops.push_back(getValue(CV->getOperand(i))); 1598 1599 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1600 } else if (isa<ConstantAggregateZero>(C)) { 1601 EVT EltVT = 1602 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1603 1604 SDValue Op; 1605 if (EltVT.isFloatingPoint()) 1606 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1607 else 1608 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1609 1610 if (isa<ScalableVectorType>(VecTy)) 1611 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1612 else { 1613 SmallVector<SDValue, 16> Ops; 1614 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1615 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1616 } 1617 } 1618 llvm_unreachable("Unknown vector constant"); 1619 } 1620 1621 // If this is a static alloca, generate it as the frameindex instead of 1622 // computation. 1623 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1624 DenseMap<const AllocaInst*, int>::iterator SI = 1625 FuncInfo.StaticAllocaMap.find(AI); 1626 if (SI != FuncInfo.StaticAllocaMap.end()) 1627 return DAG.getFrameIndex(SI->second, 1628 TLI.getFrameIndexTy(DAG.getDataLayout())); 1629 } 1630 1631 // If this is an instruction which fast-isel has deferred, select it now. 1632 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1633 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1634 1635 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1636 Inst->getType(), None); 1637 SDValue Chain = DAG.getEntryNode(); 1638 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1639 } 1640 1641 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1642 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1643 } 1644 llvm_unreachable("Can't get register for value!"); 1645 } 1646 1647 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1648 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1649 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1650 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1651 bool IsSEH = isAsynchronousEHPersonality(Pers); 1652 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1653 if (!IsSEH) 1654 CatchPadMBB->setIsEHScopeEntry(); 1655 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1656 if (IsMSVCCXX || IsCoreCLR) 1657 CatchPadMBB->setIsEHFuncletEntry(); 1658 } 1659 1660 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1661 // Update machine-CFG edge. 1662 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1663 FuncInfo.MBB->addSuccessor(TargetMBB); 1664 TargetMBB->setIsEHCatchretTarget(true); 1665 DAG.getMachineFunction().setHasEHCatchret(true); 1666 1667 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1668 bool IsSEH = isAsynchronousEHPersonality(Pers); 1669 if (IsSEH) { 1670 // If this is not a fall-through branch or optimizations are switched off, 1671 // emit the branch. 1672 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1673 TM.getOptLevel() == CodeGenOpt::None) 1674 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1675 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1676 return; 1677 } 1678 1679 // Figure out the funclet membership for the catchret's successor. 1680 // This will be used by the FuncletLayout pass to determine how to order the 1681 // BB's. 1682 // A 'catchret' returns to the outer scope's color. 1683 Value *ParentPad = I.getCatchSwitchParentPad(); 1684 const BasicBlock *SuccessorColor; 1685 if (isa<ConstantTokenNone>(ParentPad)) 1686 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1687 else 1688 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1689 assert(SuccessorColor && "No parent funclet for catchret!"); 1690 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1691 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1692 1693 // Create the terminator node. 1694 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1695 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1696 DAG.getBasicBlock(SuccessorColorMBB)); 1697 DAG.setRoot(Ret); 1698 } 1699 1700 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1701 // Don't emit any special code for the cleanuppad instruction. It just marks 1702 // the start of an EH scope/funclet. 1703 FuncInfo.MBB->setIsEHScopeEntry(); 1704 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1705 if (Pers != EHPersonality::Wasm_CXX) { 1706 FuncInfo.MBB->setIsEHFuncletEntry(); 1707 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1708 } 1709 } 1710 1711 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1712 // not match, it is OK to add only the first unwind destination catchpad to the 1713 // successors, because there will be at least one invoke instruction within the 1714 // catch scope that points to the next unwind destination, if one exists, so 1715 // CFGSort cannot mess up with BB sorting order. 1716 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1717 // call within them, and catchpads only consisting of 'catch (...)' have a 1718 // '__cxa_end_catch' call within them, both of which generate invokes in case 1719 // the next unwind destination exists, i.e., the next unwind destination is not 1720 // the caller.) 1721 // 1722 // Having at most one EH pad successor is also simpler and helps later 1723 // transformations. 1724 // 1725 // For example, 1726 // current: 1727 // invoke void @foo to ... unwind label %catch.dispatch 1728 // catch.dispatch: 1729 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1730 // catch.start: 1731 // ... 1732 // ... in this BB or some other child BB dominated by this BB there will be an 1733 // invoke that points to 'next' BB as an unwind destination 1734 // 1735 // next: ; We don't need to add this to 'current' BB's successor 1736 // ... 1737 static void findWasmUnwindDestinations( 1738 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1739 BranchProbability Prob, 1740 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1741 &UnwindDests) { 1742 while (EHPadBB) { 1743 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1744 if (isa<CleanupPadInst>(Pad)) { 1745 // Stop on cleanup pads. 1746 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1747 UnwindDests.back().first->setIsEHScopeEntry(); 1748 break; 1749 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1750 // Add the catchpad handlers to the possible destinations. We don't 1751 // continue to the unwind destination of the catchswitch for wasm. 1752 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1753 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1754 UnwindDests.back().first->setIsEHScopeEntry(); 1755 } 1756 break; 1757 } else { 1758 continue; 1759 } 1760 } 1761 } 1762 1763 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1764 /// many places it could ultimately go. In the IR, we have a single unwind 1765 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1766 /// This function skips over imaginary basic blocks that hold catchswitch 1767 /// instructions, and finds all the "real" machine 1768 /// basic block destinations. As those destinations may not be successors of 1769 /// EHPadBB, here we also calculate the edge probability to those destinations. 1770 /// The passed-in Prob is the edge probability to EHPadBB. 1771 static void findUnwindDestinations( 1772 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1773 BranchProbability Prob, 1774 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1775 &UnwindDests) { 1776 EHPersonality Personality = 1777 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1778 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1779 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1780 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1781 bool IsSEH = isAsynchronousEHPersonality(Personality); 1782 1783 if (IsWasmCXX) { 1784 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1785 assert(UnwindDests.size() <= 1 && 1786 "There should be at most one unwind destination for wasm"); 1787 return; 1788 } 1789 1790 while (EHPadBB) { 1791 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1792 BasicBlock *NewEHPadBB = nullptr; 1793 if (isa<LandingPadInst>(Pad)) { 1794 // Stop on landingpads. They are not funclets. 1795 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1796 break; 1797 } else if (isa<CleanupPadInst>(Pad)) { 1798 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1799 // personalities. 1800 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1801 UnwindDests.back().first->setIsEHScopeEntry(); 1802 UnwindDests.back().first->setIsEHFuncletEntry(); 1803 break; 1804 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1805 // Add the catchpad handlers to the possible destinations. 1806 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1807 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1808 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1809 if (IsMSVCCXX || IsCoreCLR) 1810 UnwindDests.back().first->setIsEHFuncletEntry(); 1811 if (!IsSEH) 1812 UnwindDests.back().first->setIsEHScopeEntry(); 1813 } 1814 NewEHPadBB = CatchSwitch->getUnwindDest(); 1815 } else { 1816 continue; 1817 } 1818 1819 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1820 if (BPI && NewEHPadBB) 1821 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1822 EHPadBB = NewEHPadBB; 1823 } 1824 } 1825 1826 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1827 // Update successor info. 1828 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1829 auto UnwindDest = I.getUnwindDest(); 1830 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1831 BranchProbability UnwindDestProb = 1832 (BPI && UnwindDest) 1833 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1834 : BranchProbability::getZero(); 1835 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1836 for (auto &UnwindDest : UnwindDests) { 1837 UnwindDest.first->setIsEHPad(); 1838 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1839 } 1840 FuncInfo.MBB->normalizeSuccProbs(); 1841 1842 // Create the terminator node. 1843 SDValue Ret = 1844 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1845 DAG.setRoot(Ret); 1846 } 1847 1848 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1849 report_fatal_error("visitCatchSwitch not yet implemented!"); 1850 } 1851 1852 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1853 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1854 auto &DL = DAG.getDataLayout(); 1855 SDValue Chain = getControlRoot(); 1856 SmallVector<ISD::OutputArg, 8> Outs; 1857 SmallVector<SDValue, 8> OutVals; 1858 1859 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1860 // lower 1861 // 1862 // %val = call <ty> @llvm.experimental.deoptimize() 1863 // ret <ty> %val 1864 // 1865 // differently. 1866 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1867 LowerDeoptimizingReturn(); 1868 return; 1869 } 1870 1871 if (!FuncInfo.CanLowerReturn) { 1872 unsigned DemoteReg = FuncInfo.DemoteRegister; 1873 const Function *F = I.getParent()->getParent(); 1874 1875 // Emit a store of the return value through the virtual register. 1876 // Leave Outs empty so that LowerReturn won't try to load return 1877 // registers the usual way. 1878 SmallVector<EVT, 1> PtrValueVTs; 1879 ComputeValueVTs(TLI, DL, 1880 F->getReturnType()->getPointerTo( 1881 DAG.getDataLayout().getAllocaAddrSpace()), 1882 PtrValueVTs); 1883 1884 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1885 DemoteReg, PtrValueVTs[0]); 1886 SDValue RetOp = getValue(I.getOperand(0)); 1887 1888 SmallVector<EVT, 4> ValueVTs, MemVTs; 1889 SmallVector<uint64_t, 4> Offsets; 1890 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1891 &Offsets); 1892 unsigned NumValues = ValueVTs.size(); 1893 1894 SmallVector<SDValue, 4> Chains(NumValues); 1895 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1896 for (unsigned i = 0; i != NumValues; ++i) { 1897 // An aggregate return value cannot wrap around the address space, so 1898 // offsets to its parts don't wrap either. 1899 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1900 TypeSize::Fixed(Offsets[i])); 1901 1902 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1903 if (MemVTs[i] != ValueVTs[i]) 1904 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1905 Chains[i] = DAG.getStore( 1906 Chain, getCurSDLoc(), Val, 1907 // FIXME: better loc info would be nice. 1908 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1909 commonAlignment(BaseAlign, Offsets[i])); 1910 } 1911 1912 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1913 MVT::Other, Chains); 1914 } else if (I.getNumOperands() != 0) { 1915 SmallVector<EVT, 4> ValueVTs; 1916 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1917 unsigned NumValues = ValueVTs.size(); 1918 if (NumValues) { 1919 SDValue RetOp = getValue(I.getOperand(0)); 1920 1921 const Function *F = I.getParent()->getParent(); 1922 1923 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1924 I.getOperand(0)->getType(), F->getCallingConv(), 1925 /*IsVarArg*/ false); 1926 1927 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1928 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1929 Attribute::SExt)) 1930 ExtendKind = ISD::SIGN_EXTEND; 1931 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1932 Attribute::ZExt)) 1933 ExtendKind = ISD::ZERO_EXTEND; 1934 1935 LLVMContext &Context = F->getContext(); 1936 bool RetInReg = F->getAttributes().hasAttribute( 1937 AttributeList::ReturnIndex, Attribute::InReg); 1938 1939 for (unsigned j = 0; j != NumValues; ++j) { 1940 EVT VT = ValueVTs[j]; 1941 1942 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1943 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1944 1945 CallingConv::ID CC = F->getCallingConv(); 1946 1947 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1948 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1949 SmallVector<SDValue, 4> Parts(NumParts); 1950 getCopyToParts(DAG, getCurSDLoc(), 1951 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1952 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1953 1954 // 'inreg' on function refers to return value 1955 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1956 if (RetInReg) 1957 Flags.setInReg(); 1958 1959 if (I.getOperand(0)->getType()->isPointerTy()) { 1960 Flags.setPointer(); 1961 Flags.setPointerAddrSpace( 1962 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1963 } 1964 1965 if (NeedsRegBlock) { 1966 Flags.setInConsecutiveRegs(); 1967 if (j == NumValues - 1) 1968 Flags.setInConsecutiveRegsLast(); 1969 } 1970 1971 // Propagate extension type if any 1972 if (ExtendKind == ISD::SIGN_EXTEND) 1973 Flags.setSExt(); 1974 else if (ExtendKind == ISD::ZERO_EXTEND) 1975 Flags.setZExt(); 1976 1977 for (unsigned i = 0; i < NumParts; ++i) { 1978 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1979 VT, /*isfixed=*/true, 0, 0)); 1980 OutVals.push_back(Parts[i]); 1981 } 1982 } 1983 } 1984 } 1985 1986 // Push in swifterror virtual register as the last element of Outs. This makes 1987 // sure swifterror virtual register will be returned in the swifterror 1988 // physical register. 1989 const Function *F = I.getParent()->getParent(); 1990 if (TLI.supportSwiftError() && 1991 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1992 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1993 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1994 Flags.setSwiftError(); 1995 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1996 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1997 true /*isfixed*/, 1 /*origidx*/, 1998 0 /*partOffs*/)); 1999 // Create SDNode for the swifterror virtual register. 2000 OutVals.push_back( 2001 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2002 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2003 EVT(TLI.getPointerTy(DL)))); 2004 } 2005 2006 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2007 CallingConv::ID CallConv = 2008 DAG.getMachineFunction().getFunction().getCallingConv(); 2009 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2010 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2011 2012 // Verify that the target's LowerReturn behaved as expected. 2013 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2014 "LowerReturn didn't return a valid chain!"); 2015 2016 // Update the DAG with the new chain value resulting from return lowering. 2017 DAG.setRoot(Chain); 2018 } 2019 2020 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2021 /// created for it, emit nodes to copy the value into the virtual 2022 /// registers. 2023 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2024 // Skip empty types 2025 if (V->getType()->isEmptyTy()) 2026 return; 2027 2028 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2029 if (VMI != FuncInfo.ValueMap.end()) { 2030 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2031 CopyValueToVirtualRegister(V, VMI->second); 2032 } 2033 } 2034 2035 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2036 /// the current basic block, add it to ValueMap now so that we'll get a 2037 /// CopyTo/FromReg. 2038 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2039 // No need to export constants. 2040 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2041 2042 // Already exported? 2043 if (FuncInfo.isExportedInst(V)) return; 2044 2045 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2046 CopyValueToVirtualRegister(V, Reg); 2047 } 2048 2049 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2050 const BasicBlock *FromBB) { 2051 // The operands of the setcc have to be in this block. We don't know 2052 // how to export them from some other block. 2053 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2054 // Can export from current BB. 2055 if (VI->getParent() == FromBB) 2056 return true; 2057 2058 // Is already exported, noop. 2059 return FuncInfo.isExportedInst(V); 2060 } 2061 2062 // If this is an argument, we can export it if the BB is the entry block or 2063 // if it is already exported. 2064 if (isa<Argument>(V)) { 2065 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2066 return true; 2067 2068 // Otherwise, can only export this if it is already exported. 2069 return FuncInfo.isExportedInst(V); 2070 } 2071 2072 // Otherwise, constants can always be exported. 2073 return true; 2074 } 2075 2076 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2077 BranchProbability 2078 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2079 const MachineBasicBlock *Dst) const { 2080 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2081 const BasicBlock *SrcBB = Src->getBasicBlock(); 2082 const BasicBlock *DstBB = Dst->getBasicBlock(); 2083 if (!BPI) { 2084 // If BPI is not available, set the default probability as 1 / N, where N is 2085 // the number of successors. 2086 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2087 return BranchProbability(1, SuccSize); 2088 } 2089 return BPI->getEdgeProbability(SrcBB, DstBB); 2090 } 2091 2092 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2093 MachineBasicBlock *Dst, 2094 BranchProbability Prob) { 2095 if (!FuncInfo.BPI) 2096 Src->addSuccessorWithoutProb(Dst); 2097 else { 2098 if (Prob.isUnknown()) 2099 Prob = getEdgeProbability(Src, Dst); 2100 Src->addSuccessor(Dst, Prob); 2101 } 2102 } 2103 2104 static bool InBlock(const Value *V, const BasicBlock *BB) { 2105 if (const Instruction *I = dyn_cast<Instruction>(V)) 2106 return I->getParent() == BB; 2107 return true; 2108 } 2109 2110 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2111 /// This function emits a branch and is used at the leaves of an OR or an 2112 /// AND operator tree. 2113 void 2114 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2115 MachineBasicBlock *TBB, 2116 MachineBasicBlock *FBB, 2117 MachineBasicBlock *CurBB, 2118 MachineBasicBlock *SwitchBB, 2119 BranchProbability TProb, 2120 BranchProbability FProb, 2121 bool InvertCond) { 2122 const BasicBlock *BB = CurBB->getBasicBlock(); 2123 2124 // If the leaf of the tree is a comparison, merge the condition into 2125 // the caseblock. 2126 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2127 // The operands of the cmp have to be in this block. We don't know 2128 // how to export them from some other block. If this is the first block 2129 // of the sequence, no exporting is needed. 2130 if (CurBB == SwitchBB || 2131 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2132 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2133 ISD::CondCode Condition; 2134 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2135 ICmpInst::Predicate Pred = 2136 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2137 Condition = getICmpCondCode(Pred); 2138 } else { 2139 const FCmpInst *FC = cast<FCmpInst>(Cond); 2140 FCmpInst::Predicate Pred = 2141 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2142 Condition = getFCmpCondCode(Pred); 2143 if (TM.Options.NoNaNsFPMath) 2144 Condition = getFCmpCodeWithoutNaN(Condition); 2145 } 2146 2147 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2148 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2149 SL->SwitchCases.push_back(CB); 2150 return; 2151 } 2152 } 2153 2154 // Create a CaseBlock record representing this branch. 2155 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2156 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2157 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2158 SL->SwitchCases.push_back(CB); 2159 } 2160 2161 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2162 MachineBasicBlock *TBB, 2163 MachineBasicBlock *FBB, 2164 MachineBasicBlock *CurBB, 2165 MachineBasicBlock *SwitchBB, 2166 Instruction::BinaryOps Opc, 2167 BranchProbability TProb, 2168 BranchProbability FProb, 2169 bool InvertCond) { 2170 // Skip over not part of the tree and remember to invert op and operands at 2171 // next level. 2172 Value *NotCond; 2173 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2174 InBlock(NotCond, CurBB->getBasicBlock())) { 2175 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2176 !InvertCond); 2177 return; 2178 } 2179 2180 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2181 const Value *BOpOp0, *BOpOp1; 2182 // Compute the effective opcode for Cond, taking into account whether it needs 2183 // to be inverted, e.g. 2184 // and (not (or A, B)), C 2185 // gets lowered as 2186 // and (and (not A, not B), C) 2187 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2188 if (BOp) { 2189 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2190 ? Instruction::And 2191 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2192 ? Instruction::Or 2193 : (Instruction::BinaryOps)0); 2194 if (InvertCond) { 2195 if (BOpc == Instruction::And) 2196 BOpc = Instruction::Or; 2197 else if (BOpc == Instruction::Or) 2198 BOpc = Instruction::And; 2199 } 2200 } 2201 2202 // If this node is not part of the or/and tree, emit it as a branch. 2203 // Note that all nodes in the tree should have same opcode. 2204 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2205 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2206 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2207 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2208 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2209 TProb, FProb, InvertCond); 2210 return; 2211 } 2212 2213 // Create TmpBB after CurBB. 2214 MachineFunction::iterator BBI(CurBB); 2215 MachineFunction &MF = DAG.getMachineFunction(); 2216 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2217 CurBB->getParent()->insert(++BBI, TmpBB); 2218 2219 if (Opc == Instruction::Or) { 2220 // Codegen X | Y as: 2221 // BB1: 2222 // jmp_if_X TBB 2223 // jmp TmpBB 2224 // TmpBB: 2225 // jmp_if_Y TBB 2226 // jmp FBB 2227 // 2228 2229 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2230 // The requirement is that 2231 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2232 // = TrueProb for original BB. 2233 // Assuming the original probabilities are A and B, one choice is to set 2234 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2235 // A/(1+B) and 2B/(1+B). This choice assumes that 2236 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2237 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2238 // TmpBB, but the math is more complicated. 2239 2240 auto NewTrueProb = TProb / 2; 2241 auto NewFalseProb = TProb / 2 + FProb; 2242 // Emit the LHS condition. 2243 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2244 NewFalseProb, InvertCond); 2245 2246 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2247 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2248 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2249 // Emit the RHS condition into TmpBB. 2250 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2251 Probs[1], InvertCond); 2252 } else { 2253 assert(Opc == Instruction::And && "Unknown merge op!"); 2254 // Codegen X & Y as: 2255 // BB1: 2256 // jmp_if_X TmpBB 2257 // jmp FBB 2258 // TmpBB: 2259 // jmp_if_Y TBB 2260 // jmp FBB 2261 // 2262 // This requires creation of TmpBB after CurBB. 2263 2264 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2265 // The requirement is that 2266 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2267 // = FalseProb for original BB. 2268 // Assuming the original probabilities are A and B, one choice is to set 2269 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2270 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2271 // TrueProb for BB1 * FalseProb for TmpBB. 2272 2273 auto NewTrueProb = TProb + FProb / 2; 2274 auto NewFalseProb = FProb / 2; 2275 // Emit the LHS condition. 2276 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2277 NewFalseProb, InvertCond); 2278 2279 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2280 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2281 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2282 // Emit the RHS condition into TmpBB. 2283 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2284 Probs[1], InvertCond); 2285 } 2286 } 2287 2288 /// If the set of cases should be emitted as a series of branches, return true. 2289 /// If we should emit this as a bunch of and/or'd together conditions, return 2290 /// false. 2291 bool 2292 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2293 if (Cases.size() != 2) return true; 2294 2295 // If this is two comparisons of the same values or'd or and'd together, they 2296 // will get folded into a single comparison, so don't emit two blocks. 2297 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2298 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2299 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2300 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2301 return false; 2302 } 2303 2304 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2305 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2306 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2307 Cases[0].CC == Cases[1].CC && 2308 isa<Constant>(Cases[0].CmpRHS) && 2309 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2310 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2311 return false; 2312 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2313 return false; 2314 } 2315 2316 return true; 2317 } 2318 2319 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2320 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2321 2322 // Update machine-CFG edges. 2323 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2324 2325 if (I.isUnconditional()) { 2326 // Update machine-CFG edges. 2327 BrMBB->addSuccessor(Succ0MBB); 2328 2329 // If this is not a fall-through branch or optimizations are switched off, 2330 // emit the branch. 2331 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2332 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2333 MVT::Other, getControlRoot(), 2334 DAG.getBasicBlock(Succ0MBB))); 2335 2336 return; 2337 } 2338 2339 // If this condition is one of the special cases we handle, do special stuff 2340 // now. 2341 const Value *CondVal = I.getCondition(); 2342 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2343 2344 // If this is a series of conditions that are or'd or and'd together, emit 2345 // this as a sequence of branches instead of setcc's with and/or operations. 2346 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2347 // unpredictable branches, and vector extracts because those jumps are likely 2348 // expensive for any target), this should improve performance. 2349 // For example, instead of something like: 2350 // cmp A, B 2351 // C = seteq 2352 // cmp D, E 2353 // F = setle 2354 // or C, F 2355 // jnz foo 2356 // Emit: 2357 // cmp A, B 2358 // je foo 2359 // cmp D, E 2360 // jle foo 2361 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2362 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2363 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2364 Value *Vec; 2365 const Value *BOp0, *BOp1; 2366 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2367 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2368 Opcode = Instruction::And; 2369 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2370 Opcode = Instruction::Or; 2371 2372 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2373 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2374 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2375 getEdgeProbability(BrMBB, Succ0MBB), 2376 getEdgeProbability(BrMBB, Succ1MBB), 2377 /*InvertCond=*/false); 2378 // If the compares in later blocks need to use values not currently 2379 // exported from this block, export them now. This block should always 2380 // be the first entry. 2381 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2382 2383 // Allow some cases to be rejected. 2384 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2385 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2386 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2387 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2388 } 2389 2390 // Emit the branch for this block. 2391 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2392 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2393 return; 2394 } 2395 2396 // Okay, we decided not to do this, remove any inserted MBB's and clear 2397 // SwitchCases. 2398 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2399 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2400 2401 SL->SwitchCases.clear(); 2402 } 2403 } 2404 2405 // Create a CaseBlock record representing this branch. 2406 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2407 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2408 2409 // Use visitSwitchCase to actually insert the fast branch sequence for this 2410 // cond branch. 2411 visitSwitchCase(CB, BrMBB); 2412 } 2413 2414 /// visitSwitchCase - Emits the necessary code to represent a single node in 2415 /// the binary search tree resulting from lowering a switch instruction. 2416 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2417 MachineBasicBlock *SwitchBB) { 2418 SDValue Cond; 2419 SDValue CondLHS = getValue(CB.CmpLHS); 2420 SDLoc dl = CB.DL; 2421 2422 if (CB.CC == ISD::SETTRUE) { 2423 // Branch or fall through to TrueBB. 2424 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2425 SwitchBB->normalizeSuccProbs(); 2426 if (CB.TrueBB != NextBlock(SwitchBB)) { 2427 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2428 DAG.getBasicBlock(CB.TrueBB))); 2429 } 2430 return; 2431 } 2432 2433 auto &TLI = DAG.getTargetLoweringInfo(); 2434 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2435 2436 // Build the setcc now. 2437 if (!CB.CmpMHS) { 2438 // Fold "(X == true)" to X and "(X == false)" to !X to 2439 // handle common cases produced by branch lowering. 2440 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2441 CB.CC == ISD::SETEQ) 2442 Cond = CondLHS; 2443 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2444 CB.CC == ISD::SETEQ) { 2445 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2446 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2447 } else { 2448 SDValue CondRHS = getValue(CB.CmpRHS); 2449 2450 // If a pointer's DAG type is larger than its memory type then the DAG 2451 // values are zero-extended. This breaks signed comparisons so truncate 2452 // back to the underlying type before doing the compare. 2453 if (CondLHS.getValueType() != MemVT) { 2454 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2455 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2456 } 2457 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2458 } 2459 } else { 2460 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2461 2462 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2463 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2464 2465 SDValue CmpOp = getValue(CB.CmpMHS); 2466 EVT VT = CmpOp.getValueType(); 2467 2468 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2469 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2470 ISD::SETLE); 2471 } else { 2472 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2473 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2474 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2475 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2476 } 2477 } 2478 2479 // Update successor info 2480 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2481 // TrueBB and FalseBB are always different unless the incoming IR is 2482 // degenerate. This only happens when running llc on weird IR. 2483 if (CB.TrueBB != CB.FalseBB) 2484 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2485 SwitchBB->normalizeSuccProbs(); 2486 2487 // If the lhs block is the next block, invert the condition so that we can 2488 // fall through to the lhs instead of the rhs block. 2489 if (CB.TrueBB == NextBlock(SwitchBB)) { 2490 std::swap(CB.TrueBB, CB.FalseBB); 2491 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2492 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2493 } 2494 2495 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2496 MVT::Other, getControlRoot(), Cond, 2497 DAG.getBasicBlock(CB.TrueBB)); 2498 2499 // Insert the false branch. Do this even if it's a fall through branch, 2500 // this makes it easier to do DAG optimizations which require inverting 2501 // the branch condition. 2502 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2503 DAG.getBasicBlock(CB.FalseBB)); 2504 2505 DAG.setRoot(BrCond); 2506 } 2507 2508 /// visitJumpTable - Emit JumpTable node in the current MBB 2509 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2510 // Emit the code for the jump table 2511 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2512 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2513 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2514 JT.Reg, PTy); 2515 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2516 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2517 MVT::Other, Index.getValue(1), 2518 Table, Index); 2519 DAG.setRoot(BrJumpTable); 2520 } 2521 2522 /// visitJumpTableHeader - This function emits necessary code to produce index 2523 /// in the JumpTable from switch case. 2524 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2525 JumpTableHeader &JTH, 2526 MachineBasicBlock *SwitchBB) { 2527 SDLoc dl = getCurSDLoc(); 2528 2529 // Subtract the lowest switch case value from the value being switched on. 2530 SDValue SwitchOp = getValue(JTH.SValue); 2531 EVT VT = SwitchOp.getValueType(); 2532 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2533 DAG.getConstant(JTH.First, dl, VT)); 2534 2535 // The SDNode we just created, which holds the value being switched on minus 2536 // the smallest case value, needs to be copied to a virtual register so it 2537 // can be used as an index into the jump table in a subsequent basic block. 2538 // This value may be smaller or larger than the target's pointer type, and 2539 // therefore require extension or truncating. 2540 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2541 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2542 2543 unsigned JumpTableReg = 2544 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2545 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2546 JumpTableReg, SwitchOp); 2547 JT.Reg = JumpTableReg; 2548 2549 if (!JTH.OmitRangeCheck) { 2550 // Emit the range check for the jump table, and branch to the default block 2551 // for the switch statement if the value being switched on exceeds the 2552 // largest case in the switch. 2553 SDValue CMP = DAG.getSetCC( 2554 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2555 Sub.getValueType()), 2556 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2557 2558 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2559 MVT::Other, CopyTo, CMP, 2560 DAG.getBasicBlock(JT.Default)); 2561 2562 // Avoid emitting unnecessary branches to the next block. 2563 if (JT.MBB != NextBlock(SwitchBB)) 2564 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2565 DAG.getBasicBlock(JT.MBB)); 2566 2567 DAG.setRoot(BrCond); 2568 } else { 2569 // Avoid emitting unnecessary branches to the next block. 2570 if (JT.MBB != NextBlock(SwitchBB)) 2571 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2572 DAG.getBasicBlock(JT.MBB))); 2573 else 2574 DAG.setRoot(CopyTo); 2575 } 2576 } 2577 2578 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2579 /// variable if there exists one. 2580 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2581 SDValue &Chain) { 2582 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2583 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2584 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2585 MachineFunction &MF = DAG.getMachineFunction(); 2586 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2587 MachineSDNode *Node = 2588 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2589 if (Global) { 2590 MachinePointerInfo MPInfo(Global); 2591 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2592 MachineMemOperand::MODereferenceable; 2593 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2594 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2595 DAG.setNodeMemRefs(Node, {MemRef}); 2596 } 2597 if (PtrTy != PtrMemTy) 2598 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2599 return SDValue(Node, 0); 2600 } 2601 2602 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2603 /// tail spliced into a stack protector check success bb. 2604 /// 2605 /// For a high level explanation of how this fits into the stack protector 2606 /// generation see the comment on the declaration of class 2607 /// StackProtectorDescriptor. 2608 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2609 MachineBasicBlock *ParentBB) { 2610 2611 // First create the loads to the guard/stack slot for the comparison. 2612 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2613 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2614 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2615 2616 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2617 int FI = MFI.getStackProtectorIndex(); 2618 2619 SDValue Guard; 2620 SDLoc dl = getCurSDLoc(); 2621 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2622 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2623 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2624 2625 // Generate code to load the content of the guard slot. 2626 SDValue GuardVal = DAG.getLoad( 2627 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2628 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2629 MachineMemOperand::MOVolatile); 2630 2631 if (TLI.useStackGuardXorFP()) 2632 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2633 2634 // Retrieve guard check function, nullptr if instrumentation is inlined. 2635 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2636 // The target provides a guard check function to validate the guard value. 2637 // Generate a call to that function with the content of the guard slot as 2638 // argument. 2639 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2640 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2641 2642 TargetLowering::ArgListTy Args; 2643 TargetLowering::ArgListEntry Entry; 2644 Entry.Node = GuardVal; 2645 Entry.Ty = FnTy->getParamType(0); 2646 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2647 Entry.IsInReg = true; 2648 Args.push_back(Entry); 2649 2650 TargetLowering::CallLoweringInfo CLI(DAG); 2651 CLI.setDebugLoc(getCurSDLoc()) 2652 .setChain(DAG.getEntryNode()) 2653 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2654 getValue(GuardCheckFn), std::move(Args)); 2655 2656 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2657 DAG.setRoot(Result.second); 2658 return; 2659 } 2660 2661 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2662 // Otherwise, emit a volatile load to retrieve the stack guard value. 2663 SDValue Chain = DAG.getEntryNode(); 2664 if (TLI.useLoadStackGuardNode()) { 2665 Guard = getLoadStackGuard(DAG, dl, Chain); 2666 } else { 2667 const Value *IRGuard = TLI.getSDagStackGuard(M); 2668 SDValue GuardPtr = getValue(IRGuard); 2669 2670 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2671 MachinePointerInfo(IRGuard, 0), Align, 2672 MachineMemOperand::MOVolatile); 2673 } 2674 2675 // Perform the comparison via a getsetcc. 2676 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2677 *DAG.getContext(), 2678 Guard.getValueType()), 2679 Guard, GuardVal, ISD::SETNE); 2680 2681 // If the guard/stackslot do not equal, branch to failure MBB. 2682 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2683 MVT::Other, GuardVal.getOperand(0), 2684 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2685 // Otherwise branch to success MBB. 2686 SDValue Br = DAG.getNode(ISD::BR, dl, 2687 MVT::Other, BrCond, 2688 DAG.getBasicBlock(SPD.getSuccessMBB())); 2689 2690 DAG.setRoot(Br); 2691 } 2692 2693 /// Codegen the failure basic block for a stack protector check. 2694 /// 2695 /// A failure stack protector machine basic block consists simply of a call to 2696 /// __stack_chk_fail(). 2697 /// 2698 /// For a high level explanation of how this fits into the stack protector 2699 /// generation see the comment on the declaration of class 2700 /// StackProtectorDescriptor. 2701 void 2702 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2703 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2704 TargetLowering::MakeLibCallOptions CallOptions; 2705 CallOptions.setDiscardResult(true); 2706 SDValue Chain = 2707 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2708 None, CallOptions, getCurSDLoc()).second; 2709 // On PS4, the "return address" must still be within the calling function, 2710 // even if it's at the very end, so emit an explicit TRAP here. 2711 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2712 if (TM.getTargetTriple().isPS4CPU()) 2713 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2714 // WebAssembly needs an unreachable instruction after a non-returning call, 2715 // because the function return type can be different from __stack_chk_fail's 2716 // return type (void). 2717 if (TM.getTargetTriple().isWasm()) 2718 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2719 2720 DAG.setRoot(Chain); 2721 } 2722 2723 /// visitBitTestHeader - This function emits necessary code to produce value 2724 /// suitable for "bit tests" 2725 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2726 MachineBasicBlock *SwitchBB) { 2727 SDLoc dl = getCurSDLoc(); 2728 2729 // Subtract the minimum value. 2730 SDValue SwitchOp = getValue(B.SValue); 2731 EVT VT = SwitchOp.getValueType(); 2732 SDValue RangeSub = 2733 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2734 2735 // Determine the type of the test operands. 2736 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2737 bool UsePtrType = false; 2738 if (!TLI.isTypeLegal(VT)) { 2739 UsePtrType = true; 2740 } else { 2741 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2742 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2743 // Switch table case range are encoded into series of masks. 2744 // Just use pointer type, it's guaranteed to fit. 2745 UsePtrType = true; 2746 break; 2747 } 2748 } 2749 SDValue Sub = RangeSub; 2750 if (UsePtrType) { 2751 VT = TLI.getPointerTy(DAG.getDataLayout()); 2752 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2753 } 2754 2755 B.RegVT = VT.getSimpleVT(); 2756 B.Reg = FuncInfo.CreateReg(B.RegVT); 2757 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2758 2759 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2760 2761 if (!B.OmitRangeCheck) 2762 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2763 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2764 SwitchBB->normalizeSuccProbs(); 2765 2766 SDValue Root = CopyTo; 2767 if (!B.OmitRangeCheck) { 2768 // Conditional branch to the default block. 2769 SDValue RangeCmp = DAG.getSetCC(dl, 2770 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2771 RangeSub.getValueType()), 2772 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2773 ISD::SETUGT); 2774 2775 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2776 DAG.getBasicBlock(B.Default)); 2777 } 2778 2779 // Avoid emitting unnecessary branches to the next block. 2780 if (MBB != NextBlock(SwitchBB)) 2781 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2782 2783 DAG.setRoot(Root); 2784 } 2785 2786 /// visitBitTestCase - this function produces one "bit test" 2787 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2788 MachineBasicBlock* NextMBB, 2789 BranchProbability BranchProbToNext, 2790 unsigned Reg, 2791 BitTestCase &B, 2792 MachineBasicBlock *SwitchBB) { 2793 SDLoc dl = getCurSDLoc(); 2794 MVT VT = BB.RegVT; 2795 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2796 SDValue Cmp; 2797 unsigned PopCount = countPopulation(B.Mask); 2798 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2799 if (PopCount == 1) { 2800 // Testing for a single bit; just compare the shift count with what it 2801 // would need to be to shift a 1 bit in that position. 2802 Cmp = DAG.getSetCC( 2803 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2804 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2805 ISD::SETEQ); 2806 } else if (PopCount == BB.Range) { 2807 // There is only one zero bit in the range, test for it directly. 2808 Cmp = DAG.getSetCC( 2809 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2810 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2811 ISD::SETNE); 2812 } else { 2813 // Make desired shift 2814 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2815 DAG.getConstant(1, dl, VT), ShiftOp); 2816 2817 // Emit bit tests and jumps 2818 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2819 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2820 Cmp = DAG.getSetCC( 2821 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2822 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2823 } 2824 2825 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2826 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2827 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2828 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2829 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2830 // one as they are relative probabilities (and thus work more like weights), 2831 // and hence we need to normalize them to let the sum of them become one. 2832 SwitchBB->normalizeSuccProbs(); 2833 2834 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2835 MVT::Other, getControlRoot(), 2836 Cmp, DAG.getBasicBlock(B.TargetBB)); 2837 2838 // Avoid emitting unnecessary branches to the next block. 2839 if (NextMBB != NextBlock(SwitchBB)) 2840 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2841 DAG.getBasicBlock(NextMBB)); 2842 2843 DAG.setRoot(BrAnd); 2844 } 2845 2846 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2847 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2848 2849 // Retrieve successors. Look through artificial IR level blocks like 2850 // catchswitch for successors. 2851 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2852 const BasicBlock *EHPadBB = I.getSuccessor(1); 2853 2854 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2855 // have to do anything here to lower funclet bundles. 2856 assert(!I.hasOperandBundlesOtherThan( 2857 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2858 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2859 LLVMContext::OB_cfguardtarget, 2860 LLVMContext::OB_clang_arc_attachedcall}) && 2861 "Cannot lower invokes with arbitrary operand bundles yet!"); 2862 2863 const Value *Callee(I.getCalledOperand()); 2864 const Function *Fn = dyn_cast<Function>(Callee); 2865 if (isa<InlineAsm>(Callee)) 2866 visitInlineAsm(I); 2867 else if (Fn && Fn->isIntrinsic()) { 2868 switch (Fn->getIntrinsicID()) { 2869 default: 2870 llvm_unreachable("Cannot invoke this intrinsic"); 2871 case Intrinsic::donothing: 2872 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2873 break; 2874 case Intrinsic::experimental_patchpoint_void: 2875 case Intrinsic::experimental_patchpoint_i64: 2876 visitPatchpoint(I, EHPadBB); 2877 break; 2878 case Intrinsic::experimental_gc_statepoint: 2879 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2880 break; 2881 case Intrinsic::wasm_rethrow: { 2882 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2883 // special because it can be invoked, so we manually lower it to a DAG 2884 // node here. 2885 SmallVector<SDValue, 8> Ops; 2886 Ops.push_back(getRoot()); // inchain 2887 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2888 Ops.push_back( 2889 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2890 TLI.getPointerTy(DAG.getDataLayout()))); 2891 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2892 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2893 break; 2894 } 2895 } 2896 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2897 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2898 // Eventually we will support lowering the @llvm.experimental.deoptimize 2899 // intrinsic, and right now there are no plans to support other intrinsics 2900 // with deopt state. 2901 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2902 } else { 2903 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2904 } 2905 2906 // If the value of the invoke is used outside of its defining block, make it 2907 // available as a virtual register. 2908 // We already took care of the exported value for the statepoint instruction 2909 // during call to the LowerStatepoint. 2910 if (!isa<GCStatepointInst>(I)) { 2911 CopyToExportRegsIfNeeded(&I); 2912 } 2913 2914 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2915 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2916 BranchProbability EHPadBBProb = 2917 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2918 : BranchProbability::getZero(); 2919 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2920 2921 // Update successor info. 2922 addSuccessorWithProb(InvokeMBB, Return); 2923 for (auto &UnwindDest : UnwindDests) { 2924 UnwindDest.first->setIsEHPad(); 2925 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2926 } 2927 InvokeMBB->normalizeSuccProbs(); 2928 2929 // Drop into normal successor. 2930 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2931 DAG.getBasicBlock(Return))); 2932 } 2933 2934 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2935 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2936 2937 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2938 // have to do anything here to lower funclet bundles. 2939 assert(!I.hasOperandBundlesOtherThan( 2940 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2941 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2942 2943 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2944 visitInlineAsm(I); 2945 CopyToExportRegsIfNeeded(&I); 2946 2947 // Retrieve successors. 2948 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2949 2950 // Update successor info. 2951 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2952 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2953 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2954 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2955 Target->setIsInlineAsmBrIndirectTarget(); 2956 } 2957 CallBrMBB->normalizeSuccProbs(); 2958 2959 // Drop into default successor. 2960 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2961 MVT::Other, getControlRoot(), 2962 DAG.getBasicBlock(Return))); 2963 } 2964 2965 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2966 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2967 } 2968 2969 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2970 assert(FuncInfo.MBB->isEHPad() && 2971 "Call to landingpad not in landing pad!"); 2972 2973 // If there aren't registers to copy the values into (e.g., during SjLj 2974 // exceptions), then don't bother to create these DAG nodes. 2975 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2976 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2977 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2978 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2979 return; 2980 2981 // If landingpad's return type is token type, we don't create DAG nodes 2982 // for its exception pointer and selector value. The extraction of exception 2983 // pointer or selector value from token type landingpads is not currently 2984 // supported. 2985 if (LP.getType()->isTokenTy()) 2986 return; 2987 2988 SmallVector<EVT, 2> ValueVTs; 2989 SDLoc dl = getCurSDLoc(); 2990 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2991 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2992 2993 // Get the two live-in registers as SDValues. The physregs have already been 2994 // copied into virtual registers. 2995 SDValue Ops[2]; 2996 if (FuncInfo.ExceptionPointerVirtReg) { 2997 Ops[0] = DAG.getZExtOrTrunc( 2998 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2999 FuncInfo.ExceptionPointerVirtReg, 3000 TLI.getPointerTy(DAG.getDataLayout())), 3001 dl, ValueVTs[0]); 3002 } else { 3003 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3004 } 3005 Ops[1] = DAG.getZExtOrTrunc( 3006 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3007 FuncInfo.ExceptionSelectorVirtReg, 3008 TLI.getPointerTy(DAG.getDataLayout())), 3009 dl, ValueVTs[1]); 3010 3011 // Merge into one. 3012 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3013 DAG.getVTList(ValueVTs), Ops); 3014 setValue(&LP, Res); 3015 } 3016 3017 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3018 MachineBasicBlock *Last) { 3019 // Update JTCases. 3020 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 3021 if (SL->JTCases[i].first.HeaderBB == First) 3022 SL->JTCases[i].first.HeaderBB = Last; 3023 3024 // Update BitTestCases. 3025 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 3026 if (SL->BitTestCases[i].Parent == First) 3027 SL->BitTestCases[i].Parent = Last; 3028 } 3029 3030 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3031 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3032 3033 // Update machine-CFG edges with unique successors. 3034 SmallSet<BasicBlock*, 32> Done; 3035 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3036 BasicBlock *BB = I.getSuccessor(i); 3037 bool Inserted = Done.insert(BB).second; 3038 if (!Inserted) 3039 continue; 3040 3041 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3042 addSuccessorWithProb(IndirectBrMBB, Succ); 3043 } 3044 IndirectBrMBB->normalizeSuccProbs(); 3045 3046 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3047 MVT::Other, getControlRoot(), 3048 getValue(I.getAddress()))); 3049 } 3050 3051 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3052 if (!DAG.getTarget().Options.TrapUnreachable) 3053 return; 3054 3055 // We may be able to ignore unreachable behind a noreturn call. 3056 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3057 const BasicBlock &BB = *I.getParent(); 3058 if (&I != &BB.front()) { 3059 BasicBlock::const_iterator PredI = 3060 std::prev(BasicBlock::const_iterator(&I)); 3061 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3062 if (Call->doesNotReturn()) 3063 return; 3064 } 3065 } 3066 } 3067 3068 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3069 } 3070 3071 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3072 SDNodeFlags Flags; 3073 3074 SDValue Op = getValue(I.getOperand(0)); 3075 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3076 Op, Flags); 3077 setValue(&I, UnNodeValue); 3078 } 3079 3080 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3081 SDNodeFlags Flags; 3082 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3083 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3084 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3085 } 3086 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3087 Flags.setExact(ExactOp->isExact()); 3088 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3089 Flags.copyFMF(*FPOp); 3090 3091 SDValue Op1 = getValue(I.getOperand(0)); 3092 SDValue Op2 = getValue(I.getOperand(1)); 3093 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3094 Op1, Op2, Flags); 3095 setValue(&I, BinNodeValue); 3096 } 3097 3098 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3099 SDValue Op1 = getValue(I.getOperand(0)); 3100 SDValue Op2 = getValue(I.getOperand(1)); 3101 3102 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3103 Op1.getValueType(), DAG.getDataLayout()); 3104 3105 // Coerce the shift amount to the right type if we can. 3106 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3107 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3108 unsigned Op2Size = Op2.getValueSizeInBits(); 3109 SDLoc DL = getCurSDLoc(); 3110 3111 // If the operand is smaller than the shift count type, promote it. 3112 if (ShiftSize > Op2Size) 3113 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3114 3115 // If the operand is larger than the shift count type but the shift 3116 // count type has enough bits to represent any shift value, truncate 3117 // it now. This is a common case and it exposes the truncate to 3118 // optimization early. 3119 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3120 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3121 // Otherwise we'll need to temporarily settle for some other convenient 3122 // type. Type legalization will make adjustments once the shiftee is split. 3123 else 3124 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3125 } 3126 3127 bool nuw = false; 3128 bool nsw = false; 3129 bool exact = false; 3130 3131 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3132 3133 if (const OverflowingBinaryOperator *OFBinOp = 3134 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3135 nuw = OFBinOp->hasNoUnsignedWrap(); 3136 nsw = OFBinOp->hasNoSignedWrap(); 3137 } 3138 if (const PossiblyExactOperator *ExactOp = 3139 dyn_cast<const PossiblyExactOperator>(&I)) 3140 exact = ExactOp->isExact(); 3141 } 3142 SDNodeFlags Flags; 3143 Flags.setExact(exact); 3144 Flags.setNoSignedWrap(nsw); 3145 Flags.setNoUnsignedWrap(nuw); 3146 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3147 Flags); 3148 setValue(&I, Res); 3149 } 3150 3151 void SelectionDAGBuilder::visitSDiv(const User &I) { 3152 SDValue Op1 = getValue(I.getOperand(0)); 3153 SDValue Op2 = getValue(I.getOperand(1)); 3154 3155 SDNodeFlags Flags; 3156 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3157 cast<PossiblyExactOperator>(&I)->isExact()); 3158 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3159 Op2, Flags)); 3160 } 3161 3162 void SelectionDAGBuilder::visitICmp(const User &I) { 3163 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3164 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3165 predicate = IC->getPredicate(); 3166 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3167 predicate = ICmpInst::Predicate(IC->getPredicate()); 3168 SDValue Op1 = getValue(I.getOperand(0)); 3169 SDValue Op2 = getValue(I.getOperand(1)); 3170 ISD::CondCode Opcode = getICmpCondCode(predicate); 3171 3172 auto &TLI = DAG.getTargetLoweringInfo(); 3173 EVT MemVT = 3174 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3175 3176 // If a pointer's DAG type is larger than its memory type then the DAG values 3177 // are zero-extended. This breaks signed comparisons so truncate back to the 3178 // underlying type before doing the compare. 3179 if (Op1.getValueType() != MemVT) { 3180 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3181 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3182 } 3183 3184 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3185 I.getType()); 3186 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3187 } 3188 3189 void SelectionDAGBuilder::visitFCmp(const User &I) { 3190 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3191 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3192 predicate = FC->getPredicate(); 3193 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3194 predicate = FCmpInst::Predicate(FC->getPredicate()); 3195 SDValue Op1 = getValue(I.getOperand(0)); 3196 SDValue Op2 = getValue(I.getOperand(1)); 3197 3198 ISD::CondCode Condition = getFCmpCondCode(predicate); 3199 auto *FPMO = cast<FPMathOperator>(&I); 3200 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3201 Condition = getFCmpCodeWithoutNaN(Condition); 3202 3203 SDNodeFlags Flags; 3204 Flags.copyFMF(*FPMO); 3205 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3206 3207 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3208 I.getType()); 3209 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3210 } 3211 3212 // Check if the condition of the select has one use or two users that are both 3213 // selects with the same condition. 3214 static bool hasOnlySelectUsers(const Value *Cond) { 3215 return llvm::all_of(Cond->users(), [](const Value *V) { 3216 return isa<SelectInst>(V); 3217 }); 3218 } 3219 3220 void SelectionDAGBuilder::visitSelect(const User &I) { 3221 SmallVector<EVT, 4> ValueVTs; 3222 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3223 ValueVTs); 3224 unsigned NumValues = ValueVTs.size(); 3225 if (NumValues == 0) return; 3226 3227 SmallVector<SDValue, 4> Values(NumValues); 3228 SDValue Cond = getValue(I.getOperand(0)); 3229 SDValue LHSVal = getValue(I.getOperand(1)); 3230 SDValue RHSVal = getValue(I.getOperand(2)); 3231 SmallVector<SDValue, 1> BaseOps(1, Cond); 3232 ISD::NodeType OpCode = 3233 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3234 3235 bool IsUnaryAbs = false; 3236 bool Negate = false; 3237 3238 SDNodeFlags Flags; 3239 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3240 Flags.copyFMF(*FPOp); 3241 3242 // Min/max matching is only viable if all output VTs are the same. 3243 if (is_splat(ValueVTs)) { 3244 EVT VT = ValueVTs[0]; 3245 LLVMContext &Ctx = *DAG.getContext(); 3246 auto &TLI = DAG.getTargetLoweringInfo(); 3247 3248 // We care about the legality of the operation after it has been type 3249 // legalized. 3250 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3251 VT = TLI.getTypeToTransformTo(Ctx, VT); 3252 3253 // If the vselect is legal, assume we want to leave this as a vector setcc + 3254 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3255 // min/max is legal on the scalar type. 3256 bool UseScalarMinMax = VT.isVector() && 3257 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3258 3259 Value *LHS, *RHS; 3260 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3261 ISD::NodeType Opc = ISD::DELETED_NODE; 3262 switch (SPR.Flavor) { 3263 case SPF_UMAX: Opc = ISD::UMAX; break; 3264 case SPF_UMIN: Opc = ISD::UMIN; break; 3265 case SPF_SMAX: Opc = ISD::SMAX; break; 3266 case SPF_SMIN: Opc = ISD::SMIN; break; 3267 case SPF_FMINNUM: 3268 switch (SPR.NaNBehavior) { 3269 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3270 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3271 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3272 case SPNB_RETURNS_ANY: { 3273 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3274 Opc = ISD::FMINNUM; 3275 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3276 Opc = ISD::FMINIMUM; 3277 else if (UseScalarMinMax) 3278 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3279 ISD::FMINNUM : ISD::FMINIMUM; 3280 break; 3281 } 3282 } 3283 break; 3284 case SPF_FMAXNUM: 3285 switch (SPR.NaNBehavior) { 3286 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3287 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3288 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3289 case SPNB_RETURNS_ANY: 3290 3291 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3292 Opc = ISD::FMAXNUM; 3293 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3294 Opc = ISD::FMAXIMUM; 3295 else if (UseScalarMinMax) 3296 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3297 ISD::FMAXNUM : ISD::FMAXIMUM; 3298 break; 3299 } 3300 break; 3301 case SPF_NABS: 3302 Negate = true; 3303 LLVM_FALLTHROUGH; 3304 case SPF_ABS: 3305 IsUnaryAbs = true; 3306 Opc = ISD::ABS; 3307 break; 3308 default: break; 3309 } 3310 3311 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3312 (TLI.isOperationLegalOrCustom(Opc, VT) || 3313 (UseScalarMinMax && 3314 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3315 // If the underlying comparison instruction is used by any other 3316 // instruction, the consumed instructions won't be destroyed, so it is 3317 // not profitable to convert to a min/max. 3318 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3319 OpCode = Opc; 3320 LHSVal = getValue(LHS); 3321 RHSVal = getValue(RHS); 3322 BaseOps.clear(); 3323 } 3324 3325 if (IsUnaryAbs) { 3326 OpCode = Opc; 3327 LHSVal = getValue(LHS); 3328 BaseOps.clear(); 3329 } 3330 } 3331 3332 if (IsUnaryAbs) { 3333 for (unsigned i = 0; i != NumValues; ++i) { 3334 SDLoc dl = getCurSDLoc(); 3335 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3336 Values[i] = 3337 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3338 if (Negate) 3339 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3340 Values[i]); 3341 } 3342 } else { 3343 for (unsigned i = 0; i != NumValues; ++i) { 3344 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3345 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3346 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3347 Values[i] = DAG.getNode( 3348 OpCode, getCurSDLoc(), 3349 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3350 } 3351 } 3352 3353 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3354 DAG.getVTList(ValueVTs), Values)); 3355 } 3356 3357 void SelectionDAGBuilder::visitTrunc(const User &I) { 3358 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3359 SDValue N = getValue(I.getOperand(0)); 3360 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3361 I.getType()); 3362 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3363 } 3364 3365 void SelectionDAGBuilder::visitZExt(const User &I) { 3366 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3367 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3368 SDValue N = getValue(I.getOperand(0)); 3369 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3370 I.getType()); 3371 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3372 } 3373 3374 void SelectionDAGBuilder::visitSExt(const User &I) { 3375 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3376 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3377 SDValue N = getValue(I.getOperand(0)); 3378 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3379 I.getType()); 3380 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3381 } 3382 3383 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3384 // FPTrunc is never a no-op cast, no need to check 3385 SDValue N = getValue(I.getOperand(0)); 3386 SDLoc dl = getCurSDLoc(); 3387 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3388 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3389 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3390 DAG.getTargetConstant( 3391 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3392 } 3393 3394 void SelectionDAGBuilder::visitFPExt(const User &I) { 3395 // FPExt is never a no-op cast, no need to check 3396 SDValue N = getValue(I.getOperand(0)); 3397 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3398 I.getType()); 3399 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3400 } 3401 3402 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3403 // FPToUI is never a no-op cast, no need to check 3404 SDValue N = getValue(I.getOperand(0)); 3405 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3406 I.getType()); 3407 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3408 } 3409 3410 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3411 // FPToSI is never a no-op cast, no need to check 3412 SDValue N = getValue(I.getOperand(0)); 3413 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3414 I.getType()); 3415 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3416 } 3417 3418 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3419 // UIToFP is never a no-op cast, no need to check 3420 SDValue N = getValue(I.getOperand(0)); 3421 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3422 I.getType()); 3423 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3424 } 3425 3426 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3427 // SIToFP is never a no-op cast, no need to check 3428 SDValue N = getValue(I.getOperand(0)); 3429 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3430 I.getType()); 3431 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3432 } 3433 3434 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3435 // What to do depends on the size of the integer and the size of the pointer. 3436 // We can either truncate, zero extend, or no-op, accordingly. 3437 SDValue N = getValue(I.getOperand(0)); 3438 auto &TLI = DAG.getTargetLoweringInfo(); 3439 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3440 I.getType()); 3441 EVT PtrMemVT = 3442 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3443 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3444 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3445 setValue(&I, N); 3446 } 3447 3448 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3449 // What to do depends on the size of the integer and the size of the pointer. 3450 // We can either truncate, zero extend, or no-op, accordingly. 3451 SDValue N = getValue(I.getOperand(0)); 3452 auto &TLI = DAG.getTargetLoweringInfo(); 3453 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3454 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3455 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3456 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3457 setValue(&I, N); 3458 } 3459 3460 void SelectionDAGBuilder::visitBitCast(const User &I) { 3461 SDValue N = getValue(I.getOperand(0)); 3462 SDLoc dl = getCurSDLoc(); 3463 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3464 I.getType()); 3465 3466 // BitCast assures us that source and destination are the same size so this is 3467 // either a BITCAST or a no-op. 3468 if (DestVT != N.getValueType()) 3469 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3470 DestVT, N)); // convert types. 3471 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3472 // might fold any kind of constant expression to an integer constant and that 3473 // is not what we are looking for. Only recognize a bitcast of a genuine 3474 // constant integer as an opaque constant. 3475 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3476 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3477 /*isOpaque*/true)); 3478 else 3479 setValue(&I, N); // noop cast. 3480 } 3481 3482 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3483 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3484 const Value *SV = I.getOperand(0); 3485 SDValue N = getValue(SV); 3486 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3487 3488 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3489 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3490 3491 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3492 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3493 3494 setValue(&I, N); 3495 } 3496 3497 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3498 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3499 SDValue InVec = getValue(I.getOperand(0)); 3500 SDValue InVal = getValue(I.getOperand(1)); 3501 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3502 TLI.getVectorIdxTy(DAG.getDataLayout())); 3503 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3504 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3505 InVec, InVal, InIdx)); 3506 } 3507 3508 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3509 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3510 SDValue InVec = getValue(I.getOperand(0)); 3511 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3512 TLI.getVectorIdxTy(DAG.getDataLayout())); 3513 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3514 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3515 InVec, InIdx)); 3516 } 3517 3518 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3519 SDValue Src1 = getValue(I.getOperand(0)); 3520 SDValue Src2 = getValue(I.getOperand(1)); 3521 ArrayRef<int> Mask; 3522 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3523 Mask = SVI->getShuffleMask(); 3524 else 3525 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3526 SDLoc DL = getCurSDLoc(); 3527 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3528 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3529 EVT SrcVT = Src1.getValueType(); 3530 3531 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3532 VT.isScalableVector()) { 3533 // Canonical splat form of first element of first input vector. 3534 SDValue FirstElt = 3535 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3536 DAG.getVectorIdxConstant(0, DL)); 3537 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3538 return; 3539 } 3540 3541 // For now, we only handle splats for scalable vectors. 3542 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3543 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3544 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3545 3546 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3547 unsigned MaskNumElts = Mask.size(); 3548 3549 if (SrcNumElts == MaskNumElts) { 3550 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3551 return; 3552 } 3553 3554 // Normalize the shuffle vector since mask and vector length don't match. 3555 if (SrcNumElts < MaskNumElts) { 3556 // Mask is longer than the source vectors. We can use concatenate vector to 3557 // make the mask and vectors lengths match. 3558 3559 if (MaskNumElts % SrcNumElts == 0) { 3560 // Mask length is a multiple of the source vector length. 3561 // Check if the shuffle is some kind of concatenation of the input 3562 // vectors. 3563 unsigned NumConcat = MaskNumElts / SrcNumElts; 3564 bool IsConcat = true; 3565 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3566 for (unsigned i = 0; i != MaskNumElts; ++i) { 3567 int Idx = Mask[i]; 3568 if (Idx < 0) 3569 continue; 3570 // Ensure the indices in each SrcVT sized piece are sequential and that 3571 // the same source is used for the whole piece. 3572 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3573 (ConcatSrcs[i / SrcNumElts] >= 0 && 3574 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3575 IsConcat = false; 3576 break; 3577 } 3578 // Remember which source this index came from. 3579 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3580 } 3581 3582 // The shuffle is concatenating multiple vectors together. Just emit 3583 // a CONCAT_VECTORS operation. 3584 if (IsConcat) { 3585 SmallVector<SDValue, 8> ConcatOps; 3586 for (auto Src : ConcatSrcs) { 3587 if (Src < 0) 3588 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3589 else if (Src == 0) 3590 ConcatOps.push_back(Src1); 3591 else 3592 ConcatOps.push_back(Src2); 3593 } 3594 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3595 return; 3596 } 3597 } 3598 3599 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3600 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3601 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3602 PaddedMaskNumElts); 3603 3604 // Pad both vectors with undefs to make them the same length as the mask. 3605 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3606 3607 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3608 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3609 MOps1[0] = Src1; 3610 MOps2[0] = Src2; 3611 3612 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3613 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3614 3615 // Readjust mask for new input vector length. 3616 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3617 for (unsigned i = 0; i != MaskNumElts; ++i) { 3618 int Idx = Mask[i]; 3619 if (Idx >= (int)SrcNumElts) 3620 Idx -= SrcNumElts - PaddedMaskNumElts; 3621 MappedOps[i] = Idx; 3622 } 3623 3624 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3625 3626 // If the concatenated vector was padded, extract a subvector with the 3627 // correct number of elements. 3628 if (MaskNumElts != PaddedMaskNumElts) 3629 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3630 DAG.getVectorIdxConstant(0, DL)); 3631 3632 setValue(&I, Result); 3633 return; 3634 } 3635 3636 if (SrcNumElts > MaskNumElts) { 3637 // Analyze the access pattern of the vector to see if we can extract 3638 // two subvectors and do the shuffle. 3639 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3640 bool CanExtract = true; 3641 for (int Idx : Mask) { 3642 unsigned Input = 0; 3643 if (Idx < 0) 3644 continue; 3645 3646 if (Idx >= (int)SrcNumElts) { 3647 Input = 1; 3648 Idx -= SrcNumElts; 3649 } 3650 3651 // If all the indices come from the same MaskNumElts sized portion of 3652 // the sources we can use extract. Also make sure the extract wouldn't 3653 // extract past the end of the source. 3654 int NewStartIdx = alignDown(Idx, MaskNumElts); 3655 if (NewStartIdx + MaskNumElts > SrcNumElts || 3656 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3657 CanExtract = false; 3658 // Make sure we always update StartIdx as we use it to track if all 3659 // elements are undef. 3660 StartIdx[Input] = NewStartIdx; 3661 } 3662 3663 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3664 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3665 return; 3666 } 3667 if (CanExtract) { 3668 // Extract appropriate subvector and generate a vector shuffle 3669 for (unsigned Input = 0; Input < 2; ++Input) { 3670 SDValue &Src = Input == 0 ? Src1 : Src2; 3671 if (StartIdx[Input] < 0) 3672 Src = DAG.getUNDEF(VT); 3673 else { 3674 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3675 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3676 } 3677 } 3678 3679 // Calculate new mask. 3680 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3681 for (int &Idx : MappedOps) { 3682 if (Idx >= (int)SrcNumElts) 3683 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3684 else if (Idx >= 0) 3685 Idx -= StartIdx[0]; 3686 } 3687 3688 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3689 return; 3690 } 3691 } 3692 3693 // We can't use either concat vectors or extract subvectors so fall back to 3694 // replacing the shuffle with extract and build vector. 3695 // to insert and build vector. 3696 EVT EltVT = VT.getVectorElementType(); 3697 SmallVector<SDValue,8> Ops; 3698 for (int Idx : Mask) { 3699 SDValue Res; 3700 3701 if (Idx < 0) { 3702 Res = DAG.getUNDEF(EltVT); 3703 } else { 3704 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3705 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3706 3707 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3708 DAG.getVectorIdxConstant(Idx, DL)); 3709 } 3710 3711 Ops.push_back(Res); 3712 } 3713 3714 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3715 } 3716 3717 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3718 ArrayRef<unsigned> Indices; 3719 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3720 Indices = IV->getIndices(); 3721 else 3722 Indices = cast<ConstantExpr>(&I)->getIndices(); 3723 3724 const Value *Op0 = I.getOperand(0); 3725 const Value *Op1 = I.getOperand(1); 3726 Type *AggTy = I.getType(); 3727 Type *ValTy = Op1->getType(); 3728 bool IntoUndef = isa<UndefValue>(Op0); 3729 bool FromUndef = isa<UndefValue>(Op1); 3730 3731 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3732 3733 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3734 SmallVector<EVT, 4> AggValueVTs; 3735 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3736 SmallVector<EVT, 4> ValValueVTs; 3737 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3738 3739 unsigned NumAggValues = AggValueVTs.size(); 3740 unsigned NumValValues = ValValueVTs.size(); 3741 SmallVector<SDValue, 4> Values(NumAggValues); 3742 3743 // Ignore an insertvalue that produces an empty object 3744 if (!NumAggValues) { 3745 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3746 return; 3747 } 3748 3749 SDValue Agg = getValue(Op0); 3750 unsigned i = 0; 3751 // Copy the beginning value(s) from the original aggregate. 3752 for (; i != LinearIndex; ++i) 3753 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3754 SDValue(Agg.getNode(), Agg.getResNo() + i); 3755 // Copy values from the inserted value(s). 3756 if (NumValValues) { 3757 SDValue Val = getValue(Op1); 3758 for (; i != LinearIndex + NumValValues; ++i) 3759 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3760 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3761 } 3762 // Copy remaining value(s) from the original aggregate. 3763 for (; i != NumAggValues; ++i) 3764 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3765 SDValue(Agg.getNode(), Agg.getResNo() + i); 3766 3767 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3768 DAG.getVTList(AggValueVTs), Values)); 3769 } 3770 3771 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3772 ArrayRef<unsigned> Indices; 3773 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3774 Indices = EV->getIndices(); 3775 else 3776 Indices = cast<ConstantExpr>(&I)->getIndices(); 3777 3778 const Value *Op0 = I.getOperand(0); 3779 Type *AggTy = Op0->getType(); 3780 Type *ValTy = I.getType(); 3781 bool OutOfUndef = isa<UndefValue>(Op0); 3782 3783 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3784 3785 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3786 SmallVector<EVT, 4> ValValueVTs; 3787 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3788 3789 unsigned NumValValues = ValValueVTs.size(); 3790 3791 // Ignore a extractvalue that produces an empty object 3792 if (!NumValValues) { 3793 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3794 return; 3795 } 3796 3797 SmallVector<SDValue, 4> Values(NumValValues); 3798 3799 SDValue Agg = getValue(Op0); 3800 // Copy out the selected value(s). 3801 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3802 Values[i - LinearIndex] = 3803 OutOfUndef ? 3804 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3805 SDValue(Agg.getNode(), Agg.getResNo() + i); 3806 3807 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3808 DAG.getVTList(ValValueVTs), Values)); 3809 } 3810 3811 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3812 Value *Op0 = I.getOperand(0); 3813 // Note that the pointer operand may be a vector of pointers. Take the scalar 3814 // element which holds a pointer. 3815 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3816 SDValue N = getValue(Op0); 3817 SDLoc dl = getCurSDLoc(); 3818 auto &TLI = DAG.getTargetLoweringInfo(); 3819 3820 // Normalize Vector GEP - all scalar operands should be converted to the 3821 // splat vector. 3822 bool IsVectorGEP = I.getType()->isVectorTy(); 3823 ElementCount VectorElementCount = 3824 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3825 : ElementCount::getFixed(0); 3826 3827 if (IsVectorGEP && !N.getValueType().isVector()) { 3828 LLVMContext &Context = *DAG.getContext(); 3829 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3830 if (VectorElementCount.isScalable()) 3831 N = DAG.getSplatVector(VT, dl, N); 3832 else 3833 N = DAG.getSplatBuildVector(VT, dl, N); 3834 } 3835 3836 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3837 GTI != E; ++GTI) { 3838 const Value *Idx = GTI.getOperand(); 3839 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3840 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3841 if (Field) { 3842 // N = N + Offset 3843 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3844 3845 // In an inbounds GEP with an offset that is nonnegative even when 3846 // interpreted as signed, assume there is no unsigned overflow. 3847 SDNodeFlags Flags; 3848 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3849 Flags.setNoUnsignedWrap(true); 3850 3851 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3852 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3853 } 3854 } else { 3855 // IdxSize is the width of the arithmetic according to IR semantics. 3856 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3857 // (and fix up the result later). 3858 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3859 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3860 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3861 // We intentionally mask away the high bits here; ElementSize may not 3862 // fit in IdxTy. 3863 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3864 bool ElementScalable = ElementSize.isScalable(); 3865 3866 // If this is a scalar constant or a splat vector of constants, 3867 // handle it quickly. 3868 const auto *C = dyn_cast<Constant>(Idx); 3869 if (C && isa<VectorType>(C->getType())) 3870 C = C->getSplatValue(); 3871 3872 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3873 if (CI && CI->isZero()) 3874 continue; 3875 if (CI && !ElementScalable) { 3876 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3877 LLVMContext &Context = *DAG.getContext(); 3878 SDValue OffsVal; 3879 if (IsVectorGEP) 3880 OffsVal = DAG.getConstant( 3881 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3882 else 3883 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3884 3885 // In an inbounds GEP with an offset that is nonnegative even when 3886 // interpreted as signed, assume there is no unsigned overflow. 3887 SDNodeFlags Flags; 3888 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3889 Flags.setNoUnsignedWrap(true); 3890 3891 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3892 3893 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3894 continue; 3895 } 3896 3897 // N = N + Idx * ElementMul; 3898 SDValue IdxN = getValue(Idx); 3899 3900 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3901 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3902 VectorElementCount); 3903 if (VectorElementCount.isScalable()) 3904 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3905 else 3906 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3907 } 3908 3909 // If the index is smaller or larger than intptr_t, truncate or extend 3910 // it. 3911 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3912 3913 if (ElementScalable) { 3914 EVT VScaleTy = N.getValueType().getScalarType(); 3915 SDValue VScale = DAG.getNode( 3916 ISD::VSCALE, dl, VScaleTy, 3917 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3918 if (IsVectorGEP) 3919 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3920 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3921 } else { 3922 // If this is a multiply by a power of two, turn it into a shl 3923 // immediately. This is a very common case. 3924 if (ElementMul != 1) { 3925 if (ElementMul.isPowerOf2()) { 3926 unsigned Amt = ElementMul.logBase2(); 3927 IdxN = DAG.getNode(ISD::SHL, dl, 3928 N.getValueType(), IdxN, 3929 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3930 } else { 3931 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3932 IdxN.getValueType()); 3933 IdxN = DAG.getNode(ISD::MUL, dl, 3934 N.getValueType(), IdxN, Scale); 3935 } 3936 } 3937 } 3938 3939 N = DAG.getNode(ISD::ADD, dl, 3940 N.getValueType(), N, IdxN); 3941 } 3942 } 3943 3944 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3945 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3946 if (IsVectorGEP) { 3947 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3948 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3949 } 3950 3951 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3952 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3953 3954 setValue(&I, N); 3955 } 3956 3957 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3958 // If this is a fixed sized alloca in the entry block of the function, 3959 // allocate it statically on the stack. 3960 if (FuncInfo.StaticAllocaMap.count(&I)) 3961 return; // getValue will auto-populate this. 3962 3963 SDLoc dl = getCurSDLoc(); 3964 Type *Ty = I.getAllocatedType(); 3965 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3966 auto &DL = DAG.getDataLayout(); 3967 uint64_t TySize = DL.getTypeAllocSize(Ty); 3968 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3969 3970 SDValue AllocSize = getValue(I.getArraySize()); 3971 3972 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3973 if (AllocSize.getValueType() != IntPtr) 3974 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3975 3976 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3977 AllocSize, 3978 DAG.getConstant(TySize, dl, IntPtr)); 3979 3980 // Handle alignment. If the requested alignment is less than or equal to 3981 // the stack alignment, ignore it. If the size is greater than or equal to 3982 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3983 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3984 if (*Alignment <= StackAlign) 3985 Alignment = None; 3986 3987 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3988 // Round the size of the allocation up to the stack alignment size 3989 // by add SA-1 to the size. This doesn't overflow because we're computing 3990 // an address inside an alloca. 3991 SDNodeFlags Flags; 3992 Flags.setNoUnsignedWrap(true); 3993 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3994 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3995 3996 // Mask out the low bits for alignment purposes. 3997 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3998 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3999 4000 SDValue Ops[] = { 4001 getRoot(), AllocSize, 4002 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4003 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4004 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4005 setValue(&I, DSA); 4006 DAG.setRoot(DSA.getValue(1)); 4007 4008 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4009 } 4010 4011 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4012 if (I.isAtomic()) 4013 return visitAtomicLoad(I); 4014 4015 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4016 const Value *SV = I.getOperand(0); 4017 if (TLI.supportSwiftError()) { 4018 // Swifterror values can come from either a function parameter with 4019 // swifterror attribute or an alloca with swifterror attribute. 4020 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4021 if (Arg->hasSwiftErrorAttr()) 4022 return visitLoadFromSwiftError(I); 4023 } 4024 4025 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4026 if (Alloca->isSwiftError()) 4027 return visitLoadFromSwiftError(I); 4028 } 4029 } 4030 4031 SDValue Ptr = getValue(SV); 4032 4033 Type *Ty = I.getType(); 4034 Align Alignment = I.getAlign(); 4035 4036 AAMDNodes AAInfo; 4037 I.getAAMetadata(AAInfo); 4038 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4039 4040 SmallVector<EVT, 4> ValueVTs, MemVTs; 4041 SmallVector<uint64_t, 4> Offsets; 4042 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4043 unsigned NumValues = ValueVTs.size(); 4044 if (NumValues == 0) 4045 return; 4046 4047 bool isVolatile = I.isVolatile(); 4048 4049 SDValue Root; 4050 bool ConstantMemory = false; 4051 if (isVolatile) 4052 // Serialize volatile loads with other side effects. 4053 Root = getRoot(); 4054 else if (NumValues > MaxParallelChains) 4055 Root = getMemoryRoot(); 4056 else if (AA && 4057 AA->pointsToConstantMemory(MemoryLocation( 4058 SV, 4059 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4060 AAInfo))) { 4061 // Do not serialize (non-volatile) loads of constant memory with anything. 4062 Root = DAG.getEntryNode(); 4063 ConstantMemory = true; 4064 } else { 4065 // Do not serialize non-volatile loads against each other. 4066 Root = DAG.getRoot(); 4067 } 4068 4069 SDLoc dl = getCurSDLoc(); 4070 4071 if (isVolatile) 4072 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4073 4074 // An aggregate load cannot wrap around the address space, so offsets to its 4075 // parts don't wrap either. 4076 SDNodeFlags Flags; 4077 Flags.setNoUnsignedWrap(true); 4078 4079 SmallVector<SDValue, 4> Values(NumValues); 4080 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4081 EVT PtrVT = Ptr.getValueType(); 4082 4083 MachineMemOperand::Flags MMOFlags 4084 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4085 4086 unsigned ChainI = 0; 4087 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4088 // Serializing loads here may result in excessive register pressure, and 4089 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4090 // could recover a bit by hoisting nodes upward in the chain by recognizing 4091 // they are side-effect free or do not alias. The optimizer should really 4092 // avoid this case by converting large object/array copies to llvm.memcpy 4093 // (MaxParallelChains should always remain as failsafe). 4094 if (ChainI == MaxParallelChains) { 4095 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4096 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4097 makeArrayRef(Chains.data(), ChainI)); 4098 Root = Chain; 4099 ChainI = 0; 4100 } 4101 SDValue A = DAG.getNode(ISD::ADD, dl, 4102 PtrVT, Ptr, 4103 DAG.getConstant(Offsets[i], dl, PtrVT), 4104 Flags); 4105 4106 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4107 MachinePointerInfo(SV, Offsets[i]), Alignment, 4108 MMOFlags, AAInfo, Ranges); 4109 Chains[ChainI] = L.getValue(1); 4110 4111 if (MemVTs[i] != ValueVTs[i]) 4112 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4113 4114 Values[i] = L; 4115 } 4116 4117 if (!ConstantMemory) { 4118 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4119 makeArrayRef(Chains.data(), ChainI)); 4120 if (isVolatile) 4121 DAG.setRoot(Chain); 4122 else 4123 PendingLoads.push_back(Chain); 4124 } 4125 4126 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4127 DAG.getVTList(ValueVTs), Values)); 4128 } 4129 4130 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4131 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4132 "call visitStoreToSwiftError when backend supports swifterror"); 4133 4134 SmallVector<EVT, 4> ValueVTs; 4135 SmallVector<uint64_t, 4> Offsets; 4136 const Value *SrcV = I.getOperand(0); 4137 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4138 SrcV->getType(), ValueVTs, &Offsets); 4139 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4140 "expect a single EVT for swifterror"); 4141 4142 SDValue Src = getValue(SrcV); 4143 // Create a virtual register, then update the virtual register. 4144 Register VReg = 4145 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4146 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4147 // Chain can be getRoot or getControlRoot. 4148 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4149 SDValue(Src.getNode(), Src.getResNo())); 4150 DAG.setRoot(CopyNode); 4151 } 4152 4153 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4154 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4155 "call visitLoadFromSwiftError when backend supports swifterror"); 4156 4157 assert(!I.isVolatile() && 4158 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4159 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4160 "Support volatile, non temporal, invariant for load_from_swift_error"); 4161 4162 const Value *SV = I.getOperand(0); 4163 Type *Ty = I.getType(); 4164 AAMDNodes AAInfo; 4165 I.getAAMetadata(AAInfo); 4166 assert( 4167 (!AA || 4168 !AA->pointsToConstantMemory(MemoryLocation( 4169 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4170 AAInfo))) && 4171 "load_from_swift_error should not be constant memory"); 4172 4173 SmallVector<EVT, 4> ValueVTs; 4174 SmallVector<uint64_t, 4> Offsets; 4175 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4176 ValueVTs, &Offsets); 4177 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4178 "expect a single EVT for swifterror"); 4179 4180 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4181 SDValue L = DAG.getCopyFromReg( 4182 getRoot(), getCurSDLoc(), 4183 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4184 4185 setValue(&I, L); 4186 } 4187 4188 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4189 if (I.isAtomic()) 4190 return visitAtomicStore(I); 4191 4192 const Value *SrcV = I.getOperand(0); 4193 const Value *PtrV = I.getOperand(1); 4194 4195 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4196 if (TLI.supportSwiftError()) { 4197 // Swifterror values can come from either a function parameter with 4198 // swifterror attribute or an alloca with swifterror attribute. 4199 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4200 if (Arg->hasSwiftErrorAttr()) 4201 return visitStoreToSwiftError(I); 4202 } 4203 4204 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4205 if (Alloca->isSwiftError()) 4206 return visitStoreToSwiftError(I); 4207 } 4208 } 4209 4210 SmallVector<EVT, 4> ValueVTs, MemVTs; 4211 SmallVector<uint64_t, 4> Offsets; 4212 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4213 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4214 unsigned NumValues = ValueVTs.size(); 4215 if (NumValues == 0) 4216 return; 4217 4218 // Get the lowered operands. Note that we do this after 4219 // checking if NumResults is zero, because with zero results 4220 // the operands won't have values in the map. 4221 SDValue Src = getValue(SrcV); 4222 SDValue Ptr = getValue(PtrV); 4223 4224 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4225 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4226 SDLoc dl = getCurSDLoc(); 4227 Align Alignment = I.getAlign(); 4228 AAMDNodes AAInfo; 4229 I.getAAMetadata(AAInfo); 4230 4231 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4232 4233 // An aggregate load cannot wrap around the address space, so offsets to its 4234 // parts don't wrap either. 4235 SDNodeFlags Flags; 4236 Flags.setNoUnsignedWrap(true); 4237 4238 unsigned ChainI = 0; 4239 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4240 // See visitLoad comments. 4241 if (ChainI == MaxParallelChains) { 4242 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4243 makeArrayRef(Chains.data(), ChainI)); 4244 Root = Chain; 4245 ChainI = 0; 4246 } 4247 SDValue Add = 4248 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4249 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4250 if (MemVTs[i] != ValueVTs[i]) 4251 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4252 SDValue St = 4253 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4254 Alignment, MMOFlags, AAInfo); 4255 Chains[ChainI] = St; 4256 } 4257 4258 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4259 makeArrayRef(Chains.data(), ChainI)); 4260 DAG.setRoot(StoreNode); 4261 } 4262 4263 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4264 bool IsCompressing) { 4265 SDLoc sdl = getCurSDLoc(); 4266 4267 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4268 MaybeAlign &Alignment) { 4269 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4270 Src0 = I.getArgOperand(0); 4271 Ptr = I.getArgOperand(1); 4272 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4273 Mask = I.getArgOperand(3); 4274 }; 4275 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4276 MaybeAlign &Alignment) { 4277 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4278 Src0 = I.getArgOperand(0); 4279 Ptr = I.getArgOperand(1); 4280 Mask = I.getArgOperand(2); 4281 Alignment = None; 4282 }; 4283 4284 Value *PtrOperand, *MaskOperand, *Src0Operand; 4285 MaybeAlign Alignment; 4286 if (IsCompressing) 4287 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4288 else 4289 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4290 4291 SDValue Ptr = getValue(PtrOperand); 4292 SDValue Src0 = getValue(Src0Operand); 4293 SDValue Mask = getValue(MaskOperand); 4294 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4295 4296 EVT VT = Src0.getValueType(); 4297 if (!Alignment) 4298 Alignment = DAG.getEVTAlign(VT); 4299 4300 AAMDNodes AAInfo; 4301 I.getAAMetadata(AAInfo); 4302 4303 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4304 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4305 // TODO: Make MachineMemOperands aware of scalable 4306 // vectors. 4307 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4308 SDValue StoreNode = 4309 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4310 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4311 DAG.setRoot(StoreNode); 4312 setValue(&I, StoreNode); 4313 } 4314 4315 // Get a uniform base for the Gather/Scatter intrinsic. 4316 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4317 // We try to represent it as a base pointer + vector of indices. 4318 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4319 // The first operand of the GEP may be a single pointer or a vector of pointers 4320 // Example: 4321 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4322 // or 4323 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4324 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4325 // 4326 // When the first GEP operand is a single pointer - it is the uniform base we 4327 // are looking for. If first operand of the GEP is a splat vector - we 4328 // extract the splat value and use it as a uniform base. 4329 // In all other cases the function returns 'false'. 4330 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4331 ISD::MemIndexType &IndexType, SDValue &Scale, 4332 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4333 SelectionDAG& DAG = SDB->DAG; 4334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4335 const DataLayout &DL = DAG.getDataLayout(); 4336 4337 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4338 4339 // Handle splat constant pointer. 4340 if (auto *C = dyn_cast<Constant>(Ptr)) { 4341 C = C->getSplatValue(); 4342 if (!C) 4343 return false; 4344 4345 Base = SDB->getValue(C); 4346 4347 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4348 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4349 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4350 IndexType = ISD::SIGNED_SCALED; 4351 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4352 return true; 4353 } 4354 4355 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4356 if (!GEP || GEP->getParent() != CurBB) 4357 return false; 4358 4359 if (GEP->getNumOperands() != 2) 4360 return false; 4361 4362 const Value *BasePtr = GEP->getPointerOperand(); 4363 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4364 4365 // Make sure the base is scalar and the index is a vector. 4366 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4367 return false; 4368 4369 Base = SDB->getValue(BasePtr); 4370 Index = SDB->getValue(IndexVal); 4371 IndexType = ISD::SIGNED_SCALED; 4372 Scale = DAG.getTargetConstant( 4373 DL.getTypeAllocSize(GEP->getResultElementType()), 4374 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4375 return true; 4376 } 4377 4378 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4379 SDLoc sdl = getCurSDLoc(); 4380 4381 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4382 const Value *Ptr = I.getArgOperand(1); 4383 SDValue Src0 = getValue(I.getArgOperand(0)); 4384 SDValue Mask = getValue(I.getArgOperand(3)); 4385 EVT VT = Src0.getValueType(); 4386 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4387 ->getMaybeAlignValue() 4388 .getValueOr(DAG.getEVTAlign(VT)); 4389 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4390 4391 AAMDNodes AAInfo; 4392 I.getAAMetadata(AAInfo); 4393 4394 SDValue Base; 4395 SDValue Index; 4396 ISD::MemIndexType IndexType; 4397 SDValue Scale; 4398 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4399 I.getParent()); 4400 4401 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4402 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4403 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4404 // TODO: Make MachineMemOperands aware of scalable 4405 // vectors. 4406 MemoryLocation::UnknownSize, Alignment, AAInfo); 4407 if (!UniformBase) { 4408 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4409 Index = getValue(Ptr); 4410 IndexType = ISD::SIGNED_UNSCALED; 4411 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4412 } 4413 4414 EVT IdxVT = Index.getValueType(); 4415 EVT EltTy = IdxVT.getVectorElementType(); 4416 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4417 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4418 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4419 } 4420 4421 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4422 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4423 Ops, MMO, IndexType, false); 4424 DAG.setRoot(Scatter); 4425 setValue(&I, Scatter); 4426 } 4427 4428 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4429 SDLoc sdl = getCurSDLoc(); 4430 4431 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4432 MaybeAlign &Alignment) { 4433 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4434 Ptr = I.getArgOperand(0); 4435 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4436 Mask = I.getArgOperand(2); 4437 Src0 = I.getArgOperand(3); 4438 }; 4439 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4440 MaybeAlign &Alignment) { 4441 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4442 Ptr = I.getArgOperand(0); 4443 Alignment = None; 4444 Mask = I.getArgOperand(1); 4445 Src0 = I.getArgOperand(2); 4446 }; 4447 4448 Value *PtrOperand, *MaskOperand, *Src0Operand; 4449 MaybeAlign Alignment; 4450 if (IsExpanding) 4451 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4452 else 4453 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4454 4455 SDValue Ptr = getValue(PtrOperand); 4456 SDValue Src0 = getValue(Src0Operand); 4457 SDValue Mask = getValue(MaskOperand); 4458 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4459 4460 EVT VT = Src0.getValueType(); 4461 if (!Alignment) 4462 Alignment = DAG.getEVTAlign(VT); 4463 4464 AAMDNodes AAInfo; 4465 I.getAAMetadata(AAInfo); 4466 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4467 4468 // Do not serialize masked loads of constant memory with anything. 4469 MemoryLocation ML; 4470 if (VT.isScalableVector()) 4471 ML = MemoryLocation::getAfter(PtrOperand); 4472 else 4473 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4474 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4475 AAInfo); 4476 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4477 4478 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4479 4480 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4481 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4482 // TODO: Make MachineMemOperands aware of scalable 4483 // vectors. 4484 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4485 4486 SDValue Load = 4487 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4488 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4489 if (AddToChain) 4490 PendingLoads.push_back(Load.getValue(1)); 4491 setValue(&I, Load); 4492 } 4493 4494 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4495 SDLoc sdl = getCurSDLoc(); 4496 4497 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4498 const Value *Ptr = I.getArgOperand(0); 4499 SDValue Src0 = getValue(I.getArgOperand(3)); 4500 SDValue Mask = getValue(I.getArgOperand(2)); 4501 4502 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4503 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4504 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4505 ->getMaybeAlignValue() 4506 .getValueOr(DAG.getEVTAlign(VT)); 4507 4508 AAMDNodes AAInfo; 4509 I.getAAMetadata(AAInfo); 4510 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4511 4512 SDValue Root = DAG.getRoot(); 4513 SDValue Base; 4514 SDValue Index; 4515 ISD::MemIndexType IndexType; 4516 SDValue Scale; 4517 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4518 I.getParent()); 4519 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4520 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4521 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4522 // TODO: Make MachineMemOperands aware of scalable 4523 // vectors. 4524 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4525 4526 if (!UniformBase) { 4527 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4528 Index = getValue(Ptr); 4529 IndexType = ISD::SIGNED_UNSCALED; 4530 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4531 } 4532 4533 EVT IdxVT = Index.getValueType(); 4534 EVT EltTy = IdxVT.getVectorElementType(); 4535 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4536 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4537 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4538 } 4539 4540 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4541 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4542 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4543 4544 PendingLoads.push_back(Gather.getValue(1)); 4545 setValue(&I, Gather); 4546 } 4547 4548 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4549 SDLoc dl = getCurSDLoc(); 4550 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4551 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4552 SyncScope::ID SSID = I.getSyncScopeID(); 4553 4554 SDValue InChain = getRoot(); 4555 4556 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4557 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4558 4559 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4560 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4561 4562 MachineFunction &MF = DAG.getMachineFunction(); 4563 MachineMemOperand *MMO = MF.getMachineMemOperand( 4564 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4565 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4566 FailureOrdering); 4567 4568 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4569 dl, MemVT, VTs, InChain, 4570 getValue(I.getPointerOperand()), 4571 getValue(I.getCompareOperand()), 4572 getValue(I.getNewValOperand()), MMO); 4573 4574 SDValue OutChain = L.getValue(2); 4575 4576 setValue(&I, L); 4577 DAG.setRoot(OutChain); 4578 } 4579 4580 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4581 SDLoc dl = getCurSDLoc(); 4582 ISD::NodeType NT; 4583 switch (I.getOperation()) { 4584 default: llvm_unreachable("Unknown atomicrmw operation"); 4585 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4586 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4587 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4588 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4589 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4590 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4591 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4592 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4593 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4594 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4595 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4596 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4597 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4598 } 4599 AtomicOrdering Ordering = I.getOrdering(); 4600 SyncScope::ID SSID = I.getSyncScopeID(); 4601 4602 SDValue InChain = getRoot(); 4603 4604 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4605 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4606 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4607 4608 MachineFunction &MF = DAG.getMachineFunction(); 4609 MachineMemOperand *MMO = MF.getMachineMemOperand( 4610 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4611 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4612 4613 SDValue L = 4614 DAG.getAtomic(NT, dl, MemVT, InChain, 4615 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4616 MMO); 4617 4618 SDValue OutChain = L.getValue(1); 4619 4620 setValue(&I, L); 4621 DAG.setRoot(OutChain); 4622 } 4623 4624 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4625 SDLoc dl = getCurSDLoc(); 4626 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4627 SDValue Ops[3]; 4628 Ops[0] = getRoot(); 4629 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4630 TLI.getFenceOperandTy(DAG.getDataLayout())); 4631 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4632 TLI.getFenceOperandTy(DAG.getDataLayout())); 4633 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4634 } 4635 4636 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4637 SDLoc dl = getCurSDLoc(); 4638 AtomicOrdering Order = I.getOrdering(); 4639 SyncScope::ID SSID = I.getSyncScopeID(); 4640 4641 SDValue InChain = getRoot(); 4642 4643 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4644 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4645 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4646 4647 if (!TLI.supportsUnalignedAtomics() && 4648 I.getAlignment() < MemVT.getSizeInBits() / 8) 4649 report_fatal_error("Cannot generate unaligned atomic load"); 4650 4651 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4652 4653 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4654 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4655 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4656 4657 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4658 4659 SDValue Ptr = getValue(I.getPointerOperand()); 4660 4661 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4662 // TODO: Once this is better exercised by tests, it should be merged with 4663 // the normal path for loads to prevent future divergence. 4664 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4665 if (MemVT != VT) 4666 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4667 4668 setValue(&I, L); 4669 SDValue OutChain = L.getValue(1); 4670 if (!I.isUnordered()) 4671 DAG.setRoot(OutChain); 4672 else 4673 PendingLoads.push_back(OutChain); 4674 return; 4675 } 4676 4677 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4678 Ptr, MMO); 4679 4680 SDValue OutChain = L.getValue(1); 4681 if (MemVT != VT) 4682 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4683 4684 setValue(&I, L); 4685 DAG.setRoot(OutChain); 4686 } 4687 4688 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4689 SDLoc dl = getCurSDLoc(); 4690 4691 AtomicOrdering Ordering = I.getOrdering(); 4692 SyncScope::ID SSID = I.getSyncScopeID(); 4693 4694 SDValue InChain = getRoot(); 4695 4696 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4697 EVT MemVT = 4698 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4699 4700 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4701 report_fatal_error("Cannot generate unaligned atomic store"); 4702 4703 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4704 4705 MachineFunction &MF = DAG.getMachineFunction(); 4706 MachineMemOperand *MMO = MF.getMachineMemOperand( 4707 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4708 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4709 4710 SDValue Val = getValue(I.getValueOperand()); 4711 if (Val.getValueType() != MemVT) 4712 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4713 SDValue Ptr = getValue(I.getPointerOperand()); 4714 4715 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4716 // TODO: Once this is better exercised by tests, it should be merged with 4717 // the normal path for stores to prevent future divergence. 4718 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4719 DAG.setRoot(S); 4720 return; 4721 } 4722 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4723 Ptr, Val, MMO); 4724 4725 4726 DAG.setRoot(OutChain); 4727 } 4728 4729 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4730 /// node. 4731 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4732 unsigned Intrinsic) { 4733 // Ignore the callsite's attributes. A specific call site may be marked with 4734 // readnone, but the lowering code will expect the chain based on the 4735 // definition. 4736 const Function *F = I.getCalledFunction(); 4737 bool HasChain = !F->doesNotAccessMemory(); 4738 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4739 4740 // Build the operand list. 4741 SmallVector<SDValue, 8> Ops; 4742 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4743 if (OnlyLoad) { 4744 // We don't need to serialize loads against other loads. 4745 Ops.push_back(DAG.getRoot()); 4746 } else { 4747 Ops.push_back(getRoot()); 4748 } 4749 } 4750 4751 // Info is set by getTgtMemInstrinsic 4752 TargetLowering::IntrinsicInfo Info; 4753 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4754 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4755 DAG.getMachineFunction(), 4756 Intrinsic); 4757 4758 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4759 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4760 Info.opc == ISD::INTRINSIC_W_CHAIN) 4761 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4762 TLI.getPointerTy(DAG.getDataLayout()))); 4763 4764 // Add all operands of the call to the operand list. 4765 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4766 const Value *Arg = I.getArgOperand(i); 4767 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4768 Ops.push_back(getValue(Arg)); 4769 continue; 4770 } 4771 4772 // Use TargetConstant instead of a regular constant for immarg. 4773 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4774 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4775 assert(CI->getBitWidth() <= 64 && 4776 "large intrinsic immediates not handled"); 4777 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4778 } else { 4779 Ops.push_back( 4780 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4781 } 4782 } 4783 4784 SmallVector<EVT, 4> ValueVTs; 4785 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4786 4787 if (HasChain) 4788 ValueVTs.push_back(MVT::Other); 4789 4790 SDVTList VTs = DAG.getVTList(ValueVTs); 4791 4792 // Create the node. 4793 SDValue Result; 4794 if (IsTgtIntrinsic) { 4795 // This is target intrinsic that touches memory 4796 AAMDNodes AAInfo; 4797 I.getAAMetadata(AAInfo); 4798 Result = 4799 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4800 MachinePointerInfo(Info.ptrVal, Info.offset), 4801 Info.align, Info.flags, Info.size, AAInfo); 4802 } else if (!HasChain) { 4803 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4804 } else if (!I.getType()->isVoidTy()) { 4805 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4806 } else { 4807 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4808 } 4809 4810 if (HasChain) { 4811 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4812 if (OnlyLoad) 4813 PendingLoads.push_back(Chain); 4814 else 4815 DAG.setRoot(Chain); 4816 } 4817 4818 if (!I.getType()->isVoidTy()) { 4819 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4820 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4821 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4822 } else 4823 Result = lowerRangeToAssertZExt(DAG, I, Result); 4824 4825 MaybeAlign Alignment = I.getRetAlign(); 4826 if (!Alignment) 4827 Alignment = F->getAttributes().getRetAlignment(); 4828 // Insert `assertalign` node if there's an alignment. 4829 if (InsertAssertAlign && Alignment) { 4830 Result = 4831 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4832 } 4833 4834 setValue(&I, Result); 4835 } 4836 } 4837 4838 /// GetSignificand - Get the significand and build it into a floating-point 4839 /// number with exponent of 1: 4840 /// 4841 /// Op = (Op & 0x007fffff) | 0x3f800000; 4842 /// 4843 /// where Op is the hexadecimal representation of floating point value. 4844 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4845 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4846 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4847 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4848 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4849 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4850 } 4851 4852 /// GetExponent - Get the exponent: 4853 /// 4854 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4855 /// 4856 /// where Op is the hexadecimal representation of floating point value. 4857 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4858 const TargetLowering &TLI, const SDLoc &dl) { 4859 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4860 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4861 SDValue t1 = DAG.getNode( 4862 ISD::SRL, dl, MVT::i32, t0, 4863 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4864 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4865 DAG.getConstant(127, dl, MVT::i32)); 4866 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4867 } 4868 4869 /// getF32Constant - Get 32-bit floating point constant. 4870 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4871 const SDLoc &dl) { 4872 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4873 MVT::f32); 4874 } 4875 4876 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4877 SelectionDAG &DAG) { 4878 // TODO: What fast-math-flags should be set on the floating-point nodes? 4879 4880 // IntegerPartOfX = ((int32_t)(t0); 4881 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4882 4883 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4884 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4885 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4886 4887 // IntegerPartOfX <<= 23; 4888 IntegerPartOfX = DAG.getNode( 4889 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4890 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4891 DAG.getDataLayout()))); 4892 4893 SDValue TwoToFractionalPartOfX; 4894 if (LimitFloatPrecision <= 6) { 4895 // For floating-point precision of 6: 4896 // 4897 // TwoToFractionalPartOfX = 4898 // 0.997535578f + 4899 // (0.735607626f + 0.252464424f * x) * x; 4900 // 4901 // error 0.0144103317, which is 6 bits 4902 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4903 getF32Constant(DAG, 0x3e814304, dl)); 4904 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4905 getF32Constant(DAG, 0x3f3c50c8, dl)); 4906 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4907 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4908 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4909 } else if (LimitFloatPrecision <= 12) { 4910 // For floating-point precision of 12: 4911 // 4912 // TwoToFractionalPartOfX = 4913 // 0.999892986f + 4914 // (0.696457318f + 4915 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4916 // 4917 // error 0.000107046256, which is 13 to 14 bits 4918 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4919 getF32Constant(DAG, 0x3da235e3, dl)); 4920 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4921 getF32Constant(DAG, 0x3e65b8f3, dl)); 4922 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4923 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4924 getF32Constant(DAG, 0x3f324b07, dl)); 4925 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4926 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4927 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4928 } else { // LimitFloatPrecision <= 18 4929 // For floating-point precision of 18: 4930 // 4931 // TwoToFractionalPartOfX = 4932 // 0.999999982f + 4933 // (0.693148872f + 4934 // (0.240227044f + 4935 // (0.554906021e-1f + 4936 // (0.961591928e-2f + 4937 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4938 // error 2.47208000*10^(-7), which is better than 18 bits 4939 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4940 getF32Constant(DAG, 0x3924b03e, dl)); 4941 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4942 getF32Constant(DAG, 0x3ab24b87, dl)); 4943 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4944 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4945 getF32Constant(DAG, 0x3c1d8c17, dl)); 4946 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4947 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4948 getF32Constant(DAG, 0x3d634a1d, dl)); 4949 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4950 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4951 getF32Constant(DAG, 0x3e75fe14, dl)); 4952 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4953 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4954 getF32Constant(DAG, 0x3f317234, dl)); 4955 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4956 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4957 getF32Constant(DAG, 0x3f800000, dl)); 4958 } 4959 4960 // Add the exponent into the result in integer domain. 4961 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4962 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4963 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4964 } 4965 4966 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4967 /// limited-precision mode. 4968 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4969 const TargetLowering &TLI, SDNodeFlags Flags) { 4970 if (Op.getValueType() == MVT::f32 && 4971 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4972 4973 // Put the exponent in the right bit position for later addition to the 4974 // final result: 4975 // 4976 // t0 = Op * log2(e) 4977 4978 // TODO: What fast-math-flags should be set here? 4979 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4980 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4981 return getLimitedPrecisionExp2(t0, dl, DAG); 4982 } 4983 4984 // No special expansion. 4985 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 4986 } 4987 4988 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4989 /// limited-precision mode. 4990 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4991 const TargetLowering &TLI, SDNodeFlags Flags) { 4992 // TODO: What fast-math-flags should be set on the floating-point nodes? 4993 4994 if (Op.getValueType() == MVT::f32 && 4995 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4996 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4997 4998 // Scale the exponent by log(2). 4999 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5000 SDValue LogOfExponent = 5001 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5002 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5003 5004 // Get the significand and build it into a floating-point number with 5005 // exponent of 1. 5006 SDValue X = GetSignificand(DAG, Op1, dl); 5007 5008 SDValue LogOfMantissa; 5009 if (LimitFloatPrecision <= 6) { 5010 // For floating-point precision of 6: 5011 // 5012 // LogofMantissa = 5013 // -1.1609546f + 5014 // (1.4034025f - 0.23903021f * x) * x; 5015 // 5016 // error 0.0034276066, which is better than 8 bits 5017 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5018 getF32Constant(DAG, 0xbe74c456, dl)); 5019 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5020 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5021 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5022 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5023 getF32Constant(DAG, 0x3f949a29, dl)); 5024 } else if (LimitFloatPrecision <= 12) { 5025 // For floating-point precision of 12: 5026 // 5027 // LogOfMantissa = 5028 // -1.7417939f + 5029 // (2.8212026f + 5030 // (-1.4699568f + 5031 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5032 // 5033 // error 0.000061011436, which is 14 bits 5034 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5035 getF32Constant(DAG, 0xbd67b6d6, dl)); 5036 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5037 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5038 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5039 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5040 getF32Constant(DAG, 0x3fbc278b, dl)); 5041 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5042 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5043 getF32Constant(DAG, 0x40348e95, dl)); 5044 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5045 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5046 getF32Constant(DAG, 0x3fdef31a, dl)); 5047 } else { // LimitFloatPrecision <= 18 5048 // For floating-point precision of 18: 5049 // 5050 // LogOfMantissa = 5051 // -2.1072184f + 5052 // (4.2372794f + 5053 // (-3.7029485f + 5054 // (2.2781945f + 5055 // (-0.87823314f + 5056 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5057 // 5058 // error 0.0000023660568, which is better than 18 bits 5059 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5060 getF32Constant(DAG, 0xbc91e5ac, dl)); 5061 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5062 getF32Constant(DAG, 0x3e4350aa, dl)); 5063 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5064 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5065 getF32Constant(DAG, 0x3f60d3e3, dl)); 5066 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5067 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5068 getF32Constant(DAG, 0x4011cdf0, dl)); 5069 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5070 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5071 getF32Constant(DAG, 0x406cfd1c, dl)); 5072 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5073 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5074 getF32Constant(DAG, 0x408797cb, dl)); 5075 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5076 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5077 getF32Constant(DAG, 0x4006dcab, dl)); 5078 } 5079 5080 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5081 } 5082 5083 // No special expansion. 5084 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5085 } 5086 5087 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5088 /// limited-precision mode. 5089 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5090 const TargetLowering &TLI, SDNodeFlags Flags) { 5091 // TODO: What fast-math-flags should be set on the floating-point nodes? 5092 5093 if (Op.getValueType() == MVT::f32 && 5094 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5095 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5096 5097 // Get the exponent. 5098 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5099 5100 // Get the significand and build it into a floating-point number with 5101 // exponent of 1. 5102 SDValue X = GetSignificand(DAG, Op1, dl); 5103 5104 // Different possible minimax approximations of significand in 5105 // floating-point for various degrees of accuracy over [1,2]. 5106 SDValue Log2ofMantissa; 5107 if (LimitFloatPrecision <= 6) { 5108 // For floating-point precision of 6: 5109 // 5110 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5111 // 5112 // error 0.0049451742, which is more than 7 bits 5113 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5114 getF32Constant(DAG, 0xbeb08fe0, dl)); 5115 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5116 getF32Constant(DAG, 0x40019463, dl)); 5117 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5118 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5119 getF32Constant(DAG, 0x3fd6633d, dl)); 5120 } else if (LimitFloatPrecision <= 12) { 5121 // For floating-point precision of 12: 5122 // 5123 // Log2ofMantissa = 5124 // -2.51285454f + 5125 // (4.07009056f + 5126 // (-2.12067489f + 5127 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5128 // 5129 // error 0.0000876136000, which is better than 13 bits 5130 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5131 getF32Constant(DAG, 0xbda7262e, dl)); 5132 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5133 getF32Constant(DAG, 0x3f25280b, dl)); 5134 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5135 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5136 getF32Constant(DAG, 0x4007b923, dl)); 5137 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5138 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5139 getF32Constant(DAG, 0x40823e2f, dl)); 5140 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5141 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5142 getF32Constant(DAG, 0x4020d29c, dl)); 5143 } else { // LimitFloatPrecision <= 18 5144 // For floating-point precision of 18: 5145 // 5146 // Log2ofMantissa = 5147 // -3.0400495f + 5148 // (6.1129976f + 5149 // (-5.3420409f + 5150 // (3.2865683f + 5151 // (-1.2669343f + 5152 // (0.27515199f - 5153 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5154 // 5155 // error 0.0000018516, which is better than 18 bits 5156 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5157 getF32Constant(DAG, 0xbcd2769e, dl)); 5158 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5159 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5160 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5161 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5162 getF32Constant(DAG, 0x3fa22ae7, dl)); 5163 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5164 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5165 getF32Constant(DAG, 0x40525723, dl)); 5166 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5167 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5168 getF32Constant(DAG, 0x40aaf200, dl)); 5169 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5170 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5171 getF32Constant(DAG, 0x40c39dad, dl)); 5172 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5173 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5174 getF32Constant(DAG, 0x4042902c, dl)); 5175 } 5176 5177 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5178 } 5179 5180 // No special expansion. 5181 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5182 } 5183 5184 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5185 /// limited-precision mode. 5186 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5187 const TargetLowering &TLI, SDNodeFlags Flags) { 5188 // TODO: What fast-math-flags should be set on the floating-point nodes? 5189 5190 if (Op.getValueType() == MVT::f32 && 5191 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5192 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5193 5194 // Scale the exponent by log10(2) [0.30102999f]. 5195 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5196 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5197 getF32Constant(DAG, 0x3e9a209a, dl)); 5198 5199 // Get the significand and build it into a floating-point number with 5200 // exponent of 1. 5201 SDValue X = GetSignificand(DAG, Op1, dl); 5202 5203 SDValue Log10ofMantissa; 5204 if (LimitFloatPrecision <= 6) { 5205 // For floating-point precision of 6: 5206 // 5207 // Log10ofMantissa = 5208 // -0.50419619f + 5209 // (0.60948995f - 0.10380950f * x) * x; 5210 // 5211 // error 0.0014886165, which is 6 bits 5212 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5213 getF32Constant(DAG, 0xbdd49a13, dl)); 5214 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5215 getF32Constant(DAG, 0x3f1c0789, dl)); 5216 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5217 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5218 getF32Constant(DAG, 0x3f011300, dl)); 5219 } else if (LimitFloatPrecision <= 12) { 5220 // For floating-point precision of 12: 5221 // 5222 // Log10ofMantissa = 5223 // -0.64831180f + 5224 // (0.91751397f + 5225 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5226 // 5227 // error 0.00019228036, which is better than 12 bits 5228 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5229 getF32Constant(DAG, 0x3d431f31, dl)); 5230 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5231 getF32Constant(DAG, 0x3ea21fb2, dl)); 5232 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5233 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5234 getF32Constant(DAG, 0x3f6ae232, dl)); 5235 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5236 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5237 getF32Constant(DAG, 0x3f25f7c3, dl)); 5238 } else { // LimitFloatPrecision <= 18 5239 // For floating-point precision of 18: 5240 // 5241 // Log10ofMantissa = 5242 // -0.84299375f + 5243 // (1.5327582f + 5244 // (-1.0688956f + 5245 // (0.49102474f + 5246 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5247 // 5248 // error 0.0000037995730, which is better than 18 bits 5249 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5250 getF32Constant(DAG, 0x3c5d51ce, dl)); 5251 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5252 getF32Constant(DAG, 0x3e00685a, dl)); 5253 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5254 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5255 getF32Constant(DAG, 0x3efb6798, dl)); 5256 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5257 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5258 getF32Constant(DAG, 0x3f88d192, dl)); 5259 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5260 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5261 getF32Constant(DAG, 0x3fc4316c, dl)); 5262 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5263 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5264 getF32Constant(DAG, 0x3f57ce70, dl)); 5265 } 5266 5267 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5268 } 5269 5270 // No special expansion. 5271 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5272 } 5273 5274 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5275 /// limited-precision mode. 5276 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5277 const TargetLowering &TLI, SDNodeFlags Flags) { 5278 if (Op.getValueType() == MVT::f32 && 5279 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5280 return getLimitedPrecisionExp2(Op, dl, DAG); 5281 5282 // No special expansion. 5283 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5284 } 5285 5286 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5287 /// limited-precision mode with x == 10.0f. 5288 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5289 SelectionDAG &DAG, const TargetLowering &TLI, 5290 SDNodeFlags Flags) { 5291 bool IsExp10 = false; 5292 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5293 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5294 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5295 APFloat Ten(10.0f); 5296 IsExp10 = LHSC->isExactlyValue(Ten); 5297 } 5298 } 5299 5300 // TODO: What fast-math-flags should be set on the FMUL node? 5301 if (IsExp10) { 5302 // Put the exponent in the right bit position for later addition to the 5303 // final result: 5304 // 5305 // #define LOG2OF10 3.3219281f 5306 // t0 = Op * LOG2OF10; 5307 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5308 getF32Constant(DAG, 0x40549a78, dl)); 5309 return getLimitedPrecisionExp2(t0, dl, DAG); 5310 } 5311 5312 // No special expansion. 5313 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5314 } 5315 5316 /// ExpandPowI - Expand a llvm.powi intrinsic. 5317 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5318 SelectionDAG &DAG) { 5319 // If RHS is a constant, we can expand this out to a multiplication tree, 5320 // otherwise we end up lowering to a call to __powidf2 (for example). When 5321 // optimizing for size, we only want to do this if the expansion would produce 5322 // a small number of multiplies, otherwise we do the full expansion. 5323 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5324 // Get the exponent as a positive value. 5325 unsigned Val = RHSC->getSExtValue(); 5326 if ((int)Val < 0) Val = -Val; 5327 5328 // powi(x, 0) -> 1.0 5329 if (Val == 0) 5330 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5331 5332 bool OptForSize = DAG.shouldOptForSize(); 5333 if (!OptForSize || 5334 // If optimizing for size, don't insert too many multiplies. 5335 // This inserts up to 5 multiplies. 5336 countPopulation(Val) + Log2_32(Val) < 7) { 5337 // We use the simple binary decomposition method to generate the multiply 5338 // sequence. There are more optimal ways to do this (for example, 5339 // powi(x,15) generates one more multiply than it should), but this has 5340 // the benefit of being both really simple and much better than a libcall. 5341 SDValue Res; // Logically starts equal to 1.0 5342 SDValue CurSquare = LHS; 5343 // TODO: Intrinsics should have fast-math-flags that propagate to these 5344 // nodes. 5345 while (Val) { 5346 if (Val & 1) { 5347 if (Res.getNode()) 5348 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5349 else 5350 Res = CurSquare; // 1.0*CurSquare. 5351 } 5352 5353 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5354 CurSquare, CurSquare); 5355 Val >>= 1; 5356 } 5357 5358 // If the original was negative, invert the result, producing 1/(x*x*x). 5359 if (RHSC->getSExtValue() < 0) 5360 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5361 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5362 return Res; 5363 } 5364 } 5365 5366 // Otherwise, expand to a libcall. 5367 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5368 } 5369 5370 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5371 SDValue LHS, SDValue RHS, SDValue Scale, 5372 SelectionDAG &DAG, const TargetLowering &TLI) { 5373 EVT VT = LHS.getValueType(); 5374 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5375 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5376 LLVMContext &Ctx = *DAG.getContext(); 5377 5378 // If the type is legal but the operation isn't, this node might survive all 5379 // the way to operation legalization. If we end up there and we do not have 5380 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5381 // node. 5382 5383 // Coax the legalizer into expanding the node during type legalization instead 5384 // by bumping the size by one bit. This will force it to Promote, enabling the 5385 // early expansion and avoiding the need to expand later. 5386 5387 // We don't have to do this if Scale is 0; that can always be expanded, unless 5388 // it's a saturating signed operation. Those can experience true integer 5389 // division overflow, a case which we must avoid. 5390 5391 // FIXME: We wouldn't have to do this (or any of the early 5392 // expansion/promotion) if it was possible to expand a libcall of an 5393 // illegal type during operation legalization. But it's not, so things 5394 // get a bit hacky. 5395 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5396 if ((ScaleInt > 0 || (Saturating && Signed)) && 5397 (TLI.isTypeLegal(VT) || 5398 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5399 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5400 Opcode, VT, ScaleInt); 5401 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5402 EVT PromVT; 5403 if (VT.isScalarInteger()) 5404 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5405 else if (VT.isVector()) { 5406 PromVT = VT.getVectorElementType(); 5407 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5408 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5409 } else 5410 llvm_unreachable("Wrong VT for DIVFIX?"); 5411 if (Signed) { 5412 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5413 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5414 } else { 5415 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5416 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5417 } 5418 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5419 // For saturating operations, we need to shift up the LHS to get the 5420 // proper saturation width, and then shift down again afterwards. 5421 if (Saturating) 5422 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5423 DAG.getConstant(1, DL, ShiftTy)); 5424 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5425 if (Saturating) 5426 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5427 DAG.getConstant(1, DL, ShiftTy)); 5428 return DAG.getZExtOrTrunc(Res, DL, VT); 5429 } 5430 } 5431 5432 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5433 } 5434 5435 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5436 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5437 static void 5438 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5439 const SDValue &N) { 5440 switch (N.getOpcode()) { 5441 case ISD::CopyFromReg: { 5442 SDValue Op = N.getOperand(1); 5443 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5444 Op.getValueType().getSizeInBits()); 5445 return; 5446 } 5447 case ISD::BITCAST: 5448 case ISD::AssertZext: 5449 case ISD::AssertSext: 5450 case ISD::TRUNCATE: 5451 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5452 return; 5453 case ISD::BUILD_PAIR: 5454 case ISD::BUILD_VECTOR: 5455 case ISD::CONCAT_VECTORS: 5456 for (SDValue Op : N->op_values()) 5457 getUnderlyingArgRegs(Regs, Op); 5458 return; 5459 default: 5460 return; 5461 } 5462 } 5463 5464 /// If the DbgValueInst is a dbg_value of a function argument, create the 5465 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5466 /// instruction selection, they will be inserted to the entry BB. 5467 /// We don't currently support this for variadic dbg_values, as they shouldn't 5468 /// appear for function arguments or in the prologue. 5469 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5470 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5471 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5472 const Argument *Arg = dyn_cast<Argument>(V); 5473 if (!Arg) 5474 return false; 5475 5476 if (!IsDbgDeclare) { 5477 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5478 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5479 // the entry block. 5480 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5481 if (!IsInEntryBlock) 5482 return false; 5483 5484 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5485 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5486 // variable that also is a param. 5487 // 5488 // Although, if we are at the top of the entry block already, we can still 5489 // emit using ArgDbgValue. This might catch some situations when the 5490 // dbg.value refers to an argument that isn't used in the entry block, so 5491 // any CopyToReg node would be optimized out and the only way to express 5492 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5493 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5494 // we should only emit as ArgDbgValue if the Variable is an argument to the 5495 // current function, and the dbg.value intrinsic is found in the entry 5496 // block. 5497 bool VariableIsFunctionInputArg = Variable->isParameter() && 5498 !DL->getInlinedAt(); 5499 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5500 if (!IsInPrologue && !VariableIsFunctionInputArg) 5501 return false; 5502 5503 // Here we assume that a function argument on IR level only can be used to 5504 // describe one input parameter on source level. If we for example have 5505 // source code like this 5506 // 5507 // struct A { long x, y; }; 5508 // void foo(struct A a, long b) { 5509 // ... 5510 // b = a.x; 5511 // ... 5512 // } 5513 // 5514 // and IR like this 5515 // 5516 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5517 // entry: 5518 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5519 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5520 // call void @llvm.dbg.value(metadata i32 %b, "b", 5521 // ... 5522 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5523 // ... 5524 // 5525 // then the last dbg.value is describing a parameter "b" using a value that 5526 // is an argument. But since we already has used %a1 to describe a parameter 5527 // we should not handle that last dbg.value here (that would result in an 5528 // incorrect hoisting of the DBG_VALUE to the function entry). 5529 // Notice that we allow one dbg.value per IR level argument, to accommodate 5530 // for the situation with fragments above. 5531 if (VariableIsFunctionInputArg) { 5532 unsigned ArgNo = Arg->getArgNo(); 5533 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5534 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5535 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5536 return false; 5537 FuncInfo.DescribedArgs.set(ArgNo); 5538 } 5539 } 5540 5541 MachineFunction &MF = DAG.getMachineFunction(); 5542 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5543 5544 bool IsIndirect = false; 5545 Optional<MachineOperand> Op; 5546 // Some arguments' frame index is recorded during argument lowering. 5547 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5548 if (FI != std::numeric_limits<int>::max()) 5549 Op = MachineOperand::CreateFI(FI); 5550 5551 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5552 if (!Op && N.getNode()) { 5553 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5554 Register Reg; 5555 if (ArgRegsAndSizes.size() == 1) 5556 Reg = ArgRegsAndSizes.front().first; 5557 5558 if (Reg && Reg.isVirtual()) { 5559 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5560 Register PR = RegInfo.getLiveInPhysReg(Reg); 5561 if (PR) 5562 Reg = PR; 5563 } 5564 if (Reg) { 5565 Op = MachineOperand::CreateReg(Reg, false); 5566 IsIndirect = IsDbgDeclare; 5567 } 5568 } 5569 5570 if (!Op && N.getNode()) { 5571 // Check if frame index is available. 5572 SDValue LCandidate = peekThroughBitcasts(N); 5573 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5574 if (FrameIndexSDNode *FINode = 5575 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5576 Op = MachineOperand::CreateFI(FINode->getIndex()); 5577 } 5578 5579 if (!Op) { 5580 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5581 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5582 SplitRegs) { 5583 unsigned Offset = 0; 5584 for (auto RegAndSize : SplitRegs) { 5585 // If the expression is already a fragment, the current register 5586 // offset+size might extend beyond the fragment. In this case, only 5587 // the register bits that are inside the fragment are relevant. 5588 int RegFragmentSizeInBits = RegAndSize.second; 5589 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5590 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5591 // The register is entirely outside the expression fragment, 5592 // so is irrelevant for debug info. 5593 if (Offset >= ExprFragmentSizeInBits) 5594 break; 5595 // The register is partially outside the expression fragment, only 5596 // the low bits within the fragment are relevant for debug info. 5597 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5598 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5599 } 5600 } 5601 5602 auto FragmentExpr = DIExpression::createFragmentExpression( 5603 Expr, Offset, RegFragmentSizeInBits); 5604 Offset += RegAndSize.second; 5605 // If a valid fragment expression cannot be created, the variable's 5606 // correct value cannot be determined and so it is set as Undef. 5607 if (!FragmentExpr) { 5608 SDDbgValue *SDV = DAG.getConstantDbgValue( 5609 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5610 DAG.AddDbgValue(SDV, false); 5611 continue; 5612 } 5613 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5614 FuncInfo.ArgDbgValues.push_back( 5615 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5616 RegAndSize.first, Variable, *FragmentExpr)); 5617 } 5618 }; 5619 5620 // Check if ValueMap has reg number. 5621 DenseMap<const Value *, Register>::const_iterator 5622 VMI = FuncInfo.ValueMap.find(V); 5623 if (VMI != FuncInfo.ValueMap.end()) { 5624 const auto &TLI = DAG.getTargetLoweringInfo(); 5625 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5626 V->getType(), None); 5627 if (RFV.occupiesMultipleRegs()) { 5628 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5629 return true; 5630 } 5631 5632 Op = MachineOperand::CreateReg(VMI->second, false); 5633 IsIndirect = IsDbgDeclare; 5634 } else if (ArgRegsAndSizes.size() > 1) { 5635 // This was split due to the calling convention, and no virtual register 5636 // mapping exists for the value. 5637 splitMultiRegDbgValue(ArgRegsAndSizes); 5638 return true; 5639 } 5640 } 5641 5642 if (!Op) 5643 return false; 5644 5645 assert(Variable->isValidLocationForIntrinsic(DL) && 5646 "Expected inlined-at fields to agree"); 5647 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5648 FuncInfo.ArgDbgValues.push_back( 5649 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5650 *Op, Variable, Expr)); 5651 5652 return true; 5653 } 5654 5655 /// Return the appropriate SDDbgValue based on N. 5656 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5657 DILocalVariable *Variable, 5658 DIExpression *Expr, 5659 const DebugLoc &dl, 5660 unsigned DbgSDNodeOrder) { 5661 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5662 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5663 // stack slot locations. 5664 // 5665 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5666 // debug values here after optimization: 5667 // 5668 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5669 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5670 // 5671 // Both describe the direct values of their associated variables. 5672 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5673 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5674 } 5675 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5676 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5677 } 5678 5679 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5680 switch (Intrinsic) { 5681 case Intrinsic::smul_fix: 5682 return ISD::SMULFIX; 5683 case Intrinsic::umul_fix: 5684 return ISD::UMULFIX; 5685 case Intrinsic::smul_fix_sat: 5686 return ISD::SMULFIXSAT; 5687 case Intrinsic::umul_fix_sat: 5688 return ISD::UMULFIXSAT; 5689 case Intrinsic::sdiv_fix: 5690 return ISD::SDIVFIX; 5691 case Intrinsic::udiv_fix: 5692 return ISD::UDIVFIX; 5693 case Intrinsic::sdiv_fix_sat: 5694 return ISD::SDIVFIXSAT; 5695 case Intrinsic::udiv_fix_sat: 5696 return ISD::UDIVFIXSAT; 5697 default: 5698 llvm_unreachable("Unhandled fixed point intrinsic"); 5699 } 5700 } 5701 5702 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5703 const char *FunctionName) { 5704 assert(FunctionName && "FunctionName must not be nullptr"); 5705 SDValue Callee = DAG.getExternalSymbol( 5706 FunctionName, 5707 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5708 LowerCallTo(I, Callee, I.isTailCall()); 5709 } 5710 5711 /// Given a @llvm.call.preallocated.setup, return the corresponding 5712 /// preallocated call. 5713 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5714 assert(cast<CallBase>(PreallocatedSetup) 5715 ->getCalledFunction() 5716 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5717 "expected call_preallocated_setup Value"); 5718 for (auto *U : PreallocatedSetup->users()) { 5719 auto *UseCall = cast<CallBase>(U); 5720 const Function *Fn = UseCall->getCalledFunction(); 5721 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5722 return UseCall; 5723 } 5724 } 5725 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5726 } 5727 5728 /// Lower the call to the specified intrinsic function. 5729 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5730 unsigned Intrinsic) { 5731 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5732 SDLoc sdl = getCurSDLoc(); 5733 DebugLoc dl = getCurDebugLoc(); 5734 SDValue Res; 5735 5736 SDNodeFlags Flags; 5737 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5738 Flags.copyFMF(*FPOp); 5739 5740 switch (Intrinsic) { 5741 default: 5742 // By default, turn this into a target intrinsic node. 5743 visitTargetIntrinsic(I, Intrinsic); 5744 return; 5745 case Intrinsic::vscale: { 5746 match(&I, m_VScale(DAG.getDataLayout())); 5747 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5748 setValue(&I, 5749 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5750 return; 5751 } 5752 case Intrinsic::vastart: visitVAStart(I); return; 5753 case Intrinsic::vaend: visitVAEnd(I); return; 5754 case Intrinsic::vacopy: visitVACopy(I); return; 5755 case Intrinsic::returnaddress: 5756 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5757 TLI.getPointerTy(DAG.getDataLayout()), 5758 getValue(I.getArgOperand(0)))); 5759 return; 5760 case Intrinsic::addressofreturnaddress: 5761 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5762 TLI.getPointerTy(DAG.getDataLayout()))); 5763 return; 5764 case Intrinsic::sponentry: 5765 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5766 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5767 return; 5768 case Intrinsic::frameaddress: 5769 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5770 TLI.getFrameIndexTy(DAG.getDataLayout()), 5771 getValue(I.getArgOperand(0)))); 5772 return; 5773 case Intrinsic::read_volatile_register: 5774 case Intrinsic::read_register: { 5775 Value *Reg = I.getArgOperand(0); 5776 SDValue Chain = getRoot(); 5777 SDValue RegName = 5778 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5779 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5780 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5781 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5782 setValue(&I, Res); 5783 DAG.setRoot(Res.getValue(1)); 5784 return; 5785 } 5786 case Intrinsic::write_register: { 5787 Value *Reg = I.getArgOperand(0); 5788 Value *RegValue = I.getArgOperand(1); 5789 SDValue Chain = getRoot(); 5790 SDValue RegName = 5791 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5792 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5793 RegName, getValue(RegValue))); 5794 return; 5795 } 5796 case Intrinsic::memcpy: { 5797 const auto &MCI = cast<MemCpyInst>(I); 5798 SDValue Op1 = getValue(I.getArgOperand(0)); 5799 SDValue Op2 = getValue(I.getArgOperand(1)); 5800 SDValue Op3 = getValue(I.getArgOperand(2)); 5801 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5802 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5803 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5804 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5805 bool isVol = MCI.isVolatile(); 5806 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5807 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5808 // node. 5809 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5810 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5811 /* AlwaysInline */ false, isTC, 5812 MachinePointerInfo(I.getArgOperand(0)), 5813 MachinePointerInfo(I.getArgOperand(1))); 5814 updateDAGForMaybeTailCall(MC); 5815 return; 5816 } 5817 case Intrinsic::memcpy_inline: { 5818 const auto &MCI = cast<MemCpyInlineInst>(I); 5819 SDValue Dst = getValue(I.getArgOperand(0)); 5820 SDValue Src = getValue(I.getArgOperand(1)); 5821 SDValue Size = getValue(I.getArgOperand(2)); 5822 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5823 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5824 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5825 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5826 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5827 bool isVol = MCI.isVolatile(); 5828 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5829 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5830 // node. 5831 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5832 /* AlwaysInline */ true, isTC, 5833 MachinePointerInfo(I.getArgOperand(0)), 5834 MachinePointerInfo(I.getArgOperand(1))); 5835 updateDAGForMaybeTailCall(MC); 5836 return; 5837 } 5838 case Intrinsic::memset: { 5839 const auto &MSI = cast<MemSetInst>(I); 5840 SDValue Op1 = getValue(I.getArgOperand(0)); 5841 SDValue Op2 = getValue(I.getArgOperand(1)); 5842 SDValue Op3 = getValue(I.getArgOperand(2)); 5843 // @llvm.memset defines 0 and 1 to both mean no alignment. 5844 Align Alignment = MSI.getDestAlign().valueOrOne(); 5845 bool isVol = MSI.isVolatile(); 5846 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5847 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5848 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5849 MachinePointerInfo(I.getArgOperand(0))); 5850 updateDAGForMaybeTailCall(MS); 5851 return; 5852 } 5853 case Intrinsic::memmove: { 5854 const auto &MMI = cast<MemMoveInst>(I); 5855 SDValue Op1 = getValue(I.getArgOperand(0)); 5856 SDValue Op2 = getValue(I.getArgOperand(1)); 5857 SDValue Op3 = getValue(I.getArgOperand(2)); 5858 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5859 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5860 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5861 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5862 bool isVol = MMI.isVolatile(); 5863 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5864 // FIXME: Support passing different dest/src alignments to the memmove DAG 5865 // node. 5866 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5867 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5868 isTC, MachinePointerInfo(I.getArgOperand(0)), 5869 MachinePointerInfo(I.getArgOperand(1))); 5870 updateDAGForMaybeTailCall(MM); 5871 return; 5872 } 5873 case Intrinsic::memcpy_element_unordered_atomic: { 5874 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5875 SDValue Dst = getValue(MI.getRawDest()); 5876 SDValue Src = getValue(MI.getRawSource()); 5877 SDValue Length = getValue(MI.getLength()); 5878 5879 unsigned DstAlign = MI.getDestAlignment(); 5880 unsigned SrcAlign = MI.getSourceAlignment(); 5881 Type *LengthTy = MI.getLength()->getType(); 5882 unsigned ElemSz = MI.getElementSizeInBytes(); 5883 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5884 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5885 SrcAlign, Length, LengthTy, ElemSz, isTC, 5886 MachinePointerInfo(MI.getRawDest()), 5887 MachinePointerInfo(MI.getRawSource())); 5888 updateDAGForMaybeTailCall(MC); 5889 return; 5890 } 5891 case Intrinsic::memmove_element_unordered_atomic: { 5892 auto &MI = cast<AtomicMemMoveInst>(I); 5893 SDValue Dst = getValue(MI.getRawDest()); 5894 SDValue Src = getValue(MI.getRawSource()); 5895 SDValue Length = getValue(MI.getLength()); 5896 5897 unsigned DstAlign = MI.getDestAlignment(); 5898 unsigned SrcAlign = MI.getSourceAlignment(); 5899 Type *LengthTy = MI.getLength()->getType(); 5900 unsigned ElemSz = MI.getElementSizeInBytes(); 5901 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5902 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5903 SrcAlign, Length, LengthTy, ElemSz, isTC, 5904 MachinePointerInfo(MI.getRawDest()), 5905 MachinePointerInfo(MI.getRawSource())); 5906 updateDAGForMaybeTailCall(MC); 5907 return; 5908 } 5909 case Intrinsic::memset_element_unordered_atomic: { 5910 auto &MI = cast<AtomicMemSetInst>(I); 5911 SDValue Dst = getValue(MI.getRawDest()); 5912 SDValue Val = getValue(MI.getValue()); 5913 SDValue Length = getValue(MI.getLength()); 5914 5915 unsigned DstAlign = MI.getDestAlignment(); 5916 Type *LengthTy = MI.getLength()->getType(); 5917 unsigned ElemSz = MI.getElementSizeInBytes(); 5918 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5919 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5920 LengthTy, ElemSz, isTC, 5921 MachinePointerInfo(MI.getRawDest())); 5922 updateDAGForMaybeTailCall(MC); 5923 return; 5924 } 5925 case Intrinsic::call_preallocated_setup: { 5926 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5927 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5928 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5929 getRoot(), SrcValue); 5930 setValue(&I, Res); 5931 DAG.setRoot(Res); 5932 return; 5933 } 5934 case Intrinsic::call_preallocated_arg: { 5935 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5936 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5937 SDValue Ops[3]; 5938 Ops[0] = getRoot(); 5939 Ops[1] = SrcValue; 5940 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5941 MVT::i32); // arg index 5942 SDValue Res = DAG.getNode( 5943 ISD::PREALLOCATED_ARG, sdl, 5944 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5945 setValue(&I, Res); 5946 DAG.setRoot(Res.getValue(1)); 5947 return; 5948 } 5949 case Intrinsic::dbg_addr: 5950 case Intrinsic::dbg_declare: { 5951 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 5952 // they are non-variadic. 5953 const auto &DI = cast<DbgVariableIntrinsic>(I); 5954 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 5955 DILocalVariable *Variable = DI.getVariable(); 5956 DIExpression *Expression = DI.getExpression(); 5957 dropDanglingDebugInfo(Variable, Expression); 5958 assert(Variable && "Missing variable"); 5959 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5960 << "\n"); 5961 // Check if address has undef value. 5962 const Value *Address = DI.getVariableLocationOp(0); 5963 if (!Address || isa<UndefValue>(Address) || 5964 (Address->use_empty() && !isa<Argument>(Address))) { 5965 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5966 << " (bad/undef/unused-arg address)\n"); 5967 return; 5968 } 5969 5970 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5971 5972 // Check if this variable can be described by a frame index, typically 5973 // either as a static alloca or a byval parameter. 5974 int FI = std::numeric_limits<int>::max(); 5975 if (const auto *AI = 5976 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5977 if (AI->isStaticAlloca()) { 5978 auto I = FuncInfo.StaticAllocaMap.find(AI); 5979 if (I != FuncInfo.StaticAllocaMap.end()) 5980 FI = I->second; 5981 } 5982 } else if (const auto *Arg = dyn_cast<Argument>( 5983 Address->stripInBoundsConstantOffsets())) { 5984 FI = FuncInfo.getArgumentFrameIndex(Arg); 5985 } 5986 5987 // llvm.dbg.addr is control dependent and always generates indirect 5988 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5989 // the MachineFunction variable table. 5990 if (FI != std::numeric_limits<int>::max()) { 5991 if (Intrinsic == Intrinsic::dbg_addr) { 5992 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5993 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 5994 dl, SDNodeOrder); 5995 DAG.AddDbgValue(SDV, isParameter); 5996 } else { 5997 LLVM_DEBUG(dbgs() << "Skipping " << DI 5998 << " (variable info stashed in MF side table)\n"); 5999 } 6000 return; 6001 } 6002 6003 SDValue &N = NodeMap[Address]; 6004 if (!N.getNode() && isa<Argument>(Address)) 6005 // Check unused arguments map. 6006 N = UnusedArgNodeMap[Address]; 6007 SDDbgValue *SDV; 6008 if (N.getNode()) { 6009 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6010 Address = BCI->getOperand(0); 6011 // Parameters are handled specially. 6012 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6013 if (isParameter && FINode) { 6014 // Byval parameter. We have a frame index at this point. 6015 SDV = 6016 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6017 /*IsIndirect*/ true, dl, SDNodeOrder); 6018 } else if (isa<Argument>(Address)) { 6019 // Address is an argument, so try to emit its dbg value using 6020 // virtual register info from the FuncInfo.ValueMap. 6021 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6022 return; 6023 } else { 6024 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6025 true, dl, SDNodeOrder); 6026 } 6027 DAG.AddDbgValue(SDV, isParameter); 6028 } else { 6029 // If Address is an argument then try to emit its dbg value using 6030 // virtual register info from the FuncInfo.ValueMap. 6031 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6032 N)) { 6033 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6034 << " (could not emit func-arg dbg_value)\n"); 6035 } 6036 } 6037 return; 6038 } 6039 case Intrinsic::dbg_label: { 6040 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6041 DILabel *Label = DI.getLabel(); 6042 assert(Label && "Missing label"); 6043 6044 SDDbgLabel *SDV; 6045 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6046 DAG.AddDbgLabel(SDV); 6047 return; 6048 } 6049 case Intrinsic::dbg_value: { 6050 const DbgValueInst &DI = cast<DbgValueInst>(I); 6051 assert(DI.getVariable() && "Missing variable"); 6052 6053 DILocalVariable *Variable = DI.getVariable(); 6054 DIExpression *Expression = DI.getExpression(); 6055 dropDanglingDebugInfo(Variable, Expression); 6056 SmallVector<Value *> Values(DI.getValues()); 6057 if (Values.empty()) 6058 return; 6059 6060 if (std::count(Values.begin(), Values.end(), nullptr)) 6061 return; 6062 6063 bool IsVariadic = DI.hasArgList(); 6064 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6065 SDNodeOrder, IsVariadic)) 6066 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6067 return; 6068 } 6069 6070 case Intrinsic::eh_typeid_for: { 6071 // Find the type id for the given typeinfo. 6072 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6073 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6074 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6075 setValue(&I, Res); 6076 return; 6077 } 6078 6079 case Intrinsic::eh_return_i32: 6080 case Intrinsic::eh_return_i64: 6081 DAG.getMachineFunction().setCallsEHReturn(true); 6082 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6083 MVT::Other, 6084 getControlRoot(), 6085 getValue(I.getArgOperand(0)), 6086 getValue(I.getArgOperand(1)))); 6087 return; 6088 case Intrinsic::eh_unwind_init: 6089 DAG.getMachineFunction().setCallsUnwindInit(true); 6090 return; 6091 case Intrinsic::eh_dwarf_cfa: 6092 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6093 TLI.getPointerTy(DAG.getDataLayout()), 6094 getValue(I.getArgOperand(0)))); 6095 return; 6096 case Intrinsic::eh_sjlj_callsite: { 6097 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6098 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6099 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6100 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6101 6102 MMI.setCurrentCallSite(CI->getZExtValue()); 6103 return; 6104 } 6105 case Intrinsic::eh_sjlj_functioncontext: { 6106 // Get and store the index of the function context. 6107 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6108 AllocaInst *FnCtx = 6109 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6110 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6111 MFI.setFunctionContextIndex(FI); 6112 return; 6113 } 6114 case Intrinsic::eh_sjlj_setjmp: { 6115 SDValue Ops[2]; 6116 Ops[0] = getRoot(); 6117 Ops[1] = getValue(I.getArgOperand(0)); 6118 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6119 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6120 setValue(&I, Op.getValue(0)); 6121 DAG.setRoot(Op.getValue(1)); 6122 return; 6123 } 6124 case Intrinsic::eh_sjlj_longjmp: 6125 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6126 getRoot(), getValue(I.getArgOperand(0)))); 6127 return; 6128 case Intrinsic::eh_sjlj_setup_dispatch: 6129 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6130 getRoot())); 6131 return; 6132 case Intrinsic::masked_gather: 6133 visitMaskedGather(I); 6134 return; 6135 case Intrinsic::masked_load: 6136 visitMaskedLoad(I); 6137 return; 6138 case Intrinsic::masked_scatter: 6139 visitMaskedScatter(I); 6140 return; 6141 case Intrinsic::masked_store: 6142 visitMaskedStore(I); 6143 return; 6144 case Intrinsic::masked_expandload: 6145 visitMaskedLoad(I, true /* IsExpanding */); 6146 return; 6147 case Intrinsic::masked_compressstore: 6148 visitMaskedStore(I, true /* IsCompressing */); 6149 return; 6150 case Intrinsic::powi: 6151 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6152 getValue(I.getArgOperand(1)), DAG)); 6153 return; 6154 case Intrinsic::log: 6155 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6156 return; 6157 case Intrinsic::log2: 6158 setValue(&I, 6159 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6160 return; 6161 case Intrinsic::log10: 6162 setValue(&I, 6163 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6164 return; 6165 case Intrinsic::exp: 6166 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6167 return; 6168 case Intrinsic::exp2: 6169 setValue(&I, 6170 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6171 return; 6172 case Intrinsic::pow: 6173 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6174 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6175 return; 6176 case Intrinsic::sqrt: 6177 case Intrinsic::fabs: 6178 case Intrinsic::sin: 6179 case Intrinsic::cos: 6180 case Intrinsic::floor: 6181 case Intrinsic::ceil: 6182 case Intrinsic::trunc: 6183 case Intrinsic::rint: 6184 case Intrinsic::nearbyint: 6185 case Intrinsic::round: 6186 case Intrinsic::roundeven: 6187 case Intrinsic::canonicalize: { 6188 unsigned Opcode; 6189 switch (Intrinsic) { 6190 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6191 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6192 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6193 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6194 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6195 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6196 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6197 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6198 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6199 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6200 case Intrinsic::round: Opcode = ISD::FROUND; break; 6201 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6202 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6203 } 6204 6205 setValue(&I, DAG.getNode(Opcode, sdl, 6206 getValue(I.getArgOperand(0)).getValueType(), 6207 getValue(I.getArgOperand(0)), Flags)); 6208 return; 6209 } 6210 case Intrinsic::lround: 6211 case Intrinsic::llround: 6212 case Intrinsic::lrint: 6213 case Intrinsic::llrint: { 6214 unsigned Opcode; 6215 switch (Intrinsic) { 6216 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6217 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6218 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6219 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6220 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6221 } 6222 6223 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6224 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6225 getValue(I.getArgOperand(0)))); 6226 return; 6227 } 6228 case Intrinsic::minnum: 6229 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6230 getValue(I.getArgOperand(0)).getValueType(), 6231 getValue(I.getArgOperand(0)), 6232 getValue(I.getArgOperand(1)), Flags)); 6233 return; 6234 case Intrinsic::maxnum: 6235 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6236 getValue(I.getArgOperand(0)).getValueType(), 6237 getValue(I.getArgOperand(0)), 6238 getValue(I.getArgOperand(1)), Flags)); 6239 return; 6240 case Intrinsic::minimum: 6241 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6242 getValue(I.getArgOperand(0)).getValueType(), 6243 getValue(I.getArgOperand(0)), 6244 getValue(I.getArgOperand(1)), Flags)); 6245 return; 6246 case Intrinsic::maximum: 6247 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6248 getValue(I.getArgOperand(0)).getValueType(), 6249 getValue(I.getArgOperand(0)), 6250 getValue(I.getArgOperand(1)), Flags)); 6251 return; 6252 case Intrinsic::copysign: 6253 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6254 getValue(I.getArgOperand(0)).getValueType(), 6255 getValue(I.getArgOperand(0)), 6256 getValue(I.getArgOperand(1)), Flags)); 6257 return; 6258 case Intrinsic::fma: 6259 setValue(&I, DAG.getNode( 6260 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6261 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6262 getValue(I.getArgOperand(2)), Flags)); 6263 return; 6264 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6265 case Intrinsic::INTRINSIC: 6266 #include "llvm/IR/ConstrainedOps.def" 6267 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6268 return; 6269 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6270 #include "llvm/IR/VPIntrinsics.def" 6271 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6272 return; 6273 case Intrinsic::fmuladd: { 6274 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6275 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6276 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6277 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6278 getValue(I.getArgOperand(0)).getValueType(), 6279 getValue(I.getArgOperand(0)), 6280 getValue(I.getArgOperand(1)), 6281 getValue(I.getArgOperand(2)), Flags)); 6282 } else { 6283 // TODO: Intrinsic calls should have fast-math-flags. 6284 SDValue Mul = DAG.getNode( 6285 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6286 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6287 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6288 getValue(I.getArgOperand(0)).getValueType(), 6289 Mul, getValue(I.getArgOperand(2)), Flags); 6290 setValue(&I, Add); 6291 } 6292 return; 6293 } 6294 case Intrinsic::convert_to_fp16: 6295 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6296 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6297 getValue(I.getArgOperand(0)), 6298 DAG.getTargetConstant(0, sdl, 6299 MVT::i32)))); 6300 return; 6301 case Intrinsic::convert_from_fp16: 6302 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6303 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6304 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6305 getValue(I.getArgOperand(0))))); 6306 return; 6307 case Intrinsic::fptosi_sat: { 6308 EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6309 SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32); 6310 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, Type, 6311 getValue(I.getArgOperand(0)), SatW)); 6312 return; 6313 } 6314 case Intrinsic::fptoui_sat: { 6315 EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6316 SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32); 6317 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, Type, 6318 getValue(I.getArgOperand(0)), SatW)); 6319 return; 6320 } 6321 case Intrinsic::set_rounding: 6322 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6323 {getRoot(), getValue(I.getArgOperand(0))}); 6324 setValue(&I, Res); 6325 DAG.setRoot(Res.getValue(0)); 6326 return; 6327 case Intrinsic::pcmarker: { 6328 SDValue Tmp = getValue(I.getArgOperand(0)); 6329 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6330 return; 6331 } 6332 case Intrinsic::readcyclecounter: { 6333 SDValue Op = getRoot(); 6334 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6335 DAG.getVTList(MVT::i64, MVT::Other), Op); 6336 setValue(&I, Res); 6337 DAG.setRoot(Res.getValue(1)); 6338 return; 6339 } 6340 case Intrinsic::bitreverse: 6341 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6342 getValue(I.getArgOperand(0)).getValueType(), 6343 getValue(I.getArgOperand(0)))); 6344 return; 6345 case Intrinsic::bswap: 6346 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6347 getValue(I.getArgOperand(0)).getValueType(), 6348 getValue(I.getArgOperand(0)))); 6349 return; 6350 case Intrinsic::cttz: { 6351 SDValue Arg = getValue(I.getArgOperand(0)); 6352 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6353 EVT Ty = Arg.getValueType(); 6354 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6355 sdl, Ty, Arg)); 6356 return; 6357 } 6358 case Intrinsic::ctlz: { 6359 SDValue Arg = getValue(I.getArgOperand(0)); 6360 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6361 EVT Ty = Arg.getValueType(); 6362 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6363 sdl, Ty, Arg)); 6364 return; 6365 } 6366 case Intrinsic::ctpop: { 6367 SDValue Arg = getValue(I.getArgOperand(0)); 6368 EVT Ty = Arg.getValueType(); 6369 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6370 return; 6371 } 6372 case Intrinsic::fshl: 6373 case Intrinsic::fshr: { 6374 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6375 SDValue X = getValue(I.getArgOperand(0)); 6376 SDValue Y = getValue(I.getArgOperand(1)); 6377 SDValue Z = getValue(I.getArgOperand(2)); 6378 EVT VT = X.getValueType(); 6379 6380 if (X == Y) { 6381 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6382 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6383 } else { 6384 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6385 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6386 } 6387 return; 6388 } 6389 case Intrinsic::sadd_sat: { 6390 SDValue Op1 = getValue(I.getArgOperand(0)); 6391 SDValue Op2 = getValue(I.getArgOperand(1)); 6392 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6393 return; 6394 } 6395 case Intrinsic::uadd_sat: { 6396 SDValue Op1 = getValue(I.getArgOperand(0)); 6397 SDValue Op2 = getValue(I.getArgOperand(1)); 6398 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6399 return; 6400 } 6401 case Intrinsic::ssub_sat: { 6402 SDValue Op1 = getValue(I.getArgOperand(0)); 6403 SDValue Op2 = getValue(I.getArgOperand(1)); 6404 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6405 return; 6406 } 6407 case Intrinsic::usub_sat: { 6408 SDValue Op1 = getValue(I.getArgOperand(0)); 6409 SDValue Op2 = getValue(I.getArgOperand(1)); 6410 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6411 return; 6412 } 6413 case Intrinsic::sshl_sat: { 6414 SDValue Op1 = getValue(I.getArgOperand(0)); 6415 SDValue Op2 = getValue(I.getArgOperand(1)); 6416 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6417 return; 6418 } 6419 case Intrinsic::ushl_sat: { 6420 SDValue Op1 = getValue(I.getArgOperand(0)); 6421 SDValue Op2 = getValue(I.getArgOperand(1)); 6422 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6423 return; 6424 } 6425 case Intrinsic::smul_fix: 6426 case Intrinsic::umul_fix: 6427 case Intrinsic::smul_fix_sat: 6428 case Intrinsic::umul_fix_sat: { 6429 SDValue Op1 = getValue(I.getArgOperand(0)); 6430 SDValue Op2 = getValue(I.getArgOperand(1)); 6431 SDValue Op3 = getValue(I.getArgOperand(2)); 6432 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6433 Op1.getValueType(), Op1, Op2, Op3)); 6434 return; 6435 } 6436 case Intrinsic::sdiv_fix: 6437 case Intrinsic::udiv_fix: 6438 case Intrinsic::sdiv_fix_sat: 6439 case Intrinsic::udiv_fix_sat: { 6440 SDValue Op1 = getValue(I.getArgOperand(0)); 6441 SDValue Op2 = getValue(I.getArgOperand(1)); 6442 SDValue Op3 = getValue(I.getArgOperand(2)); 6443 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6444 Op1, Op2, Op3, DAG, TLI)); 6445 return; 6446 } 6447 case Intrinsic::smax: { 6448 SDValue Op1 = getValue(I.getArgOperand(0)); 6449 SDValue Op2 = getValue(I.getArgOperand(1)); 6450 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6451 return; 6452 } 6453 case Intrinsic::smin: { 6454 SDValue Op1 = getValue(I.getArgOperand(0)); 6455 SDValue Op2 = getValue(I.getArgOperand(1)); 6456 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6457 return; 6458 } 6459 case Intrinsic::umax: { 6460 SDValue Op1 = getValue(I.getArgOperand(0)); 6461 SDValue Op2 = getValue(I.getArgOperand(1)); 6462 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6463 return; 6464 } 6465 case Intrinsic::umin: { 6466 SDValue Op1 = getValue(I.getArgOperand(0)); 6467 SDValue Op2 = getValue(I.getArgOperand(1)); 6468 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6469 return; 6470 } 6471 case Intrinsic::abs: { 6472 // TODO: Preserve "int min is poison" arg in SDAG? 6473 SDValue Op1 = getValue(I.getArgOperand(0)); 6474 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6475 return; 6476 } 6477 case Intrinsic::stacksave: { 6478 SDValue Op = getRoot(); 6479 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6480 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6481 setValue(&I, Res); 6482 DAG.setRoot(Res.getValue(1)); 6483 return; 6484 } 6485 case Intrinsic::stackrestore: 6486 Res = getValue(I.getArgOperand(0)); 6487 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6488 return; 6489 case Intrinsic::get_dynamic_area_offset: { 6490 SDValue Op = getRoot(); 6491 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6492 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6493 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6494 // target. 6495 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6496 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6497 " intrinsic!"); 6498 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6499 Op); 6500 DAG.setRoot(Op); 6501 setValue(&I, Res); 6502 return; 6503 } 6504 case Intrinsic::stackguard: { 6505 MachineFunction &MF = DAG.getMachineFunction(); 6506 const Module &M = *MF.getFunction().getParent(); 6507 SDValue Chain = getRoot(); 6508 if (TLI.useLoadStackGuardNode()) { 6509 Res = getLoadStackGuard(DAG, sdl, Chain); 6510 } else { 6511 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6512 const Value *Global = TLI.getSDagStackGuard(M); 6513 Align Align = DL->getPrefTypeAlign(Global->getType()); 6514 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6515 MachinePointerInfo(Global, 0), Align, 6516 MachineMemOperand::MOVolatile); 6517 } 6518 if (TLI.useStackGuardXorFP()) 6519 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6520 DAG.setRoot(Chain); 6521 setValue(&I, Res); 6522 return; 6523 } 6524 case Intrinsic::stackprotector: { 6525 // Emit code into the DAG to store the stack guard onto the stack. 6526 MachineFunction &MF = DAG.getMachineFunction(); 6527 MachineFrameInfo &MFI = MF.getFrameInfo(); 6528 SDValue Src, Chain = getRoot(); 6529 6530 if (TLI.useLoadStackGuardNode()) 6531 Src = getLoadStackGuard(DAG, sdl, Chain); 6532 else 6533 Src = getValue(I.getArgOperand(0)); // The guard's value. 6534 6535 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6536 6537 int FI = FuncInfo.StaticAllocaMap[Slot]; 6538 MFI.setStackProtectorIndex(FI); 6539 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6540 6541 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6542 6543 // Store the stack protector onto the stack. 6544 Res = DAG.getStore( 6545 Chain, sdl, Src, FIN, 6546 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6547 MaybeAlign(), MachineMemOperand::MOVolatile); 6548 setValue(&I, Res); 6549 DAG.setRoot(Res); 6550 return; 6551 } 6552 case Intrinsic::objectsize: 6553 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6554 6555 case Intrinsic::is_constant: 6556 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6557 6558 case Intrinsic::annotation: 6559 case Intrinsic::ptr_annotation: 6560 case Intrinsic::launder_invariant_group: 6561 case Intrinsic::strip_invariant_group: 6562 // Drop the intrinsic, but forward the value 6563 setValue(&I, getValue(I.getOperand(0))); 6564 return; 6565 6566 case Intrinsic::assume: 6567 case Intrinsic::experimental_noalias_scope_decl: 6568 case Intrinsic::var_annotation: 6569 case Intrinsic::sideeffect: 6570 // Discard annotate attributes, noalias scope declarations, assumptions, and 6571 // artificial side-effects. 6572 return; 6573 6574 case Intrinsic::codeview_annotation: { 6575 // Emit a label associated with this metadata. 6576 MachineFunction &MF = DAG.getMachineFunction(); 6577 MCSymbol *Label = 6578 MF.getMMI().getContext().createTempSymbol("annotation", true); 6579 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6580 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6581 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6582 DAG.setRoot(Res); 6583 return; 6584 } 6585 6586 case Intrinsic::init_trampoline: { 6587 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6588 6589 SDValue Ops[6]; 6590 Ops[0] = getRoot(); 6591 Ops[1] = getValue(I.getArgOperand(0)); 6592 Ops[2] = getValue(I.getArgOperand(1)); 6593 Ops[3] = getValue(I.getArgOperand(2)); 6594 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6595 Ops[5] = DAG.getSrcValue(F); 6596 6597 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6598 6599 DAG.setRoot(Res); 6600 return; 6601 } 6602 case Intrinsic::adjust_trampoline: 6603 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6604 TLI.getPointerTy(DAG.getDataLayout()), 6605 getValue(I.getArgOperand(0)))); 6606 return; 6607 case Intrinsic::gcroot: { 6608 assert(DAG.getMachineFunction().getFunction().hasGC() && 6609 "only valid in functions with gc specified, enforced by Verifier"); 6610 assert(GFI && "implied by previous"); 6611 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6612 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6613 6614 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6615 GFI->addStackRoot(FI->getIndex(), TypeMap); 6616 return; 6617 } 6618 case Intrinsic::gcread: 6619 case Intrinsic::gcwrite: 6620 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6621 case Intrinsic::flt_rounds: 6622 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6623 setValue(&I, Res); 6624 DAG.setRoot(Res.getValue(1)); 6625 return; 6626 6627 case Intrinsic::expect: 6628 // Just replace __builtin_expect(exp, c) with EXP. 6629 setValue(&I, getValue(I.getArgOperand(0))); 6630 return; 6631 6632 case Intrinsic::ubsantrap: 6633 case Intrinsic::debugtrap: 6634 case Intrinsic::trap: { 6635 StringRef TrapFuncName = 6636 I.getAttributes() 6637 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6638 .getValueAsString(); 6639 if (TrapFuncName.empty()) { 6640 switch (Intrinsic) { 6641 case Intrinsic::trap: 6642 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6643 break; 6644 case Intrinsic::debugtrap: 6645 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6646 break; 6647 case Intrinsic::ubsantrap: 6648 DAG.setRoot(DAG.getNode( 6649 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6650 DAG.getTargetConstant( 6651 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6652 MVT::i32))); 6653 break; 6654 default: llvm_unreachable("unknown trap intrinsic"); 6655 } 6656 return; 6657 } 6658 TargetLowering::ArgListTy Args; 6659 if (Intrinsic == Intrinsic::ubsantrap) { 6660 Args.push_back(TargetLoweringBase::ArgListEntry()); 6661 Args[0].Val = I.getArgOperand(0); 6662 Args[0].Node = getValue(Args[0].Val); 6663 Args[0].Ty = Args[0].Val->getType(); 6664 } 6665 6666 TargetLowering::CallLoweringInfo CLI(DAG); 6667 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6668 CallingConv::C, I.getType(), 6669 DAG.getExternalSymbol(TrapFuncName.data(), 6670 TLI.getPointerTy(DAG.getDataLayout())), 6671 std::move(Args)); 6672 6673 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6674 DAG.setRoot(Result.second); 6675 return; 6676 } 6677 6678 case Intrinsic::uadd_with_overflow: 6679 case Intrinsic::sadd_with_overflow: 6680 case Intrinsic::usub_with_overflow: 6681 case Intrinsic::ssub_with_overflow: 6682 case Intrinsic::umul_with_overflow: 6683 case Intrinsic::smul_with_overflow: { 6684 ISD::NodeType Op; 6685 switch (Intrinsic) { 6686 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6687 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6688 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6689 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6690 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6691 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6692 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6693 } 6694 SDValue Op1 = getValue(I.getArgOperand(0)); 6695 SDValue Op2 = getValue(I.getArgOperand(1)); 6696 6697 EVT ResultVT = Op1.getValueType(); 6698 EVT OverflowVT = MVT::i1; 6699 if (ResultVT.isVector()) 6700 OverflowVT = EVT::getVectorVT( 6701 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6702 6703 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6704 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6705 return; 6706 } 6707 case Intrinsic::prefetch: { 6708 SDValue Ops[5]; 6709 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6710 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6711 Ops[0] = DAG.getRoot(); 6712 Ops[1] = getValue(I.getArgOperand(0)); 6713 Ops[2] = getValue(I.getArgOperand(1)); 6714 Ops[3] = getValue(I.getArgOperand(2)); 6715 Ops[4] = getValue(I.getArgOperand(3)); 6716 SDValue Result = DAG.getMemIntrinsicNode( 6717 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6718 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6719 /* align */ None, Flags); 6720 6721 // Chain the prefetch in parallell with any pending loads, to stay out of 6722 // the way of later optimizations. 6723 PendingLoads.push_back(Result); 6724 Result = getRoot(); 6725 DAG.setRoot(Result); 6726 return; 6727 } 6728 case Intrinsic::lifetime_start: 6729 case Intrinsic::lifetime_end: { 6730 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6731 // Stack coloring is not enabled in O0, discard region information. 6732 if (TM.getOptLevel() == CodeGenOpt::None) 6733 return; 6734 6735 const int64_t ObjectSize = 6736 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6737 Value *const ObjectPtr = I.getArgOperand(1); 6738 SmallVector<const Value *, 4> Allocas; 6739 getUnderlyingObjects(ObjectPtr, Allocas); 6740 6741 for (const Value *Alloca : Allocas) { 6742 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6743 6744 // Could not find an Alloca. 6745 if (!LifetimeObject) 6746 continue; 6747 6748 // First check that the Alloca is static, otherwise it won't have a 6749 // valid frame index. 6750 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6751 if (SI == FuncInfo.StaticAllocaMap.end()) 6752 return; 6753 6754 const int FrameIndex = SI->second; 6755 int64_t Offset; 6756 if (GetPointerBaseWithConstantOffset( 6757 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6758 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6759 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6760 Offset); 6761 DAG.setRoot(Res); 6762 } 6763 return; 6764 } 6765 case Intrinsic::pseudoprobe: { 6766 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6767 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6768 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6769 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6770 DAG.setRoot(Res); 6771 return; 6772 } 6773 case Intrinsic::invariant_start: 6774 // Discard region information. 6775 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6776 return; 6777 case Intrinsic::invariant_end: 6778 // Discard region information. 6779 return; 6780 case Intrinsic::clear_cache: 6781 /// FunctionName may be null. 6782 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6783 lowerCallToExternalSymbol(I, FunctionName); 6784 return; 6785 case Intrinsic::donothing: 6786 // ignore 6787 return; 6788 case Intrinsic::experimental_stackmap: 6789 visitStackmap(I); 6790 return; 6791 case Intrinsic::experimental_patchpoint_void: 6792 case Intrinsic::experimental_patchpoint_i64: 6793 visitPatchpoint(I); 6794 return; 6795 case Intrinsic::experimental_gc_statepoint: 6796 LowerStatepoint(cast<GCStatepointInst>(I)); 6797 return; 6798 case Intrinsic::experimental_gc_result: 6799 visitGCResult(cast<GCResultInst>(I)); 6800 return; 6801 case Intrinsic::experimental_gc_relocate: 6802 visitGCRelocate(cast<GCRelocateInst>(I)); 6803 return; 6804 case Intrinsic::instrprof_increment: 6805 llvm_unreachable("instrprof failed to lower an increment"); 6806 case Intrinsic::instrprof_value_profile: 6807 llvm_unreachable("instrprof failed to lower a value profiling call"); 6808 case Intrinsic::localescape: { 6809 MachineFunction &MF = DAG.getMachineFunction(); 6810 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6811 6812 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6813 // is the same on all targets. 6814 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6815 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6816 if (isa<ConstantPointerNull>(Arg)) 6817 continue; // Skip null pointers. They represent a hole in index space. 6818 AllocaInst *Slot = cast<AllocaInst>(Arg); 6819 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6820 "can only escape static allocas"); 6821 int FI = FuncInfo.StaticAllocaMap[Slot]; 6822 MCSymbol *FrameAllocSym = 6823 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6824 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6825 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6826 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6827 .addSym(FrameAllocSym) 6828 .addFrameIndex(FI); 6829 } 6830 6831 return; 6832 } 6833 6834 case Intrinsic::localrecover: { 6835 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6836 MachineFunction &MF = DAG.getMachineFunction(); 6837 6838 // Get the symbol that defines the frame offset. 6839 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6840 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6841 unsigned IdxVal = 6842 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6843 MCSymbol *FrameAllocSym = 6844 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6845 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6846 6847 Value *FP = I.getArgOperand(1); 6848 SDValue FPVal = getValue(FP); 6849 EVT PtrVT = FPVal.getValueType(); 6850 6851 // Create a MCSymbol for the label to avoid any target lowering 6852 // that would make this PC relative. 6853 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6854 SDValue OffsetVal = 6855 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6856 6857 // Add the offset to the FP. 6858 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6859 setValue(&I, Add); 6860 6861 return; 6862 } 6863 6864 case Intrinsic::eh_exceptionpointer: 6865 case Intrinsic::eh_exceptioncode: { 6866 // Get the exception pointer vreg, copy from it, and resize it to fit. 6867 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6868 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6869 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6870 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6871 SDValue N = 6872 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6873 if (Intrinsic == Intrinsic::eh_exceptioncode) 6874 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6875 setValue(&I, N); 6876 return; 6877 } 6878 case Intrinsic::xray_customevent: { 6879 // Here we want to make sure that the intrinsic behaves as if it has a 6880 // specific calling convention, and only for x86_64. 6881 // FIXME: Support other platforms later. 6882 const auto &Triple = DAG.getTarget().getTargetTriple(); 6883 if (Triple.getArch() != Triple::x86_64) 6884 return; 6885 6886 SDLoc DL = getCurSDLoc(); 6887 SmallVector<SDValue, 8> Ops; 6888 6889 // We want to say that we always want the arguments in registers. 6890 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6891 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6892 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6893 SDValue Chain = getRoot(); 6894 Ops.push_back(LogEntryVal); 6895 Ops.push_back(StrSizeVal); 6896 Ops.push_back(Chain); 6897 6898 // We need to enforce the calling convention for the callsite, so that 6899 // argument ordering is enforced correctly, and that register allocation can 6900 // see that some registers may be assumed clobbered and have to preserve 6901 // them across calls to the intrinsic. 6902 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6903 DL, NodeTys, Ops); 6904 SDValue patchableNode = SDValue(MN, 0); 6905 DAG.setRoot(patchableNode); 6906 setValue(&I, patchableNode); 6907 return; 6908 } 6909 case Intrinsic::xray_typedevent: { 6910 // Here we want to make sure that the intrinsic behaves as if it has a 6911 // specific calling convention, and only for x86_64. 6912 // FIXME: Support other platforms later. 6913 const auto &Triple = DAG.getTarget().getTargetTriple(); 6914 if (Triple.getArch() != Triple::x86_64) 6915 return; 6916 6917 SDLoc DL = getCurSDLoc(); 6918 SmallVector<SDValue, 8> Ops; 6919 6920 // We want to say that we always want the arguments in registers. 6921 // It's unclear to me how manipulating the selection DAG here forces callers 6922 // to provide arguments in registers instead of on the stack. 6923 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6924 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6925 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6926 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6927 SDValue Chain = getRoot(); 6928 Ops.push_back(LogTypeId); 6929 Ops.push_back(LogEntryVal); 6930 Ops.push_back(StrSizeVal); 6931 Ops.push_back(Chain); 6932 6933 // We need to enforce the calling convention for the callsite, so that 6934 // argument ordering is enforced correctly, and that register allocation can 6935 // see that some registers may be assumed clobbered and have to preserve 6936 // them across calls to the intrinsic. 6937 MachineSDNode *MN = DAG.getMachineNode( 6938 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6939 SDValue patchableNode = SDValue(MN, 0); 6940 DAG.setRoot(patchableNode); 6941 setValue(&I, patchableNode); 6942 return; 6943 } 6944 case Intrinsic::experimental_deoptimize: 6945 LowerDeoptimizeCall(&I); 6946 return; 6947 6948 case Intrinsic::vector_reduce_fadd: 6949 case Intrinsic::vector_reduce_fmul: 6950 case Intrinsic::vector_reduce_add: 6951 case Intrinsic::vector_reduce_mul: 6952 case Intrinsic::vector_reduce_and: 6953 case Intrinsic::vector_reduce_or: 6954 case Intrinsic::vector_reduce_xor: 6955 case Intrinsic::vector_reduce_smax: 6956 case Intrinsic::vector_reduce_smin: 6957 case Intrinsic::vector_reduce_umax: 6958 case Intrinsic::vector_reduce_umin: 6959 case Intrinsic::vector_reduce_fmax: 6960 case Intrinsic::vector_reduce_fmin: 6961 visitVectorReduce(I, Intrinsic); 6962 return; 6963 6964 case Intrinsic::icall_branch_funnel: { 6965 SmallVector<SDValue, 16> Ops; 6966 Ops.push_back(getValue(I.getArgOperand(0))); 6967 6968 int64_t Offset; 6969 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6970 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6971 if (!Base) 6972 report_fatal_error( 6973 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6974 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6975 6976 struct BranchFunnelTarget { 6977 int64_t Offset; 6978 SDValue Target; 6979 }; 6980 SmallVector<BranchFunnelTarget, 8> Targets; 6981 6982 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6983 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6984 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6985 if (ElemBase != Base) 6986 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6987 "to the same GlobalValue"); 6988 6989 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6990 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6991 if (!GA) 6992 report_fatal_error( 6993 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6994 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6995 GA->getGlobal(), getCurSDLoc(), 6996 Val.getValueType(), GA->getOffset())}); 6997 } 6998 llvm::sort(Targets, 6999 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7000 return T1.Offset < T2.Offset; 7001 }); 7002 7003 for (auto &T : Targets) { 7004 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 7005 Ops.push_back(T.Target); 7006 } 7007 7008 Ops.push_back(DAG.getRoot()); // Chain 7009 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 7010 getCurSDLoc(), MVT::Other, Ops), 7011 0); 7012 DAG.setRoot(N); 7013 setValue(&I, N); 7014 HasTailCall = true; 7015 return; 7016 } 7017 7018 case Intrinsic::wasm_landingpad_index: 7019 // Information this intrinsic contained has been transferred to 7020 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7021 // delete it now. 7022 return; 7023 7024 case Intrinsic::aarch64_settag: 7025 case Intrinsic::aarch64_settag_zero: { 7026 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7027 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7028 SDValue Val = TSI.EmitTargetCodeForSetTag( 7029 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 7030 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7031 ZeroMemory); 7032 DAG.setRoot(Val); 7033 setValue(&I, Val); 7034 return; 7035 } 7036 case Intrinsic::ptrmask: { 7037 SDValue Ptr = getValue(I.getOperand(0)); 7038 SDValue Const = getValue(I.getOperand(1)); 7039 7040 EVT PtrVT = Ptr.getValueType(); 7041 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 7042 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 7043 return; 7044 } 7045 case Intrinsic::get_active_lane_mask: { 7046 auto DL = getCurSDLoc(); 7047 SDValue Index = getValue(I.getOperand(0)); 7048 SDValue TripCount = getValue(I.getOperand(1)); 7049 Type *ElementTy = I.getOperand(0)->getType(); 7050 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7051 unsigned VecWidth = VT.getVectorNumElements(); 7052 7053 SmallVector<SDValue, 16> OpsTripCount; 7054 SmallVector<SDValue, 16> OpsIndex; 7055 SmallVector<SDValue, 16> OpsStepConstants; 7056 for (unsigned i = 0; i < VecWidth; i++) { 7057 OpsTripCount.push_back(TripCount); 7058 OpsIndex.push_back(Index); 7059 OpsStepConstants.push_back( 7060 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 7061 } 7062 7063 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 7064 7065 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 7066 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 7067 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 7068 SDValue VectorInduction = DAG.getNode( 7069 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 7070 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 7071 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 7072 VectorTripCount, ISD::CondCode::SETULT); 7073 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 7074 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 7075 SetCC)); 7076 return; 7077 } 7078 case Intrinsic::experimental_vector_insert: { 7079 auto DL = getCurSDLoc(); 7080 7081 SDValue Vec = getValue(I.getOperand(0)); 7082 SDValue SubVec = getValue(I.getOperand(1)); 7083 SDValue Index = getValue(I.getOperand(2)); 7084 7085 // The intrinsic's index type is i64, but the SDNode requires an index type 7086 // suitable for the target. Convert the index as required. 7087 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7088 if (Index.getValueType() != VectorIdxTy) 7089 Index = DAG.getVectorIdxConstant( 7090 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7091 7092 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7093 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec, 7094 Index)); 7095 return; 7096 } 7097 case Intrinsic::experimental_vector_extract: { 7098 auto DL = getCurSDLoc(); 7099 7100 SDValue Vec = getValue(I.getOperand(0)); 7101 SDValue Index = getValue(I.getOperand(1)); 7102 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7103 7104 // The intrinsic's index type is i64, but the SDNode requires an index type 7105 // suitable for the target. Convert the index as required. 7106 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7107 if (Index.getValueType() != VectorIdxTy) 7108 Index = DAG.getVectorIdxConstant( 7109 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7110 7111 setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index)); 7112 return; 7113 } 7114 case Intrinsic::experimental_vector_reverse: 7115 visitVectorReverse(I); 7116 return; 7117 case Intrinsic::experimental_vector_splice: 7118 visitVectorSplice(I); 7119 return; 7120 } 7121 } 7122 7123 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7124 const ConstrainedFPIntrinsic &FPI) { 7125 SDLoc sdl = getCurSDLoc(); 7126 7127 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7128 SmallVector<EVT, 4> ValueVTs; 7129 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7130 ValueVTs.push_back(MVT::Other); // Out chain 7131 7132 // We do not need to serialize constrained FP intrinsics against 7133 // each other or against (nonvolatile) loads, so they can be 7134 // chained like loads. 7135 SDValue Chain = DAG.getRoot(); 7136 SmallVector<SDValue, 4> Opers; 7137 Opers.push_back(Chain); 7138 if (FPI.isUnaryOp()) { 7139 Opers.push_back(getValue(FPI.getArgOperand(0))); 7140 } else if (FPI.isTernaryOp()) { 7141 Opers.push_back(getValue(FPI.getArgOperand(0))); 7142 Opers.push_back(getValue(FPI.getArgOperand(1))); 7143 Opers.push_back(getValue(FPI.getArgOperand(2))); 7144 } else { 7145 Opers.push_back(getValue(FPI.getArgOperand(0))); 7146 Opers.push_back(getValue(FPI.getArgOperand(1))); 7147 } 7148 7149 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7150 assert(Result.getNode()->getNumValues() == 2); 7151 7152 // Push node to the appropriate list so that future instructions can be 7153 // chained up correctly. 7154 SDValue OutChain = Result.getValue(1); 7155 switch (EB) { 7156 case fp::ExceptionBehavior::ebIgnore: 7157 // The only reason why ebIgnore nodes still need to be chained is that 7158 // they might depend on the current rounding mode, and therefore must 7159 // not be moved across instruction that may change that mode. 7160 LLVM_FALLTHROUGH; 7161 case fp::ExceptionBehavior::ebMayTrap: 7162 // These must not be moved across calls or instructions that may change 7163 // floating-point exception masks. 7164 PendingConstrainedFP.push_back(OutChain); 7165 break; 7166 case fp::ExceptionBehavior::ebStrict: 7167 // These must not be moved across calls or instructions that may change 7168 // floating-point exception masks or read floating-point exception flags. 7169 // In addition, they cannot be optimized out even if unused. 7170 PendingConstrainedFPStrict.push_back(OutChain); 7171 break; 7172 } 7173 }; 7174 7175 SDVTList VTs = DAG.getVTList(ValueVTs); 7176 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7177 7178 SDNodeFlags Flags; 7179 if (EB == fp::ExceptionBehavior::ebIgnore) 7180 Flags.setNoFPExcept(true); 7181 7182 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7183 Flags.copyFMF(*FPOp); 7184 7185 unsigned Opcode; 7186 switch (FPI.getIntrinsicID()) { 7187 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7188 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7189 case Intrinsic::INTRINSIC: \ 7190 Opcode = ISD::STRICT_##DAGN; \ 7191 break; 7192 #include "llvm/IR/ConstrainedOps.def" 7193 case Intrinsic::experimental_constrained_fmuladd: { 7194 Opcode = ISD::STRICT_FMA; 7195 // Break fmuladd into fmul and fadd. 7196 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7197 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7198 ValueVTs[0])) { 7199 Opers.pop_back(); 7200 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7201 pushOutChain(Mul, EB); 7202 Opcode = ISD::STRICT_FADD; 7203 Opers.clear(); 7204 Opers.push_back(Mul.getValue(1)); 7205 Opers.push_back(Mul.getValue(0)); 7206 Opers.push_back(getValue(FPI.getArgOperand(2))); 7207 } 7208 break; 7209 } 7210 } 7211 7212 // A few strict DAG nodes carry additional operands that are not 7213 // set up by the default code above. 7214 switch (Opcode) { 7215 default: break; 7216 case ISD::STRICT_FP_ROUND: 7217 Opers.push_back( 7218 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7219 break; 7220 case ISD::STRICT_FSETCC: 7221 case ISD::STRICT_FSETCCS: { 7222 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7223 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7224 if (TM.Options.NoNaNsFPMath) 7225 Condition = getFCmpCodeWithoutNaN(Condition); 7226 Opers.push_back(DAG.getCondCode(Condition)); 7227 break; 7228 } 7229 } 7230 7231 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7232 pushOutChain(Result, EB); 7233 7234 SDValue FPResult = Result.getValue(0); 7235 setValue(&FPI, FPResult); 7236 } 7237 7238 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7239 Optional<unsigned> ResOPC; 7240 switch (VPIntrin.getIntrinsicID()) { 7241 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN: 7242 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID; 7243 #define END_REGISTER_VP_INTRINSIC(...) break; 7244 #include "llvm/IR/VPIntrinsics.def" 7245 } 7246 7247 if (!ResOPC.hasValue()) 7248 llvm_unreachable( 7249 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7250 7251 return ResOPC.getValue(); 7252 } 7253 7254 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7255 const VPIntrinsic &VPIntrin) { 7256 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7257 7258 SmallVector<EVT, 4> ValueVTs; 7259 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7260 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7261 SDVTList VTs = DAG.getVTList(ValueVTs); 7262 7263 // Request operands. 7264 SmallVector<SDValue, 7> OpValues; 7265 for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i) 7266 OpValues.push_back(getValue(VPIntrin.getArgOperand(i))); 7267 7268 SDLoc DL = getCurSDLoc(); 7269 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7270 setValue(&VPIntrin, Result); 7271 } 7272 7273 std::pair<SDValue, SDValue> 7274 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7275 const BasicBlock *EHPadBB) { 7276 MachineFunction &MF = DAG.getMachineFunction(); 7277 MachineModuleInfo &MMI = MF.getMMI(); 7278 MCSymbol *BeginLabel = nullptr; 7279 7280 if (EHPadBB) { 7281 // Insert a label before the invoke call to mark the try range. This can be 7282 // used to detect deletion of the invoke via the MachineModuleInfo. 7283 BeginLabel = MMI.getContext().createTempSymbol(); 7284 7285 // For SjLj, keep track of which landing pads go with which invokes 7286 // so as to maintain the ordering of pads in the LSDA. 7287 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7288 if (CallSiteIndex) { 7289 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7290 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7291 7292 // Now that the call site is handled, stop tracking it. 7293 MMI.setCurrentCallSite(0); 7294 } 7295 7296 // Both PendingLoads and PendingExports must be flushed here; 7297 // this call might not return. 7298 (void)getRoot(); 7299 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7300 7301 CLI.setChain(getRoot()); 7302 } 7303 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7304 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7305 7306 assert((CLI.IsTailCall || Result.second.getNode()) && 7307 "Non-null chain expected with non-tail call!"); 7308 assert((Result.second.getNode() || !Result.first.getNode()) && 7309 "Null value expected with tail call!"); 7310 7311 if (!Result.second.getNode()) { 7312 // As a special case, a null chain means that a tail call has been emitted 7313 // and the DAG root is already updated. 7314 HasTailCall = true; 7315 7316 // Since there's no actual continuation from this block, nothing can be 7317 // relying on us setting vregs for them. 7318 PendingExports.clear(); 7319 } else { 7320 DAG.setRoot(Result.second); 7321 } 7322 7323 if (EHPadBB) { 7324 // Insert a label at the end of the invoke call to mark the try range. This 7325 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7326 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7327 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7328 7329 // Inform MachineModuleInfo of range. 7330 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7331 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7332 // actually use outlined funclets and their LSDA info style. 7333 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7334 assert(CLI.CB); 7335 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7336 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel); 7337 } else if (!isScopedEHPersonality(Pers)) { 7338 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7339 } 7340 } 7341 7342 return Result; 7343 } 7344 7345 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7346 bool isTailCall, 7347 const BasicBlock *EHPadBB) { 7348 auto &DL = DAG.getDataLayout(); 7349 FunctionType *FTy = CB.getFunctionType(); 7350 Type *RetTy = CB.getType(); 7351 7352 TargetLowering::ArgListTy Args; 7353 Args.reserve(CB.arg_size()); 7354 7355 const Value *SwiftErrorVal = nullptr; 7356 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7357 7358 if (isTailCall) { 7359 // Avoid emitting tail calls in functions with the disable-tail-calls 7360 // attribute. 7361 auto *Caller = CB.getParent()->getParent(); 7362 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7363 "true") 7364 isTailCall = false; 7365 7366 // We can't tail call inside a function with a swifterror argument. Lowering 7367 // does not support this yet. It would have to move into the swifterror 7368 // register before the call. 7369 if (TLI.supportSwiftError() && 7370 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7371 isTailCall = false; 7372 } 7373 7374 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7375 TargetLowering::ArgListEntry Entry; 7376 const Value *V = *I; 7377 7378 // Skip empty types 7379 if (V->getType()->isEmptyTy()) 7380 continue; 7381 7382 SDValue ArgNode = getValue(V); 7383 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7384 7385 Entry.setAttributes(&CB, I - CB.arg_begin()); 7386 7387 // Use swifterror virtual register as input to the call. 7388 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7389 SwiftErrorVal = V; 7390 // We find the virtual register for the actual swifterror argument. 7391 // Instead of using the Value, we use the virtual register instead. 7392 Entry.Node = 7393 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7394 EVT(TLI.getPointerTy(DL))); 7395 } 7396 7397 Args.push_back(Entry); 7398 7399 // If we have an explicit sret argument that is an Instruction, (i.e., it 7400 // might point to function-local memory), we can't meaningfully tail-call. 7401 if (Entry.IsSRet && isa<Instruction>(V)) 7402 isTailCall = false; 7403 } 7404 7405 // If call site has a cfguardtarget operand bundle, create and add an 7406 // additional ArgListEntry. 7407 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7408 TargetLowering::ArgListEntry Entry; 7409 Value *V = Bundle->Inputs[0]; 7410 SDValue ArgNode = getValue(V); 7411 Entry.Node = ArgNode; 7412 Entry.Ty = V->getType(); 7413 Entry.IsCFGuardTarget = true; 7414 Args.push_back(Entry); 7415 } 7416 7417 // Check if target-independent constraints permit a tail call here. 7418 // Target-dependent constraints are checked within TLI->LowerCallTo. 7419 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7420 isTailCall = false; 7421 7422 // Disable tail calls if there is an swifterror argument. Targets have not 7423 // been updated to support tail calls. 7424 if (TLI.supportSwiftError() && SwiftErrorVal) 7425 isTailCall = false; 7426 7427 TargetLowering::CallLoweringInfo CLI(DAG); 7428 CLI.setDebugLoc(getCurSDLoc()) 7429 .setChain(getRoot()) 7430 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7431 .setTailCall(isTailCall) 7432 .setConvergent(CB.isConvergent()) 7433 .setIsPreallocated( 7434 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7435 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7436 7437 if (Result.first.getNode()) { 7438 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7439 setValue(&CB, Result.first); 7440 } 7441 7442 // The last element of CLI.InVals has the SDValue for swifterror return. 7443 // Here we copy it to a virtual register and update SwiftErrorMap for 7444 // book-keeping. 7445 if (SwiftErrorVal && TLI.supportSwiftError()) { 7446 // Get the last element of InVals. 7447 SDValue Src = CLI.InVals.back(); 7448 Register VReg = 7449 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7450 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7451 DAG.setRoot(CopyNode); 7452 } 7453 } 7454 7455 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7456 SelectionDAGBuilder &Builder) { 7457 // Check to see if this load can be trivially constant folded, e.g. if the 7458 // input is from a string literal. 7459 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7460 // Cast pointer to the type we really want to load. 7461 Type *LoadTy = 7462 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7463 if (LoadVT.isVector()) 7464 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7465 7466 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7467 PointerType::getUnqual(LoadTy)); 7468 7469 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7470 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7471 return Builder.getValue(LoadCst); 7472 } 7473 7474 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7475 // still constant memory, the input chain can be the entry node. 7476 SDValue Root; 7477 bool ConstantMemory = false; 7478 7479 // Do not serialize (non-volatile) loads of constant memory with anything. 7480 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7481 Root = Builder.DAG.getEntryNode(); 7482 ConstantMemory = true; 7483 } else { 7484 // Do not serialize non-volatile loads against each other. 7485 Root = Builder.DAG.getRoot(); 7486 } 7487 7488 SDValue Ptr = Builder.getValue(PtrVal); 7489 SDValue LoadVal = 7490 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7491 MachinePointerInfo(PtrVal), Align(1)); 7492 7493 if (!ConstantMemory) 7494 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7495 return LoadVal; 7496 } 7497 7498 /// Record the value for an instruction that produces an integer result, 7499 /// converting the type where necessary. 7500 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7501 SDValue Value, 7502 bool IsSigned) { 7503 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7504 I.getType(), true); 7505 if (IsSigned) 7506 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7507 else 7508 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7509 setValue(&I, Value); 7510 } 7511 7512 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7513 /// true and lower it. Otherwise return false, and it will be lowered like a 7514 /// normal call. 7515 /// The caller already checked that \p I calls the appropriate LibFunc with a 7516 /// correct prototype. 7517 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7518 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7519 const Value *Size = I.getArgOperand(2); 7520 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7521 if (CSize && CSize->getZExtValue() == 0) { 7522 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7523 I.getType(), true); 7524 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7525 return true; 7526 } 7527 7528 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7529 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7530 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7531 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7532 if (Res.first.getNode()) { 7533 processIntegerCallValue(I, Res.first, true); 7534 PendingLoads.push_back(Res.second); 7535 return true; 7536 } 7537 7538 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7539 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7540 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7541 return false; 7542 7543 // If the target has a fast compare for the given size, it will return a 7544 // preferred load type for that size. Require that the load VT is legal and 7545 // that the target supports unaligned loads of that type. Otherwise, return 7546 // INVALID. 7547 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7548 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7549 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7550 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7551 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7552 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7553 // TODO: Check alignment of src and dest ptrs. 7554 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7555 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7556 if (!TLI.isTypeLegal(LVT) || 7557 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7558 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7559 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7560 } 7561 7562 return LVT; 7563 }; 7564 7565 // This turns into unaligned loads. We only do this if the target natively 7566 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7567 // we'll only produce a small number of byte loads. 7568 MVT LoadVT; 7569 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7570 switch (NumBitsToCompare) { 7571 default: 7572 return false; 7573 case 16: 7574 LoadVT = MVT::i16; 7575 break; 7576 case 32: 7577 LoadVT = MVT::i32; 7578 break; 7579 case 64: 7580 case 128: 7581 case 256: 7582 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7583 break; 7584 } 7585 7586 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7587 return false; 7588 7589 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7590 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7591 7592 // Bitcast to a wide integer type if the loads are vectors. 7593 if (LoadVT.isVector()) { 7594 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7595 LoadL = DAG.getBitcast(CmpVT, LoadL); 7596 LoadR = DAG.getBitcast(CmpVT, LoadR); 7597 } 7598 7599 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7600 processIntegerCallValue(I, Cmp, false); 7601 return true; 7602 } 7603 7604 /// See if we can lower a memchr call into an optimized form. If so, return 7605 /// true and lower it. Otherwise return false, and it will be lowered like a 7606 /// normal call. 7607 /// The caller already checked that \p I calls the appropriate LibFunc with a 7608 /// correct prototype. 7609 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7610 const Value *Src = I.getArgOperand(0); 7611 const Value *Char = I.getArgOperand(1); 7612 const Value *Length = I.getArgOperand(2); 7613 7614 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7615 std::pair<SDValue, SDValue> Res = 7616 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7617 getValue(Src), getValue(Char), getValue(Length), 7618 MachinePointerInfo(Src)); 7619 if (Res.first.getNode()) { 7620 setValue(&I, Res.first); 7621 PendingLoads.push_back(Res.second); 7622 return true; 7623 } 7624 7625 return false; 7626 } 7627 7628 /// See if we can lower a mempcpy call into an optimized form. If so, return 7629 /// true and lower it. Otherwise return false, and it will be lowered like a 7630 /// normal call. 7631 /// The caller already checked that \p I calls the appropriate LibFunc with a 7632 /// correct prototype. 7633 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7634 SDValue Dst = getValue(I.getArgOperand(0)); 7635 SDValue Src = getValue(I.getArgOperand(1)); 7636 SDValue Size = getValue(I.getArgOperand(2)); 7637 7638 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7639 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7640 // DAG::getMemcpy needs Alignment to be defined. 7641 Align Alignment = std::min(DstAlign, SrcAlign); 7642 7643 bool isVol = false; 7644 SDLoc sdl = getCurSDLoc(); 7645 7646 // In the mempcpy context we need to pass in a false value for isTailCall 7647 // because the return pointer needs to be adjusted by the size of 7648 // the copied memory. 7649 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7650 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7651 /*isTailCall=*/false, 7652 MachinePointerInfo(I.getArgOperand(0)), 7653 MachinePointerInfo(I.getArgOperand(1))); 7654 assert(MC.getNode() != nullptr && 7655 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7656 DAG.setRoot(MC); 7657 7658 // Check if Size needs to be truncated or extended. 7659 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7660 7661 // Adjust return pointer to point just past the last dst byte. 7662 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7663 Dst, Size); 7664 setValue(&I, DstPlusSize); 7665 return true; 7666 } 7667 7668 /// See if we can lower a strcpy call into an optimized form. If so, return 7669 /// true and lower it, otherwise return false and it will be lowered like a 7670 /// normal call. 7671 /// The caller already checked that \p I calls the appropriate LibFunc with a 7672 /// correct prototype. 7673 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7674 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7675 7676 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7677 std::pair<SDValue, SDValue> Res = 7678 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7679 getValue(Arg0), getValue(Arg1), 7680 MachinePointerInfo(Arg0), 7681 MachinePointerInfo(Arg1), isStpcpy); 7682 if (Res.first.getNode()) { 7683 setValue(&I, Res.first); 7684 DAG.setRoot(Res.second); 7685 return true; 7686 } 7687 7688 return false; 7689 } 7690 7691 /// See if we can lower a strcmp call into an optimized form. If so, return 7692 /// true and lower it, otherwise return false and it will be lowered like a 7693 /// normal call. 7694 /// The caller already checked that \p I calls the appropriate LibFunc with a 7695 /// correct prototype. 7696 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7697 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7698 7699 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7700 std::pair<SDValue, SDValue> Res = 7701 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7702 getValue(Arg0), getValue(Arg1), 7703 MachinePointerInfo(Arg0), 7704 MachinePointerInfo(Arg1)); 7705 if (Res.first.getNode()) { 7706 processIntegerCallValue(I, Res.first, true); 7707 PendingLoads.push_back(Res.second); 7708 return true; 7709 } 7710 7711 return false; 7712 } 7713 7714 /// See if we can lower a strlen call into an optimized form. If so, return 7715 /// true and lower it, otherwise return false and it will be lowered like a 7716 /// normal call. 7717 /// The caller already checked that \p I calls the appropriate LibFunc with a 7718 /// correct prototype. 7719 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7720 const Value *Arg0 = I.getArgOperand(0); 7721 7722 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7723 std::pair<SDValue, SDValue> Res = 7724 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7725 getValue(Arg0), MachinePointerInfo(Arg0)); 7726 if (Res.first.getNode()) { 7727 processIntegerCallValue(I, Res.first, false); 7728 PendingLoads.push_back(Res.second); 7729 return true; 7730 } 7731 7732 return false; 7733 } 7734 7735 /// See if we can lower a strnlen call into an optimized form. If so, return 7736 /// true and lower it, otherwise return false and it will be lowered like a 7737 /// normal call. 7738 /// The caller already checked that \p I calls the appropriate LibFunc with a 7739 /// correct prototype. 7740 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7741 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7742 7743 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7744 std::pair<SDValue, SDValue> Res = 7745 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7746 getValue(Arg0), getValue(Arg1), 7747 MachinePointerInfo(Arg0)); 7748 if (Res.first.getNode()) { 7749 processIntegerCallValue(I, Res.first, false); 7750 PendingLoads.push_back(Res.second); 7751 return true; 7752 } 7753 7754 return false; 7755 } 7756 7757 /// See if we can lower a unary floating-point operation into an SDNode with 7758 /// the specified Opcode. If so, return true and lower it, otherwise return 7759 /// false and it will be lowered like a normal call. 7760 /// The caller already checked that \p I calls the appropriate LibFunc with a 7761 /// correct prototype. 7762 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7763 unsigned Opcode) { 7764 // We already checked this call's prototype; verify it doesn't modify errno. 7765 if (!I.onlyReadsMemory()) 7766 return false; 7767 7768 SDNodeFlags Flags; 7769 Flags.copyFMF(cast<FPMathOperator>(I)); 7770 7771 SDValue Tmp = getValue(I.getArgOperand(0)); 7772 setValue(&I, 7773 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7774 return true; 7775 } 7776 7777 /// See if we can lower a binary floating-point operation into an SDNode with 7778 /// the specified Opcode. If so, return true and lower it. Otherwise return 7779 /// false, and it will be lowered like a normal call. 7780 /// The caller already checked that \p I calls the appropriate LibFunc with a 7781 /// correct prototype. 7782 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7783 unsigned Opcode) { 7784 // We already checked this call's prototype; verify it doesn't modify errno. 7785 if (!I.onlyReadsMemory()) 7786 return false; 7787 7788 SDNodeFlags Flags; 7789 Flags.copyFMF(cast<FPMathOperator>(I)); 7790 7791 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7792 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7793 EVT VT = Tmp0.getValueType(); 7794 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7795 return true; 7796 } 7797 7798 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7799 // Handle inline assembly differently. 7800 if (I.isInlineAsm()) { 7801 visitInlineAsm(I); 7802 return; 7803 } 7804 7805 if (Function *F = I.getCalledFunction()) { 7806 if (F->isDeclaration()) { 7807 // Is this an LLVM intrinsic or a target-specific intrinsic? 7808 unsigned IID = F->getIntrinsicID(); 7809 if (!IID) 7810 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7811 IID = II->getIntrinsicID(F); 7812 7813 if (IID) { 7814 visitIntrinsicCall(I, IID); 7815 return; 7816 } 7817 } 7818 7819 // Check for well-known libc/libm calls. If the function is internal, it 7820 // can't be a library call. Don't do the check if marked as nobuiltin for 7821 // some reason or the call site requires strict floating point semantics. 7822 LibFunc Func; 7823 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7824 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7825 LibInfo->hasOptimizedCodeGen(Func)) { 7826 switch (Func) { 7827 default: break; 7828 case LibFunc_bcmp: 7829 if (visitMemCmpBCmpCall(I)) 7830 return; 7831 break; 7832 case LibFunc_copysign: 7833 case LibFunc_copysignf: 7834 case LibFunc_copysignl: 7835 // We already checked this call's prototype; verify it doesn't modify 7836 // errno. 7837 if (I.onlyReadsMemory()) { 7838 SDValue LHS = getValue(I.getArgOperand(0)); 7839 SDValue RHS = getValue(I.getArgOperand(1)); 7840 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7841 LHS.getValueType(), LHS, RHS)); 7842 return; 7843 } 7844 break; 7845 case LibFunc_fabs: 7846 case LibFunc_fabsf: 7847 case LibFunc_fabsl: 7848 if (visitUnaryFloatCall(I, ISD::FABS)) 7849 return; 7850 break; 7851 case LibFunc_fmin: 7852 case LibFunc_fminf: 7853 case LibFunc_fminl: 7854 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7855 return; 7856 break; 7857 case LibFunc_fmax: 7858 case LibFunc_fmaxf: 7859 case LibFunc_fmaxl: 7860 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7861 return; 7862 break; 7863 case LibFunc_sin: 7864 case LibFunc_sinf: 7865 case LibFunc_sinl: 7866 if (visitUnaryFloatCall(I, ISD::FSIN)) 7867 return; 7868 break; 7869 case LibFunc_cos: 7870 case LibFunc_cosf: 7871 case LibFunc_cosl: 7872 if (visitUnaryFloatCall(I, ISD::FCOS)) 7873 return; 7874 break; 7875 case LibFunc_sqrt: 7876 case LibFunc_sqrtf: 7877 case LibFunc_sqrtl: 7878 case LibFunc_sqrt_finite: 7879 case LibFunc_sqrtf_finite: 7880 case LibFunc_sqrtl_finite: 7881 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7882 return; 7883 break; 7884 case LibFunc_floor: 7885 case LibFunc_floorf: 7886 case LibFunc_floorl: 7887 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7888 return; 7889 break; 7890 case LibFunc_nearbyint: 7891 case LibFunc_nearbyintf: 7892 case LibFunc_nearbyintl: 7893 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7894 return; 7895 break; 7896 case LibFunc_ceil: 7897 case LibFunc_ceilf: 7898 case LibFunc_ceill: 7899 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7900 return; 7901 break; 7902 case LibFunc_rint: 7903 case LibFunc_rintf: 7904 case LibFunc_rintl: 7905 if (visitUnaryFloatCall(I, ISD::FRINT)) 7906 return; 7907 break; 7908 case LibFunc_round: 7909 case LibFunc_roundf: 7910 case LibFunc_roundl: 7911 if (visitUnaryFloatCall(I, ISD::FROUND)) 7912 return; 7913 break; 7914 case LibFunc_trunc: 7915 case LibFunc_truncf: 7916 case LibFunc_truncl: 7917 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7918 return; 7919 break; 7920 case LibFunc_log2: 7921 case LibFunc_log2f: 7922 case LibFunc_log2l: 7923 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7924 return; 7925 break; 7926 case LibFunc_exp2: 7927 case LibFunc_exp2f: 7928 case LibFunc_exp2l: 7929 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7930 return; 7931 break; 7932 case LibFunc_memcmp: 7933 if (visitMemCmpBCmpCall(I)) 7934 return; 7935 break; 7936 case LibFunc_mempcpy: 7937 if (visitMemPCpyCall(I)) 7938 return; 7939 break; 7940 case LibFunc_memchr: 7941 if (visitMemChrCall(I)) 7942 return; 7943 break; 7944 case LibFunc_strcpy: 7945 if (visitStrCpyCall(I, false)) 7946 return; 7947 break; 7948 case LibFunc_stpcpy: 7949 if (visitStrCpyCall(I, true)) 7950 return; 7951 break; 7952 case LibFunc_strcmp: 7953 if (visitStrCmpCall(I)) 7954 return; 7955 break; 7956 case LibFunc_strlen: 7957 if (visitStrLenCall(I)) 7958 return; 7959 break; 7960 case LibFunc_strnlen: 7961 if (visitStrNLenCall(I)) 7962 return; 7963 break; 7964 } 7965 } 7966 } 7967 7968 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7969 // have to do anything here to lower funclet bundles. 7970 // CFGuardTarget bundles are lowered in LowerCallTo. 7971 assert(!I.hasOperandBundlesOtherThan( 7972 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 7973 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 7974 LLVMContext::OB_clang_arc_attachedcall}) && 7975 "Cannot lower calls with arbitrary operand bundles!"); 7976 7977 SDValue Callee = getValue(I.getCalledOperand()); 7978 7979 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7980 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7981 else 7982 // Check if we can potentially perform a tail call. More detailed checking 7983 // is be done within LowerCallTo, after more information about the call is 7984 // known. 7985 LowerCallTo(I, Callee, I.isTailCall()); 7986 } 7987 7988 namespace { 7989 7990 /// AsmOperandInfo - This contains information for each constraint that we are 7991 /// lowering. 7992 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7993 public: 7994 /// CallOperand - If this is the result output operand or a clobber 7995 /// this is null, otherwise it is the incoming operand to the CallInst. 7996 /// This gets modified as the asm is processed. 7997 SDValue CallOperand; 7998 7999 /// AssignedRegs - If this is a register or register class operand, this 8000 /// contains the set of register corresponding to the operand. 8001 RegsForValue AssignedRegs; 8002 8003 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8004 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8005 } 8006 8007 /// Whether or not this operand accesses memory 8008 bool hasMemory(const TargetLowering &TLI) const { 8009 // Indirect operand accesses access memory. 8010 if (isIndirect) 8011 return true; 8012 8013 for (const auto &Code : Codes) 8014 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8015 return true; 8016 8017 return false; 8018 } 8019 8020 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8021 /// corresponds to. If there is no Value* for this operand, it returns 8022 /// MVT::Other. 8023 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8024 const DataLayout &DL) const { 8025 if (!CallOperandVal) return MVT::Other; 8026 8027 if (isa<BasicBlock>(CallOperandVal)) 8028 return TLI.getProgramPointerTy(DL); 8029 8030 llvm::Type *OpTy = CallOperandVal->getType(); 8031 8032 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8033 // If this is an indirect operand, the operand is a pointer to the 8034 // accessed type. 8035 if (isIndirect) { 8036 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 8037 if (!PtrTy) 8038 report_fatal_error("Indirect operand for inline asm not a pointer!"); 8039 OpTy = PtrTy->getElementType(); 8040 } 8041 8042 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8043 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8044 if (STy->getNumElements() == 1) 8045 OpTy = STy->getElementType(0); 8046 8047 // If OpTy is not a single value, it may be a struct/union that we 8048 // can tile with integers. 8049 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8050 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8051 switch (BitSize) { 8052 default: break; 8053 case 1: 8054 case 8: 8055 case 16: 8056 case 32: 8057 case 64: 8058 case 128: 8059 OpTy = IntegerType::get(Context, BitSize); 8060 break; 8061 } 8062 } 8063 8064 return TLI.getValueType(DL, OpTy, true); 8065 } 8066 }; 8067 8068 8069 } // end anonymous namespace 8070 8071 /// Make sure that the output operand \p OpInfo and its corresponding input 8072 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8073 /// out). 8074 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8075 SDISelAsmOperandInfo &MatchingOpInfo, 8076 SelectionDAG &DAG) { 8077 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8078 return; 8079 8080 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8081 const auto &TLI = DAG.getTargetLoweringInfo(); 8082 8083 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8084 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8085 OpInfo.ConstraintVT); 8086 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8087 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8088 MatchingOpInfo.ConstraintVT); 8089 if ((OpInfo.ConstraintVT.isInteger() != 8090 MatchingOpInfo.ConstraintVT.isInteger()) || 8091 (MatchRC.second != InputRC.second)) { 8092 // FIXME: error out in a more elegant fashion 8093 report_fatal_error("Unsupported asm: input constraint" 8094 " with a matching output constraint of" 8095 " incompatible type!"); 8096 } 8097 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8098 } 8099 8100 /// Get a direct memory input to behave well as an indirect operand. 8101 /// This may introduce stores, hence the need for a \p Chain. 8102 /// \return The (possibly updated) chain. 8103 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8104 SDISelAsmOperandInfo &OpInfo, 8105 SelectionDAG &DAG) { 8106 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8107 8108 // If we don't have an indirect input, put it in the constpool if we can, 8109 // otherwise spill it to a stack slot. 8110 // TODO: This isn't quite right. We need to handle these according to 8111 // the addressing mode that the constraint wants. Also, this may take 8112 // an additional register for the computation and we don't want that 8113 // either. 8114 8115 // If the operand is a float, integer, or vector constant, spill to a 8116 // constant pool entry to get its address. 8117 const Value *OpVal = OpInfo.CallOperandVal; 8118 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8119 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8120 OpInfo.CallOperand = DAG.getConstantPool( 8121 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8122 return Chain; 8123 } 8124 8125 // Otherwise, create a stack slot and emit a store to it before the asm. 8126 Type *Ty = OpVal->getType(); 8127 auto &DL = DAG.getDataLayout(); 8128 uint64_t TySize = DL.getTypeAllocSize(Ty); 8129 MachineFunction &MF = DAG.getMachineFunction(); 8130 int SSFI = MF.getFrameInfo().CreateStackObject( 8131 TySize, DL.getPrefTypeAlign(Ty), false); 8132 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8133 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8134 MachinePointerInfo::getFixedStack(MF, SSFI), 8135 TLI.getMemValueType(DL, Ty)); 8136 OpInfo.CallOperand = StackSlot; 8137 8138 return Chain; 8139 } 8140 8141 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8142 /// specified operand. We prefer to assign virtual registers, to allow the 8143 /// register allocator to handle the assignment process. However, if the asm 8144 /// uses features that we can't model on machineinstrs, we have SDISel do the 8145 /// allocation. This produces generally horrible, but correct, code. 8146 /// 8147 /// OpInfo describes the operand 8148 /// RefOpInfo describes the matching operand if any, the operand otherwise 8149 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8150 SDISelAsmOperandInfo &OpInfo, 8151 SDISelAsmOperandInfo &RefOpInfo) { 8152 LLVMContext &Context = *DAG.getContext(); 8153 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8154 8155 MachineFunction &MF = DAG.getMachineFunction(); 8156 SmallVector<unsigned, 4> Regs; 8157 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8158 8159 // No work to do for memory operations. 8160 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8161 return; 8162 8163 // If this is a constraint for a single physreg, or a constraint for a 8164 // register class, find it. 8165 unsigned AssignedReg; 8166 const TargetRegisterClass *RC; 8167 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8168 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8169 // RC is unset only on failure. Return immediately. 8170 if (!RC) 8171 return; 8172 8173 // Get the actual register value type. This is important, because the user 8174 // may have asked for (e.g.) the AX register in i32 type. We need to 8175 // remember that AX is actually i16 to get the right extension. 8176 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8177 8178 if (OpInfo.ConstraintVT != MVT::Other) { 8179 // If this is an FP operand in an integer register (or visa versa), or more 8180 // generally if the operand value disagrees with the register class we plan 8181 // to stick it in, fix the operand type. 8182 // 8183 // If this is an input value, the bitcast to the new type is done now. 8184 // Bitcast for output value is done at the end of visitInlineAsm(). 8185 if ((OpInfo.Type == InlineAsm::isOutput || 8186 OpInfo.Type == InlineAsm::isInput) && 8187 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8188 // Try to convert to the first EVT that the reg class contains. If the 8189 // types are identical size, use a bitcast to convert (e.g. two differing 8190 // vector types). Note: output bitcast is done at the end of 8191 // visitInlineAsm(). 8192 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8193 // Exclude indirect inputs while they are unsupported because the code 8194 // to perform the load is missing and thus OpInfo.CallOperand still 8195 // refers to the input address rather than the pointed-to value. 8196 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8197 OpInfo.CallOperand = 8198 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8199 OpInfo.ConstraintVT = RegVT; 8200 // If the operand is an FP value and we want it in integer registers, 8201 // use the corresponding integer type. This turns an f64 value into 8202 // i64, which can be passed with two i32 values on a 32-bit machine. 8203 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8204 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8205 if (OpInfo.Type == InlineAsm::isInput) 8206 OpInfo.CallOperand = 8207 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8208 OpInfo.ConstraintVT = VT; 8209 } 8210 } 8211 } 8212 8213 // No need to allocate a matching input constraint since the constraint it's 8214 // matching to has already been allocated. 8215 if (OpInfo.isMatchingInputConstraint()) 8216 return; 8217 8218 EVT ValueVT = OpInfo.ConstraintVT; 8219 if (OpInfo.ConstraintVT == MVT::Other) 8220 ValueVT = RegVT; 8221 8222 // Initialize NumRegs. 8223 unsigned NumRegs = 1; 8224 if (OpInfo.ConstraintVT != MVT::Other) 8225 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8226 8227 // If this is a constraint for a specific physical register, like {r17}, 8228 // assign it now. 8229 8230 // If this associated to a specific register, initialize iterator to correct 8231 // place. If virtual, make sure we have enough registers 8232 8233 // Initialize iterator if necessary 8234 TargetRegisterClass::iterator I = RC->begin(); 8235 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8236 8237 // Do not check for single registers. 8238 if (AssignedReg) { 8239 for (; *I != AssignedReg; ++I) 8240 assert(I != RC->end() && "AssignedReg should be member of RC"); 8241 } 8242 8243 for (; NumRegs; --NumRegs, ++I) { 8244 assert(I != RC->end() && "Ran out of registers to allocate!"); 8245 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8246 Regs.push_back(R); 8247 } 8248 8249 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8250 } 8251 8252 static unsigned 8253 findMatchingInlineAsmOperand(unsigned OperandNo, 8254 const std::vector<SDValue> &AsmNodeOperands) { 8255 // Scan until we find the definition we already emitted of this operand. 8256 unsigned CurOp = InlineAsm::Op_FirstOperand; 8257 for (; OperandNo; --OperandNo) { 8258 // Advance to the next operand. 8259 unsigned OpFlag = 8260 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8261 assert((InlineAsm::isRegDefKind(OpFlag) || 8262 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8263 InlineAsm::isMemKind(OpFlag)) && 8264 "Skipped past definitions?"); 8265 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8266 } 8267 return CurOp; 8268 } 8269 8270 namespace { 8271 8272 class ExtraFlags { 8273 unsigned Flags = 0; 8274 8275 public: 8276 explicit ExtraFlags(const CallBase &Call) { 8277 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8278 if (IA->hasSideEffects()) 8279 Flags |= InlineAsm::Extra_HasSideEffects; 8280 if (IA->isAlignStack()) 8281 Flags |= InlineAsm::Extra_IsAlignStack; 8282 if (Call.isConvergent()) 8283 Flags |= InlineAsm::Extra_IsConvergent; 8284 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8285 } 8286 8287 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8288 // Ideally, we would only check against memory constraints. However, the 8289 // meaning of an Other constraint can be target-specific and we can't easily 8290 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8291 // for Other constraints as well. 8292 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8293 OpInfo.ConstraintType == TargetLowering::C_Other) { 8294 if (OpInfo.Type == InlineAsm::isInput) 8295 Flags |= InlineAsm::Extra_MayLoad; 8296 else if (OpInfo.Type == InlineAsm::isOutput) 8297 Flags |= InlineAsm::Extra_MayStore; 8298 else if (OpInfo.Type == InlineAsm::isClobber) 8299 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8300 } 8301 } 8302 8303 unsigned get() const { return Flags; } 8304 }; 8305 8306 } // end anonymous namespace 8307 8308 /// visitInlineAsm - Handle a call to an InlineAsm object. 8309 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 8310 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8311 8312 /// ConstraintOperands - Information about all of the constraints. 8313 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8314 8315 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8316 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8317 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8318 8319 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8320 // AsmDialect, MayLoad, MayStore). 8321 bool HasSideEffect = IA->hasSideEffects(); 8322 ExtraFlags ExtraInfo(Call); 8323 8324 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8325 unsigned ResNo = 0; // ResNo - The result number of the next output. 8326 unsigned NumMatchingOps = 0; 8327 for (auto &T : TargetConstraints) { 8328 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8329 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8330 8331 // Compute the value type for each operand. 8332 if (OpInfo.Type == InlineAsm::isInput || 8333 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8334 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8335 8336 // Process the call argument. BasicBlocks are labels, currently appearing 8337 // only in asm's. 8338 if (isa<CallBrInst>(Call) && 8339 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8340 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8341 NumMatchingOps) && 8342 (NumMatchingOps == 0 || 8343 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8344 NumMatchingOps))) { 8345 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8346 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8347 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8348 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8349 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8350 } else { 8351 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8352 } 8353 8354 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8355 DAG.getDataLayout()); 8356 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8357 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8358 // The return value of the call is this value. As such, there is no 8359 // corresponding argument. 8360 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8361 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8362 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8363 DAG.getDataLayout(), STy->getElementType(ResNo)); 8364 } else { 8365 assert(ResNo == 0 && "Asm only has one result!"); 8366 OpInfo.ConstraintVT = 8367 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8368 } 8369 ++ResNo; 8370 } else { 8371 OpInfo.ConstraintVT = MVT::Other; 8372 } 8373 8374 if (OpInfo.hasMatchingInput()) 8375 ++NumMatchingOps; 8376 8377 if (!HasSideEffect) 8378 HasSideEffect = OpInfo.hasMemory(TLI); 8379 8380 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8381 // FIXME: Could we compute this on OpInfo rather than T? 8382 8383 // Compute the constraint code and ConstraintType to use. 8384 TLI.ComputeConstraintToUse(T, SDValue()); 8385 8386 if (T.ConstraintType == TargetLowering::C_Immediate && 8387 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8388 // We've delayed emitting a diagnostic like the "n" constraint because 8389 // inlining could cause an integer showing up. 8390 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8391 "' expects an integer constant " 8392 "expression"); 8393 8394 ExtraInfo.update(T); 8395 } 8396 8397 8398 // We won't need to flush pending loads if this asm doesn't touch 8399 // memory and is nonvolatile. 8400 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8401 8402 bool IsCallBr = isa<CallBrInst>(Call); 8403 if (IsCallBr) { 8404 // If this is a callbr we need to flush pending exports since inlineasm_br 8405 // is a terminator. We need to do this before nodes are glued to 8406 // the inlineasm_br node. 8407 Chain = getControlRoot(); 8408 } 8409 8410 // Second pass over the constraints: compute which constraint option to use. 8411 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8412 // If this is an output operand with a matching input operand, look up the 8413 // matching input. If their types mismatch, e.g. one is an integer, the 8414 // other is floating point, or their sizes are different, flag it as an 8415 // error. 8416 if (OpInfo.hasMatchingInput()) { 8417 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8418 patchMatchingInput(OpInfo, Input, DAG); 8419 } 8420 8421 // Compute the constraint code and ConstraintType to use. 8422 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8423 8424 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8425 OpInfo.Type == InlineAsm::isClobber) 8426 continue; 8427 8428 // If this is a memory input, and if the operand is not indirect, do what we 8429 // need to provide an address for the memory input. 8430 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8431 !OpInfo.isIndirect) { 8432 assert((OpInfo.isMultipleAlternative || 8433 (OpInfo.Type == InlineAsm::isInput)) && 8434 "Can only indirectify direct input operands!"); 8435 8436 // Memory operands really want the address of the value. 8437 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8438 8439 // There is no longer a Value* corresponding to this operand. 8440 OpInfo.CallOperandVal = nullptr; 8441 8442 // It is now an indirect operand. 8443 OpInfo.isIndirect = true; 8444 } 8445 8446 } 8447 8448 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8449 std::vector<SDValue> AsmNodeOperands; 8450 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8451 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8452 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8453 8454 // If we have a !srcloc metadata node associated with it, we want to attach 8455 // this to the ultimately generated inline asm machineinstr. To do this, we 8456 // pass in the third operand as this (potentially null) inline asm MDNode. 8457 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8458 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8459 8460 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8461 // bits as operand 3. 8462 AsmNodeOperands.push_back(DAG.getTargetConstant( 8463 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8464 8465 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8466 // this, assign virtual and physical registers for inputs and otput. 8467 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8468 // Assign Registers. 8469 SDISelAsmOperandInfo &RefOpInfo = 8470 OpInfo.isMatchingInputConstraint() 8471 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8472 : OpInfo; 8473 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8474 8475 auto DetectWriteToReservedRegister = [&]() { 8476 const MachineFunction &MF = DAG.getMachineFunction(); 8477 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8478 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8479 if (Register::isPhysicalRegister(Reg) && 8480 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8481 const char *RegName = TRI.getName(Reg); 8482 emitInlineAsmError(Call, "write to reserved register '" + 8483 Twine(RegName) + "'"); 8484 return true; 8485 } 8486 } 8487 return false; 8488 }; 8489 8490 switch (OpInfo.Type) { 8491 case InlineAsm::isOutput: 8492 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8493 unsigned ConstraintID = 8494 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8495 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8496 "Failed to convert memory constraint code to constraint id."); 8497 8498 // Add information to the INLINEASM node to know about this output. 8499 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8500 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8501 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8502 MVT::i32)); 8503 AsmNodeOperands.push_back(OpInfo.CallOperand); 8504 } else { 8505 // Otherwise, this outputs to a register (directly for C_Register / 8506 // C_RegisterClass, and a target-defined fashion for 8507 // C_Immediate/C_Other). Find a register that we can use. 8508 if (OpInfo.AssignedRegs.Regs.empty()) { 8509 emitInlineAsmError( 8510 Call, "couldn't allocate output register for constraint '" + 8511 Twine(OpInfo.ConstraintCode) + "'"); 8512 return; 8513 } 8514 8515 if (DetectWriteToReservedRegister()) 8516 return; 8517 8518 // Add information to the INLINEASM node to know that this register is 8519 // set. 8520 OpInfo.AssignedRegs.AddInlineAsmOperands( 8521 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8522 : InlineAsm::Kind_RegDef, 8523 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8524 } 8525 break; 8526 8527 case InlineAsm::isInput: { 8528 SDValue InOperandVal = OpInfo.CallOperand; 8529 8530 if (OpInfo.isMatchingInputConstraint()) { 8531 // If this is required to match an output register we have already set, 8532 // just use its register. 8533 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8534 AsmNodeOperands); 8535 unsigned OpFlag = 8536 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8537 if (InlineAsm::isRegDefKind(OpFlag) || 8538 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8539 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8540 if (OpInfo.isIndirect) { 8541 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8542 emitInlineAsmError(Call, "inline asm not supported yet: " 8543 "don't know how to handle tied " 8544 "indirect register inputs"); 8545 return; 8546 } 8547 8548 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8549 SmallVector<unsigned, 4> Regs; 8550 8551 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8552 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8553 MachineRegisterInfo &RegInfo = 8554 DAG.getMachineFunction().getRegInfo(); 8555 for (unsigned i = 0; i != NumRegs; ++i) 8556 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8557 } else { 8558 emitInlineAsmError(Call, 8559 "inline asm error: This value type register " 8560 "class is not natively supported!"); 8561 return; 8562 } 8563 8564 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8565 8566 SDLoc dl = getCurSDLoc(); 8567 // Use the produced MatchedRegs object to 8568 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8569 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8570 true, OpInfo.getMatchedOperand(), dl, 8571 DAG, AsmNodeOperands); 8572 break; 8573 } 8574 8575 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8576 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8577 "Unexpected number of operands"); 8578 // Add information to the INLINEASM node to know about this input. 8579 // See InlineAsm.h isUseOperandTiedToDef. 8580 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8581 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8582 OpInfo.getMatchedOperand()); 8583 AsmNodeOperands.push_back(DAG.getTargetConstant( 8584 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8585 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8586 break; 8587 } 8588 8589 // Treat indirect 'X' constraint as memory. 8590 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8591 OpInfo.isIndirect) 8592 OpInfo.ConstraintType = TargetLowering::C_Memory; 8593 8594 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8595 OpInfo.ConstraintType == TargetLowering::C_Other) { 8596 std::vector<SDValue> Ops; 8597 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8598 Ops, DAG); 8599 if (Ops.empty()) { 8600 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8601 if (isa<ConstantSDNode>(InOperandVal)) { 8602 emitInlineAsmError(Call, "value out of range for constraint '" + 8603 Twine(OpInfo.ConstraintCode) + "'"); 8604 return; 8605 } 8606 8607 emitInlineAsmError(Call, 8608 "invalid operand for inline asm constraint '" + 8609 Twine(OpInfo.ConstraintCode) + "'"); 8610 return; 8611 } 8612 8613 // Add information to the INLINEASM node to know about this input. 8614 unsigned ResOpType = 8615 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8616 AsmNodeOperands.push_back(DAG.getTargetConstant( 8617 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8618 llvm::append_range(AsmNodeOperands, Ops); 8619 break; 8620 } 8621 8622 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8623 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8624 assert(InOperandVal.getValueType() == 8625 TLI.getPointerTy(DAG.getDataLayout()) && 8626 "Memory operands expect pointer values"); 8627 8628 unsigned ConstraintID = 8629 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8630 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8631 "Failed to convert memory constraint code to constraint id."); 8632 8633 // Add information to the INLINEASM node to know about this input. 8634 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8635 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8636 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8637 getCurSDLoc(), 8638 MVT::i32)); 8639 AsmNodeOperands.push_back(InOperandVal); 8640 break; 8641 } 8642 8643 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8644 OpInfo.ConstraintType == TargetLowering::C_Register) && 8645 "Unknown constraint type!"); 8646 8647 // TODO: Support this. 8648 if (OpInfo.isIndirect) { 8649 emitInlineAsmError( 8650 Call, "Don't know how to handle indirect register inputs yet " 8651 "for constraint '" + 8652 Twine(OpInfo.ConstraintCode) + "'"); 8653 return; 8654 } 8655 8656 // Copy the input into the appropriate registers. 8657 if (OpInfo.AssignedRegs.Regs.empty()) { 8658 emitInlineAsmError(Call, 8659 "couldn't allocate input reg for constraint '" + 8660 Twine(OpInfo.ConstraintCode) + "'"); 8661 return; 8662 } 8663 8664 if (DetectWriteToReservedRegister()) 8665 return; 8666 8667 SDLoc dl = getCurSDLoc(); 8668 8669 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8670 &Call); 8671 8672 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8673 dl, DAG, AsmNodeOperands); 8674 break; 8675 } 8676 case InlineAsm::isClobber: 8677 // Add the clobbered value to the operand list, so that the register 8678 // allocator is aware that the physreg got clobbered. 8679 if (!OpInfo.AssignedRegs.Regs.empty()) 8680 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8681 false, 0, getCurSDLoc(), DAG, 8682 AsmNodeOperands); 8683 break; 8684 } 8685 } 8686 8687 // Finish up input operands. Set the input chain and add the flag last. 8688 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8689 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8690 8691 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8692 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8693 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8694 Flag = Chain.getValue(1); 8695 8696 // Do additional work to generate outputs. 8697 8698 SmallVector<EVT, 1> ResultVTs; 8699 SmallVector<SDValue, 1> ResultValues; 8700 SmallVector<SDValue, 8> OutChains; 8701 8702 llvm::Type *CallResultType = Call.getType(); 8703 ArrayRef<Type *> ResultTypes; 8704 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8705 ResultTypes = StructResult->elements(); 8706 else if (!CallResultType->isVoidTy()) 8707 ResultTypes = makeArrayRef(CallResultType); 8708 8709 auto CurResultType = ResultTypes.begin(); 8710 auto handleRegAssign = [&](SDValue V) { 8711 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8712 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8713 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8714 ++CurResultType; 8715 // If the type of the inline asm call site return value is different but has 8716 // same size as the type of the asm output bitcast it. One example of this 8717 // is for vectors with different width / number of elements. This can 8718 // happen for register classes that can contain multiple different value 8719 // types. The preg or vreg allocated may not have the same VT as was 8720 // expected. 8721 // 8722 // This can also happen for a return value that disagrees with the register 8723 // class it is put in, eg. a double in a general-purpose register on a 8724 // 32-bit machine. 8725 if (ResultVT != V.getValueType() && 8726 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8727 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8728 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8729 V.getValueType().isInteger()) { 8730 // If a result value was tied to an input value, the computed result 8731 // may have a wider width than the expected result. Extract the 8732 // relevant portion. 8733 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8734 } 8735 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8736 ResultVTs.push_back(ResultVT); 8737 ResultValues.push_back(V); 8738 }; 8739 8740 // Deal with output operands. 8741 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8742 if (OpInfo.Type == InlineAsm::isOutput) { 8743 SDValue Val; 8744 // Skip trivial output operands. 8745 if (OpInfo.AssignedRegs.Regs.empty()) 8746 continue; 8747 8748 switch (OpInfo.ConstraintType) { 8749 case TargetLowering::C_Register: 8750 case TargetLowering::C_RegisterClass: 8751 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8752 Chain, &Flag, &Call); 8753 break; 8754 case TargetLowering::C_Immediate: 8755 case TargetLowering::C_Other: 8756 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8757 OpInfo, DAG); 8758 break; 8759 case TargetLowering::C_Memory: 8760 break; // Already handled. 8761 case TargetLowering::C_Unknown: 8762 assert(false && "Unexpected unknown constraint"); 8763 } 8764 8765 // Indirect output manifest as stores. Record output chains. 8766 if (OpInfo.isIndirect) { 8767 const Value *Ptr = OpInfo.CallOperandVal; 8768 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8769 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8770 MachinePointerInfo(Ptr)); 8771 OutChains.push_back(Store); 8772 } else { 8773 // generate CopyFromRegs to associated registers. 8774 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8775 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8776 for (const SDValue &V : Val->op_values()) 8777 handleRegAssign(V); 8778 } else 8779 handleRegAssign(Val); 8780 } 8781 } 8782 } 8783 8784 // Set results. 8785 if (!ResultValues.empty()) { 8786 assert(CurResultType == ResultTypes.end() && 8787 "Mismatch in number of ResultTypes"); 8788 assert(ResultValues.size() == ResultTypes.size() && 8789 "Mismatch in number of output operands in asm result"); 8790 8791 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8792 DAG.getVTList(ResultVTs), ResultValues); 8793 setValue(&Call, V); 8794 } 8795 8796 // Collect store chains. 8797 if (!OutChains.empty()) 8798 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8799 8800 // Only Update Root if inline assembly has a memory effect. 8801 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8802 DAG.setRoot(Chain); 8803 } 8804 8805 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8806 const Twine &Message) { 8807 LLVMContext &Ctx = *DAG.getContext(); 8808 Ctx.emitError(&Call, Message); 8809 8810 // Make sure we leave the DAG in a valid state 8811 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8812 SmallVector<EVT, 1> ValueVTs; 8813 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8814 8815 if (ValueVTs.empty()) 8816 return; 8817 8818 SmallVector<SDValue, 1> Ops; 8819 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8820 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8821 8822 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8823 } 8824 8825 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8826 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8827 MVT::Other, getRoot(), 8828 getValue(I.getArgOperand(0)), 8829 DAG.getSrcValue(I.getArgOperand(0)))); 8830 } 8831 8832 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8833 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8834 const DataLayout &DL = DAG.getDataLayout(); 8835 SDValue V = DAG.getVAArg( 8836 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8837 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8838 DL.getABITypeAlign(I.getType()).value()); 8839 DAG.setRoot(V.getValue(1)); 8840 8841 if (I.getType()->isPointerTy()) 8842 V = DAG.getPtrExtOrTrunc( 8843 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8844 setValue(&I, V); 8845 } 8846 8847 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8848 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8849 MVT::Other, getRoot(), 8850 getValue(I.getArgOperand(0)), 8851 DAG.getSrcValue(I.getArgOperand(0)))); 8852 } 8853 8854 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8855 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8856 MVT::Other, getRoot(), 8857 getValue(I.getArgOperand(0)), 8858 getValue(I.getArgOperand(1)), 8859 DAG.getSrcValue(I.getArgOperand(0)), 8860 DAG.getSrcValue(I.getArgOperand(1)))); 8861 } 8862 8863 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8864 const Instruction &I, 8865 SDValue Op) { 8866 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8867 if (!Range) 8868 return Op; 8869 8870 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8871 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8872 return Op; 8873 8874 APInt Lo = CR.getUnsignedMin(); 8875 if (!Lo.isMinValue()) 8876 return Op; 8877 8878 APInt Hi = CR.getUnsignedMax(); 8879 unsigned Bits = std::max(Hi.getActiveBits(), 8880 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8881 8882 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8883 8884 SDLoc SL = getCurSDLoc(); 8885 8886 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8887 DAG.getValueType(SmallVT)); 8888 unsigned NumVals = Op.getNode()->getNumValues(); 8889 if (NumVals == 1) 8890 return ZExt; 8891 8892 SmallVector<SDValue, 4> Ops; 8893 8894 Ops.push_back(ZExt); 8895 for (unsigned I = 1; I != NumVals; ++I) 8896 Ops.push_back(Op.getValue(I)); 8897 8898 return DAG.getMergeValues(Ops, SL); 8899 } 8900 8901 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8902 /// the call being lowered. 8903 /// 8904 /// This is a helper for lowering intrinsics that follow a target calling 8905 /// convention or require stack pointer adjustment. Only a subset of the 8906 /// intrinsic's operands need to participate in the calling convention. 8907 void SelectionDAGBuilder::populateCallLoweringInfo( 8908 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8909 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8910 bool IsPatchPoint) { 8911 TargetLowering::ArgListTy Args; 8912 Args.reserve(NumArgs); 8913 8914 // Populate the argument list. 8915 // Attributes for args start at offset 1, after the return attribute. 8916 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8917 ArgI != ArgE; ++ArgI) { 8918 const Value *V = Call->getOperand(ArgI); 8919 8920 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8921 8922 TargetLowering::ArgListEntry Entry; 8923 Entry.Node = getValue(V); 8924 Entry.Ty = V->getType(); 8925 Entry.setAttributes(Call, ArgI); 8926 Args.push_back(Entry); 8927 } 8928 8929 CLI.setDebugLoc(getCurSDLoc()) 8930 .setChain(getRoot()) 8931 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8932 .setDiscardResult(Call->use_empty()) 8933 .setIsPatchPoint(IsPatchPoint) 8934 .setIsPreallocated( 8935 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8936 } 8937 8938 /// Add a stack map intrinsic call's live variable operands to a stackmap 8939 /// or patchpoint target node's operand list. 8940 /// 8941 /// Constants are converted to TargetConstants purely as an optimization to 8942 /// avoid constant materialization and register allocation. 8943 /// 8944 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8945 /// generate addess computation nodes, and so FinalizeISel can convert the 8946 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8947 /// address materialization and register allocation, but may also be required 8948 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8949 /// alloca in the entry block, then the runtime may assume that the alloca's 8950 /// StackMap location can be read immediately after compilation and that the 8951 /// location is valid at any point during execution (this is similar to the 8952 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8953 /// only available in a register, then the runtime would need to trap when 8954 /// execution reaches the StackMap in order to read the alloca's location. 8955 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8956 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8957 SelectionDAGBuilder &Builder) { 8958 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8959 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8960 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8961 Ops.push_back( 8962 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8963 Ops.push_back( 8964 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8965 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8966 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8967 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8968 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8969 } else 8970 Ops.push_back(OpVal); 8971 } 8972 } 8973 8974 /// Lower llvm.experimental.stackmap directly to its target opcode. 8975 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8976 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8977 // [live variables...]) 8978 8979 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8980 8981 SDValue Chain, InFlag, Callee, NullPtr; 8982 SmallVector<SDValue, 32> Ops; 8983 8984 SDLoc DL = getCurSDLoc(); 8985 Callee = getValue(CI.getCalledOperand()); 8986 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8987 8988 // The stackmap intrinsic only records the live variables (the arguments 8989 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8990 // intrinsic, this won't be lowered to a function call. This means we don't 8991 // have to worry about calling conventions and target specific lowering code. 8992 // Instead we perform the call lowering right here. 8993 // 8994 // chain, flag = CALLSEQ_START(chain, 0, 0) 8995 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8996 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8997 // 8998 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8999 InFlag = Chain.getValue(1); 9000 9001 // Add the <id> and <numBytes> constants. 9002 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 9003 Ops.push_back(DAG.getTargetConstant( 9004 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 9005 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 9006 Ops.push_back(DAG.getTargetConstant( 9007 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 9008 MVT::i32)); 9009 9010 // Push live variables for the stack map. 9011 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9012 9013 // We are not pushing any register mask info here on the operands list, 9014 // because the stackmap doesn't clobber anything. 9015 9016 // Push the chain and the glue flag. 9017 Ops.push_back(Chain); 9018 Ops.push_back(InFlag); 9019 9020 // Create the STACKMAP node. 9021 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9022 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9023 Chain = SDValue(SM, 0); 9024 InFlag = Chain.getValue(1); 9025 9026 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9027 9028 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9029 9030 // Set the root to the target-lowered call chain. 9031 DAG.setRoot(Chain); 9032 9033 // Inform the Frame Information that we have a stackmap in this function. 9034 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9035 } 9036 9037 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9038 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9039 const BasicBlock *EHPadBB) { 9040 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9041 // i32 <numBytes>, 9042 // i8* <target>, 9043 // i32 <numArgs>, 9044 // [Args...], 9045 // [live variables...]) 9046 9047 CallingConv::ID CC = CB.getCallingConv(); 9048 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9049 bool HasDef = !CB.getType()->isVoidTy(); 9050 SDLoc dl = getCurSDLoc(); 9051 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9052 9053 // Handle immediate and symbolic callees. 9054 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9055 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9056 /*isTarget=*/true); 9057 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9058 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9059 SDLoc(SymbolicCallee), 9060 SymbolicCallee->getValueType(0)); 9061 9062 // Get the real number of arguments participating in the call <numArgs> 9063 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9064 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9065 9066 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9067 // Intrinsics include all meta-operands up to but not including CC. 9068 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9069 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9070 "Not enough arguments provided to the patchpoint intrinsic"); 9071 9072 // For AnyRegCC the arguments are lowered later on manually. 9073 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9074 Type *ReturnTy = 9075 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9076 9077 TargetLowering::CallLoweringInfo CLI(DAG); 9078 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9079 ReturnTy, true); 9080 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9081 9082 SDNode *CallEnd = Result.second.getNode(); 9083 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9084 CallEnd = CallEnd->getOperand(0).getNode(); 9085 9086 /// Get a call instruction from the call sequence chain. 9087 /// Tail calls are not allowed. 9088 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9089 "Expected a callseq node."); 9090 SDNode *Call = CallEnd->getOperand(0).getNode(); 9091 bool HasGlue = Call->getGluedNode(); 9092 9093 // Replace the target specific call node with the patchable intrinsic. 9094 SmallVector<SDValue, 8> Ops; 9095 9096 // Add the <id> and <numBytes> constants. 9097 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9098 Ops.push_back(DAG.getTargetConstant( 9099 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9100 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9101 Ops.push_back(DAG.getTargetConstant( 9102 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9103 MVT::i32)); 9104 9105 // Add the callee. 9106 Ops.push_back(Callee); 9107 9108 // Adjust <numArgs> to account for any arguments that have been passed on the 9109 // stack instead. 9110 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9111 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9112 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9113 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9114 9115 // Add the calling convention 9116 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9117 9118 // Add the arguments we omitted previously. The register allocator should 9119 // place these in any free register. 9120 if (IsAnyRegCC) 9121 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9122 Ops.push_back(getValue(CB.getArgOperand(i))); 9123 9124 // Push the arguments from the call instruction up to the register mask. 9125 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9126 Ops.append(Call->op_begin() + 2, e); 9127 9128 // Push live variables for the stack map. 9129 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9130 9131 // Push the register mask info. 9132 if (HasGlue) 9133 Ops.push_back(*(Call->op_end()-2)); 9134 else 9135 Ops.push_back(*(Call->op_end()-1)); 9136 9137 // Push the chain (this is originally the first operand of the call, but 9138 // becomes now the last or second to last operand). 9139 Ops.push_back(*(Call->op_begin())); 9140 9141 // Push the glue flag (last operand). 9142 if (HasGlue) 9143 Ops.push_back(*(Call->op_end()-1)); 9144 9145 SDVTList NodeTys; 9146 if (IsAnyRegCC && HasDef) { 9147 // Create the return types based on the intrinsic definition 9148 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9149 SmallVector<EVT, 3> ValueVTs; 9150 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9151 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9152 9153 // There is always a chain and a glue type at the end 9154 ValueVTs.push_back(MVT::Other); 9155 ValueVTs.push_back(MVT::Glue); 9156 NodeTys = DAG.getVTList(ValueVTs); 9157 } else 9158 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9159 9160 // Replace the target specific call node with a PATCHPOINT node. 9161 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9162 dl, NodeTys, Ops); 9163 9164 // Update the NodeMap. 9165 if (HasDef) { 9166 if (IsAnyRegCC) 9167 setValue(&CB, SDValue(MN, 0)); 9168 else 9169 setValue(&CB, Result.first); 9170 } 9171 9172 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9173 // call sequence. Furthermore the location of the chain and glue can change 9174 // when the AnyReg calling convention is used and the intrinsic returns a 9175 // value. 9176 if (IsAnyRegCC && HasDef) { 9177 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9178 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9179 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9180 } else 9181 DAG.ReplaceAllUsesWith(Call, MN); 9182 DAG.DeleteNode(Call); 9183 9184 // Inform the Frame Information that we have a patchpoint in this function. 9185 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9186 } 9187 9188 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9189 unsigned Intrinsic) { 9190 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9191 SDValue Op1 = getValue(I.getArgOperand(0)); 9192 SDValue Op2; 9193 if (I.getNumArgOperands() > 1) 9194 Op2 = getValue(I.getArgOperand(1)); 9195 SDLoc dl = getCurSDLoc(); 9196 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9197 SDValue Res; 9198 SDNodeFlags SDFlags; 9199 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9200 SDFlags.copyFMF(*FPMO); 9201 9202 switch (Intrinsic) { 9203 case Intrinsic::vector_reduce_fadd: 9204 if (SDFlags.hasAllowReassociation()) 9205 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9206 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9207 SDFlags); 9208 else 9209 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9210 break; 9211 case Intrinsic::vector_reduce_fmul: 9212 if (SDFlags.hasAllowReassociation()) 9213 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9214 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9215 SDFlags); 9216 else 9217 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9218 break; 9219 case Intrinsic::vector_reduce_add: 9220 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9221 break; 9222 case Intrinsic::vector_reduce_mul: 9223 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9224 break; 9225 case Intrinsic::vector_reduce_and: 9226 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9227 break; 9228 case Intrinsic::vector_reduce_or: 9229 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9230 break; 9231 case Intrinsic::vector_reduce_xor: 9232 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9233 break; 9234 case Intrinsic::vector_reduce_smax: 9235 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9236 break; 9237 case Intrinsic::vector_reduce_smin: 9238 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9239 break; 9240 case Intrinsic::vector_reduce_umax: 9241 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9242 break; 9243 case Intrinsic::vector_reduce_umin: 9244 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9245 break; 9246 case Intrinsic::vector_reduce_fmax: 9247 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9248 break; 9249 case Intrinsic::vector_reduce_fmin: 9250 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9251 break; 9252 default: 9253 llvm_unreachable("Unhandled vector reduce intrinsic"); 9254 } 9255 setValue(&I, Res); 9256 } 9257 9258 /// Returns an AttributeList representing the attributes applied to the return 9259 /// value of the given call. 9260 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9261 SmallVector<Attribute::AttrKind, 2> Attrs; 9262 if (CLI.RetSExt) 9263 Attrs.push_back(Attribute::SExt); 9264 if (CLI.RetZExt) 9265 Attrs.push_back(Attribute::ZExt); 9266 if (CLI.IsInReg) 9267 Attrs.push_back(Attribute::InReg); 9268 9269 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9270 Attrs); 9271 } 9272 9273 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9274 /// implementation, which just calls LowerCall. 9275 /// FIXME: When all targets are 9276 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9277 std::pair<SDValue, SDValue> 9278 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9279 // Handle the incoming return values from the call. 9280 CLI.Ins.clear(); 9281 Type *OrigRetTy = CLI.RetTy; 9282 SmallVector<EVT, 4> RetTys; 9283 SmallVector<uint64_t, 4> Offsets; 9284 auto &DL = CLI.DAG.getDataLayout(); 9285 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9286 9287 if (CLI.IsPostTypeLegalization) { 9288 // If we are lowering a libcall after legalization, split the return type. 9289 SmallVector<EVT, 4> OldRetTys; 9290 SmallVector<uint64_t, 4> OldOffsets; 9291 RetTys.swap(OldRetTys); 9292 Offsets.swap(OldOffsets); 9293 9294 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9295 EVT RetVT = OldRetTys[i]; 9296 uint64_t Offset = OldOffsets[i]; 9297 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9298 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9299 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9300 RetTys.append(NumRegs, RegisterVT); 9301 for (unsigned j = 0; j != NumRegs; ++j) 9302 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9303 } 9304 } 9305 9306 SmallVector<ISD::OutputArg, 4> Outs; 9307 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9308 9309 bool CanLowerReturn = 9310 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9311 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9312 9313 SDValue DemoteStackSlot; 9314 int DemoteStackIdx = -100; 9315 if (!CanLowerReturn) { 9316 // FIXME: equivalent assert? 9317 // assert(!CS.hasInAllocaArgument() && 9318 // "sret demotion is incompatible with inalloca"); 9319 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9320 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9321 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9322 DemoteStackIdx = 9323 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9324 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9325 DL.getAllocaAddrSpace()); 9326 9327 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9328 ArgListEntry Entry; 9329 Entry.Node = DemoteStackSlot; 9330 Entry.Ty = StackSlotPtrType; 9331 Entry.IsSExt = false; 9332 Entry.IsZExt = false; 9333 Entry.IsInReg = false; 9334 Entry.IsSRet = true; 9335 Entry.IsNest = false; 9336 Entry.IsByVal = false; 9337 Entry.IsByRef = false; 9338 Entry.IsReturned = false; 9339 Entry.IsSwiftSelf = false; 9340 Entry.IsSwiftError = false; 9341 Entry.IsCFGuardTarget = false; 9342 Entry.Alignment = Alignment; 9343 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9344 CLI.NumFixedArgs += 1; 9345 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9346 9347 // sret demotion isn't compatible with tail-calls, since the sret argument 9348 // points into the callers stack frame. 9349 CLI.IsTailCall = false; 9350 } else { 9351 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9352 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9353 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9354 ISD::ArgFlagsTy Flags; 9355 if (NeedsRegBlock) { 9356 Flags.setInConsecutiveRegs(); 9357 if (I == RetTys.size() - 1) 9358 Flags.setInConsecutiveRegsLast(); 9359 } 9360 EVT VT = RetTys[I]; 9361 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9362 CLI.CallConv, VT); 9363 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9364 CLI.CallConv, VT); 9365 for (unsigned i = 0; i != NumRegs; ++i) { 9366 ISD::InputArg MyFlags; 9367 MyFlags.Flags = Flags; 9368 MyFlags.VT = RegisterVT; 9369 MyFlags.ArgVT = VT; 9370 MyFlags.Used = CLI.IsReturnValueUsed; 9371 if (CLI.RetTy->isPointerTy()) { 9372 MyFlags.Flags.setPointer(); 9373 MyFlags.Flags.setPointerAddrSpace( 9374 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9375 } 9376 if (CLI.RetSExt) 9377 MyFlags.Flags.setSExt(); 9378 if (CLI.RetZExt) 9379 MyFlags.Flags.setZExt(); 9380 if (CLI.IsInReg) 9381 MyFlags.Flags.setInReg(); 9382 CLI.Ins.push_back(MyFlags); 9383 } 9384 } 9385 } 9386 9387 // We push in swifterror return as the last element of CLI.Ins. 9388 ArgListTy &Args = CLI.getArgs(); 9389 if (supportSwiftError()) { 9390 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9391 if (Args[i].IsSwiftError) { 9392 ISD::InputArg MyFlags; 9393 MyFlags.VT = getPointerTy(DL); 9394 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9395 MyFlags.Flags.setSwiftError(); 9396 CLI.Ins.push_back(MyFlags); 9397 } 9398 } 9399 } 9400 9401 // Handle all of the outgoing arguments. 9402 CLI.Outs.clear(); 9403 CLI.OutVals.clear(); 9404 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9405 SmallVector<EVT, 4> ValueVTs; 9406 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9407 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9408 Type *FinalType = Args[i].Ty; 9409 if (Args[i].IsByVal) 9410 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9411 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9412 FinalType, CLI.CallConv, CLI.IsVarArg); 9413 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9414 ++Value) { 9415 EVT VT = ValueVTs[Value]; 9416 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9417 SDValue Op = SDValue(Args[i].Node.getNode(), 9418 Args[i].Node.getResNo() + Value); 9419 ISD::ArgFlagsTy Flags; 9420 9421 // Certain targets (such as MIPS), may have a different ABI alignment 9422 // for a type depending on the context. Give the target a chance to 9423 // specify the alignment it wants. 9424 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9425 9426 if (Args[i].Ty->isPointerTy()) { 9427 Flags.setPointer(); 9428 Flags.setPointerAddrSpace( 9429 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9430 } 9431 if (Args[i].IsZExt) 9432 Flags.setZExt(); 9433 if (Args[i].IsSExt) 9434 Flags.setSExt(); 9435 if (Args[i].IsInReg) { 9436 // If we are using vectorcall calling convention, a structure that is 9437 // passed InReg - is surely an HVA 9438 if (CLI.CallConv == CallingConv::X86_VectorCall && 9439 isa<StructType>(FinalType)) { 9440 // The first value of a structure is marked 9441 if (0 == Value) 9442 Flags.setHvaStart(); 9443 Flags.setHva(); 9444 } 9445 // Set InReg Flag 9446 Flags.setInReg(); 9447 } 9448 if (Args[i].IsSRet) 9449 Flags.setSRet(); 9450 if (Args[i].IsSwiftSelf) 9451 Flags.setSwiftSelf(); 9452 if (Args[i].IsSwiftError) 9453 Flags.setSwiftError(); 9454 if (Args[i].IsCFGuardTarget) 9455 Flags.setCFGuardTarget(); 9456 if (Args[i].IsByVal) 9457 Flags.setByVal(); 9458 if (Args[i].IsByRef) 9459 Flags.setByRef(); 9460 if (Args[i].IsPreallocated) { 9461 Flags.setPreallocated(); 9462 // Set the byval flag for CCAssignFn callbacks that don't know about 9463 // preallocated. This way we can know how many bytes we should've 9464 // allocated and how many bytes a callee cleanup function will pop. If 9465 // we port preallocated to more targets, we'll have to add custom 9466 // preallocated handling in the various CC lowering callbacks. 9467 Flags.setByVal(); 9468 } 9469 if (Args[i].IsInAlloca) { 9470 Flags.setInAlloca(); 9471 // Set the byval flag for CCAssignFn callbacks that don't know about 9472 // inalloca. This way we can know how many bytes we should've allocated 9473 // and how many bytes a callee cleanup function will pop. If we port 9474 // inalloca to more targets, we'll have to add custom inalloca handling 9475 // in the various CC lowering callbacks. 9476 Flags.setByVal(); 9477 } 9478 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9479 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9480 Type *ElementTy = Ty->getElementType(); 9481 9482 unsigned FrameSize = DL.getTypeAllocSize( 9483 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9484 Flags.setByValSize(FrameSize); 9485 9486 // info is not there but there are cases it cannot get right. 9487 Align FrameAlign; 9488 if (auto MA = Args[i].Alignment) 9489 FrameAlign = *MA; 9490 else 9491 FrameAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9492 Flags.setByValAlign(FrameAlign); 9493 } 9494 if (Args[i].IsNest) 9495 Flags.setNest(); 9496 if (NeedsRegBlock) 9497 Flags.setInConsecutiveRegs(); 9498 Flags.setOrigAlign(OriginalAlignment); 9499 9500 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9501 CLI.CallConv, VT); 9502 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9503 CLI.CallConv, VT); 9504 SmallVector<SDValue, 4> Parts(NumParts); 9505 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9506 9507 if (Args[i].IsSExt) 9508 ExtendKind = ISD::SIGN_EXTEND; 9509 else if (Args[i].IsZExt) 9510 ExtendKind = ISD::ZERO_EXTEND; 9511 9512 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9513 // for now. 9514 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9515 CanLowerReturn) { 9516 assert((CLI.RetTy == Args[i].Ty || 9517 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9518 CLI.RetTy->getPointerAddressSpace() == 9519 Args[i].Ty->getPointerAddressSpace())) && 9520 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9521 // Before passing 'returned' to the target lowering code, ensure that 9522 // either the register MVT and the actual EVT are the same size or that 9523 // the return value and argument are extended in the same way; in these 9524 // cases it's safe to pass the argument register value unchanged as the 9525 // return register value (although it's at the target's option whether 9526 // to do so) 9527 // TODO: allow code generation to take advantage of partially preserved 9528 // registers rather than clobbering the entire register when the 9529 // parameter extension method is not compatible with the return 9530 // extension method 9531 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9532 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9533 CLI.RetZExt == Args[i].IsZExt)) 9534 Flags.setReturned(); 9535 } 9536 9537 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9538 CLI.CallConv, ExtendKind); 9539 9540 for (unsigned j = 0; j != NumParts; ++j) { 9541 // if it isn't first piece, alignment must be 1 9542 // For scalable vectors the scalable part is currently handled 9543 // by individual targets, so we just use the known minimum size here. 9544 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9545 i < CLI.NumFixedArgs, i, 9546 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9547 if (NumParts > 1 && j == 0) 9548 MyFlags.Flags.setSplit(); 9549 else if (j != 0) { 9550 MyFlags.Flags.setOrigAlign(Align(1)); 9551 if (j == NumParts - 1) 9552 MyFlags.Flags.setSplitEnd(); 9553 } 9554 9555 CLI.Outs.push_back(MyFlags); 9556 CLI.OutVals.push_back(Parts[j]); 9557 } 9558 9559 if (NeedsRegBlock && Value == NumValues - 1) 9560 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9561 } 9562 } 9563 9564 SmallVector<SDValue, 4> InVals; 9565 CLI.Chain = LowerCall(CLI, InVals); 9566 9567 // Update CLI.InVals to use outside of this function. 9568 CLI.InVals = InVals; 9569 9570 // Verify that the target's LowerCall behaved as expected. 9571 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9572 "LowerCall didn't return a valid chain!"); 9573 assert((!CLI.IsTailCall || InVals.empty()) && 9574 "LowerCall emitted a return value for a tail call!"); 9575 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9576 "LowerCall didn't emit the correct number of values!"); 9577 9578 // For a tail call, the return value is merely live-out and there aren't 9579 // any nodes in the DAG representing it. Return a special value to 9580 // indicate that a tail call has been emitted and no more Instructions 9581 // should be processed in the current block. 9582 if (CLI.IsTailCall) { 9583 CLI.DAG.setRoot(CLI.Chain); 9584 return std::make_pair(SDValue(), SDValue()); 9585 } 9586 9587 #ifndef NDEBUG 9588 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9589 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9590 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9591 "LowerCall emitted a value with the wrong type!"); 9592 } 9593 #endif 9594 9595 SmallVector<SDValue, 4> ReturnValues; 9596 if (!CanLowerReturn) { 9597 // The instruction result is the result of loading from the 9598 // hidden sret parameter. 9599 SmallVector<EVT, 1> PVTs; 9600 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9601 9602 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9603 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9604 EVT PtrVT = PVTs[0]; 9605 9606 unsigned NumValues = RetTys.size(); 9607 ReturnValues.resize(NumValues); 9608 SmallVector<SDValue, 4> Chains(NumValues); 9609 9610 // An aggregate return value cannot wrap around the address space, so 9611 // offsets to its parts don't wrap either. 9612 SDNodeFlags Flags; 9613 Flags.setNoUnsignedWrap(true); 9614 9615 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9616 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9617 for (unsigned i = 0; i < NumValues; ++i) { 9618 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9619 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9620 PtrVT), Flags); 9621 SDValue L = CLI.DAG.getLoad( 9622 RetTys[i], CLI.DL, CLI.Chain, Add, 9623 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9624 DemoteStackIdx, Offsets[i]), 9625 HiddenSRetAlign); 9626 ReturnValues[i] = L; 9627 Chains[i] = L.getValue(1); 9628 } 9629 9630 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9631 } else { 9632 // Collect the legal value parts into potentially illegal values 9633 // that correspond to the original function's return values. 9634 Optional<ISD::NodeType> AssertOp; 9635 if (CLI.RetSExt) 9636 AssertOp = ISD::AssertSext; 9637 else if (CLI.RetZExt) 9638 AssertOp = ISD::AssertZext; 9639 unsigned CurReg = 0; 9640 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9641 EVT VT = RetTys[I]; 9642 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9643 CLI.CallConv, VT); 9644 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9645 CLI.CallConv, VT); 9646 9647 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9648 NumRegs, RegisterVT, VT, nullptr, 9649 CLI.CallConv, AssertOp)); 9650 CurReg += NumRegs; 9651 } 9652 9653 // For a function returning void, there is no return value. We can't create 9654 // such a node, so we just return a null return value in that case. In 9655 // that case, nothing will actually look at the value. 9656 if (ReturnValues.empty()) 9657 return std::make_pair(SDValue(), CLI.Chain); 9658 } 9659 9660 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9661 CLI.DAG.getVTList(RetTys), ReturnValues); 9662 return std::make_pair(Res, CLI.Chain); 9663 } 9664 9665 /// Places new result values for the node in Results (their number 9666 /// and types must exactly match those of the original return values of 9667 /// the node), or leaves Results empty, which indicates that the node is not 9668 /// to be custom lowered after all. 9669 void TargetLowering::LowerOperationWrapper(SDNode *N, 9670 SmallVectorImpl<SDValue> &Results, 9671 SelectionDAG &DAG) const { 9672 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9673 9674 if (!Res.getNode()) 9675 return; 9676 9677 // If the original node has one result, take the return value from 9678 // LowerOperation as is. It might not be result number 0. 9679 if (N->getNumValues() == 1) { 9680 Results.push_back(Res); 9681 return; 9682 } 9683 9684 // If the original node has multiple results, then the return node should 9685 // have the same number of results. 9686 assert((N->getNumValues() == Res->getNumValues()) && 9687 "Lowering returned the wrong number of results!"); 9688 9689 // Places new result values base on N result number. 9690 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9691 Results.push_back(Res.getValue(I)); 9692 } 9693 9694 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9695 llvm_unreachable("LowerOperation not implemented for this target!"); 9696 } 9697 9698 void 9699 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9700 SDValue Op = getNonRegisterValue(V); 9701 assert((Op.getOpcode() != ISD::CopyFromReg || 9702 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9703 "Copy from a reg to the same reg!"); 9704 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9705 9706 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9707 // If this is an InlineAsm we have to match the registers required, not the 9708 // notional registers required by the type. 9709 9710 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9711 None); // This is not an ABI copy. 9712 SDValue Chain = DAG.getEntryNode(); 9713 9714 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9715 FuncInfo.PreferredExtendType.end()) 9716 ? ISD::ANY_EXTEND 9717 : FuncInfo.PreferredExtendType[V]; 9718 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9719 PendingExports.push_back(Chain); 9720 } 9721 9722 #include "llvm/CodeGen/SelectionDAGISel.h" 9723 9724 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9725 /// entry block, return true. This includes arguments used by switches, since 9726 /// the switch may expand into multiple basic blocks. 9727 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9728 // With FastISel active, we may be splitting blocks, so force creation 9729 // of virtual registers for all non-dead arguments. 9730 if (FastISel) 9731 return A->use_empty(); 9732 9733 const BasicBlock &Entry = A->getParent()->front(); 9734 for (const User *U : A->users()) 9735 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9736 return false; // Use not in entry block. 9737 9738 return true; 9739 } 9740 9741 using ArgCopyElisionMapTy = 9742 DenseMap<const Argument *, 9743 std::pair<const AllocaInst *, const StoreInst *>>; 9744 9745 /// Scan the entry block of the function in FuncInfo for arguments that look 9746 /// like copies into a local alloca. Record any copied arguments in 9747 /// ArgCopyElisionCandidates. 9748 static void 9749 findArgumentCopyElisionCandidates(const DataLayout &DL, 9750 FunctionLoweringInfo *FuncInfo, 9751 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9752 // Record the state of every static alloca used in the entry block. Argument 9753 // allocas are all used in the entry block, so we need approximately as many 9754 // entries as we have arguments. 9755 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9756 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9757 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9758 StaticAllocas.reserve(NumArgs * 2); 9759 9760 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9761 if (!V) 9762 return nullptr; 9763 V = V->stripPointerCasts(); 9764 const auto *AI = dyn_cast<AllocaInst>(V); 9765 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9766 return nullptr; 9767 auto Iter = StaticAllocas.insert({AI, Unknown}); 9768 return &Iter.first->second; 9769 }; 9770 9771 // Look for stores of arguments to static allocas. Look through bitcasts and 9772 // GEPs to handle type coercions, as long as the alloca is fully initialized 9773 // by the store. Any non-store use of an alloca escapes it and any subsequent 9774 // unanalyzed store might write it. 9775 // FIXME: Handle structs initialized with multiple stores. 9776 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9777 // Look for stores, and handle non-store uses conservatively. 9778 const auto *SI = dyn_cast<StoreInst>(&I); 9779 if (!SI) { 9780 // We will look through cast uses, so ignore them completely. 9781 if (I.isCast()) 9782 continue; 9783 // Ignore debug info and pseudo op intrinsics, they don't escape or store 9784 // to allocas. 9785 if (I.isDebugOrPseudoInst()) 9786 continue; 9787 // This is an unknown instruction. Assume it escapes or writes to all 9788 // static alloca operands. 9789 for (const Use &U : I.operands()) { 9790 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9791 *Info = StaticAllocaInfo::Clobbered; 9792 } 9793 continue; 9794 } 9795 9796 // If the stored value is a static alloca, mark it as escaped. 9797 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9798 *Info = StaticAllocaInfo::Clobbered; 9799 9800 // Check if the destination is a static alloca. 9801 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9802 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9803 if (!Info) 9804 continue; 9805 const AllocaInst *AI = cast<AllocaInst>(Dst); 9806 9807 // Skip allocas that have been initialized or clobbered. 9808 if (*Info != StaticAllocaInfo::Unknown) 9809 continue; 9810 9811 // Check if the stored value is an argument, and that this store fully 9812 // initializes the alloca. Don't elide copies from the same argument twice. 9813 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9814 const auto *Arg = dyn_cast<Argument>(Val); 9815 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9816 Arg->getType()->isEmptyTy() || 9817 DL.getTypeStoreSize(Arg->getType()) != 9818 DL.getTypeAllocSize(AI->getAllocatedType()) || 9819 ArgCopyElisionCandidates.count(Arg)) { 9820 *Info = StaticAllocaInfo::Clobbered; 9821 continue; 9822 } 9823 9824 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9825 << '\n'); 9826 9827 // Mark this alloca and store for argument copy elision. 9828 *Info = StaticAllocaInfo::Elidable; 9829 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9830 9831 // Stop scanning if we've seen all arguments. This will happen early in -O0 9832 // builds, which is useful, because -O0 builds have large entry blocks and 9833 // many allocas. 9834 if (ArgCopyElisionCandidates.size() == NumArgs) 9835 break; 9836 } 9837 } 9838 9839 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9840 /// ArgVal is a load from a suitable fixed stack object. 9841 static void tryToElideArgumentCopy( 9842 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9843 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9844 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9845 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9846 SDValue ArgVal, bool &ArgHasUses) { 9847 // Check if this is a load from a fixed stack object. 9848 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9849 if (!LNode) 9850 return; 9851 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9852 if (!FINode) 9853 return; 9854 9855 // Check that the fixed stack object is the right size and alignment. 9856 // Look at the alignment that the user wrote on the alloca instead of looking 9857 // at the stack object. 9858 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9859 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9860 const AllocaInst *AI = ArgCopyIter->second.first; 9861 int FixedIndex = FINode->getIndex(); 9862 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9863 int OldIndex = AllocaIndex; 9864 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9865 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9866 LLVM_DEBUG( 9867 dbgs() << " argument copy elision failed due to bad fixed stack " 9868 "object size\n"); 9869 return; 9870 } 9871 Align RequiredAlignment = AI->getAlign(); 9872 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9873 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9874 "greater than stack argument alignment (" 9875 << DebugStr(RequiredAlignment) << " vs " 9876 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9877 return; 9878 } 9879 9880 // Perform the elision. Delete the old stack object and replace its only use 9881 // in the variable info map. Mark the stack object as mutable. 9882 LLVM_DEBUG({ 9883 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9884 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9885 << '\n'; 9886 }); 9887 MFI.RemoveStackObject(OldIndex); 9888 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9889 AllocaIndex = FixedIndex; 9890 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9891 Chains.push_back(ArgVal.getValue(1)); 9892 9893 // Avoid emitting code for the store implementing the copy. 9894 const StoreInst *SI = ArgCopyIter->second.second; 9895 ElidedArgCopyInstrs.insert(SI); 9896 9897 // Check for uses of the argument again so that we can avoid exporting ArgVal 9898 // if it is't used by anything other than the store. 9899 for (const Value *U : Arg.users()) { 9900 if (U != SI) { 9901 ArgHasUses = true; 9902 break; 9903 } 9904 } 9905 } 9906 9907 void SelectionDAGISel::LowerArguments(const Function &F) { 9908 SelectionDAG &DAG = SDB->DAG; 9909 SDLoc dl = SDB->getCurSDLoc(); 9910 const DataLayout &DL = DAG.getDataLayout(); 9911 SmallVector<ISD::InputArg, 16> Ins; 9912 9913 // In Naked functions we aren't going to save any registers. 9914 if (F.hasFnAttribute(Attribute::Naked)) 9915 return; 9916 9917 if (!FuncInfo->CanLowerReturn) { 9918 // Put in an sret pointer parameter before all the other parameters. 9919 SmallVector<EVT, 1> ValueVTs; 9920 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9921 F.getReturnType()->getPointerTo( 9922 DAG.getDataLayout().getAllocaAddrSpace()), 9923 ValueVTs); 9924 9925 // NOTE: Assuming that a pointer will never break down to more than one VT 9926 // or one register. 9927 ISD::ArgFlagsTy Flags; 9928 Flags.setSRet(); 9929 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9930 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9931 ISD::InputArg::NoArgIndex, 0); 9932 Ins.push_back(RetArg); 9933 } 9934 9935 // Look for stores of arguments to static allocas. Mark such arguments with a 9936 // flag to ask the target to give us the memory location of that argument if 9937 // available. 9938 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9939 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9940 ArgCopyElisionCandidates); 9941 9942 // Set up the incoming argument description vector. 9943 for (const Argument &Arg : F.args()) { 9944 unsigned ArgNo = Arg.getArgNo(); 9945 SmallVector<EVT, 4> ValueVTs; 9946 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9947 bool isArgValueUsed = !Arg.use_empty(); 9948 unsigned PartBase = 0; 9949 Type *FinalType = Arg.getType(); 9950 if (Arg.hasAttribute(Attribute::ByVal)) 9951 FinalType = Arg.getParamByValType(); 9952 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9953 FinalType, F.getCallingConv(), F.isVarArg()); 9954 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9955 Value != NumValues; ++Value) { 9956 EVT VT = ValueVTs[Value]; 9957 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9958 ISD::ArgFlagsTy Flags; 9959 9960 // Certain targets (such as MIPS), may have a different ABI alignment 9961 // for a type depending on the context. Give the target a chance to 9962 // specify the alignment it wants. 9963 const Align OriginalAlignment( 9964 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9965 9966 if (Arg.getType()->isPointerTy()) { 9967 Flags.setPointer(); 9968 Flags.setPointerAddrSpace( 9969 cast<PointerType>(Arg.getType())->getAddressSpace()); 9970 } 9971 if (Arg.hasAttribute(Attribute::ZExt)) 9972 Flags.setZExt(); 9973 if (Arg.hasAttribute(Attribute::SExt)) 9974 Flags.setSExt(); 9975 if (Arg.hasAttribute(Attribute::InReg)) { 9976 // If we are using vectorcall calling convention, a structure that is 9977 // passed InReg - is surely an HVA 9978 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9979 isa<StructType>(Arg.getType())) { 9980 // The first value of a structure is marked 9981 if (0 == Value) 9982 Flags.setHvaStart(); 9983 Flags.setHva(); 9984 } 9985 // Set InReg Flag 9986 Flags.setInReg(); 9987 } 9988 if (Arg.hasAttribute(Attribute::StructRet)) 9989 Flags.setSRet(); 9990 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9991 Flags.setSwiftSelf(); 9992 if (Arg.hasAttribute(Attribute::SwiftError)) 9993 Flags.setSwiftError(); 9994 if (Arg.hasAttribute(Attribute::ByVal)) 9995 Flags.setByVal(); 9996 if (Arg.hasAttribute(Attribute::ByRef)) 9997 Flags.setByRef(); 9998 if (Arg.hasAttribute(Attribute::InAlloca)) { 9999 Flags.setInAlloca(); 10000 // Set the byval flag for CCAssignFn callbacks that don't know about 10001 // inalloca. This way we can know how many bytes we should've allocated 10002 // and how many bytes a callee cleanup function will pop. If we port 10003 // inalloca to more targets, we'll have to add custom inalloca handling 10004 // in the various CC lowering callbacks. 10005 Flags.setByVal(); 10006 } 10007 if (Arg.hasAttribute(Attribute::Preallocated)) { 10008 Flags.setPreallocated(); 10009 // Set the byval flag for CCAssignFn callbacks that don't know about 10010 // preallocated. This way we can know how many bytes we should've 10011 // allocated and how many bytes a callee cleanup function will pop. If 10012 // we port preallocated to more targets, we'll have to add custom 10013 // preallocated handling in the various CC lowering callbacks. 10014 Flags.setByVal(); 10015 } 10016 10017 Type *ArgMemTy = nullptr; 10018 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10019 Flags.isByRef()) { 10020 if (!ArgMemTy) 10021 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10022 10023 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10024 10025 // For in-memory arguments, size and alignment should be passed from FE. 10026 // BE will guess if this info is not there but there are cases it cannot 10027 // get right. 10028 MaybeAlign MemAlign = Arg.getParamAlign(); 10029 if (!MemAlign) 10030 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10031 10032 if (Flags.isByRef()) { 10033 Flags.setByRefSize(MemSize); 10034 Flags.setByRefAlign(*MemAlign); 10035 } else { 10036 Flags.setByValSize(MemSize); 10037 Flags.setByValAlign(*MemAlign); 10038 } 10039 } 10040 10041 if (Arg.hasAttribute(Attribute::Nest)) 10042 Flags.setNest(); 10043 if (NeedsRegBlock) 10044 Flags.setInConsecutiveRegs(); 10045 Flags.setOrigAlign(OriginalAlignment); 10046 if (ArgCopyElisionCandidates.count(&Arg)) 10047 Flags.setCopyElisionCandidate(); 10048 if (Arg.hasAttribute(Attribute::Returned)) 10049 Flags.setReturned(); 10050 10051 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10052 *CurDAG->getContext(), F.getCallingConv(), VT); 10053 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10054 *CurDAG->getContext(), F.getCallingConv(), VT); 10055 for (unsigned i = 0; i != NumRegs; ++i) { 10056 // For scalable vectors, use the minimum size; individual targets 10057 // are responsible for handling scalable vector arguments and 10058 // return values. 10059 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10060 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10061 if (NumRegs > 1 && i == 0) 10062 MyFlags.Flags.setSplit(); 10063 // if it isn't first piece, alignment must be 1 10064 else if (i > 0) { 10065 MyFlags.Flags.setOrigAlign(Align(1)); 10066 if (i == NumRegs - 1) 10067 MyFlags.Flags.setSplitEnd(); 10068 } 10069 Ins.push_back(MyFlags); 10070 } 10071 if (NeedsRegBlock && Value == NumValues - 1) 10072 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10073 PartBase += VT.getStoreSize().getKnownMinSize(); 10074 } 10075 } 10076 10077 // Call the target to set up the argument values. 10078 SmallVector<SDValue, 8> InVals; 10079 SDValue NewRoot = TLI->LowerFormalArguments( 10080 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10081 10082 // Verify that the target's LowerFormalArguments behaved as expected. 10083 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10084 "LowerFormalArguments didn't return a valid chain!"); 10085 assert(InVals.size() == Ins.size() && 10086 "LowerFormalArguments didn't emit the correct number of values!"); 10087 LLVM_DEBUG({ 10088 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10089 assert(InVals[i].getNode() && 10090 "LowerFormalArguments emitted a null value!"); 10091 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10092 "LowerFormalArguments emitted a value with the wrong type!"); 10093 } 10094 }); 10095 10096 // Update the DAG with the new chain value resulting from argument lowering. 10097 DAG.setRoot(NewRoot); 10098 10099 // Set up the argument values. 10100 unsigned i = 0; 10101 if (!FuncInfo->CanLowerReturn) { 10102 // Create a virtual register for the sret pointer, and put in a copy 10103 // from the sret argument into it. 10104 SmallVector<EVT, 1> ValueVTs; 10105 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10106 F.getReturnType()->getPointerTo( 10107 DAG.getDataLayout().getAllocaAddrSpace()), 10108 ValueVTs); 10109 MVT VT = ValueVTs[0].getSimpleVT(); 10110 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10111 Optional<ISD::NodeType> AssertOp = None; 10112 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10113 nullptr, F.getCallingConv(), AssertOp); 10114 10115 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10116 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10117 Register SRetReg = 10118 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10119 FuncInfo->DemoteRegister = SRetReg; 10120 NewRoot = 10121 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10122 DAG.setRoot(NewRoot); 10123 10124 // i indexes lowered arguments. Bump it past the hidden sret argument. 10125 ++i; 10126 } 10127 10128 SmallVector<SDValue, 4> Chains; 10129 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10130 for (const Argument &Arg : F.args()) { 10131 SmallVector<SDValue, 4> ArgValues; 10132 SmallVector<EVT, 4> ValueVTs; 10133 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10134 unsigned NumValues = ValueVTs.size(); 10135 if (NumValues == 0) 10136 continue; 10137 10138 bool ArgHasUses = !Arg.use_empty(); 10139 10140 // Elide the copying store if the target loaded this argument from a 10141 // suitable fixed stack object. 10142 if (Ins[i].Flags.isCopyElisionCandidate()) { 10143 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10144 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10145 InVals[i], ArgHasUses); 10146 } 10147 10148 // If this argument is unused then remember its value. It is used to generate 10149 // debugging information. 10150 bool isSwiftErrorArg = 10151 TLI->supportSwiftError() && 10152 Arg.hasAttribute(Attribute::SwiftError); 10153 if (!ArgHasUses && !isSwiftErrorArg) { 10154 SDB->setUnusedArgValue(&Arg, InVals[i]); 10155 10156 // Also remember any frame index for use in FastISel. 10157 if (FrameIndexSDNode *FI = 10158 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10159 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10160 } 10161 10162 for (unsigned Val = 0; Val != NumValues; ++Val) { 10163 EVT VT = ValueVTs[Val]; 10164 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10165 F.getCallingConv(), VT); 10166 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10167 *CurDAG->getContext(), F.getCallingConv(), VT); 10168 10169 // Even an apparent 'unused' swifterror argument needs to be returned. So 10170 // we do generate a copy for it that can be used on return from the 10171 // function. 10172 if (ArgHasUses || isSwiftErrorArg) { 10173 Optional<ISD::NodeType> AssertOp; 10174 if (Arg.hasAttribute(Attribute::SExt)) 10175 AssertOp = ISD::AssertSext; 10176 else if (Arg.hasAttribute(Attribute::ZExt)) 10177 AssertOp = ISD::AssertZext; 10178 10179 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10180 PartVT, VT, nullptr, 10181 F.getCallingConv(), AssertOp)); 10182 } 10183 10184 i += NumParts; 10185 } 10186 10187 // We don't need to do anything else for unused arguments. 10188 if (ArgValues.empty()) 10189 continue; 10190 10191 // Note down frame index. 10192 if (FrameIndexSDNode *FI = 10193 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10194 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10195 10196 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10197 SDB->getCurSDLoc()); 10198 10199 SDB->setValue(&Arg, Res); 10200 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10201 // We want to associate the argument with the frame index, among 10202 // involved operands, that correspond to the lowest address. The 10203 // getCopyFromParts function, called earlier, is swapping the order of 10204 // the operands to BUILD_PAIR depending on endianness. The result of 10205 // that swapping is that the least significant bits of the argument will 10206 // be in the first operand of the BUILD_PAIR node, and the most 10207 // significant bits will be in the second operand. 10208 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10209 if (LoadSDNode *LNode = 10210 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10211 if (FrameIndexSDNode *FI = 10212 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10213 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10214 } 10215 10216 // Analyses past this point are naive and don't expect an assertion. 10217 if (Res.getOpcode() == ISD::AssertZext) 10218 Res = Res.getOperand(0); 10219 10220 // Update the SwiftErrorVRegDefMap. 10221 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10222 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10223 if (Register::isVirtualRegister(Reg)) 10224 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10225 Reg); 10226 } 10227 10228 // If this argument is live outside of the entry block, insert a copy from 10229 // wherever we got it to the vreg that other BB's will reference it as. 10230 if (Res.getOpcode() == ISD::CopyFromReg) { 10231 // If we can, though, try to skip creating an unnecessary vreg. 10232 // FIXME: This isn't very clean... it would be nice to make this more 10233 // general. 10234 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10235 if (Register::isVirtualRegister(Reg)) { 10236 FuncInfo->ValueMap[&Arg] = Reg; 10237 continue; 10238 } 10239 } 10240 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10241 FuncInfo->InitializeRegForValue(&Arg); 10242 SDB->CopyToExportRegsIfNeeded(&Arg); 10243 } 10244 } 10245 10246 if (!Chains.empty()) { 10247 Chains.push_back(NewRoot); 10248 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10249 } 10250 10251 DAG.setRoot(NewRoot); 10252 10253 assert(i == InVals.size() && "Argument register count mismatch!"); 10254 10255 // If any argument copy elisions occurred and we have debug info, update the 10256 // stale frame indices used in the dbg.declare variable info table. 10257 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10258 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10259 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10260 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10261 if (I != ArgCopyElisionFrameIndexMap.end()) 10262 VI.Slot = I->second; 10263 } 10264 } 10265 10266 // Finally, if the target has anything special to do, allow it to do so. 10267 emitFunctionEntryCode(); 10268 } 10269 10270 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10271 /// ensure constants are generated when needed. Remember the virtual registers 10272 /// that need to be added to the Machine PHI nodes as input. We cannot just 10273 /// directly add them, because expansion might result in multiple MBB's for one 10274 /// BB. As such, the start of the BB might correspond to a different MBB than 10275 /// the end. 10276 void 10277 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10278 const Instruction *TI = LLVMBB->getTerminator(); 10279 10280 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10281 10282 // Check PHI nodes in successors that expect a value to be available from this 10283 // block. 10284 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10285 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10286 if (!isa<PHINode>(SuccBB->begin())) continue; 10287 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10288 10289 // If this terminator has multiple identical successors (common for 10290 // switches), only handle each succ once. 10291 if (!SuccsHandled.insert(SuccMBB).second) 10292 continue; 10293 10294 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10295 10296 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10297 // nodes and Machine PHI nodes, but the incoming operands have not been 10298 // emitted yet. 10299 for (const PHINode &PN : SuccBB->phis()) { 10300 // Ignore dead phi's. 10301 if (PN.use_empty()) 10302 continue; 10303 10304 // Skip empty types 10305 if (PN.getType()->isEmptyTy()) 10306 continue; 10307 10308 unsigned Reg; 10309 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10310 10311 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10312 unsigned &RegOut = ConstantsOut[C]; 10313 if (RegOut == 0) { 10314 RegOut = FuncInfo.CreateRegs(C); 10315 CopyValueToVirtualRegister(C, RegOut); 10316 } 10317 Reg = RegOut; 10318 } else { 10319 DenseMap<const Value *, Register>::iterator I = 10320 FuncInfo.ValueMap.find(PHIOp); 10321 if (I != FuncInfo.ValueMap.end()) 10322 Reg = I->second; 10323 else { 10324 assert(isa<AllocaInst>(PHIOp) && 10325 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10326 "Didn't codegen value into a register!??"); 10327 Reg = FuncInfo.CreateRegs(PHIOp); 10328 CopyValueToVirtualRegister(PHIOp, Reg); 10329 } 10330 } 10331 10332 // Remember that this register needs to added to the machine PHI node as 10333 // the input for this MBB. 10334 SmallVector<EVT, 4> ValueVTs; 10335 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10336 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10337 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10338 EVT VT = ValueVTs[vti]; 10339 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10340 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10341 FuncInfo.PHINodesToUpdate.push_back( 10342 std::make_pair(&*MBBI++, Reg + i)); 10343 Reg += NumRegisters; 10344 } 10345 } 10346 } 10347 10348 ConstantsOut.clear(); 10349 } 10350 10351 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10352 /// is 0. 10353 MachineBasicBlock * 10354 SelectionDAGBuilder::StackProtectorDescriptor:: 10355 AddSuccessorMBB(const BasicBlock *BB, 10356 MachineBasicBlock *ParentMBB, 10357 bool IsLikely, 10358 MachineBasicBlock *SuccMBB) { 10359 // If SuccBB has not been created yet, create it. 10360 if (!SuccMBB) { 10361 MachineFunction *MF = ParentMBB->getParent(); 10362 MachineFunction::iterator BBI(ParentMBB); 10363 SuccMBB = MF->CreateMachineBasicBlock(BB); 10364 MF->insert(++BBI, SuccMBB); 10365 } 10366 // Add it as a successor of ParentMBB. 10367 ParentMBB->addSuccessor( 10368 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10369 return SuccMBB; 10370 } 10371 10372 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10373 MachineFunction::iterator I(MBB); 10374 if (++I == FuncInfo.MF->end()) 10375 return nullptr; 10376 return &*I; 10377 } 10378 10379 /// During lowering new call nodes can be created (such as memset, etc.). 10380 /// Those will become new roots of the current DAG, but complications arise 10381 /// when they are tail calls. In such cases, the call lowering will update 10382 /// the root, but the builder still needs to know that a tail call has been 10383 /// lowered in order to avoid generating an additional return. 10384 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10385 // If the node is null, we do have a tail call. 10386 if (MaybeTC.getNode() != nullptr) 10387 DAG.setRoot(MaybeTC); 10388 else 10389 HasTailCall = true; 10390 } 10391 10392 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10393 MachineBasicBlock *SwitchMBB, 10394 MachineBasicBlock *DefaultMBB) { 10395 MachineFunction *CurMF = FuncInfo.MF; 10396 MachineBasicBlock *NextMBB = nullptr; 10397 MachineFunction::iterator BBI(W.MBB); 10398 if (++BBI != FuncInfo.MF->end()) 10399 NextMBB = &*BBI; 10400 10401 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10402 10403 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10404 10405 if (Size == 2 && W.MBB == SwitchMBB) { 10406 // If any two of the cases has the same destination, and if one value 10407 // is the same as the other, but has one bit unset that the other has set, 10408 // use bit manipulation to do two compares at once. For example: 10409 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10410 // TODO: This could be extended to merge any 2 cases in switches with 3 10411 // cases. 10412 // TODO: Handle cases where W.CaseBB != SwitchBB. 10413 CaseCluster &Small = *W.FirstCluster; 10414 CaseCluster &Big = *W.LastCluster; 10415 10416 if (Small.Low == Small.High && Big.Low == Big.High && 10417 Small.MBB == Big.MBB) { 10418 const APInt &SmallValue = Small.Low->getValue(); 10419 const APInt &BigValue = Big.Low->getValue(); 10420 10421 // Check that there is only one bit different. 10422 APInt CommonBit = BigValue ^ SmallValue; 10423 if (CommonBit.isPowerOf2()) { 10424 SDValue CondLHS = getValue(Cond); 10425 EVT VT = CondLHS.getValueType(); 10426 SDLoc DL = getCurSDLoc(); 10427 10428 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10429 DAG.getConstant(CommonBit, DL, VT)); 10430 SDValue Cond = DAG.getSetCC( 10431 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10432 ISD::SETEQ); 10433 10434 // Update successor info. 10435 // Both Small and Big will jump to Small.BB, so we sum up the 10436 // probabilities. 10437 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10438 if (BPI) 10439 addSuccessorWithProb( 10440 SwitchMBB, DefaultMBB, 10441 // The default destination is the first successor in IR. 10442 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10443 else 10444 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10445 10446 // Insert the true branch. 10447 SDValue BrCond = 10448 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10449 DAG.getBasicBlock(Small.MBB)); 10450 // Insert the false branch. 10451 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10452 DAG.getBasicBlock(DefaultMBB)); 10453 10454 DAG.setRoot(BrCond); 10455 return; 10456 } 10457 } 10458 } 10459 10460 if (TM.getOptLevel() != CodeGenOpt::None) { 10461 // Here, we order cases by probability so the most likely case will be 10462 // checked first. However, two clusters can have the same probability in 10463 // which case their relative ordering is non-deterministic. So we use Low 10464 // as a tie-breaker as clusters are guaranteed to never overlap. 10465 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10466 [](const CaseCluster &a, const CaseCluster &b) { 10467 return a.Prob != b.Prob ? 10468 a.Prob > b.Prob : 10469 a.Low->getValue().slt(b.Low->getValue()); 10470 }); 10471 10472 // Rearrange the case blocks so that the last one falls through if possible 10473 // without changing the order of probabilities. 10474 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10475 --I; 10476 if (I->Prob > W.LastCluster->Prob) 10477 break; 10478 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10479 std::swap(*I, *W.LastCluster); 10480 break; 10481 } 10482 } 10483 } 10484 10485 // Compute total probability. 10486 BranchProbability DefaultProb = W.DefaultProb; 10487 BranchProbability UnhandledProbs = DefaultProb; 10488 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10489 UnhandledProbs += I->Prob; 10490 10491 MachineBasicBlock *CurMBB = W.MBB; 10492 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10493 bool FallthroughUnreachable = false; 10494 MachineBasicBlock *Fallthrough; 10495 if (I == W.LastCluster) { 10496 // For the last cluster, fall through to the default destination. 10497 Fallthrough = DefaultMBB; 10498 FallthroughUnreachable = isa<UnreachableInst>( 10499 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10500 } else { 10501 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10502 CurMF->insert(BBI, Fallthrough); 10503 // Put Cond in a virtual register to make it available from the new blocks. 10504 ExportFromCurrentBlock(Cond); 10505 } 10506 UnhandledProbs -= I->Prob; 10507 10508 switch (I->Kind) { 10509 case CC_JumpTable: { 10510 // FIXME: Optimize away range check based on pivot comparisons. 10511 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10512 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10513 10514 // The jump block hasn't been inserted yet; insert it here. 10515 MachineBasicBlock *JumpMBB = JT->MBB; 10516 CurMF->insert(BBI, JumpMBB); 10517 10518 auto JumpProb = I->Prob; 10519 auto FallthroughProb = UnhandledProbs; 10520 10521 // If the default statement is a target of the jump table, we evenly 10522 // distribute the default probability to successors of CurMBB. Also 10523 // update the probability on the edge from JumpMBB to Fallthrough. 10524 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10525 SE = JumpMBB->succ_end(); 10526 SI != SE; ++SI) { 10527 if (*SI == DefaultMBB) { 10528 JumpProb += DefaultProb / 2; 10529 FallthroughProb -= DefaultProb / 2; 10530 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10531 JumpMBB->normalizeSuccProbs(); 10532 break; 10533 } 10534 } 10535 10536 if (FallthroughUnreachable) { 10537 // Skip the range check if the fallthrough block is unreachable. 10538 JTH->OmitRangeCheck = true; 10539 } 10540 10541 if (!JTH->OmitRangeCheck) 10542 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10543 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10544 CurMBB->normalizeSuccProbs(); 10545 10546 // The jump table header will be inserted in our current block, do the 10547 // range check, and fall through to our fallthrough block. 10548 JTH->HeaderBB = CurMBB; 10549 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10550 10551 // If we're in the right place, emit the jump table header right now. 10552 if (CurMBB == SwitchMBB) { 10553 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10554 JTH->Emitted = true; 10555 } 10556 break; 10557 } 10558 case CC_BitTests: { 10559 // FIXME: Optimize away range check based on pivot comparisons. 10560 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10561 10562 // The bit test blocks haven't been inserted yet; insert them here. 10563 for (BitTestCase &BTC : BTB->Cases) 10564 CurMF->insert(BBI, BTC.ThisBB); 10565 10566 // Fill in fields of the BitTestBlock. 10567 BTB->Parent = CurMBB; 10568 BTB->Default = Fallthrough; 10569 10570 BTB->DefaultProb = UnhandledProbs; 10571 // If the cases in bit test don't form a contiguous range, we evenly 10572 // distribute the probability on the edge to Fallthrough to two 10573 // successors of CurMBB. 10574 if (!BTB->ContiguousRange) { 10575 BTB->Prob += DefaultProb / 2; 10576 BTB->DefaultProb -= DefaultProb / 2; 10577 } 10578 10579 if (FallthroughUnreachable) { 10580 // Skip the range check if the fallthrough block is unreachable. 10581 BTB->OmitRangeCheck = true; 10582 } 10583 10584 // If we're in the right place, emit the bit test header right now. 10585 if (CurMBB == SwitchMBB) { 10586 visitBitTestHeader(*BTB, SwitchMBB); 10587 BTB->Emitted = true; 10588 } 10589 break; 10590 } 10591 case CC_Range: { 10592 const Value *RHS, *LHS, *MHS; 10593 ISD::CondCode CC; 10594 if (I->Low == I->High) { 10595 // Check Cond == I->Low. 10596 CC = ISD::SETEQ; 10597 LHS = Cond; 10598 RHS=I->Low; 10599 MHS = nullptr; 10600 } else { 10601 // Check I->Low <= Cond <= I->High. 10602 CC = ISD::SETLE; 10603 LHS = I->Low; 10604 MHS = Cond; 10605 RHS = I->High; 10606 } 10607 10608 // If Fallthrough is unreachable, fold away the comparison. 10609 if (FallthroughUnreachable) 10610 CC = ISD::SETTRUE; 10611 10612 // The false probability is the sum of all unhandled cases. 10613 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10614 getCurSDLoc(), I->Prob, UnhandledProbs); 10615 10616 if (CurMBB == SwitchMBB) 10617 visitSwitchCase(CB, SwitchMBB); 10618 else 10619 SL->SwitchCases.push_back(CB); 10620 10621 break; 10622 } 10623 } 10624 CurMBB = Fallthrough; 10625 } 10626 } 10627 10628 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10629 CaseClusterIt First, 10630 CaseClusterIt Last) { 10631 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10632 if (X.Prob != CC.Prob) 10633 return X.Prob > CC.Prob; 10634 10635 // Ties are broken by comparing the case value. 10636 return X.Low->getValue().slt(CC.Low->getValue()); 10637 }); 10638 } 10639 10640 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10641 const SwitchWorkListItem &W, 10642 Value *Cond, 10643 MachineBasicBlock *SwitchMBB) { 10644 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10645 "Clusters not sorted?"); 10646 10647 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10648 10649 // Balance the tree based on branch probabilities to create a near-optimal (in 10650 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10651 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10652 CaseClusterIt LastLeft = W.FirstCluster; 10653 CaseClusterIt FirstRight = W.LastCluster; 10654 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10655 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10656 10657 // Move LastLeft and FirstRight towards each other from opposite directions to 10658 // find a partitioning of the clusters which balances the probability on both 10659 // sides. If LeftProb and RightProb are equal, alternate which side is 10660 // taken to ensure 0-probability nodes are distributed evenly. 10661 unsigned I = 0; 10662 while (LastLeft + 1 < FirstRight) { 10663 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10664 LeftProb += (++LastLeft)->Prob; 10665 else 10666 RightProb += (--FirstRight)->Prob; 10667 I++; 10668 } 10669 10670 while (true) { 10671 // Our binary search tree differs from a typical BST in that ours can have up 10672 // to three values in each leaf. The pivot selection above doesn't take that 10673 // into account, which means the tree might require more nodes and be less 10674 // efficient. We compensate for this here. 10675 10676 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10677 unsigned NumRight = W.LastCluster - FirstRight + 1; 10678 10679 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10680 // If one side has less than 3 clusters, and the other has more than 3, 10681 // consider taking a cluster from the other side. 10682 10683 if (NumLeft < NumRight) { 10684 // Consider moving the first cluster on the right to the left side. 10685 CaseCluster &CC = *FirstRight; 10686 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10687 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10688 if (LeftSideRank <= RightSideRank) { 10689 // Moving the cluster to the left does not demote it. 10690 ++LastLeft; 10691 ++FirstRight; 10692 continue; 10693 } 10694 } else { 10695 assert(NumRight < NumLeft); 10696 // Consider moving the last element on the left to the right side. 10697 CaseCluster &CC = *LastLeft; 10698 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10699 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10700 if (RightSideRank <= LeftSideRank) { 10701 // Moving the cluster to the right does not demot it. 10702 --LastLeft; 10703 --FirstRight; 10704 continue; 10705 } 10706 } 10707 } 10708 break; 10709 } 10710 10711 assert(LastLeft + 1 == FirstRight); 10712 assert(LastLeft >= W.FirstCluster); 10713 assert(FirstRight <= W.LastCluster); 10714 10715 // Use the first element on the right as pivot since we will make less-than 10716 // comparisons against it. 10717 CaseClusterIt PivotCluster = FirstRight; 10718 assert(PivotCluster > W.FirstCluster); 10719 assert(PivotCluster <= W.LastCluster); 10720 10721 CaseClusterIt FirstLeft = W.FirstCluster; 10722 CaseClusterIt LastRight = W.LastCluster; 10723 10724 const ConstantInt *Pivot = PivotCluster->Low; 10725 10726 // New blocks will be inserted immediately after the current one. 10727 MachineFunction::iterator BBI(W.MBB); 10728 ++BBI; 10729 10730 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10731 // we can branch to its destination directly if it's squeezed exactly in 10732 // between the known lower bound and Pivot - 1. 10733 MachineBasicBlock *LeftMBB; 10734 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10735 FirstLeft->Low == W.GE && 10736 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10737 LeftMBB = FirstLeft->MBB; 10738 } else { 10739 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10740 FuncInfo.MF->insert(BBI, LeftMBB); 10741 WorkList.push_back( 10742 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10743 // Put Cond in a virtual register to make it available from the new blocks. 10744 ExportFromCurrentBlock(Cond); 10745 } 10746 10747 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10748 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10749 // directly if RHS.High equals the current upper bound. 10750 MachineBasicBlock *RightMBB; 10751 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10752 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10753 RightMBB = FirstRight->MBB; 10754 } else { 10755 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10756 FuncInfo.MF->insert(BBI, RightMBB); 10757 WorkList.push_back( 10758 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10759 // Put Cond in a virtual register to make it available from the new blocks. 10760 ExportFromCurrentBlock(Cond); 10761 } 10762 10763 // Create the CaseBlock record that will be used to lower the branch. 10764 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10765 getCurSDLoc(), LeftProb, RightProb); 10766 10767 if (W.MBB == SwitchMBB) 10768 visitSwitchCase(CB, SwitchMBB); 10769 else 10770 SL->SwitchCases.push_back(CB); 10771 } 10772 10773 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10774 // from the swith statement. 10775 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10776 BranchProbability PeeledCaseProb) { 10777 if (PeeledCaseProb == BranchProbability::getOne()) 10778 return BranchProbability::getZero(); 10779 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10780 10781 uint32_t Numerator = CaseProb.getNumerator(); 10782 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10783 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10784 } 10785 10786 // Try to peel the top probability case if it exceeds the threshold. 10787 // Return current MachineBasicBlock for the switch statement if the peeling 10788 // does not occur. 10789 // If the peeling is performed, return the newly created MachineBasicBlock 10790 // for the peeled switch statement. Also update Clusters to remove the peeled 10791 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10792 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10793 const SwitchInst &SI, CaseClusterVector &Clusters, 10794 BranchProbability &PeeledCaseProb) { 10795 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10796 // Don't perform if there is only one cluster or optimizing for size. 10797 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10798 TM.getOptLevel() == CodeGenOpt::None || 10799 SwitchMBB->getParent()->getFunction().hasMinSize()) 10800 return SwitchMBB; 10801 10802 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10803 unsigned PeeledCaseIndex = 0; 10804 bool SwitchPeeled = false; 10805 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10806 CaseCluster &CC = Clusters[Index]; 10807 if (CC.Prob < TopCaseProb) 10808 continue; 10809 TopCaseProb = CC.Prob; 10810 PeeledCaseIndex = Index; 10811 SwitchPeeled = true; 10812 } 10813 if (!SwitchPeeled) 10814 return SwitchMBB; 10815 10816 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10817 << TopCaseProb << "\n"); 10818 10819 // Record the MBB for the peeled switch statement. 10820 MachineFunction::iterator BBI(SwitchMBB); 10821 ++BBI; 10822 MachineBasicBlock *PeeledSwitchMBB = 10823 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10824 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10825 10826 ExportFromCurrentBlock(SI.getCondition()); 10827 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10828 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10829 nullptr, nullptr, TopCaseProb.getCompl()}; 10830 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10831 10832 Clusters.erase(PeeledCaseIt); 10833 for (CaseCluster &CC : Clusters) { 10834 LLVM_DEBUG( 10835 dbgs() << "Scale the probablity for one cluster, before scaling: " 10836 << CC.Prob << "\n"); 10837 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10838 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10839 } 10840 PeeledCaseProb = TopCaseProb; 10841 return PeeledSwitchMBB; 10842 } 10843 10844 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10845 // Extract cases from the switch. 10846 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10847 CaseClusterVector Clusters; 10848 Clusters.reserve(SI.getNumCases()); 10849 for (auto I : SI.cases()) { 10850 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10851 const ConstantInt *CaseVal = I.getCaseValue(); 10852 BranchProbability Prob = 10853 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10854 : BranchProbability(1, SI.getNumCases() + 1); 10855 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10856 } 10857 10858 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10859 10860 // Cluster adjacent cases with the same destination. We do this at all 10861 // optimization levels because it's cheap to do and will make codegen faster 10862 // if there are many clusters. 10863 sortAndRangeify(Clusters); 10864 10865 // The branch probablity of the peeled case. 10866 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10867 MachineBasicBlock *PeeledSwitchMBB = 10868 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10869 10870 // If there is only the default destination, jump there directly. 10871 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10872 if (Clusters.empty()) { 10873 assert(PeeledSwitchMBB == SwitchMBB); 10874 SwitchMBB->addSuccessor(DefaultMBB); 10875 if (DefaultMBB != NextBlock(SwitchMBB)) { 10876 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10877 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10878 } 10879 return; 10880 } 10881 10882 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10883 SL->findBitTestClusters(Clusters, &SI); 10884 10885 LLVM_DEBUG({ 10886 dbgs() << "Case clusters: "; 10887 for (const CaseCluster &C : Clusters) { 10888 if (C.Kind == CC_JumpTable) 10889 dbgs() << "JT:"; 10890 if (C.Kind == CC_BitTests) 10891 dbgs() << "BT:"; 10892 10893 C.Low->getValue().print(dbgs(), true); 10894 if (C.Low != C.High) { 10895 dbgs() << '-'; 10896 C.High->getValue().print(dbgs(), true); 10897 } 10898 dbgs() << ' '; 10899 } 10900 dbgs() << '\n'; 10901 }); 10902 10903 assert(!Clusters.empty()); 10904 SwitchWorkList WorkList; 10905 CaseClusterIt First = Clusters.begin(); 10906 CaseClusterIt Last = Clusters.end() - 1; 10907 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10908 // Scale the branchprobability for DefaultMBB if the peel occurs and 10909 // DefaultMBB is not replaced. 10910 if (PeeledCaseProb != BranchProbability::getZero() && 10911 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10912 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10913 WorkList.push_back( 10914 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10915 10916 while (!WorkList.empty()) { 10917 SwitchWorkListItem W = WorkList.pop_back_val(); 10918 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10919 10920 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10921 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10922 // For optimized builds, lower large range as a balanced binary tree. 10923 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10924 continue; 10925 } 10926 10927 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10928 } 10929 } 10930 10931 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 10932 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10933 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10934 10935 SDLoc DL = getCurSDLoc(); 10936 SDValue V = getValue(I.getOperand(0)); 10937 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 10938 10939 if (VT.isScalableVector()) { 10940 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 10941 return; 10942 } 10943 10944 // Use VECTOR_SHUFFLE for the fixed-length vector 10945 // to maintain existing behavior. 10946 SmallVector<int, 8> Mask; 10947 unsigned NumElts = VT.getVectorMinNumElements(); 10948 for (unsigned i = 0; i != NumElts; ++i) 10949 Mask.push_back(NumElts - 1 - i); 10950 10951 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 10952 } 10953 10954 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10955 SmallVector<EVT, 4> ValueVTs; 10956 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10957 ValueVTs); 10958 unsigned NumValues = ValueVTs.size(); 10959 if (NumValues == 0) return; 10960 10961 SmallVector<SDValue, 4> Values(NumValues); 10962 SDValue Op = getValue(I.getOperand(0)); 10963 10964 for (unsigned i = 0; i != NumValues; ++i) 10965 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10966 SDValue(Op.getNode(), Op.getResNo() + i)); 10967 10968 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10969 DAG.getVTList(ValueVTs), Values)); 10970 } 10971 10972 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 10973 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10974 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10975 10976 SDLoc DL = getCurSDLoc(); 10977 SDValue V1 = getValue(I.getOperand(0)); 10978 SDValue V2 = getValue(I.getOperand(1)); 10979 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 10980 10981 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 10982 if (VT.isScalableVector()) { 10983 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 10984 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 10985 DAG.getConstant(Imm, DL, IdxVT))); 10986 return; 10987 } 10988 10989 unsigned NumElts = VT.getVectorNumElements(); 10990 10991 if ((-Imm > NumElts) || (Imm >= NumElts)) { 10992 // Result is undefined if immediate is out-of-bounds. 10993 setValue(&I, DAG.getUNDEF(VT)); 10994 return; 10995 } 10996 10997 uint64_t Idx = (NumElts + Imm) % NumElts; 10998 10999 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11000 SmallVector<int, 8> Mask; 11001 for (unsigned i = 0; i < NumElts; ++i) 11002 Mask.push_back(Idx + i); 11003 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11004 } 11005