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/ArrayRef.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Triple.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Analysis/AliasAnalysis.h" 30 #include "llvm/Analysis/BlockFrequencyInfo.h" 31 #include "llvm/Analysis/BranchProbabilityInfo.h" 32 #include "llvm/Analysis/ConstantFolding.h" 33 #include "llvm/Analysis/EHPersonalities.h" 34 #include "llvm/Analysis/Loads.h" 35 #include "llvm/Analysis/MemoryLocation.h" 36 #include "llvm/Analysis/ProfileSummaryInfo.h" 37 #include "llvm/Analysis/TargetLibraryInfo.h" 38 #include "llvm/Analysis/ValueTracking.h" 39 #include "llvm/Analysis/VectorUtils.h" 40 #include "llvm/CodeGen/Analysis.h" 41 #include "llvm/CodeGen/FunctionLoweringInfo.h" 42 #include "llvm/CodeGen/GCMetadata.h" 43 #include "llvm/CodeGen/ISDOpcodes.h" 44 #include "llvm/CodeGen/MachineBasicBlock.h" 45 #include "llvm/CodeGen/MachineFrameInfo.h" 46 #include "llvm/CodeGen/MachineFunction.h" 47 #include "llvm/CodeGen/MachineInstr.h" 48 #include "llvm/CodeGen/MachineInstrBuilder.h" 49 #include "llvm/CodeGen/MachineJumpTableInfo.h" 50 #include "llvm/CodeGen/MachineMemOperand.h" 51 #include "llvm/CodeGen/MachineModuleInfo.h" 52 #include "llvm/CodeGen/MachineOperand.h" 53 #include "llvm/CodeGen/MachineRegisterInfo.h" 54 #include "llvm/CodeGen/RuntimeLibcalls.h" 55 #include "llvm/CodeGen/SelectionDAG.h" 56 #include "llvm/CodeGen/SelectionDAGNodes.h" 57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 58 #include "llvm/CodeGen/StackMaps.h" 59 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 60 #include "llvm/CodeGen/TargetFrameLowering.h" 61 #include "llvm/CodeGen/TargetInstrInfo.h" 62 #include "llvm/CodeGen/TargetLowering.h" 63 #include "llvm/CodeGen/TargetOpcodes.h" 64 #include "llvm/CodeGen/TargetRegisterInfo.h" 65 #include "llvm/CodeGen/TargetSubtargetInfo.h" 66 #include "llvm/CodeGen/ValueTypes.h" 67 #include "llvm/CodeGen/WinEHFuncInfo.h" 68 #include "llvm/IR/Argument.h" 69 #include "llvm/IR/Attributes.h" 70 #include "llvm/IR/BasicBlock.h" 71 #include "llvm/IR/CFG.h" 72 #include "llvm/IR/CallSite.h" 73 #include "llvm/IR/CallingConv.h" 74 #include "llvm/IR/Constant.h" 75 #include "llvm/IR/ConstantRange.h" 76 #include "llvm/IR/Constants.h" 77 #include "llvm/IR/DataLayout.h" 78 #include "llvm/IR/DebugInfoMetadata.h" 79 #include "llvm/IR/DebugLoc.h" 80 #include "llvm/IR/DerivedTypes.h" 81 #include "llvm/IR/Function.h" 82 #include "llvm/IR/GetElementPtrTypeIterator.h" 83 #include "llvm/IR/InlineAsm.h" 84 #include "llvm/IR/InstrTypes.h" 85 #include "llvm/IR/Instruction.h" 86 #include "llvm/IR/Instructions.h" 87 #include "llvm/IR/IntrinsicInst.h" 88 #include "llvm/IR/Intrinsics.h" 89 #include "llvm/IR/IntrinsicsAArch64.h" 90 #include "llvm/IR/IntrinsicsWebAssembly.h" 91 #include "llvm/IR/LLVMContext.h" 92 #include "llvm/IR/Metadata.h" 93 #include "llvm/IR/Module.h" 94 #include "llvm/IR/Operator.h" 95 #include "llvm/IR/PatternMatch.h" 96 #include "llvm/IR/Statepoint.h" 97 #include "llvm/IR/Type.h" 98 #include "llvm/IR/User.h" 99 #include "llvm/IR/Value.h" 100 #include "llvm/MC/MCContext.h" 101 #include "llvm/MC/MCSymbol.h" 102 #include "llvm/Support/AtomicOrdering.h" 103 #include "llvm/Support/BranchProbability.h" 104 #include "llvm/Support/Casting.h" 105 #include "llvm/Support/CodeGen.h" 106 #include "llvm/Support/CommandLine.h" 107 #include "llvm/Support/Compiler.h" 108 #include "llvm/Support/Debug.h" 109 #include "llvm/Support/ErrorHandling.h" 110 #include "llvm/Support/MachineValueType.h" 111 #include "llvm/Support/MathExtras.h" 112 #include "llvm/Support/raw_ostream.h" 113 #include "llvm/Target/TargetIntrinsicInfo.h" 114 #include "llvm/Target/TargetMachine.h" 115 #include "llvm/Target/TargetOptions.h" 116 #include "llvm/Transforms/Utils/Local.h" 117 #include <algorithm> 118 #include <cassert> 119 #include <cstddef> 120 #include <cstdint> 121 #include <cstring> 122 #include <iterator> 123 #include <limits> 124 #include <numeric> 125 #include <tuple> 126 #include <utility> 127 #include <vector> 128 129 using namespace llvm; 130 using namespace PatternMatch; 131 using namespace SwitchCG; 132 133 #define DEBUG_TYPE "isel" 134 135 /// LimitFloatPrecision - Generate low-precision inline sequences for 136 /// some float libcalls (6, 8 or 12 bits). 137 static unsigned LimitFloatPrecision; 138 139 static cl::opt<unsigned, true> 140 LimitFPPrecision("limit-float-precision", 141 cl::desc("Generate low-precision inline sequences " 142 "for some float libcalls"), 143 cl::location(LimitFloatPrecision), cl::Hidden, 144 cl::init(0)); 145 146 static cl::opt<unsigned> SwitchPeelThreshold( 147 "switch-peel-threshold", cl::Hidden, cl::init(66), 148 cl::desc("Set the case probability threshold for peeling the case from a " 149 "switch statement. A value greater than 100 will void this " 150 "optimization")); 151 152 // Limit the width of DAG chains. This is important in general to prevent 153 // DAG-based analysis from blowing up. For example, alias analysis and 154 // load clustering may not complete in reasonable time. It is difficult to 155 // recognize and avoid this situation within each individual analysis, and 156 // future analyses are likely to have the same behavior. Limiting DAG width is 157 // the safe approach and will be especially important with global DAGs. 158 // 159 // MaxParallelChains default is arbitrarily high to avoid affecting 160 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 161 // sequence over this should have been converted to llvm.memcpy by the 162 // frontend. It is easy to induce this behavior with .ll code such as: 163 // %buffer = alloca [4096 x i8] 164 // %data = load [4096 x i8]* %argPtr 165 // store [4096 x i8] %data, [4096 x i8]* %buffer 166 static const unsigned MaxParallelChains = 64; 167 168 // Return the calling convention if the Value passed requires ABI mangling as it 169 // is a parameter to a function or a return value from a function which is not 170 // an intrinsic. 171 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 172 if (auto *R = dyn_cast<ReturnInst>(V)) 173 return R->getParent()->getParent()->getCallingConv(); 174 175 if (auto *CI = dyn_cast<CallInst>(V)) { 176 const bool IsInlineAsm = CI->isInlineAsm(); 177 const bool IsIndirectFunctionCall = 178 !IsInlineAsm && !CI->getCalledFunction(); 179 180 // It is possible that the call instruction is an inline asm statement or an 181 // indirect function call in which case the return value of 182 // getCalledFunction() would be nullptr. 183 const bool IsInstrinsicCall = 184 !IsInlineAsm && !IsIndirectFunctionCall && 185 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 186 187 if (!IsInlineAsm && !IsInstrinsicCall) 188 return CI->getCallingConv(); 189 } 190 191 return None; 192 } 193 194 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 195 const SDValue *Parts, unsigned NumParts, 196 MVT PartVT, EVT ValueVT, const Value *V, 197 Optional<CallingConv::ID> CC); 198 199 /// getCopyFromParts - Create a value that contains the specified legal parts 200 /// combined into the value they represent. If the parts combine to a type 201 /// larger than ValueVT then AssertOp can be used to specify whether the extra 202 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 203 /// (ISD::AssertSext). 204 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 205 const SDValue *Parts, unsigned NumParts, 206 MVT PartVT, EVT ValueVT, const Value *V, 207 Optional<CallingConv::ID> CC = None, 208 Optional<ISD::NodeType> AssertOp = None) { 209 if (ValueVT.isVector()) 210 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 211 CC); 212 213 assert(NumParts > 0 && "No parts to assemble!"); 214 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 215 SDValue Val = Parts[0]; 216 217 if (NumParts > 1) { 218 // Assemble the value from multiple parts. 219 if (ValueVT.isInteger()) { 220 unsigned PartBits = PartVT.getSizeInBits(); 221 unsigned ValueBits = ValueVT.getSizeInBits(); 222 223 // Assemble the power of 2 part. 224 unsigned RoundParts = 225 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 226 unsigned RoundBits = PartBits * RoundParts; 227 EVT RoundVT = RoundBits == ValueBits ? 228 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 229 SDValue Lo, Hi; 230 231 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 232 233 if (RoundParts > 2) { 234 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 235 PartVT, HalfVT, V); 236 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 237 RoundParts / 2, PartVT, HalfVT, V); 238 } else { 239 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 240 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 241 } 242 243 if (DAG.getDataLayout().isBigEndian()) 244 std::swap(Lo, Hi); 245 246 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 247 248 if (RoundParts < NumParts) { 249 // Assemble the trailing non-power-of-2 part. 250 unsigned OddParts = NumParts - RoundParts; 251 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 252 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 253 OddVT, V, CC); 254 255 // Combine the round and odd parts. 256 Lo = Val; 257 if (DAG.getDataLayout().isBigEndian()) 258 std::swap(Lo, Hi); 259 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 260 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 261 Hi = 262 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 263 DAG.getConstant(Lo.getValueSizeInBits(), DL, 264 TLI.getPointerTy(DAG.getDataLayout()))); 265 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 266 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 267 } 268 } else if (PartVT.isFloatingPoint()) { 269 // FP split into multiple FP parts (for ppcf128) 270 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 271 "Unexpected split"); 272 SDValue Lo, Hi; 273 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 274 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 275 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 276 std::swap(Lo, Hi); 277 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 278 } else { 279 // FP split into integer parts (soft fp) 280 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 281 !PartVT.isVector() && "Unexpected split"); 282 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 283 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 284 } 285 } 286 287 // There is now one part, held in Val. Correct it to match ValueVT. 288 // PartEVT is the type of the register class that holds the value. 289 // ValueVT is the type of the inline asm operation. 290 EVT PartEVT = Val.getValueType(); 291 292 if (PartEVT == ValueVT) 293 return Val; 294 295 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 296 ValueVT.bitsLT(PartEVT)) { 297 // For an FP value in an integer part, we need to truncate to the right 298 // width first. 299 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 300 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 301 } 302 303 // Handle types that have the same size. 304 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 305 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 306 307 // Handle types with different sizes. 308 if (PartEVT.isInteger() && ValueVT.isInteger()) { 309 if (ValueVT.bitsLT(PartEVT)) { 310 // For a truncate, see if we have any information to 311 // indicate whether the truncated bits will always be 312 // zero or sign-extension. 313 if (AssertOp.hasValue()) 314 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 315 DAG.getValueType(ValueVT)); 316 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 317 } 318 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 319 } 320 321 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 322 // FP_ROUND's are always exact here. 323 if (ValueVT.bitsLT(Val.getValueType())) 324 return DAG.getNode( 325 ISD::FP_ROUND, DL, ValueVT, Val, 326 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 327 328 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 329 } 330 331 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 332 // then truncating. 333 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 334 ValueVT.bitsLT(PartEVT)) { 335 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 336 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 337 } 338 339 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 340 } 341 342 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 343 const Twine &ErrMsg) { 344 const Instruction *I = dyn_cast_or_null<Instruction>(V); 345 if (!V) 346 return Ctx.emitError(ErrMsg); 347 348 const char *AsmError = ", possible invalid constraint for vector type"; 349 if (const CallInst *CI = dyn_cast<CallInst>(I)) 350 if (isa<InlineAsm>(CI->getCalledValue())) 351 return Ctx.emitError(I, ErrMsg + AsmError); 352 353 return Ctx.emitError(I, ErrMsg); 354 } 355 356 /// getCopyFromPartsVector - Create a value that contains the specified legal 357 /// parts combined into the value they represent. If the parts combine to a 358 /// type larger than ValueVT then AssertOp can be used to specify whether the 359 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 360 /// ValueVT (ISD::AssertSext). 361 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 362 const SDValue *Parts, unsigned NumParts, 363 MVT PartVT, EVT ValueVT, const Value *V, 364 Optional<CallingConv::ID> CallConv) { 365 assert(ValueVT.isVector() && "Not a vector value"); 366 assert(NumParts > 0 && "No parts to assemble!"); 367 const bool IsABIRegCopy = CallConv.hasValue(); 368 369 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 370 SDValue Val = Parts[0]; 371 372 // Handle a multi-element vector. 373 if (NumParts > 1) { 374 EVT IntermediateVT; 375 MVT RegisterVT; 376 unsigned NumIntermediates; 377 unsigned NumRegs; 378 379 if (IsABIRegCopy) { 380 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 381 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 382 NumIntermediates, RegisterVT); 383 } else { 384 NumRegs = 385 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 386 NumIntermediates, RegisterVT); 387 } 388 389 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 390 NumParts = NumRegs; // Silence a compiler warning. 391 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 392 assert(RegisterVT.getSizeInBits() == 393 Parts[0].getSimpleValueType().getSizeInBits() && 394 "Part type sizes don't match!"); 395 396 // Assemble the parts into intermediate operands. 397 SmallVector<SDValue, 8> Ops(NumIntermediates); 398 if (NumIntermediates == NumParts) { 399 // If the register was not expanded, truncate or copy the value, 400 // as appropriate. 401 for (unsigned i = 0; i != NumParts; ++i) 402 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 403 PartVT, IntermediateVT, V); 404 } else if (NumParts > 0) { 405 // If the intermediate type was expanded, build the intermediate 406 // operands from the parts. 407 assert(NumParts % NumIntermediates == 0 && 408 "Must expand into a divisible number of parts!"); 409 unsigned Factor = NumParts / NumIntermediates; 410 for (unsigned i = 0; i != NumIntermediates; ++i) 411 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 412 PartVT, IntermediateVT, V); 413 } 414 415 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 416 // intermediate operands. 417 EVT BuiltVectorTy = 418 IntermediateVT.isVector() 419 ? EVT::getVectorVT( 420 *DAG.getContext(), IntermediateVT.getScalarType(), 421 IntermediateVT.getVectorElementCount() * NumParts) 422 : EVT::getVectorVT(*DAG.getContext(), 423 IntermediateVT.getScalarType(), 424 NumIntermediates); 425 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 426 : ISD::BUILD_VECTOR, 427 DL, BuiltVectorTy, Ops); 428 } 429 430 // There is now one part, held in Val. Correct it to match ValueVT. 431 EVT PartEVT = Val.getValueType(); 432 433 if (PartEVT == ValueVT) 434 return Val; 435 436 if (PartEVT.isVector()) { 437 // If the element type of the source/dest vectors are the same, but the 438 // parts vector has more elements than the value vector, then we have a 439 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 440 // elements we want. 441 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 442 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 443 "Cannot narrow, it would be a lossy transformation"); 444 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 445 DAG.getVectorIdxConstant(0, DL)); 446 } 447 448 // Vector/Vector bitcast. 449 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 450 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 451 452 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 453 "Cannot handle this kind of promotion"); 454 // Promoted vector extract 455 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 456 457 } 458 459 // Trivial bitcast if the types are the same size and the destination 460 // vector type is legal. 461 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 462 TLI.isTypeLegal(ValueVT)) 463 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 464 465 if (ValueVT.getVectorNumElements() != 1) { 466 // Certain ABIs require that vectors are passed as integers. For vectors 467 // are the same size, this is an obvious bitcast. 468 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 469 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 470 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 471 // Bitcast Val back the original type and extract the corresponding 472 // vector we want. 473 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 474 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 475 ValueVT.getVectorElementType(), Elts); 476 Val = DAG.getBitcast(WiderVecType, Val); 477 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 478 DAG.getVectorIdxConstant(0, DL)); 479 } 480 481 diagnosePossiblyInvalidConstraint( 482 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 483 return DAG.getUNDEF(ValueVT); 484 } 485 486 // Handle cases such as i8 -> <1 x i1> 487 EVT ValueSVT = ValueVT.getVectorElementType(); 488 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 489 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 490 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 491 else 492 Val = ValueVT.isFloatingPoint() 493 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 494 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 495 } 496 497 return DAG.getBuildVector(ValueVT, DL, Val); 498 } 499 500 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 501 SDValue Val, SDValue *Parts, unsigned NumParts, 502 MVT PartVT, const Value *V, 503 Optional<CallingConv::ID> CallConv); 504 505 /// getCopyToParts - Create a series of nodes that contain the specified value 506 /// split into legal parts. If the parts contain more bits than Val, then, for 507 /// integers, ExtendKind can be used to specify how to generate the extra bits. 508 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 509 SDValue *Parts, unsigned NumParts, MVT PartVT, 510 const Value *V, 511 Optional<CallingConv::ID> CallConv = None, 512 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 513 EVT ValueVT = Val.getValueType(); 514 515 // Handle the vector case separately. 516 if (ValueVT.isVector()) 517 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 518 CallConv); 519 520 unsigned PartBits = PartVT.getSizeInBits(); 521 unsigned OrigNumParts = NumParts; 522 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 523 "Copying to an illegal type!"); 524 525 if (NumParts == 0) 526 return; 527 528 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 529 EVT PartEVT = PartVT; 530 if (PartEVT == ValueVT) { 531 assert(NumParts == 1 && "No-op copy with multiple parts!"); 532 Parts[0] = Val; 533 return; 534 } 535 536 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 537 // If the parts cover more bits than the value has, promote the value. 538 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 539 assert(NumParts == 1 && "Do not know what to promote to!"); 540 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 541 } else { 542 if (ValueVT.isFloatingPoint()) { 543 // FP values need to be bitcast, then extended if they are being put 544 // into a larger container. 545 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 546 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 547 } 548 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 549 ValueVT.isInteger() && 550 "Unknown mismatch!"); 551 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 552 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 553 if (PartVT == MVT::x86mmx) 554 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 555 } 556 } else if (PartBits == ValueVT.getSizeInBits()) { 557 // Different types of the same size. 558 assert(NumParts == 1 && PartEVT != ValueVT); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 561 // If the parts cover less bits than value has, truncate the value. 562 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 563 ValueVT.isInteger() && 564 "Unknown mismatch!"); 565 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 566 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 567 if (PartVT == MVT::x86mmx) 568 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 569 } 570 571 // The value may have changed - recompute ValueVT. 572 ValueVT = Val.getValueType(); 573 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 574 "Failed to tile the value with PartVT!"); 575 576 if (NumParts == 1) { 577 if (PartEVT != ValueVT) { 578 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 579 "scalar-to-vector conversion failed"); 580 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 581 } 582 583 Parts[0] = Val; 584 return; 585 } 586 587 // Expand the value into multiple parts. 588 if (NumParts & (NumParts - 1)) { 589 // The number of parts is not a power of 2. Split off and copy the tail. 590 assert(PartVT.isInteger() && ValueVT.isInteger() && 591 "Do not know what to expand to!"); 592 unsigned RoundParts = 1 << Log2_32(NumParts); 593 unsigned RoundBits = RoundParts * PartBits; 594 unsigned OddParts = NumParts - RoundParts; 595 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 596 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 597 598 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 599 CallConv); 600 601 if (DAG.getDataLayout().isBigEndian()) 602 // The odd parts were reversed by getCopyToParts - unreverse them. 603 std::reverse(Parts + RoundParts, Parts + NumParts); 604 605 NumParts = RoundParts; 606 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 607 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 608 } 609 610 // The number of parts is a power of 2. Repeatedly bisect the value using 611 // EXTRACT_ELEMENT. 612 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 613 EVT::getIntegerVT(*DAG.getContext(), 614 ValueVT.getSizeInBits()), 615 Val); 616 617 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 618 for (unsigned i = 0; i < NumParts; i += StepSize) { 619 unsigned ThisBits = StepSize * PartBits / 2; 620 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 621 SDValue &Part0 = Parts[i]; 622 SDValue &Part1 = Parts[i+StepSize/2]; 623 624 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 625 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 626 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 627 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 628 629 if (ThisBits == PartBits && ThisVT != PartVT) { 630 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 631 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 632 } 633 } 634 } 635 636 if (DAG.getDataLayout().isBigEndian()) 637 std::reverse(Parts, Parts + OrigNumParts); 638 } 639 640 static SDValue widenVectorToPartType(SelectionDAG &DAG, 641 SDValue Val, const SDLoc &DL, EVT PartVT) { 642 if (!PartVT.isVector()) 643 return SDValue(); 644 645 EVT ValueVT = Val.getValueType(); 646 unsigned PartNumElts = PartVT.getVectorNumElements(); 647 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 648 if (PartNumElts > ValueNumElts && 649 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 650 EVT ElementVT = PartVT.getVectorElementType(); 651 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 652 // undef elements. 653 SmallVector<SDValue, 16> Ops; 654 DAG.ExtractVectorElements(Val, Ops); 655 SDValue EltUndef = DAG.getUNDEF(ElementVT); 656 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 657 Ops.push_back(EltUndef); 658 659 // FIXME: Use CONCAT for 2x -> 4x. 660 return DAG.getBuildVector(PartVT, DL, Ops); 661 } 662 663 return SDValue(); 664 } 665 666 /// getCopyToPartsVector - Create a series of nodes that contain the specified 667 /// value split into legal parts. 668 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 669 SDValue Val, SDValue *Parts, unsigned NumParts, 670 MVT PartVT, const Value *V, 671 Optional<CallingConv::ID> CallConv) { 672 EVT ValueVT = Val.getValueType(); 673 assert(ValueVT.isVector() && "Not a vector"); 674 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 675 const bool IsABIRegCopy = CallConv.hasValue(); 676 677 if (NumParts == 1) { 678 EVT PartEVT = PartVT; 679 if (PartEVT == ValueVT) { 680 // Nothing to do. 681 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 682 // Bitconvert vector->vector case. 683 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 684 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 685 Val = Widened; 686 } else if (PartVT.isVector() && 687 PartEVT.getVectorElementType().bitsGE( 688 ValueVT.getVectorElementType()) && 689 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 690 691 // Promoted vector extract 692 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 693 } else { 694 if (ValueVT.getVectorNumElements() == 1) { 695 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 696 DAG.getVectorIdxConstant(0, DL)); 697 } else { 698 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 699 "lossy conversion of vector to scalar type"); 700 EVT IntermediateType = 701 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 702 Val = DAG.getBitcast(IntermediateType, Val); 703 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 704 } 705 } 706 707 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 708 Parts[0] = Val; 709 return; 710 } 711 712 // Handle a multi-element vector. 713 EVT IntermediateVT; 714 MVT RegisterVT; 715 unsigned NumIntermediates; 716 unsigned NumRegs; 717 if (IsABIRegCopy) { 718 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 719 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 720 NumIntermediates, RegisterVT); 721 } else { 722 NumRegs = 723 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 724 NumIntermediates, RegisterVT); 725 } 726 727 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 728 NumParts = NumRegs; // Silence a compiler warning. 729 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 730 731 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 732 IntermediateVT.getVectorNumElements() : 1; 733 734 // Convert the vector to the appropriate type if necessary. 735 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 736 737 EVT BuiltVectorTy = EVT::getVectorVT( 738 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 739 if (ValueVT != BuiltVectorTy) { 740 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 741 Val = Widened; 742 743 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 744 } 745 746 // Split the vector into intermediate operands. 747 SmallVector<SDValue, 8> Ops(NumIntermediates); 748 for (unsigned i = 0; i != NumIntermediates; ++i) { 749 if (IntermediateVT.isVector()) { 750 Ops[i] = 751 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 752 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 753 } else { 754 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 755 DAG.getVectorIdxConstant(i, DL)); 756 } 757 } 758 759 // Split the intermediate operands into legal parts. 760 if (NumParts == NumIntermediates) { 761 // If the register was not expanded, promote or copy the value, 762 // as appropriate. 763 for (unsigned i = 0; i != NumParts; ++i) 764 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 765 } else if (NumParts > 0) { 766 // If the intermediate type was expanded, split each the value into 767 // legal parts. 768 assert(NumIntermediates != 0 && "division by zero"); 769 assert(NumParts % NumIntermediates == 0 && 770 "Must expand into a divisible number of parts!"); 771 unsigned Factor = NumParts / NumIntermediates; 772 for (unsigned i = 0; i != NumIntermediates; ++i) 773 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 774 CallConv); 775 } 776 } 777 778 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 779 EVT valuevt, Optional<CallingConv::ID> CC) 780 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 781 RegCount(1, regs.size()), CallConv(CC) {} 782 783 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 784 const DataLayout &DL, unsigned Reg, Type *Ty, 785 Optional<CallingConv::ID> CC) { 786 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 787 788 CallConv = CC; 789 790 for (EVT ValueVT : ValueVTs) { 791 unsigned NumRegs = 792 isABIMangled() 793 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 794 : TLI.getNumRegisters(Context, ValueVT); 795 MVT RegisterVT = 796 isABIMangled() 797 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 798 : TLI.getRegisterType(Context, ValueVT); 799 for (unsigned i = 0; i != NumRegs; ++i) 800 Regs.push_back(Reg + i); 801 RegVTs.push_back(RegisterVT); 802 RegCount.push_back(NumRegs); 803 Reg += NumRegs; 804 } 805 } 806 807 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 808 FunctionLoweringInfo &FuncInfo, 809 const SDLoc &dl, SDValue &Chain, 810 SDValue *Flag, const Value *V) const { 811 // A Value with type {} or [0 x %t] needs no registers. 812 if (ValueVTs.empty()) 813 return SDValue(); 814 815 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 816 817 // Assemble the legal parts into the final values. 818 SmallVector<SDValue, 4> Values(ValueVTs.size()); 819 SmallVector<SDValue, 8> Parts; 820 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 821 // Copy the legal parts from the registers. 822 EVT ValueVT = ValueVTs[Value]; 823 unsigned NumRegs = RegCount[Value]; 824 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 825 *DAG.getContext(), 826 CallConv.getValue(), RegVTs[Value]) 827 : RegVTs[Value]; 828 829 Parts.resize(NumRegs); 830 for (unsigned i = 0; i != NumRegs; ++i) { 831 SDValue P; 832 if (!Flag) { 833 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 834 } else { 835 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 836 *Flag = P.getValue(2); 837 } 838 839 Chain = P.getValue(1); 840 Parts[i] = P; 841 842 // If the source register was virtual and if we know something about it, 843 // add an assert node. 844 if (!Register::isVirtualRegister(Regs[Part + i]) || 845 !RegisterVT.isInteger()) 846 continue; 847 848 const FunctionLoweringInfo::LiveOutInfo *LOI = 849 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 850 if (!LOI) 851 continue; 852 853 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 854 unsigned NumSignBits = LOI->NumSignBits; 855 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 856 857 if (NumZeroBits == RegSize) { 858 // The current value is a zero. 859 // Explicitly express that as it would be easier for 860 // optimizations to kick in. 861 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 862 continue; 863 } 864 865 // FIXME: We capture more information than the dag can represent. For 866 // now, just use the tightest assertzext/assertsext possible. 867 bool isSExt; 868 EVT FromVT(MVT::Other); 869 if (NumZeroBits) { 870 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 871 isSExt = false; 872 } else if (NumSignBits > 1) { 873 FromVT = 874 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 875 isSExt = true; 876 } else { 877 continue; 878 } 879 // Add an assertion node. 880 assert(FromVT != MVT::Other); 881 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 882 RegisterVT, P, DAG.getValueType(FromVT)); 883 } 884 885 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 886 RegisterVT, ValueVT, V, CallConv); 887 Part += NumRegs; 888 Parts.clear(); 889 } 890 891 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 892 } 893 894 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 895 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 896 const Value *V, 897 ISD::NodeType PreferredExtendType) const { 898 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 899 ISD::NodeType ExtendKind = PreferredExtendType; 900 901 // Get the list of the values's legal parts. 902 unsigned NumRegs = Regs.size(); 903 SmallVector<SDValue, 8> Parts(NumRegs); 904 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 905 unsigned NumParts = RegCount[Value]; 906 907 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 908 *DAG.getContext(), 909 CallConv.getValue(), RegVTs[Value]) 910 : RegVTs[Value]; 911 912 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 913 ExtendKind = ISD::ZERO_EXTEND; 914 915 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 916 NumParts, RegisterVT, V, CallConv, ExtendKind); 917 Part += NumParts; 918 } 919 920 // Copy the parts into the registers. 921 SmallVector<SDValue, 8> Chains(NumRegs); 922 for (unsigned i = 0; i != NumRegs; ++i) { 923 SDValue Part; 924 if (!Flag) { 925 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 926 } else { 927 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 928 *Flag = Part.getValue(1); 929 } 930 931 Chains[i] = Part.getValue(0); 932 } 933 934 if (NumRegs == 1 || Flag) 935 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 936 // flagged to it. That is the CopyToReg nodes and the user are considered 937 // a single scheduling unit. If we create a TokenFactor and return it as 938 // chain, then the TokenFactor is both a predecessor (operand) of the 939 // user as well as a successor (the TF operands are flagged to the user). 940 // c1, f1 = CopyToReg 941 // c2, f2 = CopyToReg 942 // c3 = TokenFactor c1, c2 943 // ... 944 // = op c3, ..., f2 945 Chain = Chains[NumRegs-1]; 946 else 947 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 948 } 949 950 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 951 unsigned MatchingIdx, const SDLoc &dl, 952 SelectionDAG &DAG, 953 std::vector<SDValue> &Ops) const { 954 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 955 956 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 957 if (HasMatching) 958 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 959 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 960 // Put the register class of the virtual registers in the flag word. That 961 // way, later passes can recompute register class constraints for inline 962 // assembly as well as normal instructions. 963 // Don't do this for tied operands that can use the regclass information 964 // from the def. 965 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 966 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 967 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 968 } 969 970 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 971 Ops.push_back(Res); 972 973 if (Code == InlineAsm::Kind_Clobber) { 974 // Clobbers should always have a 1:1 mapping with registers, and may 975 // reference registers that have illegal (e.g. vector) types. Hence, we 976 // shouldn't try to apply any sort of splitting logic to them. 977 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 978 "No 1:1 mapping from clobbers to regs?"); 979 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 980 (void)SP; 981 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 982 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 983 assert( 984 (Regs[I] != SP || 985 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 986 "If we clobbered the stack pointer, MFI should know about it."); 987 } 988 return; 989 } 990 991 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 992 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 993 MVT RegisterVT = RegVTs[Value]; 994 for (unsigned i = 0; i != NumRegs; ++i) { 995 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 996 unsigned TheReg = Regs[Reg++]; 997 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 998 } 999 } 1000 } 1001 1002 SmallVector<std::pair<unsigned, unsigned>, 4> 1003 RegsForValue::getRegsAndSizes() const { 1004 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 1005 unsigned I = 0; 1006 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1007 unsigned RegCount = std::get<0>(CountAndVT); 1008 MVT RegisterVT = std::get<1>(CountAndVT); 1009 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1010 for (unsigned E = I + RegCount; I != E; ++I) 1011 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1012 } 1013 return OutVec; 1014 } 1015 1016 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1017 const TargetLibraryInfo *li) { 1018 AA = aa; 1019 GFI = gfi; 1020 LibInfo = li; 1021 DL = &DAG.getDataLayout(); 1022 Context = DAG.getContext(); 1023 LPadToCallSiteMap.clear(); 1024 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1025 } 1026 1027 void SelectionDAGBuilder::clear() { 1028 NodeMap.clear(); 1029 UnusedArgNodeMap.clear(); 1030 PendingLoads.clear(); 1031 PendingExports.clear(); 1032 PendingConstrainedFP.clear(); 1033 PendingConstrainedFPStrict.clear(); 1034 CurInst = nullptr; 1035 HasTailCall = false; 1036 SDNodeOrder = LowestSDNodeOrder; 1037 StatepointLowering.clear(); 1038 } 1039 1040 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1041 DanglingDebugInfoMap.clear(); 1042 } 1043 1044 // Update DAG root to include dependencies on Pending chains. 1045 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1046 SDValue Root = DAG.getRoot(); 1047 1048 if (Pending.empty()) 1049 return Root; 1050 1051 // Add current root to PendingChains, unless we already indirectly 1052 // depend on it. 1053 if (Root.getOpcode() != ISD::EntryToken) { 1054 unsigned i = 0, e = Pending.size(); 1055 for (; i != e; ++i) { 1056 assert(Pending[i].getNode()->getNumOperands() > 1); 1057 if (Pending[i].getNode()->getOperand(0) == Root) 1058 break; // Don't add the root if we already indirectly depend on it. 1059 } 1060 1061 if (i == e) 1062 Pending.push_back(Root); 1063 } 1064 1065 if (Pending.size() == 1) 1066 Root = Pending[0]; 1067 else 1068 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1069 1070 DAG.setRoot(Root); 1071 Pending.clear(); 1072 return Root; 1073 } 1074 1075 SDValue SelectionDAGBuilder::getMemoryRoot() { 1076 return updateRoot(PendingLoads); 1077 } 1078 1079 SDValue SelectionDAGBuilder::getRoot() { 1080 // Chain up all pending constrained intrinsics together with all 1081 // pending loads, by simply appending them to PendingLoads and 1082 // then calling getMemoryRoot(). 1083 PendingLoads.reserve(PendingLoads.size() + 1084 PendingConstrainedFP.size() + 1085 PendingConstrainedFPStrict.size()); 1086 PendingLoads.append(PendingConstrainedFP.begin(), 1087 PendingConstrainedFP.end()); 1088 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1089 PendingConstrainedFPStrict.end()); 1090 PendingConstrainedFP.clear(); 1091 PendingConstrainedFPStrict.clear(); 1092 return getMemoryRoot(); 1093 } 1094 1095 SDValue SelectionDAGBuilder::getControlRoot() { 1096 // We need to emit pending fpexcept.strict constrained intrinsics, 1097 // so append them to the PendingExports list. 1098 PendingExports.append(PendingConstrainedFPStrict.begin(), 1099 PendingConstrainedFPStrict.end()); 1100 PendingConstrainedFPStrict.clear(); 1101 return updateRoot(PendingExports); 1102 } 1103 1104 void SelectionDAGBuilder::visit(const Instruction &I) { 1105 // Set up outgoing PHI node register values before emitting the terminator. 1106 if (I.isTerminator()) { 1107 HandlePHINodesInSuccessorBlocks(I.getParent()); 1108 } 1109 1110 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1111 if (!isa<DbgInfoIntrinsic>(I)) 1112 ++SDNodeOrder; 1113 1114 CurInst = &I; 1115 1116 visit(I.getOpcode(), I); 1117 1118 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1119 // ConstrainedFPIntrinsics handle their own FMF. 1120 if (!isa<ConstrainedFPIntrinsic>(&I)) { 1121 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1122 // maps to this instruction. 1123 // TODO: We could handle all flags (nsw, etc) here. 1124 // TODO: If an IR instruction maps to >1 node, only the final node will have 1125 // flags set. 1126 if (SDNode *Node = getNodeForIRValue(&I)) { 1127 SDNodeFlags IncomingFlags; 1128 IncomingFlags.copyFMF(*FPMO); 1129 if (!Node->getFlags().isDefined()) 1130 Node->setFlags(IncomingFlags); 1131 else 1132 Node->intersectFlagsWith(IncomingFlags); 1133 } 1134 } 1135 } 1136 1137 if (!I.isTerminator() && !HasTailCall && 1138 !isStatepoint(&I)) // statepoints handle their exports internally 1139 CopyToExportRegsIfNeeded(&I); 1140 1141 CurInst = nullptr; 1142 } 1143 1144 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1145 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1146 } 1147 1148 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1149 // Note: this doesn't use InstVisitor, because it has to work with 1150 // ConstantExpr's in addition to instructions. 1151 switch (Opcode) { 1152 default: llvm_unreachable("Unknown instruction type encountered!"); 1153 // Build the switch statement using the Instruction.def file. 1154 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1155 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1156 #include "llvm/IR/Instruction.def" 1157 } 1158 } 1159 1160 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1161 const DIExpression *Expr) { 1162 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1163 const DbgValueInst *DI = DDI.getDI(); 1164 DIVariable *DanglingVariable = DI->getVariable(); 1165 DIExpression *DanglingExpr = DI->getExpression(); 1166 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1167 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1168 return true; 1169 } 1170 return false; 1171 }; 1172 1173 for (auto &DDIMI : DanglingDebugInfoMap) { 1174 DanglingDebugInfoVector &DDIV = DDIMI.second; 1175 1176 // If debug info is to be dropped, run it through final checks to see 1177 // whether it can be salvaged. 1178 for (auto &DDI : DDIV) 1179 if (isMatchingDbgValue(DDI)) 1180 salvageUnresolvedDbgValue(DDI); 1181 1182 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1183 } 1184 } 1185 1186 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1187 // generate the debug data structures now that we've seen its definition. 1188 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1189 SDValue Val) { 1190 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1191 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1192 return; 1193 1194 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1195 for (auto &DDI : DDIV) { 1196 const DbgValueInst *DI = DDI.getDI(); 1197 assert(DI && "Ill-formed DanglingDebugInfo"); 1198 DebugLoc dl = DDI.getdl(); 1199 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1200 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1201 DILocalVariable *Variable = DI->getVariable(); 1202 DIExpression *Expr = DI->getExpression(); 1203 assert(Variable->isValidLocationForIntrinsic(dl) && 1204 "Expected inlined-at fields to agree"); 1205 SDDbgValue *SDV; 1206 if (Val.getNode()) { 1207 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1208 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1209 // we couldn't resolve it directly when examining the DbgValue intrinsic 1210 // in the first place we should not be more successful here). Unless we 1211 // have some test case that prove this to be correct we should avoid 1212 // calling EmitFuncArgumentDbgValue here. 1213 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1214 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1215 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1216 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1217 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1218 // inserted after the definition of Val when emitting the instructions 1219 // after ISel. An alternative could be to teach 1220 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1221 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1222 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1223 << ValSDNodeOrder << "\n"); 1224 SDV = getDbgValue(Val, Variable, Expr, dl, 1225 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1226 DAG.AddDbgValue(SDV, Val.getNode(), false); 1227 } else 1228 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1229 << "in EmitFuncArgumentDbgValue\n"); 1230 } else { 1231 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1232 auto Undef = 1233 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1234 auto SDV = 1235 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1236 DAG.AddDbgValue(SDV, nullptr, false); 1237 } 1238 } 1239 DDIV.clear(); 1240 } 1241 1242 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1243 Value *V = DDI.getDI()->getValue(); 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 1250 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1251 // that DW_OP_stack_value is desired. 1252 assert(isa<DbgValueInst>(DDI.getDI())); 1253 bool StackValue = true; 1254 1255 // Can this Value can be encoded without any further work? 1256 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1257 return; 1258 1259 // Attempt to salvage back through as many instructions as possible. Bail if 1260 // a non-instruction is seen, such as a constant expression or global 1261 // variable. FIXME: Further work could recover those too. 1262 while (isa<Instruction>(V)) { 1263 Instruction &VAsInst = *cast<Instruction>(V); 1264 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1265 1266 // If we cannot salvage any further, and haven't yet found a suitable debug 1267 // expression, bail out. 1268 if (!NewExpr) 1269 break; 1270 1271 // New value and expr now represent this debuginfo. 1272 V = VAsInst.getOperand(0); 1273 Expr = NewExpr; 1274 1275 // Some kind of simplification occurred: check whether the operand of the 1276 // salvaged debug expression can be encoded in this DAG. 1277 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 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()->getVariableLocation()->getType()); 1288 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1289 DAG.AddDbgValue(SDV, nullptr, 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(const Value *V, DILocalVariable *Var, 1298 DIExpression *Expr, DebugLoc dl, 1299 DebugLoc InstDL, unsigned Order) { 1300 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1301 SDDbgValue *SDV; 1302 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1303 isa<ConstantPointerNull>(V)) { 1304 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1305 DAG.AddDbgValue(SDV, nullptr, false); 1306 return true; 1307 } 1308 1309 // If the Value is a frame index, we can create a FrameIndex debug value 1310 // without relying on the DAG at all. 1311 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1312 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1313 if (SI != FuncInfo.StaticAllocaMap.end()) { 1314 auto SDV = 1315 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1316 /*IsIndirect*/ false, dl, SDNodeOrder); 1317 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1318 // is still available even if the SDNode gets optimized out. 1319 DAG.AddDbgValue(SDV, nullptr, false); 1320 return true; 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 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1331 return true; 1332 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1333 DAG.AddDbgValue(SDV, N.getNode(), false); 1334 return true; 1335 } 1336 1337 // Special rules apply for the first dbg.values of parameter variables in a 1338 // function. Identify them by the fact they reference Argument Values, that 1339 // they're parameters, and they are parameters of the current function. We 1340 // need to let them dangle until they get an SDNode. 1341 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1342 !InstDL.getInlinedAt(); 1343 if (!IsParamOfFunc) { 1344 // The value is not used in this block yet (or it would have an SDNode). 1345 // We still want the value to appear for the user if possible -- if it has 1346 // an associated VReg, we can refer to that instead. 1347 auto VMI = FuncInfo.ValueMap.find(V); 1348 if (VMI != FuncInfo.ValueMap.end()) { 1349 unsigned Reg = VMI->second; 1350 // If this is a PHI node, it may be split up into several MI PHI nodes 1351 // (in FunctionLoweringInfo::set). 1352 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1353 V->getType(), None); 1354 if (RFV.occupiesMultipleRegs()) { 1355 unsigned Offset = 0; 1356 unsigned BitsToDescribe = 0; 1357 if (auto VarSize = Var->getSizeInBits()) 1358 BitsToDescribe = *VarSize; 1359 if (auto Fragment = Expr->getFragmentInfo()) 1360 BitsToDescribe = Fragment->SizeInBits; 1361 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1362 unsigned RegisterSize = RegAndSize.second; 1363 // Bail out if all bits are described already. 1364 if (Offset >= BitsToDescribe) 1365 break; 1366 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1367 ? BitsToDescribe - Offset 1368 : RegisterSize; 1369 auto FragmentExpr = DIExpression::createFragmentExpression( 1370 Expr, Offset, FragmentSize); 1371 if (!FragmentExpr) 1372 continue; 1373 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1374 false, dl, SDNodeOrder); 1375 DAG.AddDbgValue(SDV, nullptr, false); 1376 Offset += RegisterSize; 1377 } 1378 } else { 1379 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1380 DAG.AddDbgValue(SDV, nullptr, false); 1381 } 1382 return true; 1383 } 1384 } 1385 1386 return false; 1387 } 1388 1389 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1390 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1391 for (auto &Pair : DanglingDebugInfoMap) 1392 for (auto &DDI : Pair.second) 1393 salvageUnresolvedDbgValue(DDI); 1394 clearDanglingDebugInfo(); 1395 } 1396 1397 /// getCopyFromRegs - If there was virtual register allocated for the value V 1398 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1399 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1400 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1401 SDValue Result; 1402 1403 if (It != FuncInfo.ValueMap.end()) { 1404 unsigned InReg = It->second; 1405 1406 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1407 DAG.getDataLayout(), InReg, Ty, 1408 None); // This is not an ABI copy. 1409 SDValue Chain = DAG.getEntryNode(); 1410 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1411 V); 1412 resolveDanglingDebugInfo(V, Result); 1413 } 1414 1415 return Result; 1416 } 1417 1418 /// getValue - Return an SDValue for the given Value. 1419 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1420 // If we already have an SDValue for this value, use it. It's important 1421 // to do this first, so that we don't create a CopyFromReg if we already 1422 // have a regular SDValue. 1423 SDValue &N = NodeMap[V]; 1424 if (N.getNode()) return N; 1425 1426 // If there's a virtual register allocated and initialized for this 1427 // value, use it. 1428 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1429 return copyFromReg; 1430 1431 // Otherwise create a new SDValue and remember it. 1432 SDValue Val = getValueImpl(V); 1433 NodeMap[V] = Val; 1434 resolveDanglingDebugInfo(V, Val); 1435 return Val; 1436 } 1437 1438 // Return true if SDValue exists for the given Value 1439 bool SelectionDAGBuilder::findValue(const Value *V) const { 1440 return (NodeMap.find(V) != NodeMap.end()) || 1441 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1442 } 1443 1444 /// getNonRegisterValue - Return an SDValue for the given Value, but 1445 /// don't look in FuncInfo.ValueMap for a virtual register. 1446 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1447 // If we already have an SDValue for this value, use it. 1448 SDValue &N = NodeMap[V]; 1449 if (N.getNode()) { 1450 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1451 // Remove the debug location from the node as the node is about to be used 1452 // in a location which may differ from the original debug location. This 1453 // is relevant to Constant and ConstantFP nodes because they can appear 1454 // as constant expressions inside PHI nodes. 1455 N->setDebugLoc(DebugLoc()); 1456 } 1457 return N; 1458 } 1459 1460 // Otherwise create a new SDValue and remember it. 1461 SDValue Val = getValueImpl(V); 1462 NodeMap[V] = Val; 1463 resolveDanglingDebugInfo(V, Val); 1464 return Val; 1465 } 1466 1467 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1468 /// Create an SDValue for the given value. 1469 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1470 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1471 1472 if (const Constant *C = dyn_cast<Constant>(V)) { 1473 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1474 1475 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1476 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1477 1478 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1479 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1480 1481 if (isa<ConstantPointerNull>(C)) { 1482 unsigned AS = V->getType()->getPointerAddressSpace(); 1483 return DAG.getConstant(0, getCurSDLoc(), 1484 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1485 } 1486 1487 if (match(C, m_VScale(DAG.getDataLayout()))) 1488 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1489 1490 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1491 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1492 1493 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1494 return DAG.getUNDEF(VT); 1495 1496 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1497 visit(CE->getOpcode(), *CE); 1498 SDValue N1 = NodeMap[V]; 1499 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1500 return N1; 1501 } 1502 1503 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1504 SmallVector<SDValue, 4> Constants; 1505 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1506 OI != OE; ++OI) { 1507 SDNode *Val = getValue(*OI).getNode(); 1508 // If the operand is an empty aggregate, there are no values. 1509 if (!Val) continue; 1510 // Add each leaf value from the operand to the Constants list 1511 // to form a flattened list of all the values. 1512 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1513 Constants.push_back(SDValue(Val, i)); 1514 } 1515 1516 return DAG.getMergeValues(Constants, getCurSDLoc()); 1517 } 1518 1519 if (const ConstantDataSequential *CDS = 1520 dyn_cast<ConstantDataSequential>(C)) { 1521 SmallVector<SDValue, 4> Ops; 1522 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1523 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1524 // Add each leaf value from the operand to the Constants list 1525 // to form a flattened list of all the values. 1526 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1527 Ops.push_back(SDValue(Val, i)); 1528 } 1529 1530 if (isa<ArrayType>(CDS->getType())) 1531 return DAG.getMergeValues(Ops, getCurSDLoc()); 1532 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1533 } 1534 1535 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1536 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1537 "Unknown struct or array constant!"); 1538 1539 SmallVector<EVT, 4> ValueVTs; 1540 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1541 unsigned NumElts = ValueVTs.size(); 1542 if (NumElts == 0) 1543 return SDValue(); // empty struct 1544 SmallVector<SDValue, 4> Constants(NumElts); 1545 for (unsigned i = 0; i != NumElts; ++i) { 1546 EVT EltVT = ValueVTs[i]; 1547 if (isa<UndefValue>(C)) 1548 Constants[i] = DAG.getUNDEF(EltVT); 1549 else if (EltVT.isFloatingPoint()) 1550 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1551 else 1552 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1553 } 1554 1555 return DAG.getMergeValues(Constants, getCurSDLoc()); 1556 } 1557 1558 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1559 return DAG.getBlockAddress(BA, VT); 1560 1561 VectorType *VecTy = cast<VectorType>(V->getType()); 1562 unsigned NumElements = VecTy->getNumElements(); 1563 1564 // Now that we know the number and type of the elements, get that number of 1565 // elements into the Ops array based on what kind of constant it is. 1566 SmallVector<SDValue, 16> Ops; 1567 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1568 for (unsigned i = 0; i != NumElements; ++i) 1569 Ops.push_back(getValue(CV->getOperand(i))); 1570 } else { 1571 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1572 EVT EltVT = 1573 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1574 1575 SDValue Op; 1576 if (EltVT.isFloatingPoint()) 1577 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1578 else 1579 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1580 Ops.assign(NumElements, Op); 1581 } 1582 1583 // Create a BUILD_VECTOR node. 1584 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1585 } 1586 1587 // If this is a static alloca, generate it as the frameindex instead of 1588 // computation. 1589 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1590 DenseMap<const AllocaInst*, int>::iterator SI = 1591 FuncInfo.StaticAllocaMap.find(AI); 1592 if (SI != FuncInfo.StaticAllocaMap.end()) 1593 return DAG.getFrameIndex(SI->second, 1594 TLI.getFrameIndexTy(DAG.getDataLayout())); 1595 } 1596 1597 // If this is an instruction which fast-isel has deferred, select it now. 1598 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1599 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1600 1601 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1602 Inst->getType(), getABIRegCopyCC(V)); 1603 SDValue Chain = DAG.getEntryNode(); 1604 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1605 } 1606 1607 llvm_unreachable("Can't get register for value!"); 1608 } 1609 1610 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1611 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1612 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1613 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1614 bool IsSEH = isAsynchronousEHPersonality(Pers); 1615 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1616 if (!IsSEH) 1617 CatchPadMBB->setIsEHScopeEntry(); 1618 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1619 if (IsMSVCCXX || IsCoreCLR) 1620 CatchPadMBB->setIsEHFuncletEntry(); 1621 } 1622 1623 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1624 // Update machine-CFG edge. 1625 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1626 FuncInfo.MBB->addSuccessor(TargetMBB); 1627 1628 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1629 bool IsSEH = isAsynchronousEHPersonality(Pers); 1630 if (IsSEH) { 1631 // If this is not a fall-through branch or optimizations are switched off, 1632 // emit the branch. 1633 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1634 TM.getOptLevel() == CodeGenOpt::None) 1635 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1636 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1637 return; 1638 } 1639 1640 // Figure out the funclet membership for the catchret's successor. 1641 // This will be used by the FuncletLayout pass to determine how to order the 1642 // BB's. 1643 // A 'catchret' returns to the outer scope's color. 1644 Value *ParentPad = I.getCatchSwitchParentPad(); 1645 const BasicBlock *SuccessorColor; 1646 if (isa<ConstantTokenNone>(ParentPad)) 1647 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1648 else 1649 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1650 assert(SuccessorColor && "No parent funclet for catchret!"); 1651 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1652 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1653 1654 // Create the terminator node. 1655 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1656 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1657 DAG.getBasicBlock(SuccessorColorMBB)); 1658 DAG.setRoot(Ret); 1659 } 1660 1661 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1662 // Don't emit any special code for the cleanuppad instruction. It just marks 1663 // the start of an EH scope/funclet. 1664 FuncInfo.MBB->setIsEHScopeEntry(); 1665 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1666 if (Pers != EHPersonality::Wasm_CXX) { 1667 FuncInfo.MBB->setIsEHFuncletEntry(); 1668 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1669 } 1670 } 1671 1672 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1673 // the control flow always stops at the single catch pad, as it does for a 1674 // cleanup pad. In case the exception caught is not of the types the catch pad 1675 // catches, it will be rethrown by a rethrow. 1676 static void findWasmUnwindDestinations( 1677 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1678 BranchProbability Prob, 1679 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1680 &UnwindDests) { 1681 while (EHPadBB) { 1682 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1683 if (isa<CleanupPadInst>(Pad)) { 1684 // Stop on cleanup pads. 1685 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1686 UnwindDests.back().first->setIsEHScopeEntry(); 1687 break; 1688 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1689 // Add the catchpad handlers to the possible destinations. We don't 1690 // continue to the unwind destination of the catchswitch for wasm. 1691 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1692 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1693 UnwindDests.back().first->setIsEHScopeEntry(); 1694 } 1695 break; 1696 } else { 1697 continue; 1698 } 1699 } 1700 } 1701 1702 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1703 /// many places it could ultimately go. In the IR, we have a single unwind 1704 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1705 /// This function skips over imaginary basic blocks that hold catchswitch 1706 /// instructions, and finds all the "real" machine 1707 /// basic block destinations. As those destinations may not be successors of 1708 /// EHPadBB, here we also calculate the edge probability to those destinations. 1709 /// The passed-in Prob is the edge probability to EHPadBB. 1710 static void findUnwindDestinations( 1711 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1712 BranchProbability Prob, 1713 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1714 &UnwindDests) { 1715 EHPersonality Personality = 1716 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1717 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1718 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1719 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1720 bool IsSEH = isAsynchronousEHPersonality(Personality); 1721 1722 if (IsWasmCXX) { 1723 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1724 assert(UnwindDests.size() <= 1 && 1725 "There should be at most one unwind destination for wasm"); 1726 return; 1727 } 1728 1729 while (EHPadBB) { 1730 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1731 BasicBlock *NewEHPadBB = nullptr; 1732 if (isa<LandingPadInst>(Pad)) { 1733 // Stop on landingpads. They are not funclets. 1734 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1735 break; 1736 } else if (isa<CleanupPadInst>(Pad)) { 1737 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1738 // personalities. 1739 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1740 UnwindDests.back().first->setIsEHScopeEntry(); 1741 UnwindDests.back().first->setIsEHFuncletEntry(); 1742 break; 1743 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1744 // Add the catchpad handlers to the possible destinations. 1745 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1746 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1747 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1748 if (IsMSVCCXX || IsCoreCLR) 1749 UnwindDests.back().first->setIsEHFuncletEntry(); 1750 if (!IsSEH) 1751 UnwindDests.back().first->setIsEHScopeEntry(); 1752 } 1753 NewEHPadBB = CatchSwitch->getUnwindDest(); 1754 } else { 1755 continue; 1756 } 1757 1758 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1759 if (BPI && NewEHPadBB) 1760 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1761 EHPadBB = NewEHPadBB; 1762 } 1763 } 1764 1765 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1766 // Update successor info. 1767 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1768 auto UnwindDest = I.getUnwindDest(); 1769 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1770 BranchProbability UnwindDestProb = 1771 (BPI && UnwindDest) 1772 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1773 : BranchProbability::getZero(); 1774 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1775 for (auto &UnwindDest : UnwindDests) { 1776 UnwindDest.first->setIsEHPad(); 1777 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1778 } 1779 FuncInfo.MBB->normalizeSuccProbs(); 1780 1781 // Create the terminator node. 1782 SDValue Ret = 1783 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1784 DAG.setRoot(Ret); 1785 } 1786 1787 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1788 report_fatal_error("visitCatchSwitch not yet implemented!"); 1789 } 1790 1791 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1792 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1793 auto &DL = DAG.getDataLayout(); 1794 SDValue Chain = getControlRoot(); 1795 SmallVector<ISD::OutputArg, 8> Outs; 1796 SmallVector<SDValue, 8> OutVals; 1797 1798 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1799 // lower 1800 // 1801 // %val = call <ty> @llvm.experimental.deoptimize() 1802 // ret <ty> %val 1803 // 1804 // differently. 1805 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1806 LowerDeoptimizingReturn(); 1807 return; 1808 } 1809 1810 if (!FuncInfo.CanLowerReturn) { 1811 unsigned DemoteReg = FuncInfo.DemoteRegister; 1812 const Function *F = I.getParent()->getParent(); 1813 1814 // Emit a store of the return value through the virtual register. 1815 // Leave Outs empty so that LowerReturn won't try to load return 1816 // registers the usual way. 1817 SmallVector<EVT, 1> PtrValueVTs; 1818 ComputeValueVTs(TLI, DL, 1819 F->getReturnType()->getPointerTo( 1820 DAG.getDataLayout().getAllocaAddrSpace()), 1821 PtrValueVTs); 1822 1823 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1824 DemoteReg, PtrValueVTs[0]); 1825 SDValue RetOp = getValue(I.getOperand(0)); 1826 1827 SmallVector<EVT, 4> ValueVTs, MemVTs; 1828 SmallVector<uint64_t, 4> Offsets; 1829 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1830 &Offsets); 1831 unsigned NumValues = ValueVTs.size(); 1832 1833 SmallVector<SDValue, 4> Chains(NumValues); 1834 for (unsigned i = 0; i != NumValues; ++i) { 1835 // An aggregate return value cannot wrap around the address space, so 1836 // offsets to its parts don't wrap either. 1837 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1838 1839 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1840 if (MemVTs[i] != ValueVTs[i]) 1841 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1842 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val, 1843 // FIXME: better loc info would be nice. 1844 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1845 } 1846 1847 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1848 MVT::Other, Chains); 1849 } else if (I.getNumOperands() != 0) { 1850 SmallVector<EVT, 4> ValueVTs; 1851 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1852 unsigned NumValues = ValueVTs.size(); 1853 if (NumValues) { 1854 SDValue RetOp = getValue(I.getOperand(0)); 1855 1856 const Function *F = I.getParent()->getParent(); 1857 1858 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1859 I.getOperand(0)->getType(), F->getCallingConv(), 1860 /*IsVarArg*/ false); 1861 1862 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1863 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1864 Attribute::SExt)) 1865 ExtendKind = ISD::SIGN_EXTEND; 1866 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1867 Attribute::ZExt)) 1868 ExtendKind = ISD::ZERO_EXTEND; 1869 1870 LLVMContext &Context = F->getContext(); 1871 bool RetInReg = F->getAttributes().hasAttribute( 1872 AttributeList::ReturnIndex, Attribute::InReg); 1873 1874 for (unsigned j = 0; j != NumValues; ++j) { 1875 EVT VT = ValueVTs[j]; 1876 1877 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1878 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1879 1880 CallingConv::ID CC = F->getCallingConv(); 1881 1882 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1883 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1884 SmallVector<SDValue, 4> Parts(NumParts); 1885 getCopyToParts(DAG, getCurSDLoc(), 1886 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1887 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1888 1889 // 'inreg' on function refers to return value 1890 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1891 if (RetInReg) 1892 Flags.setInReg(); 1893 1894 if (I.getOperand(0)->getType()->isPointerTy()) { 1895 Flags.setPointer(); 1896 Flags.setPointerAddrSpace( 1897 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1898 } 1899 1900 if (NeedsRegBlock) { 1901 Flags.setInConsecutiveRegs(); 1902 if (j == NumValues - 1) 1903 Flags.setInConsecutiveRegsLast(); 1904 } 1905 1906 // Propagate extension type if any 1907 if (ExtendKind == ISD::SIGN_EXTEND) 1908 Flags.setSExt(); 1909 else if (ExtendKind == ISD::ZERO_EXTEND) 1910 Flags.setZExt(); 1911 1912 for (unsigned i = 0; i < NumParts; ++i) { 1913 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1914 VT, /*isfixed=*/true, 0, 0)); 1915 OutVals.push_back(Parts[i]); 1916 } 1917 } 1918 } 1919 } 1920 1921 // Push in swifterror virtual register as the last element of Outs. This makes 1922 // sure swifterror virtual register will be returned in the swifterror 1923 // physical register. 1924 const Function *F = I.getParent()->getParent(); 1925 if (TLI.supportSwiftError() && 1926 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1927 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1928 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1929 Flags.setSwiftError(); 1930 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1931 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1932 true /*isfixed*/, 1 /*origidx*/, 1933 0 /*partOffs*/)); 1934 // Create SDNode for the swifterror virtual register. 1935 OutVals.push_back( 1936 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1937 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1938 EVT(TLI.getPointerTy(DL)))); 1939 } 1940 1941 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1942 CallingConv::ID CallConv = 1943 DAG.getMachineFunction().getFunction().getCallingConv(); 1944 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1945 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1946 1947 // Verify that the target's LowerReturn behaved as expected. 1948 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1949 "LowerReturn didn't return a valid chain!"); 1950 1951 // Update the DAG with the new chain value resulting from return lowering. 1952 DAG.setRoot(Chain); 1953 } 1954 1955 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1956 /// created for it, emit nodes to copy the value into the virtual 1957 /// registers. 1958 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1959 // Skip empty types 1960 if (V->getType()->isEmptyTy()) 1961 return; 1962 1963 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1964 if (VMI != FuncInfo.ValueMap.end()) { 1965 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1966 CopyValueToVirtualRegister(V, VMI->second); 1967 } 1968 } 1969 1970 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1971 /// the current basic block, add it to ValueMap now so that we'll get a 1972 /// CopyTo/FromReg. 1973 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1974 // No need to export constants. 1975 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1976 1977 // Already exported? 1978 if (FuncInfo.isExportedInst(V)) return; 1979 1980 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1981 CopyValueToVirtualRegister(V, Reg); 1982 } 1983 1984 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1985 const BasicBlock *FromBB) { 1986 // The operands of the setcc have to be in this block. We don't know 1987 // how to export them from some other block. 1988 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1989 // Can export from current BB. 1990 if (VI->getParent() == FromBB) 1991 return true; 1992 1993 // Is already exported, noop. 1994 return FuncInfo.isExportedInst(V); 1995 } 1996 1997 // If this is an argument, we can export it if the BB is the entry block or 1998 // if it is already exported. 1999 if (isa<Argument>(V)) { 2000 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2001 return true; 2002 2003 // Otherwise, can only export this if it is already exported. 2004 return FuncInfo.isExportedInst(V); 2005 } 2006 2007 // Otherwise, constants can always be exported. 2008 return true; 2009 } 2010 2011 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2012 BranchProbability 2013 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2014 const MachineBasicBlock *Dst) const { 2015 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2016 const BasicBlock *SrcBB = Src->getBasicBlock(); 2017 const BasicBlock *DstBB = Dst->getBasicBlock(); 2018 if (!BPI) { 2019 // If BPI is not available, set the default probability as 1 / N, where N is 2020 // the number of successors. 2021 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2022 return BranchProbability(1, SuccSize); 2023 } 2024 return BPI->getEdgeProbability(SrcBB, DstBB); 2025 } 2026 2027 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2028 MachineBasicBlock *Dst, 2029 BranchProbability Prob) { 2030 if (!FuncInfo.BPI) 2031 Src->addSuccessorWithoutProb(Dst); 2032 else { 2033 if (Prob.isUnknown()) 2034 Prob = getEdgeProbability(Src, Dst); 2035 Src->addSuccessor(Dst, Prob); 2036 } 2037 } 2038 2039 static bool InBlock(const Value *V, const BasicBlock *BB) { 2040 if (const Instruction *I = dyn_cast<Instruction>(V)) 2041 return I->getParent() == BB; 2042 return true; 2043 } 2044 2045 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2046 /// This function emits a branch and is used at the leaves of an OR or an 2047 /// AND operator tree. 2048 void 2049 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2050 MachineBasicBlock *TBB, 2051 MachineBasicBlock *FBB, 2052 MachineBasicBlock *CurBB, 2053 MachineBasicBlock *SwitchBB, 2054 BranchProbability TProb, 2055 BranchProbability FProb, 2056 bool InvertCond) { 2057 const BasicBlock *BB = CurBB->getBasicBlock(); 2058 2059 // If the leaf of the tree is a comparison, merge the condition into 2060 // the caseblock. 2061 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2062 // The operands of the cmp have to be in this block. We don't know 2063 // how to export them from some other block. If this is the first block 2064 // of the sequence, no exporting is needed. 2065 if (CurBB == SwitchBB || 2066 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2067 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2068 ISD::CondCode Condition; 2069 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2070 ICmpInst::Predicate Pred = 2071 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2072 Condition = getICmpCondCode(Pred); 2073 } else { 2074 const FCmpInst *FC = cast<FCmpInst>(Cond); 2075 FCmpInst::Predicate Pred = 2076 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2077 Condition = getFCmpCondCode(Pred); 2078 if (TM.Options.NoNaNsFPMath) 2079 Condition = getFCmpCodeWithoutNaN(Condition); 2080 } 2081 2082 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2083 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2084 SL->SwitchCases.push_back(CB); 2085 return; 2086 } 2087 } 2088 2089 // Create a CaseBlock record representing this branch. 2090 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2091 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2092 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2093 SL->SwitchCases.push_back(CB); 2094 } 2095 2096 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2097 MachineBasicBlock *TBB, 2098 MachineBasicBlock *FBB, 2099 MachineBasicBlock *CurBB, 2100 MachineBasicBlock *SwitchBB, 2101 Instruction::BinaryOps Opc, 2102 BranchProbability TProb, 2103 BranchProbability FProb, 2104 bool InvertCond) { 2105 // Skip over not part of the tree and remember to invert op and operands at 2106 // next level. 2107 Value *NotCond; 2108 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2109 InBlock(NotCond, CurBB->getBasicBlock())) { 2110 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2111 !InvertCond); 2112 return; 2113 } 2114 2115 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2116 // Compute the effective opcode for Cond, taking into account whether it needs 2117 // to be inverted, e.g. 2118 // and (not (or A, B)), C 2119 // gets lowered as 2120 // and (and (not A, not B), C) 2121 unsigned BOpc = 0; 2122 if (BOp) { 2123 BOpc = BOp->getOpcode(); 2124 if (InvertCond) { 2125 if (BOpc == Instruction::And) 2126 BOpc = Instruction::Or; 2127 else if (BOpc == Instruction::Or) 2128 BOpc = Instruction::And; 2129 } 2130 } 2131 2132 // If this node is not part of the or/and tree, emit it as a branch. 2133 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2134 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2135 BOp->getParent() != CurBB->getBasicBlock() || 2136 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2137 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2138 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2139 TProb, FProb, InvertCond); 2140 return; 2141 } 2142 2143 // Create TmpBB after CurBB. 2144 MachineFunction::iterator BBI(CurBB); 2145 MachineFunction &MF = DAG.getMachineFunction(); 2146 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2147 CurBB->getParent()->insert(++BBI, TmpBB); 2148 2149 if (Opc == Instruction::Or) { 2150 // Codegen X | Y as: 2151 // BB1: 2152 // jmp_if_X TBB 2153 // jmp TmpBB 2154 // TmpBB: 2155 // jmp_if_Y TBB 2156 // jmp FBB 2157 // 2158 2159 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2160 // The requirement is that 2161 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2162 // = TrueProb for original BB. 2163 // Assuming the original probabilities are A and B, one choice is to set 2164 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2165 // A/(1+B) and 2B/(1+B). This choice assumes that 2166 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2167 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2168 // TmpBB, but the math is more complicated. 2169 2170 auto NewTrueProb = TProb / 2; 2171 auto NewFalseProb = TProb / 2 + FProb; 2172 // Emit the LHS condition. 2173 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2174 NewTrueProb, NewFalseProb, InvertCond); 2175 2176 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2177 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2178 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2179 // Emit the RHS condition into TmpBB. 2180 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2181 Probs[0], Probs[1], InvertCond); 2182 } else { 2183 assert(Opc == Instruction::And && "Unknown merge op!"); 2184 // Codegen X & Y as: 2185 // BB1: 2186 // jmp_if_X TmpBB 2187 // jmp FBB 2188 // TmpBB: 2189 // jmp_if_Y TBB 2190 // jmp FBB 2191 // 2192 // This requires creation of TmpBB after CurBB. 2193 2194 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2195 // The requirement is that 2196 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2197 // = FalseProb for original BB. 2198 // Assuming the original probabilities are A and B, one choice is to set 2199 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2200 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2201 // TrueProb for BB1 * FalseProb for TmpBB. 2202 2203 auto NewTrueProb = TProb + FProb / 2; 2204 auto NewFalseProb = FProb / 2; 2205 // Emit the LHS condition. 2206 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2207 NewTrueProb, NewFalseProb, InvertCond); 2208 2209 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2210 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2211 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2212 // Emit the RHS condition into TmpBB. 2213 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2214 Probs[0], Probs[1], InvertCond); 2215 } 2216 } 2217 2218 /// If the set of cases should be emitted as a series of branches, return true. 2219 /// If we should emit this as a bunch of and/or'd together conditions, return 2220 /// false. 2221 bool 2222 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2223 if (Cases.size() != 2) return true; 2224 2225 // If this is two comparisons of the same values or'd or and'd together, they 2226 // will get folded into a single comparison, so don't emit two blocks. 2227 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2228 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2229 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2230 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2231 return false; 2232 } 2233 2234 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2235 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2236 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2237 Cases[0].CC == Cases[1].CC && 2238 isa<Constant>(Cases[0].CmpRHS) && 2239 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2240 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2241 return false; 2242 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2243 return false; 2244 } 2245 2246 return true; 2247 } 2248 2249 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2250 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2251 2252 // Update machine-CFG edges. 2253 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2254 2255 if (I.isUnconditional()) { 2256 // Update machine-CFG edges. 2257 BrMBB->addSuccessor(Succ0MBB); 2258 2259 // If this is not a fall-through branch or optimizations are switched off, 2260 // emit the branch. 2261 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2262 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2263 MVT::Other, getControlRoot(), 2264 DAG.getBasicBlock(Succ0MBB))); 2265 2266 return; 2267 } 2268 2269 // If this condition is one of the special cases we handle, do special stuff 2270 // now. 2271 const Value *CondVal = I.getCondition(); 2272 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2273 2274 // If this is a series of conditions that are or'd or and'd together, emit 2275 // this as a sequence of branches instead of setcc's with and/or operations. 2276 // As long as jumps are not expensive, this should improve performance. 2277 // For example, instead of something like: 2278 // cmp A, B 2279 // C = seteq 2280 // cmp D, E 2281 // F = setle 2282 // or C, F 2283 // jnz foo 2284 // Emit: 2285 // cmp A, B 2286 // je foo 2287 // cmp D, E 2288 // jle foo 2289 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2290 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2291 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2292 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2293 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2294 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2295 Opcode, 2296 getEdgeProbability(BrMBB, Succ0MBB), 2297 getEdgeProbability(BrMBB, Succ1MBB), 2298 /*InvertCond=*/false); 2299 // If the compares in later blocks need to use values not currently 2300 // exported from this block, export them now. This block should always 2301 // be the first entry. 2302 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2303 2304 // Allow some cases to be rejected. 2305 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2306 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2307 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2308 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2309 } 2310 2311 // Emit the branch for this block. 2312 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2313 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2314 return; 2315 } 2316 2317 // Okay, we decided not to do this, remove any inserted MBB's and clear 2318 // SwitchCases. 2319 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2320 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2321 2322 SL->SwitchCases.clear(); 2323 } 2324 } 2325 2326 // Create a CaseBlock record representing this branch. 2327 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2328 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2329 2330 // Use visitSwitchCase to actually insert the fast branch sequence for this 2331 // cond branch. 2332 visitSwitchCase(CB, BrMBB); 2333 } 2334 2335 /// visitSwitchCase - Emits the necessary code to represent a single node in 2336 /// the binary search tree resulting from lowering a switch instruction. 2337 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2338 MachineBasicBlock *SwitchBB) { 2339 SDValue Cond; 2340 SDValue CondLHS = getValue(CB.CmpLHS); 2341 SDLoc dl = CB.DL; 2342 2343 if (CB.CC == ISD::SETTRUE) { 2344 // Branch or fall through to TrueBB. 2345 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2346 SwitchBB->normalizeSuccProbs(); 2347 if (CB.TrueBB != NextBlock(SwitchBB)) { 2348 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2349 DAG.getBasicBlock(CB.TrueBB))); 2350 } 2351 return; 2352 } 2353 2354 auto &TLI = DAG.getTargetLoweringInfo(); 2355 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2356 2357 // Build the setcc now. 2358 if (!CB.CmpMHS) { 2359 // Fold "(X == true)" to X and "(X == false)" to !X to 2360 // handle common cases produced by branch lowering. 2361 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2362 CB.CC == ISD::SETEQ) 2363 Cond = CondLHS; 2364 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2365 CB.CC == ISD::SETEQ) { 2366 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2367 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2368 } else { 2369 SDValue CondRHS = getValue(CB.CmpRHS); 2370 2371 // If a pointer's DAG type is larger than its memory type then the DAG 2372 // values are zero-extended. This breaks signed comparisons so truncate 2373 // back to the underlying type before doing the compare. 2374 if (CondLHS.getValueType() != MemVT) { 2375 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2376 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2377 } 2378 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2379 } 2380 } else { 2381 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2382 2383 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2384 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2385 2386 SDValue CmpOp = getValue(CB.CmpMHS); 2387 EVT VT = CmpOp.getValueType(); 2388 2389 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2390 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2391 ISD::SETLE); 2392 } else { 2393 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2394 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2395 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2396 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2397 } 2398 } 2399 2400 // Update successor info 2401 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2402 // TrueBB and FalseBB are always different unless the incoming IR is 2403 // degenerate. This only happens when running llc on weird IR. 2404 if (CB.TrueBB != CB.FalseBB) 2405 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2406 SwitchBB->normalizeSuccProbs(); 2407 2408 // If the lhs block is the next block, invert the condition so that we can 2409 // fall through to the lhs instead of the rhs block. 2410 if (CB.TrueBB == NextBlock(SwitchBB)) { 2411 std::swap(CB.TrueBB, CB.FalseBB); 2412 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2413 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2414 } 2415 2416 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2417 MVT::Other, getControlRoot(), Cond, 2418 DAG.getBasicBlock(CB.TrueBB)); 2419 2420 // Insert the false branch. Do this even if it's a fall through branch, 2421 // this makes it easier to do DAG optimizations which require inverting 2422 // the branch condition. 2423 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2424 DAG.getBasicBlock(CB.FalseBB)); 2425 2426 DAG.setRoot(BrCond); 2427 } 2428 2429 /// visitJumpTable - Emit JumpTable node in the current MBB 2430 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2431 // Emit the code for the jump table 2432 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2433 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2434 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2435 JT.Reg, PTy); 2436 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2437 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2438 MVT::Other, Index.getValue(1), 2439 Table, Index); 2440 DAG.setRoot(BrJumpTable); 2441 } 2442 2443 /// visitJumpTableHeader - This function emits necessary code to produce index 2444 /// in the JumpTable from switch case. 2445 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2446 JumpTableHeader &JTH, 2447 MachineBasicBlock *SwitchBB) { 2448 SDLoc dl = getCurSDLoc(); 2449 2450 // Subtract the lowest switch case value from the value being switched on. 2451 SDValue SwitchOp = getValue(JTH.SValue); 2452 EVT VT = SwitchOp.getValueType(); 2453 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2454 DAG.getConstant(JTH.First, dl, VT)); 2455 2456 // The SDNode we just created, which holds the value being switched on minus 2457 // the smallest case value, needs to be copied to a virtual register so it 2458 // can be used as an index into the jump table in a subsequent basic block. 2459 // This value may be smaller or larger than the target's pointer type, and 2460 // therefore require extension or truncating. 2461 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2462 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2463 2464 unsigned JumpTableReg = 2465 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2466 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2467 JumpTableReg, SwitchOp); 2468 JT.Reg = JumpTableReg; 2469 2470 if (!JTH.OmitRangeCheck) { 2471 // Emit the range check for the jump table, and branch to the default block 2472 // for the switch statement if the value being switched on exceeds the 2473 // largest case in the switch. 2474 SDValue CMP = DAG.getSetCC( 2475 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2476 Sub.getValueType()), 2477 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2478 2479 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2480 MVT::Other, CopyTo, CMP, 2481 DAG.getBasicBlock(JT.Default)); 2482 2483 // Avoid emitting unnecessary branches to the next block. 2484 if (JT.MBB != NextBlock(SwitchBB)) 2485 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2486 DAG.getBasicBlock(JT.MBB)); 2487 2488 DAG.setRoot(BrCond); 2489 } else { 2490 // Avoid emitting unnecessary branches to the next block. 2491 if (JT.MBB != NextBlock(SwitchBB)) 2492 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2493 DAG.getBasicBlock(JT.MBB))); 2494 else 2495 DAG.setRoot(CopyTo); 2496 } 2497 } 2498 2499 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2500 /// variable if there exists one. 2501 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2502 SDValue &Chain) { 2503 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2504 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2505 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2506 MachineFunction &MF = DAG.getMachineFunction(); 2507 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2508 MachineSDNode *Node = 2509 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2510 if (Global) { 2511 MachinePointerInfo MPInfo(Global); 2512 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2513 MachineMemOperand::MODereferenceable; 2514 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2515 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2516 DAG.setNodeMemRefs(Node, {MemRef}); 2517 } 2518 if (PtrTy != PtrMemTy) 2519 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2520 return SDValue(Node, 0); 2521 } 2522 2523 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2524 /// tail spliced into a stack protector check success bb. 2525 /// 2526 /// For a high level explanation of how this fits into the stack protector 2527 /// generation see the comment on the declaration of class 2528 /// StackProtectorDescriptor. 2529 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2530 MachineBasicBlock *ParentBB) { 2531 2532 // First create the loads to the guard/stack slot for the comparison. 2533 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2534 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2535 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2536 2537 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2538 int FI = MFI.getStackProtectorIndex(); 2539 2540 SDValue Guard; 2541 SDLoc dl = getCurSDLoc(); 2542 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2543 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2544 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2545 2546 // Generate code to load the content of the guard slot. 2547 SDValue GuardVal = DAG.getLoad( 2548 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2549 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2550 MachineMemOperand::MOVolatile); 2551 2552 if (TLI.useStackGuardXorFP()) 2553 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2554 2555 // Retrieve guard check function, nullptr if instrumentation is inlined. 2556 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2557 // The target provides a guard check function to validate the guard value. 2558 // Generate a call to that function with the content of the guard slot as 2559 // argument. 2560 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2561 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2562 2563 TargetLowering::ArgListTy Args; 2564 TargetLowering::ArgListEntry Entry; 2565 Entry.Node = GuardVal; 2566 Entry.Ty = FnTy->getParamType(0); 2567 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2568 Entry.IsInReg = true; 2569 Args.push_back(Entry); 2570 2571 TargetLowering::CallLoweringInfo CLI(DAG); 2572 CLI.setDebugLoc(getCurSDLoc()) 2573 .setChain(DAG.getEntryNode()) 2574 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2575 getValue(GuardCheckFn), std::move(Args)); 2576 2577 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2578 DAG.setRoot(Result.second); 2579 return; 2580 } 2581 2582 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2583 // Otherwise, emit a volatile load to retrieve the stack guard value. 2584 SDValue Chain = DAG.getEntryNode(); 2585 if (TLI.useLoadStackGuardNode()) { 2586 Guard = getLoadStackGuard(DAG, dl, Chain); 2587 } else { 2588 const Value *IRGuard = TLI.getSDagStackGuard(M); 2589 SDValue GuardPtr = getValue(IRGuard); 2590 2591 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2592 MachinePointerInfo(IRGuard, 0), Align, 2593 MachineMemOperand::MOVolatile); 2594 } 2595 2596 // Perform the comparison via a getsetcc. 2597 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2598 *DAG.getContext(), 2599 Guard.getValueType()), 2600 Guard, GuardVal, ISD::SETNE); 2601 2602 // If the guard/stackslot do not equal, branch to failure MBB. 2603 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2604 MVT::Other, GuardVal.getOperand(0), 2605 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2606 // Otherwise branch to success MBB. 2607 SDValue Br = DAG.getNode(ISD::BR, dl, 2608 MVT::Other, BrCond, 2609 DAG.getBasicBlock(SPD.getSuccessMBB())); 2610 2611 DAG.setRoot(Br); 2612 } 2613 2614 /// Codegen the failure basic block for a stack protector check. 2615 /// 2616 /// A failure stack protector machine basic block consists simply of a call to 2617 /// __stack_chk_fail(). 2618 /// 2619 /// For a high level explanation of how this fits into the stack protector 2620 /// generation see the comment on the declaration of class 2621 /// StackProtectorDescriptor. 2622 void 2623 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2624 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2625 TargetLowering::MakeLibCallOptions CallOptions; 2626 CallOptions.setDiscardResult(true); 2627 SDValue Chain = 2628 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2629 None, CallOptions, getCurSDLoc()).second; 2630 // On PS4, the "return address" must still be within the calling function, 2631 // even if it's at the very end, so emit an explicit TRAP here. 2632 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2633 if (TM.getTargetTriple().isPS4CPU()) 2634 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2635 2636 DAG.setRoot(Chain); 2637 } 2638 2639 /// visitBitTestHeader - This function emits necessary code to produce value 2640 /// suitable for "bit tests" 2641 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2642 MachineBasicBlock *SwitchBB) { 2643 SDLoc dl = getCurSDLoc(); 2644 2645 // Subtract the minimum value. 2646 SDValue SwitchOp = getValue(B.SValue); 2647 EVT VT = SwitchOp.getValueType(); 2648 SDValue RangeSub = 2649 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2650 2651 // Determine the type of the test operands. 2652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2653 bool UsePtrType = false; 2654 if (!TLI.isTypeLegal(VT)) { 2655 UsePtrType = true; 2656 } else { 2657 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2658 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2659 // Switch table case range are encoded into series of masks. 2660 // Just use pointer type, it's guaranteed to fit. 2661 UsePtrType = true; 2662 break; 2663 } 2664 } 2665 SDValue Sub = RangeSub; 2666 if (UsePtrType) { 2667 VT = TLI.getPointerTy(DAG.getDataLayout()); 2668 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2669 } 2670 2671 B.RegVT = VT.getSimpleVT(); 2672 B.Reg = FuncInfo.CreateReg(B.RegVT); 2673 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2674 2675 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2676 2677 if (!B.OmitRangeCheck) 2678 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2679 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2680 SwitchBB->normalizeSuccProbs(); 2681 2682 SDValue Root = CopyTo; 2683 if (!B.OmitRangeCheck) { 2684 // Conditional branch to the default block. 2685 SDValue RangeCmp = DAG.getSetCC(dl, 2686 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2687 RangeSub.getValueType()), 2688 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2689 ISD::SETUGT); 2690 2691 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2692 DAG.getBasicBlock(B.Default)); 2693 } 2694 2695 // Avoid emitting unnecessary branches to the next block. 2696 if (MBB != NextBlock(SwitchBB)) 2697 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2698 2699 DAG.setRoot(Root); 2700 } 2701 2702 /// visitBitTestCase - this function produces one "bit test" 2703 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2704 MachineBasicBlock* NextMBB, 2705 BranchProbability BranchProbToNext, 2706 unsigned Reg, 2707 BitTestCase &B, 2708 MachineBasicBlock *SwitchBB) { 2709 SDLoc dl = getCurSDLoc(); 2710 MVT VT = BB.RegVT; 2711 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2712 SDValue Cmp; 2713 unsigned PopCount = countPopulation(B.Mask); 2714 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2715 if (PopCount == 1) { 2716 // Testing for a single bit; just compare the shift count with what it 2717 // would need to be to shift a 1 bit in that position. 2718 Cmp = DAG.getSetCC( 2719 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2720 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2721 ISD::SETEQ); 2722 } else if (PopCount == BB.Range) { 2723 // There is only one zero bit in the range, test for it directly. 2724 Cmp = DAG.getSetCC( 2725 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2726 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2727 ISD::SETNE); 2728 } else { 2729 // Make desired shift 2730 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2731 DAG.getConstant(1, dl, VT), ShiftOp); 2732 2733 // Emit bit tests and jumps 2734 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2735 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2736 Cmp = DAG.getSetCC( 2737 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2738 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2739 } 2740 2741 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2742 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2743 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2744 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2745 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2746 // one as they are relative probabilities (and thus work more like weights), 2747 // and hence we need to normalize them to let the sum of them become one. 2748 SwitchBB->normalizeSuccProbs(); 2749 2750 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2751 MVT::Other, getControlRoot(), 2752 Cmp, DAG.getBasicBlock(B.TargetBB)); 2753 2754 // Avoid emitting unnecessary branches to the next block. 2755 if (NextMBB != NextBlock(SwitchBB)) 2756 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2757 DAG.getBasicBlock(NextMBB)); 2758 2759 DAG.setRoot(BrAnd); 2760 } 2761 2762 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2763 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2764 2765 // Retrieve successors. Look through artificial IR level blocks like 2766 // catchswitch for successors. 2767 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2768 const BasicBlock *EHPadBB = I.getSuccessor(1); 2769 2770 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2771 // have to do anything here to lower funclet bundles. 2772 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2773 LLVMContext::OB_funclet, 2774 LLVMContext::OB_cfguardtarget}) && 2775 "Cannot lower invokes with arbitrary operand bundles yet!"); 2776 2777 const Value *Callee(I.getCalledValue()); 2778 const Function *Fn = dyn_cast<Function>(Callee); 2779 if (isa<InlineAsm>(Callee)) 2780 visitInlineAsm(&I); 2781 else if (Fn && Fn->isIntrinsic()) { 2782 switch (Fn->getIntrinsicID()) { 2783 default: 2784 llvm_unreachable("Cannot invoke this intrinsic"); 2785 case Intrinsic::donothing: 2786 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2787 break; 2788 case Intrinsic::experimental_patchpoint_void: 2789 case Intrinsic::experimental_patchpoint_i64: 2790 visitPatchpoint(&I, EHPadBB); 2791 break; 2792 case Intrinsic::experimental_gc_statepoint: 2793 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2794 break; 2795 case Intrinsic::wasm_rethrow_in_catch: { 2796 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2797 // special because it can be invoked, so we manually lower it to a DAG 2798 // node here. 2799 SmallVector<SDValue, 8> Ops; 2800 Ops.push_back(getRoot()); // inchain 2801 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2802 Ops.push_back( 2803 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2804 TLI.getPointerTy(DAG.getDataLayout()))); 2805 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2806 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2807 break; 2808 } 2809 } 2810 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2811 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2812 // Eventually we will support lowering the @llvm.experimental.deoptimize 2813 // intrinsic, and right now there are no plans to support other intrinsics 2814 // with deopt state. 2815 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2816 } else { 2817 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2818 } 2819 2820 // If the value of the invoke is used outside of its defining block, make it 2821 // available as a virtual register. 2822 // We already took care of the exported value for the statepoint instruction 2823 // during call to the LowerStatepoint. 2824 if (!isStatepoint(I)) { 2825 CopyToExportRegsIfNeeded(&I); 2826 } 2827 2828 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2829 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2830 BranchProbability EHPadBBProb = 2831 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2832 : BranchProbability::getZero(); 2833 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2834 2835 // Update successor info. 2836 addSuccessorWithProb(InvokeMBB, Return); 2837 for (auto &UnwindDest : UnwindDests) { 2838 UnwindDest.first->setIsEHPad(); 2839 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2840 } 2841 InvokeMBB->normalizeSuccProbs(); 2842 2843 // Drop into normal successor. 2844 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2845 DAG.getBasicBlock(Return))); 2846 } 2847 2848 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2849 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2850 2851 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2852 // have to do anything here to lower funclet bundles. 2853 assert(!I.hasOperandBundlesOtherThan( 2854 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2855 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2856 2857 assert(isa<InlineAsm>(I.getCalledValue()) && 2858 "Only know how to handle inlineasm callbr"); 2859 visitInlineAsm(&I); 2860 CopyToExportRegsIfNeeded(&I); 2861 2862 // Retrieve successors. 2863 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2864 Return->setInlineAsmBrDefaultTarget(); 2865 2866 // Update successor info. 2867 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2868 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2869 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2870 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2871 CallBrMBB->addInlineAsmBrIndirectTarget(Target); 2872 } 2873 CallBrMBB->normalizeSuccProbs(); 2874 2875 // Drop into default successor. 2876 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2877 MVT::Other, getControlRoot(), 2878 DAG.getBasicBlock(Return))); 2879 } 2880 2881 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2882 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2883 } 2884 2885 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2886 assert(FuncInfo.MBB->isEHPad() && 2887 "Call to landingpad not in landing pad!"); 2888 2889 // If there aren't registers to copy the values into (e.g., during SjLj 2890 // exceptions), then don't bother to create these DAG nodes. 2891 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2892 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2893 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2894 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2895 return; 2896 2897 // If landingpad's return type is token type, we don't create DAG nodes 2898 // for its exception pointer and selector value. The extraction of exception 2899 // pointer or selector value from token type landingpads is not currently 2900 // supported. 2901 if (LP.getType()->isTokenTy()) 2902 return; 2903 2904 SmallVector<EVT, 2> ValueVTs; 2905 SDLoc dl = getCurSDLoc(); 2906 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2907 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2908 2909 // Get the two live-in registers as SDValues. The physregs have already been 2910 // copied into virtual registers. 2911 SDValue Ops[2]; 2912 if (FuncInfo.ExceptionPointerVirtReg) { 2913 Ops[0] = DAG.getZExtOrTrunc( 2914 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2915 FuncInfo.ExceptionPointerVirtReg, 2916 TLI.getPointerTy(DAG.getDataLayout())), 2917 dl, ValueVTs[0]); 2918 } else { 2919 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2920 } 2921 Ops[1] = DAG.getZExtOrTrunc( 2922 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2923 FuncInfo.ExceptionSelectorVirtReg, 2924 TLI.getPointerTy(DAG.getDataLayout())), 2925 dl, ValueVTs[1]); 2926 2927 // Merge into one. 2928 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2929 DAG.getVTList(ValueVTs), Ops); 2930 setValue(&LP, Res); 2931 } 2932 2933 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2934 MachineBasicBlock *Last) { 2935 // Update JTCases. 2936 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2937 if (SL->JTCases[i].first.HeaderBB == First) 2938 SL->JTCases[i].first.HeaderBB = Last; 2939 2940 // Update BitTestCases. 2941 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2942 if (SL->BitTestCases[i].Parent == First) 2943 SL->BitTestCases[i].Parent = Last; 2944 } 2945 2946 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2947 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2948 2949 // Update machine-CFG edges with unique successors. 2950 SmallSet<BasicBlock*, 32> Done; 2951 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2952 BasicBlock *BB = I.getSuccessor(i); 2953 bool Inserted = Done.insert(BB).second; 2954 if (!Inserted) 2955 continue; 2956 2957 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2958 addSuccessorWithProb(IndirectBrMBB, Succ); 2959 } 2960 IndirectBrMBB->normalizeSuccProbs(); 2961 2962 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2963 MVT::Other, getControlRoot(), 2964 getValue(I.getAddress()))); 2965 } 2966 2967 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2968 if (!DAG.getTarget().Options.TrapUnreachable) 2969 return; 2970 2971 // We may be able to ignore unreachable behind a noreturn call. 2972 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2973 const BasicBlock &BB = *I.getParent(); 2974 if (&I != &BB.front()) { 2975 BasicBlock::const_iterator PredI = 2976 std::prev(BasicBlock::const_iterator(&I)); 2977 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2978 if (Call->doesNotReturn()) 2979 return; 2980 } 2981 } 2982 } 2983 2984 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2985 } 2986 2987 void SelectionDAGBuilder::visitFSub(const User &I) { 2988 // -0.0 - X --> fneg 2989 Type *Ty = I.getType(); 2990 if (isa<Constant>(I.getOperand(0)) && 2991 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2992 SDValue Op2 = getValue(I.getOperand(1)); 2993 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2994 Op2.getValueType(), Op2)); 2995 return; 2996 } 2997 2998 visitBinary(I, ISD::FSUB); 2999 } 3000 3001 /// Checks if the given instruction performs a vector reduction, in which case 3002 /// we have the freedom to alter the elements in the result as long as the 3003 /// reduction of them stays unchanged. 3004 static bool isVectorReductionOp(const User *I) { 3005 const Instruction *Inst = dyn_cast<Instruction>(I); 3006 if (!Inst || !Inst->getType()->isVectorTy()) 3007 return false; 3008 3009 auto OpCode = Inst->getOpcode(); 3010 switch (OpCode) { 3011 case Instruction::Add: 3012 case Instruction::Mul: 3013 case Instruction::And: 3014 case Instruction::Or: 3015 case Instruction::Xor: 3016 break; 3017 case Instruction::FAdd: 3018 case Instruction::FMul: 3019 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3020 if (FPOp->getFastMathFlags().isFast()) 3021 break; 3022 LLVM_FALLTHROUGH; 3023 default: 3024 return false; 3025 } 3026 3027 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 3028 // Ensure the reduction size is a power of 2. 3029 if (!isPowerOf2_32(ElemNum)) 3030 return false; 3031 3032 unsigned ElemNumToReduce = ElemNum; 3033 3034 // Do DFS search on the def-use chain from the given instruction. We only 3035 // allow four kinds of operations during the search until we reach the 3036 // instruction that extracts the first element from the vector: 3037 // 3038 // 1. The reduction operation of the same opcode as the given instruction. 3039 // 3040 // 2. PHI node. 3041 // 3042 // 3. ShuffleVector instruction together with a reduction operation that 3043 // does a partial reduction. 3044 // 3045 // 4. ExtractElement that extracts the first element from the vector, and we 3046 // stop searching the def-use chain here. 3047 // 3048 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 3049 // from 1-3 to the stack to continue the DFS. The given instruction is not 3050 // a reduction operation if we meet any other instructions other than those 3051 // listed above. 3052 3053 SmallVector<const User *, 16> UsersToVisit{Inst}; 3054 SmallPtrSet<const User *, 16> Visited; 3055 bool ReduxExtracted = false; 3056 3057 while (!UsersToVisit.empty()) { 3058 auto User = UsersToVisit.back(); 3059 UsersToVisit.pop_back(); 3060 if (!Visited.insert(User).second) 3061 continue; 3062 3063 for (const auto *U : User->users()) { 3064 auto Inst = dyn_cast<Instruction>(U); 3065 if (!Inst) 3066 return false; 3067 3068 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 3069 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3070 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 3071 return false; 3072 UsersToVisit.push_back(U); 3073 } else if (const ShuffleVectorInst *ShufInst = 3074 dyn_cast<ShuffleVectorInst>(U)) { 3075 // Detect the following pattern: A ShuffleVector instruction together 3076 // with a reduction that do partial reduction on the first and second 3077 // ElemNumToReduce / 2 elements, and store the result in 3078 // ElemNumToReduce / 2 elements in another vector. 3079 3080 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 3081 if (ResultElements < ElemNum) 3082 return false; 3083 3084 if (ElemNumToReduce == 1) 3085 return false; 3086 if (!isa<UndefValue>(U->getOperand(1))) 3087 return false; 3088 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 3089 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 3090 return false; 3091 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 3092 if (ShufInst->getMaskValue(i) != -1) 3093 return false; 3094 3095 // There is only one user of this ShuffleVector instruction, which 3096 // must be a reduction operation. 3097 if (!U->hasOneUse()) 3098 return false; 3099 3100 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 3101 if (!U2 || U2->getOpcode() != OpCode) 3102 return false; 3103 3104 // Check operands of the reduction operation. 3105 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 3106 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 3107 UsersToVisit.push_back(U2); 3108 ElemNumToReduce /= 2; 3109 } else 3110 return false; 3111 } else if (isa<ExtractElementInst>(U)) { 3112 // At this moment we should have reduced all elements in the vector. 3113 if (ElemNumToReduce != 1) 3114 return false; 3115 3116 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 3117 if (!Val || !Val->isZero()) 3118 return false; 3119 3120 ReduxExtracted = true; 3121 } else 3122 return false; 3123 } 3124 } 3125 return ReduxExtracted; 3126 } 3127 3128 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3129 SDNodeFlags Flags; 3130 3131 SDValue Op = getValue(I.getOperand(0)); 3132 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3133 Op, Flags); 3134 setValue(&I, UnNodeValue); 3135 } 3136 3137 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3138 SDNodeFlags Flags; 3139 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3140 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3141 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3142 } 3143 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3144 Flags.setExact(ExactOp->isExact()); 3145 } 3146 if (isVectorReductionOp(&I)) { 3147 Flags.setVectorReduction(true); 3148 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 3149 3150 // If no flags are set we will propagate the incoming flags, if any flags 3151 // are set, we will intersect them with the incoming flag and so we need to 3152 // copy the FMF flags here. 3153 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) { 3154 Flags.copyFMF(*FPOp); 3155 } 3156 } 3157 3158 SDValue Op1 = getValue(I.getOperand(0)); 3159 SDValue Op2 = getValue(I.getOperand(1)); 3160 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3161 Op1, Op2, Flags); 3162 setValue(&I, BinNodeValue); 3163 } 3164 3165 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3166 SDValue Op1 = getValue(I.getOperand(0)); 3167 SDValue Op2 = getValue(I.getOperand(1)); 3168 3169 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3170 Op1.getValueType(), DAG.getDataLayout()); 3171 3172 // Coerce the shift amount to the right type if we can. 3173 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3174 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3175 unsigned Op2Size = Op2.getValueSizeInBits(); 3176 SDLoc DL = getCurSDLoc(); 3177 3178 // If the operand is smaller than the shift count type, promote it. 3179 if (ShiftSize > Op2Size) 3180 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3181 3182 // If the operand is larger than the shift count type but the shift 3183 // count type has enough bits to represent any shift value, truncate 3184 // it now. This is a common case and it exposes the truncate to 3185 // optimization early. 3186 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3187 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3188 // Otherwise we'll need to temporarily settle for some other convenient 3189 // type. Type legalization will make adjustments once the shiftee is split. 3190 else 3191 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3192 } 3193 3194 bool nuw = false; 3195 bool nsw = false; 3196 bool exact = false; 3197 3198 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3199 3200 if (const OverflowingBinaryOperator *OFBinOp = 3201 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3202 nuw = OFBinOp->hasNoUnsignedWrap(); 3203 nsw = OFBinOp->hasNoSignedWrap(); 3204 } 3205 if (const PossiblyExactOperator *ExactOp = 3206 dyn_cast<const PossiblyExactOperator>(&I)) 3207 exact = ExactOp->isExact(); 3208 } 3209 SDNodeFlags Flags; 3210 Flags.setExact(exact); 3211 Flags.setNoSignedWrap(nsw); 3212 Flags.setNoUnsignedWrap(nuw); 3213 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3214 Flags); 3215 setValue(&I, Res); 3216 } 3217 3218 void SelectionDAGBuilder::visitSDiv(const User &I) { 3219 SDValue Op1 = getValue(I.getOperand(0)); 3220 SDValue Op2 = getValue(I.getOperand(1)); 3221 3222 SDNodeFlags Flags; 3223 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3224 cast<PossiblyExactOperator>(&I)->isExact()); 3225 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3226 Op2, Flags)); 3227 } 3228 3229 void SelectionDAGBuilder::visitICmp(const User &I) { 3230 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3231 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3232 predicate = IC->getPredicate(); 3233 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3234 predicate = ICmpInst::Predicate(IC->getPredicate()); 3235 SDValue Op1 = getValue(I.getOperand(0)); 3236 SDValue Op2 = getValue(I.getOperand(1)); 3237 ISD::CondCode Opcode = getICmpCondCode(predicate); 3238 3239 auto &TLI = DAG.getTargetLoweringInfo(); 3240 EVT MemVT = 3241 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3242 3243 // If a pointer's DAG type is larger than its memory type then the DAG values 3244 // are zero-extended. This breaks signed comparisons so truncate back to the 3245 // underlying type before doing the compare. 3246 if (Op1.getValueType() != MemVT) { 3247 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3248 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3249 } 3250 3251 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3252 I.getType()); 3253 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3254 } 3255 3256 void SelectionDAGBuilder::visitFCmp(const User &I) { 3257 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3258 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3259 predicate = FC->getPredicate(); 3260 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3261 predicate = FCmpInst::Predicate(FC->getPredicate()); 3262 SDValue Op1 = getValue(I.getOperand(0)); 3263 SDValue Op2 = getValue(I.getOperand(1)); 3264 3265 ISD::CondCode Condition = getFCmpCondCode(predicate); 3266 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3267 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3268 Condition = getFCmpCodeWithoutNaN(Condition); 3269 3270 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3271 I.getType()); 3272 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3273 } 3274 3275 // Check if the condition of the select has one use or two users that are both 3276 // selects with the same condition. 3277 static bool hasOnlySelectUsers(const Value *Cond) { 3278 return llvm::all_of(Cond->users(), [](const Value *V) { 3279 return isa<SelectInst>(V); 3280 }); 3281 } 3282 3283 void SelectionDAGBuilder::visitSelect(const User &I) { 3284 SmallVector<EVT, 4> ValueVTs; 3285 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3286 ValueVTs); 3287 unsigned NumValues = ValueVTs.size(); 3288 if (NumValues == 0) return; 3289 3290 SmallVector<SDValue, 4> Values(NumValues); 3291 SDValue Cond = getValue(I.getOperand(0)); 3292 SDValue LHSVal = getValue(I.getOperand(1)); 3293 SDValue RHSVal = getValue(I.getOperand(2)); 3294 SmallVector<SDValue, 1> BaseOps(1, Cond); 3295 ISD::NodeType OpCode = 3296 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3297 3298 bool IsUnaryAbs = false; 3299 3300 // Min/max matching is only viable if all output VTs are the same. 3301 if (is_splat(ValueVTs)) { 3302 EVT VT = ValueVTs[0]; 3303 LLVMContext &Ctx = *DAG.getContext(); 3304 auto &TLI = DAG.getTargetLoweringInfo(); 3305 3306 // We care about the legality of the operation after it has been type 3307 // legalized. 3308 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3309 VT = TLI.getTypeToTransformTo(Ctx, VT); 3310 3311 // If the vselect is legal, assume we want to leave this as a vector setcc + 3312 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3313 // min/max is legal on the scalar type. 3314 bool UseScalarMinMax = VT.isVector() && 3315 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3316 3317 Value *LHS, *RHS; 3318 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3319 ISD::NodeType Opc = ISD::DELETED_NODE; 3320 switch (SPR.Flavor) { 3321 case SPF_UMAX: Opc = ISD::UMAX; break; 3322 case SPF_UMIN: Opc = ISD::UMIN; break; 3323 case SPF_SMAX: Opc = ISD::SMAX; break; 3324 case SPF_SMIN: Opc = ISD::SMIN; break; 3325 case SPF_FMINNUM: 3326 switch (SPR.NaNBehavior) { 3327 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3328 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3329 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3330 case SPNB_RETURNS_ANY: { 3331 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3332 Opc = ISD::FMINNUM; 3333 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3334 Opc = ISD::FMINIMUM; 3335 else if (UseScalarMinMax) 3336 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3337 ISD::FMINNUM : ISD::FMINIMUM; 3338 break; 3339 } 3340 } 3341 break; 3342 case SPF_FMAXNUM: 3343 switch (SPR.NaNBehavior) { 3344 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3345 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3346 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3347 case SPNB_RETURNS_ANY: 3348 3349 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3350 Opc = ISD::FMAXNUM; 3351 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3352 Opc = ISD::FMAXIMUM; 3353 else if (UseScalarMinMax) 3354 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3355 ISD::FMAXNUM : ISD::FMAXIMUM; 3356 break; 3357 } 3358 break; 3359 case SPF_ABS: 3360 IsUnaryAbs = true; 3361 Opc = ISD::ABS; 3362 break; 3363 case SPF_NABS: 3364 // TODO: we need to produce sub(0, abs(X)). 3365 default: break; 3366 } 3367 3368 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3369 (TLI.isOperationLegalOrCustom(Opc, VT) || 3370 (UseScalarMinMax && 3371 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3372 // If the underlying comparison instruction is used by any other 3373 // instruction, the consumed instructions won't be destroyed, so it is 3374 // not profitable to convert to a min/max. 3375 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3376 OpCode = Opc; 3377 LHSVal = getValue(LHS); 3378 RHSVal = getValue(RHS); 3379 BaseOps.clear(); 3380 } 3381 3382 if (IsUnaryAbs) { 3383 OpCode = Opc; 3384 LHSVal = getValue(LHS); 3385 BaseOps.clear(); 3386 } 3387 } 3388 3389 if (IsUnaryAbs) { 3390 for (unsigned i = 0; i != NumValues; ++i) { 3391 Values[i] = 3392 DAG.getNode(OpCode, getCurSDLoc(), 3393 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3394 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3395 } 3396 } else { 3397 for (unsigned i = 0; i != NumValues; ++i) { 3398 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3399 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3400 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3401 Values[i] = DAG.getNode( 3402 OpCode, getCurSDLoc(), 3403 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3404 } 3405 } 3406 3407 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3408 DAG.getVTList(ValueVTs), Values)); 3409 } 3410 3411 void SelectionDAGBuilder::visitTrunc(const User &I) { 3412 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3413 SDValue N = getValue(I.getOperand(0)); 3414 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3415 I.getType()); 3416 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3417 } 3418 3419 void SelectionDAGBuilder::visitZExt(const User &I) { 3420 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3421 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3422 SDValue N = getValue(I.getOperand(0)); 3423 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3424 I.getType()); 3425 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3426 } 3427 3428 void SelectionDAGBuilder::visitSExt(const User &I) { 3429 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3430 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3431 SDValue N = getValue(I.getOperand(0)); 3432 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3433 I.getType()); 3434 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3435 } 3436 3437 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3438 // FPTrunc is never a no-op cast, no need to check 3439 SDValue N = getValue(I.getOperand(0)); 3440 SDLoc dl = getCurSDLoc(); 3441 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3442 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3443 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3444 DAG.getTargetConstant( 3445 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3446 } 3447 3448 void SelectionDAGBuilder::visitFPExt(const User &I) { 3449 // FPExt is never a no-op cast, no need to check 3450 SDValue N = getValue(I.getOperand(0)); 3451 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3452 I.getType()); 3453 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3454 } 3455 3456 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3457 // FPToUI is never a no-op cast, no need to check 3458 SDValue N = getValue(I.getOperand(0)); 3459 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3460 I.getType()); 3461 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3462 } 3463 3464 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3465 // FPToSI is never a no-op cast, no need to check 3466 SDValue N = getValue(I.getOperand(0)); 3467 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3468 I.getType()); 3469 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3470 } 3471 3472 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3473 // UIToFP is never a no-op cast, no need to check 3474 SDValue N = getValue(I.getOperand(0)); 3475 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3476 I.getType()); 3477 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3478 } 3479 3480 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3481 // SIToFP is never a no-op cast, no need to check 3482 SDValue N = getValue(I.getOperand(0)); 3483 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3484 I.getType()); 3485 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3486 } 3487 3488 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3489 // What to do depends on the size of the integer and the size of the pointer. 3490 // We can either truncate, zero extend, or no-op, accordingly. 3491 SDValue N = getValue(I.getOperand(0)); 3492 auto &TLI = DAG.getTargetLoweringInfo(); 3493 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3494 I.getType()); 3495 EVT PtrMemVT = 3496 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3497 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3498 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3499 setValue(&I, N); 3500 } 3501 3502 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3503 // What to do depends on the size of the integer and the size of the pointer. 3504 // We can either truncate, zero extend, or no-op, accordingly. 3505 SDValue N = getValue(I.getOperand(0)); 3506 auto &TLI = DAG.getTargetLoweringInfo(); 3507 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3508 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3509 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3510 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3511 setValue(&I, N); 3512 } 3513 3514 void SelectionDAGBuilder::visitBitCast(const User &I) { 3515 SDValue N = getValue(I.getOperand(0)); 3516 SDLoc dl = getCurSDLoc(); 3517 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3518 I.getType()); 3519 3520 // BitCast assures us that source and destination are the same size so this is 3521 // either a BITCAST or a no-op. 3522 if (DestVT != N.getValueType()) 3523 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3524 DestVT, N)); // convert types. 3525 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3526 // might fold any kind of constant expression to an integer constant and that 3527 // is not what we are looking for. Only recognize a bitcast of a genuine 3528 // constant integer as an opaque constant. 3529 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3530 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3531 /*isOpaque*/true)); 3532 else 3533 setValue(&I, N); // noop cast. 3534 } 3535 3536 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3537 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3538 const Value *SV = I.getOperand(0); 3539 SDValue N = getValue(SV); 3540 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3541 3542 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3543 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3544 3545 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3546 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3547 3548 setValue(&I, N); 3549 } 3550 3551 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3552 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3553 SDValue InVec = getValue(I.getOperand(0)); 3554 SDValue InVal = getValue(I.getOperand(1)); 3555 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3556 TLI.getVectorIdxTy(DAG.getDataLayout())); 3557 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3558 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3559 InVec, InVal, InIdx)); 3560 } 3561 3562 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3563 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3564 SDValue InVec = getValue(I.getOperand(0)); 3565 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3566 TLI.getVectorIdxTy(DAG.getDataLayout())); 3567 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3568 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3569 InVec, InIdx)); 3570 } 3571 3572 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3573 SDValue Src1 = getValue(I.getOperand(0)); 3574 SDValue Src2 = getValue(I.getOperand(1)); 3575 Constant *MaskV = cast<Constant>(I.getOperand(2)); 3576 SDLoc DL = getCurSDLoc(); 3577 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3578 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3579 EVT SrcVT = Src1.getValueType(); 3580 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3581 3582 if (MaskV->isNullValue() && VT.isScalableVector()) { 3583 // Canonical splat form of first element of first input vector. 3584 SDValue FirstElt = 3585 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3586 DAG.getVectorIdxConstant(0, DL)); 3587 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3588 return; 3589 } 3590 3591 // For now, we only handle splats for scalable vectors. 3592 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3593 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3594 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3595 3596 SmallVector<int, 8> Mask; 3597 ShuffleVectorInst::getShuffleMask(MaskV, Mask); 3598 unsigned MaskNumElts = Mask.size(); 3599 3600 if (SrcNumElts == MaskNumElts) { 3601 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3602 return; 3603 } 3604 3605 // Normalize the shuffle vector since mask and vector length don't match. 3606 if (SrcNumElts < MaskNumElts) { 3607 // Mask is longer than the source vectors. We can use concatenate vector to 3608 // make the mask and vectors lengths match. 3609 3610 if (MaskNumElts % SrcNumElts == 0) { 3611 // Mask length is a multiple of the source vector length. 3612 // Check if the shuffle is some kind of concatenation of the input 3613 // vectors. 3614 unsigned NumConcat = MaskNumElts / SrcNumElts; 3615 bool IsConcat = true; 3616 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3617 for (unsigned i = 0; i != MaskNumElts; ++i) { 3618 int Idx = Mask[i]; 3619 if (Idx < 0) 3620 continue; 3621 // Ensure the indices in each SrcVT sized piece are sequential and that 3622 // the same source is used for the whole piece. 3623 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3624 (ConcatSrcs[i / SrcNumElts] >= 0 && 3625 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3626 IsConcat = false; 3627 break; 3628 } 3629 // Remember which source this index came from. 3630 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3631 } 3632 3633 // The shuffle is concatenating multiple vectors together. Just emit 3634 // a CONCAT_VECTORS operation. 3635 if (IsConcat) { 3636 SmallVector<SDValue, 8> ConcatOps; 3637 for (auto Src : ConcatSrcs) { 3638 if (Src < 0) 3639 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3640 else if (Src == 0) 3641 ConcatOps.push_back(Src1); 3642 else 3643 ConcatOps.push_back(Src2); 3644 } 3645 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3646 return; 3647 } 3648 } 3649 3650 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3651 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3652 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3653 PaddedMaskNumElts); 3654 3655 // Pad both vectors with undefs to make them the same length as the mask. 3656 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3657 3658 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3659 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3660 MOps1[0] = Src1; 3661 MOps2[0] = Src2; 3662 3663 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3664 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3665 3666 // Readjust mask for new input vector length. 3667 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3668 for (unsigned i = 0; i != MaskNumElts; ++i) { 3669 int Idx = Mask[i]; 3670 if (Idx >= (int)SrcNumElts) 3671 Idx -= SrcNumElts - PaddedMaskNumElts; 3672 MappedOps[i] = Idx; 3673 } 3674 3675 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3676 3677 // If the concatenated vector was padded, extract a subvector with the 3678 // correct number of elements. 3679 if (MaskNumElts != PaddedMaskNumElts) 3680 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3681 DAG.getVectorIdxConstant(0, DL)); 3682 3683 setValue(&I, Result); 3684 return; 3685 } 3686 3687 if (SrcNumElts > MaskNumElts) { 3688 // Analyze the access pattern of the vector to see if we can extract 3689 // two subvectors and do the shuffle. 3690 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3691 bool CanExtract = true; 3692 for (int Idx : Mask) { 3693 unsigned Input = 0; 3694 if (Idx < 0) 3695 continue; 3696 3697 if (Idx >= (int)SrcNumElts) { 3698 Input = 1; 3699 Idx -= SrcNumElts; 3700 } 3701 3702 // If all the indices come from the same MaskNumElts sized portion of 3703 // the sources we can use extract. Also make sure the extract wouldn't 3704 // extract past the end of the source. 3705 int NewStartIdx = alignDown(Idx, MaskNumElts); 3706 if (NewStartIdx + MaskNumElts > SrcNumElts || 3707 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3708 CanExtract = false; 3709 // Make sure we always update StartIdx as we use it to track if all 3710 // elements are undef. 3711 StartIdx[Input] = NewStartIdx; 3712 } 3713 3714 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3715 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3716 return; 3717 } 3718 if (CanExtract) { 3719 // Extract appropriate subvector and generate a vector shuffle 3720 for (unsigned Input = 0; Input < 2; ++Input) { 3721 SDValue &Src = Input == 0 ? Src1 : Src2; 3722 if (StartIdx[Input] < 0) 3723 Src = DAG.getUNDEF(VT); 3724 else { 3725 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3726 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3727 } 3728 } 3729 3730 // Calculate new mask. 3731 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3732 for (int &Idx : MappedOps) { 3733 if (Idx >= (int)SrcNumElts) 3734 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3735 else if (Idx >= 0) 3736 Idx -= StartIdx[0]; 3737 } 3738 3739 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3740 return; 3741 } 3742 } 3743 3744 // We can't use either concat vectors or extract subvectors so fall back to 3745 // replacing the shuffle with extract and build vector. 3746 // to insert and build vector. 3747 EVT EltVT = VT.getVectorElementType(); 3748 SmallVector<SDValue,8> Ops; 3749 for (int Idx : Mask) { 3750 SDValue Res; 3751 3752 if (Idx < 0) { 3753 Res = DAG.getUNDEF(EltVT); 3754 } else { 3755 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3756 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3757 3758 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3759 DAG.getVectorIdxConstant(Idx, DL)); 3760 } 3761 3762 Ops.push_back(Res); 3763 } 3764 3765 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3766 } 3767 3768 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3769 ArrayRef<unsigned> Indices; 3770 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3771 Indices = IV->getIndices(); 3772 else 3773 Indices = cast<ConstantExpr>(&I)->getIndices(); 3774 3775 const Value *Op0 = I.getOperand(0); 3776 const Value *Op1 = I.getOperand(1); 3777 Type *AggTy = I.getType(); 3778 Type *ValTy = Op1->getType(); 3779 bool IntoUndef = isa<UndefValue>(Op0); 3780 bool FromUndef = isa<UndefValue>(Op1); 3781 3782 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3783 3784 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3785 SmallVector<EVT, 4> AggValueVTs; 3786 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3787 SmallVector<EVT, 4> ValValueVTs; 3788 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3789 3790 unsigned NumAggValues = AggValueVTs.size(); 3791 unsigned NumValValues = ValValueVTs.size(); 3792 SmallVector<SDValue, 4> Values(NumAggValues); 3793 3794 // Ignore an insertvalue that produces an empty object 3795 if (!NumAggValues) { 3796 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3797 return; 3798 } 3799 3800 SDValue Agg = getValue(Op0); 3801 unsigned i = 0; 3802 // Copy the beginning value(s) from the original aggregate. 3803 for (; i != LinearIndex; ++i) 3804 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3805 SDValue(Agg.getNode(), Agg.getResNo() + i); 3806 // Copy values from the inserted value(s). 3807 if (NumValValues) { 3808 SDValue Val = getValue(Op1); 3809 for (; i != LinearIndex + NumValValues; ++i) 3810 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3811 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3812 } 3813 // Copy remaining value(s) from the original aggregate. 3814 for (; i != NumAggValues; ++i) 3815 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3816 SDValue(Agg.getNode(), Agg.getResNo() + i); 3817 3818 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3819 DAG.getVTList(AggValueVTs), Values)); 3820 } 3821 3822 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3823 ArrayRef<unsigned> Indices; 3824 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3825 Indices = EV->getIndices(); 3826 else 3827 Indices = cast<ConstantExpr>(&I)->getIndices(); 3828 3829 const Value *Op0 = I.getOperand(0); 3830 Type *AggTy = Op0->getType(); 3831 Type *ValTy = I.getType(); 3832 bool OutOfUndef = isa<UndefValue>(Op0); 3833 3834 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3835 3836 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3837 SmallVector<EVT, 4> ValValueVTs; 3838 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3839 3840 unsigned NumValValues = ValValueVTs.size(); 3841 3842 // Ignore a extractvalue that produces an empty object 3843 if (!NumValValues) { 3844 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3845 return; 3846 } 3847 3848 SmallVector<SDValue, 4> Values(NumValValues); 3849 3850 SDValue Agg = getValue(Op0); 3851 // Copy out the selected value(s). 3852 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3853 Values[i - LinearIndex] = 3854 OutOfUndef ? 3855 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3856 SDValue(Agg.getNode(), Agg.getResNo() + i); 3857 3858 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3859 DAG.getVTList(ValValueVTs), Values)); 3860 } 3861 3862 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3863 Value *Op0 = I.getOperand(0); 3864 // Note that the pointer operand may be a vector of pointers. Take the scalar 3865 // element which holds a pointer. 3866 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3867 SDValue N = getValue(Op0); 3868 SDLoc dl = getCurSDLoc(); 3869 auto &TLI = DAG.getTargetLoweringInfo(); 3870 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3871 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3872 3873 // Normalize Vector GEP - all scalar operands should be converted to the 3874 // splat vector. 3875 bool IsVectorGEP = I.getType()->isVectorTy(); 3876 ElementCount VectorElementCount = IsVectorGEP ? 3877 I.getType()->getVectorElementCount() : ElementCount(0, false); 3878 3879 if (IsVectorGEP && !N.getValueType().isVector()) { 3880 LLVMContext &Context = *DAG.getContext(); 3881 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3882 if (VectorElementCount.Scalable) 3883 N = DAG.getSplatVector(VT, dl, N); 3884 else 3885 N = DAG.getSplatBuildVector(VT, dl, N); 3886 } 3887 3888 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3889 GTI != E; ++GTI) { 3890 const Value *Idx = GTI.getOperand(); 3891 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3892 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3893 if (Field) { 3894 // N = N + Offset 3895 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3896 3897 // In an inbounds GEP with an offset that is nonnegative even when 3898 // interpreted as signed, assume there is no unsigned overflow. 3899 SDNodeFlags Flags; 3900 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3901 Flags.setNoUnsignedWrap(true); 3902 3903 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3904 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3905 } 3906 } else { 3907 // IdxSize is the width of the arithmetic according to IR semantics. 3908 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3909 // (and fix up the result later). 3910 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3911 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3912 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3913 // We intentionally mask away the high bits here; ElementSize may not 3914 // fit in IdxTy. 3915 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3916 bool ElementScalable = ElementSize.isScalable(); 3917 3918 // If this is a scalar constant or a splat vector of constants, 3919 // handle it quickly. 3920 const auto *C = dyn_cast<Constant>(Idx); 3921 if (C && isa<VectorType>(C->getType())) 3922 C = C->getSplatValue(); 3923 3924 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3925 if (CI && CI->isZero()) 3926 continue; 3927 if (CI && !ElementScalable) { 3928 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3929 LLVMContext &Context = *DAG.getContext(); 3930 SDValue OffsVal; 3931 if (IsVectorGEP) 3932 OffsVal = DAG.getConstant( 3933 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3934 else 3935 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3936 3937 // In an inbounds GEP with an offset that is nonnegative even when 3938 // interpreted as signed, assume there is no unsigned overflow. 3939 SDNodeFlags Flags; 3940 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3941 Flags.setNoUnsignedWrap(true); 3942 3943 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3944 3945 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3946 continue; 3947 } 3948 3949 // N = N + Idx * ElementMul; 3950 SDValue IdxN = getValue(Idx); 3951 3952 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3953 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3954 VectorElementCount); 3955 if (VectorElementCount.Scalable) 3956 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3957 else 3958 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3959 } 3960 3961 // If the index is smaller or larger than intptr_t, truncate or extend 3962 // it. 3963 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3964 3965 if (ElementScalable) { 3966 EVT VScaleTy = N.getValueType().getScalarType(); 3967 SDValue VScale = DAG.getNode( 3968 ISD::VSCALE, dl, VScaleTy, 3969 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3970 if (IsVectorGEP) 3971 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3972 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3973 } else { 3974 // If this is a multiply by a power of two, turn it into a shl 3975 // immediately. This is a very common case. 3976 if (ElementMul != 1) { 3977 if (ElementMul.isPowerOf2()) { 3978 unsigned Amt = ElementMul.logBase2(); 3979 IdxN = DAG.getNode(ISD::SHL, dl, 3980 N.getValueType(), IdxN, 3981 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3982 } else { 3983 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3984 IdxN.getValueType()); 3985 IdxN = DAG.getNode(ISD::MUL, dl, 3986 N.getValueType(), IdxN, Scale); 3987 } 3988 } 3989 } 3990 3991 N = DAG.getNode(ISD::ADD, dl, 3992 N.getValueType(), N, IdxN); 3993 } 3994 } 3995 3996 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3997 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3998 3999 setValue(&I, N); 4000 } 4001 4002 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4003 // If this is a fixed sized alloca in the entry block of the function, 4004 // allocate it statically on the stack. 4005 if (FuncInfo.StaticAllocaMap.count(&I)) 4006 return; // getValue will auto-populate this. 4007 4008 SDLoc dl = getCurSDLoc(); 4009 Type *Ty = I.getAllocatedType(); 4010 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4011 auto &DL = DAG.getDataLayout(); 4012 uint64_t TySize = DL.getTypeAllocSize(Ty); 4013 MaybeAlign Alignment = max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4014 4015 SDValue AllocSize = getValue(I.getArraySize()); 4016 4017 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 4018 if (AllocSize.getValueType() != IntPtr) 4019 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4020 4021 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 4022 AllocSize, 4023 DAG.getConstant(TySize, dl, IntPtr)); 4024 4025 // Handle alignment. If the requested alignment is less than or equal to 4026 // the stack alignment, ignore it. If the size is greater than or equal to 4027 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4028 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4029 if (Alignment <= StackAlign) 4030 Alignment = None; 4031 4032 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4033 // Round the size of the allocation up to the stack alignment size 4034 // by add SA-1 to the size. This doesn't overflow because we're computing 4035 // an address inside an alloca. 4036 SDNodeFlags Flags; 4037 Flags.setNoUnsignedWrap(true); 4038 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4039 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4040 4041 // Mask out the low bits for alignment purposes. 4042 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4043 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4044 4045 SDValue Ops[] = { 4046 getRoot(), AllocSize, 4047 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4048 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4049 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4050 setValue(&I, DSA); 4051 DAG.setRoot(DSA.getValue(1)); 4052 4053 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4054 } 4055 4056 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4057 if (I.isAtomic()) 4058 return visitAtomicLoad(I); 4059 4060 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4061 const Value *SV = I.getOperand(0); 4062 if (TLI.supportSwiftError()) { 4063 // Swifterror values can come from either a function parameter with 4064 // swifterror attribute or an alloca with swifterror attribute. 4065 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4066 if (Arg->hasSwiftErrorAttr()) 4067 return visitLoadFromSwiftError(I); 4068 } 4069 4070 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4071 if (Alloca->isSwiftError()) 4072 return visitLoadFromSwiftError(I); 4073 } 4074 } 4075 4076 SDValue Ptr = getValue(SV); 4077 4078 Type *Ty = I.getType(); 4079 unsigned Alignment = I.getAlignment(); 4080 4081 AAMDNodes AAInfo; 4082 I.getAAMetadata(AAInfo); 4083 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4084 4085 SmallVector<EVT, 4> ValueVTs, MemVTs; 4086 SmallVector<uint64_t, 4> Offsets; 4087 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4088 unsigned NumValues = ValueVTs.size(); 4089 if (NumValues == 0) 4090 return; 4091 4092 bool isVolatile = I.isVolatile(); 4093 4094 SDValue Root; 4095 bool ConstantMemory = false; 4096 if (isVolatile) 4097 // Serialize volatile loads with other side effects. 4098 Root = getRoot(); 4099 else if (NumValues > MaxParallelChains) 4100 Root = getMemoryRoot(); 4101 else if (AA && 4102 AA->pointsToConstantMemory(MemoryLocation( 4103 SV, 4104 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4105 AAInfo))) { 4106 // Do not serialize (non-volatile) loads of constant memory with anything. 4107 Root = DAG.getEntryNode(); 4108 ConstantMemory = true; 4109 } else { 4110 // Do not serialize non-volatile loads against each other. 4111 Root = DAG.getRoot(); 4112 } 4113 4114 SDLoc dl = getCurSDLoc(); 4115 4116 if (isVolatile) 4117 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4118 4119 // An aggregate load cannot wrap around the address space, so offsets to its 4120 // parts don't wrap either. 4121 SDNodeFlags Flags; 4122 Flags.setNoUnsignedWrap(true); 4123 4124 SmallVector<SDValue, 4> Values(NumValues); 4125 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4126 EVT PtrVT = Ptr.getValueType(); 4127 4128 MachineMemOperand::Flags MMOFlags 4129 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4130 4131 unsigned ChainI = 0; 4132 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4133 // Serializing loads here may result in excessive register pressure, and 4134 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4135 // could recover a bit by hoisting nodes upward in the chain by recognizing 4136 // they are side-effect free or do not alias. The optimizer should really 4137 // avoid this case by converting large object/array copies to llvm.memcpy 4138 // (MaxParallelChains should always remain as failsafe). 4139 if (ChainI == MaxParallelChains) { 4140 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4141 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4142 makeArrayRef(Chains.data(), ChainI)); 4143 Root = Chain; 4144 ChainI = 0; 4145 } 4146 SDValue A = DAG.getNode(ISD::ADD, dl, 4147 PtrVT, Ptr, 4148 DAG.getConstant(Offsets[i], dl, PtrVT), 4149 Flags); 4150 4151 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4152 MachinePointerInfo(SV, Offsets[i]), Alignment, 4153 MMOFlags, AAInfo, Ranges); 4154 Chains[ChainI] = L.getValue(1); 4155 4156 if (MemVTs[i] != ValueVTs[i]) 4157 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4158 4159 Values[i] = L; 4160 } 4161 4162 if (!ConstantMemory) { 4163 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4164 makeArrayRef(Chains.data(), ChainI)); 4165 if (isVolatile) 4166 DAG.setRoot(Chain); 4167 else 4168 PendingLoads.push_back(Chain); 4169 } 4170 4171 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4172 DAG.getVTList(ValueVTs), Values)); 4173 } 4174 4175 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4176 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4177 "call visitStoreToSwiftError when backend supports swifterror"); 4178 4179 SmallVector<EVT, 4> ValueVTs; 4180 SmallVector<uint64_t, 4> Offsets; 4181 const Value *SrcV = I.getOperand(0); 4182 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4183 SrcV->getType(), ValueVTs, &Offsets); 4184 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4185 "expect a single EVT for swifterror"); 4186 4187 SDValue Src = getValue(SrcV); 4188 // Create a virtual register, then update the virtual register. 4189 Register VReg = 4190 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4191 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4192 // Chain can be getRoot or getControlRoot. 4193 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4194 SDValue(Src.getNode(), Src.getResNo())); 4195 DAG.setRoot(CopyNode); 4196 } 4197 4198 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4199 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4200 "call visitLoadFromSwiftError when backend supports swifterror"); 4201 4202 assert(!I.isVolatile() && 4203 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4204 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4205 "Support volatile, non temporal, invariant for load_from_swift_error"); 4206 4207 const Value *SV = I.getOperand(0); 4208 Type *Ty = I.getType(); 4209 AAMDNodes AAInfo; 4210 I.getAAMetadata(AAInfo); 4211 assert( 4212 (!AA || 4213 !AA->pointsToConstantMemory(MemoryLocation( 4214 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4215 AAInfo))) && 4216 "load_from_swift_error should not be constant memory"); 4217 4218 SmallVector<EVT, 4> ValueVTs; 4219 SmallVector<uint64_t, 4> Offsets; 4220 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4221 ValueVTs, &Offsets); 4222 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4223 "expect a single EVT for swifterror"); 4224 4225 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4226 SDValue L = DAG.getCopyFromReg( 4227 getRoot(), getCurSDLoc(), 4228 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4229 4230 setValue(&I, L); 4231 } 4232 4233 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4234 if (I.isAtomic()) 4235 return visitAtomicStore(I); 4236 4237 const Value *SrcV = I.getOperand(0); 4238 const Value *PtrV = I.getOperand(1); 4239 4240 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4241 if (TLI.supportSwiftError()) { 4242 // Swifterror values can come from either a function parameter with 4243 // swifterror attribute or an alloca with swifterror attribute. 4244 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4245 if (Arg->hasSwiftErrorAttr()) 4246 return visitStoreToSwiftError(I); 4247 } 4248 4249 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4250 if (Alloca->isSwiftError()) 4251 return visitStoreToSwiftError(I); 4252 } 4253 } 4254 4255 SmallVector<EVT, 4> ValueVTs, MemVTs; 4256 SmallVector<uint64_t, 4> Offsets; 4257 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4258 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4259 unsigned NumValues = ValueVTs.size(); 4260 if (NumValues == 0) 4261 return; 4262 4263 // Get the lowered operands. Note that we do this after 4264 // checking if NumResults is zero, because with zero results 4265 // the operands won't have values in the map. 4266 SDValue Src = getValue(SrcV); 4267 SDValue Ptr = getValue(PtrV); 4268 4269 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4270 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4271 SDLoc dl = getCurSDLoc(); 4272 unsigned Alignment = I.getAlignment(); 4273 AAMDNodes AAInfo; 4274 I.getAAMetadata(AAInfo); 4275 4276 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4277 4278 // An aggregate load cannot wrap around the address space, so offsets to its 4279 // parts don't wrap either. 4280 SDNodeFlags Flags; 4281 Flags.setNoUnsignedWrap(true); 4282 4283 unsigned ChainI = 0; 4284 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4285 // See visitLoad comments. 4286 if (ChainI == MaxParallelChains) { 4287 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4288 makeArrayRef(Chains.data(), ChainI)); 4289 Root = Chain; 4290 ChainI = 0; 4291 } 4292 SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags); 4293 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4294 if (MemVTs[i] != ValueVTs[i]) 4295 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4296 SDValue St = 4297 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4298 Alignment, MMOFlags, AAInfo); 4299 Chains[ChainI] = St; 4300 } 4301 4302 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4303 makeArrayRef(Chains.data(), ChainI)); 4304 DAG.setRoot(StoreNode); 4305 } 4306 4307 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4308 bool IsCompressing) { 4309 SDLoc sdl = getCurSDLoc(); 4310 4311 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4312 unsigned& Alignment) { 4313 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4314 Src0 = I.getArgOperand(0); 4315 Ptr = I.getArgOperand(1); 4316 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 4317 Mask = I.getArgOperand(3); 4318 }; 4319 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4320 unsigned& Alignment) { 4321 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4322 Src0 = I.getArgOperand(0); 4323 Ptr = I.getArgOperand(1); 4324 Mask = I.getArgOperand(2); 4325 Alignment = 0; 4326 }; 4327 4328 Value *PtrOperand, *MaskOperand, *Src0Operand; 4329 unsigned Alignment; 4330 if (IsCompressing) 4331 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4332 else 4333 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4334 4335 SDValue Ptr = getValue(PtrOperand); 4336 SDValue Src0 = getValue(Src0Operand); 4337 SDValue Mask = getValue(MaskOperand); 4338 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4339 4340 EVT VT = Src0.getValueType(); 4341 if (!Alignment) 4342 Alignment = DAG.getEVTAlignment(VT); 4343 4344 AAMDNodes AAInfo; 4345 I.getAAMetadata(AAInfo); 4346 4347 MachineMemOperand *MMO = 4348 DAG.getMachineFunction(). 4349 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4350 MachineMemOperand::MOStore, 4351 // TODO: Make MachineMemOperands aware of scalable 4352 // vectors. 4353 VT.getStoreSize().getKnownMinSize(), 4354 Alignment, AAInfo); 4355 SDValue StoreNode = 4356 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4357 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4358 DAG.setRoot(StoreNode); 4359 setValue(&I, StoreNode); 4360 } 4361 4362 // Get a uniform base for the Gather/Scatter intrinsic. 4363 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4364 // We try to represent it as a base pointer + vector of indices. 4365 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4366 // The first operand of the GEP may be a single pointer or a vector of pointers 4367 // Example: 4368 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4369 // or 4370 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4371 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4372 // 4373 // When the first GEP operand is a single pointer - it is the uniform base we 4374 // are looking for. If first operand of the GEP is a splat vector - we 4375 // extract the splat value and use it as a uniform base. 4376 // In all other cases the function returns 'false'. 4377 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4378 ISD::MemIndexType &IndexType, SDValue &Scale, 4379 SelectionDAGBuilder *SDB) { 4380 SelectionDAG& DAG = SDB->DAG; 4381 LLVMContext &Context = *DAG.getContext(); 4382 4383 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4384 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4385 if (!GEP) 4386 return false; 4387 4388 const Value *BasePtr = GEP->getPointerOperand(); 4389 if (BasePtr->getType()->isVectorTy()) { 4390 BasePtr = getSplatValue(BasePtr); 4391 if (!BasePtr) 4392 return false; 4393 } 4394 4395 unsigned FinalIndex = GEP->getNumOperands() - 1; 4396 Value *IndexVal = GEP->getOperand(FinalIndex); 4397 gep_type_iterator GTI = gep_type_begin(*GEP); 4398 4399 // Ensure all the other indices are 0. 4400 for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) { 4401 auto *C = dyn_cast<Constant>(GEP->getOperand(i)); 4402 if (!C) 4403 return false; 4404 if (isa<VectorType>(C->getType())) 4405 C = C->getSplatValue(); 4406 auto *CI = dyn_cast_or_null<ConstantInt>(C); 4407 if (!CI || !CI->isZero()) 4408 return false; 4409 } 4410 4411 // The operands of the GEP may be defined in another basic block. 4412 // In this case we'll not find nodes for the operands. 4413 if (!SDB->findValue(BasePtr)) 4414 return false; 4415 Constant *C = dyn_cast<Constant>(IndexVal); 4416 if (!C && !SDB->findValue(IndexVal)) 4417 return false; 4418 4419 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4420 const DataLayout &DL = DAG.getDataLayout(); 4421 StructType *STy = GTI.getStructTypeOrNull(); 4422 4423 if (STy) { 4424 const StructLayout *SL = DL.getStructLayout(STy); 4425 unsigned Field = cast<Constant>(IndexVal)->getUniqueInteger().getZExtValue(); 4426 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4427 Index = DAG.getConstant(SL->getElementOffset(Field), 4428 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4429 } else { 4430 Scale = DAG.getTargetConstant( 4431 DL.getTypeAllocSize(GEP->getResultElementType()), 4432 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4433 Index = SDB->getValue(IndexVal); 4434 } 4435 Base = SDB->getValue(BasePtr); 4436 IndexType = ISD::SIGNED_SCALED; 4437 4438 if (STy || !Index.getValueType().isVector()) { 4439 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4440 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4441 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4442 } 4443 return true; 4444 } 4445 4446 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4447 SDLoc sdl = getCurSDLoc(); 4448 4449 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4450 const Value *Ptr = I.getArgOperand(1); 4451 SDValue Src0 = getValue(I.getArgOperand(0)); 4452 SDValue Mask = getValue(I.getArgOperand(3)); 4453 EVT VT = Src0.getValueType(); 4454 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4455 if (!Alignment) 4456 Alignment = DAG.getEVTAlignment(VT); 4457 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4458 4459 AAMDNodes AAInfo; 4460 I.getAAMetadata(AAInfo); 4461 4462 SDValue Base; 4463 SDValue Index; 4464 ISD::MemIndexType IndexType; 4465 SDValue Scale; 4466 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this); 4467 4468 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4469 MachineMemOperand *MMO = DAG.getMachineFunction(). 4470 getMachineMemOperand(MachinePointerInfo(AS), 4471 MachineMemOperand::MOStore, 4472 // TODO: Make MachineMemOperands aware of scalable 4473 // vectors. 4474 MemoryLocation::UnknownSize, 4475 Alignment, AAInfo); 4476 if (!UniformBase) { 4477 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4478 Index = getValue(Ptr); 4479 IndexType = ISD::SIGNED_SCALED; 4480 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4481 } 4482 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4483 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4484 Ops, MMO, IndexType); 4485 DAG.setRoot(Scatter); 4486 setValue(&I, Scatter); 4487 } 4488 4489 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4490 SDLoc sdl = getCurSDLoc(); 4491 4492 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4493 unsigned& Alignment) { 4494 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4495 Ptr = I.getArgOperand(0); 4496 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4497 Mask = I.getArgOperand(2); 4498 Src0 = I.getArgOperand(3); 4499 }; 4500 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4501 unsigned& Alignment) { 4502 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4503 Ptr = I.getArgOperand(0); 4504 Alignment = 0; 4505 Mask = I.getArgOperand(1); 4506 Src0 = I.getArgOperand(2); 4507 }; 4508 4509 Value *PtrOperand, *MaskOperand, *Src0Operand; 4510 unsigned Alignment; 4511 if (IsExpanding) 4512 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4513 else 4514 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4515 4516 SDValue Ptr = getValue(PtrOperand); 4517 SDValue Src0 = getValue(Src0Operand); 4518 SDValue Mask = getValue(MaskOperand); 4519 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4520 4521 EVT VT = Src0.getValueType(); 4522 if (!Alignment) 4523 Alignment = DAG.getEVTAlignment(VT); 4524 4525 AAMDNodes AAInfo; 4526 I.getAAMetadata(AAInfo); 4527 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4528 4529 // Do not serialize masked loads of constant memory with anything. 4530 MemoryLocation ML; 4531 if (VT.isScalableVector()) 4532 ML = MemoryLocation(PtrOperand); 4533 else 4534 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4535 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4536 AAInfo); 4537 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4538 4539 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4540 4541 MachineMemOperand *MMO = 4542 DAG.getMachineFunction(). 4543 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4544 MachineMemOperand::MOLoad, 4545 // TODO: Make MachineMemOperands aware of scalable 4546 // vectors. 4547 VT.getStoreSize().getKnownMinSize(), 4548 Alignment, AAInfo, Ranges); 4549 4550 SDValue Load = 4551 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4552 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4553 if (AddToChain) 4554 PendingLoads.push_back(Load.getValue(1)); 4555 setValue(&I, Load); 4556 } 4557 4558 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4559 SDLoc sdl = getCurSDLoc(); 4560 4561 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4562 const Value *Ptr = I.getArgOperand(0); 4563 SDValue Src0 = getValue(I.getArgOperand(3)); 4564 SDValue Mask = getValue(I.getArgOperand(2)); 4565 4566 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4567 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4568 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4569 if (!Alignment) 4570 Alignment = DAG.getEVTAlignment(VT); 4571 4572 AAMDNodes AAInfo; 4573 I.getAAMetadata(AAInfo); 4574 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4575 4576 SDValue Root = DAG.getRoot(); 4577 SDValue Base; 4578 SDValue Index; 4579 ISD::MemIndexType IndexType; 4580 SDValue Scale; 4581 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this); 4582 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4583 MachineMemOperand *MMO = 4584 DAG.getMachineFunction(). 4585 getMachineMemOperand(MachinePointerInfo(AS), 4586 MachineMemOperand::MOLoad, 4587 // TODO: Make MachineMemOperands aware of scalable 4588 // vectors. 4589 MemoryLocation::UnknownSize, 4590 Alignment, AAInfo, Ranges); 4591 4592 if (!UniformBase) { 4593 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4594 Index = getValue(Ptr); 4595 IndexType = ISD::SIGNED_SCALED; 4596 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4597 } 4598 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4599 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4600 Ops, MMO, IndexType); 4601 4602 PendingLoads.push_back(Gather.getValue(1)); 4603 setValue(&I, Gather); 4604 } 4605 4606 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4607 SDLoc dl = getCurSDLoc(); 4608 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4609 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4610 SyncScope::ID SSID = I.getSyncScopeID(); 4611 4612 SDValue InChain = getRoot(); 4613 4614 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4615 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4616 4617 auto Alignment = DAG.getEVTAlignment(MemVT); 4618 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4619 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4620 4621 MachineFunction &MF = DAG.getMachineFunction(); 4622 MachineMemOperand *MMO = 4623 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4624 Flags, MemVT.getStoreSize(), Alignment, 4625 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4626 FailureOrdering); 4627 4628 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4629 dl, MemVT, VTs, InChain, 4630 getValue(I.getPointerOperand()), 4631 getValue(I.getCompareOperand()), 4632 getValue(I.getNewValOperand()), MMO); 4633 4634 SDValue OutChain = L.getValue(2); 4635 4636 setValue(&I, L); 4637 DAG.setRoot(OutChain); 4638 } 4639 4640 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4641 SDLoc dl = getCurSDLoc(); 4642 ISD::NodeType NT; 4643 switch (I.getOperation()) { 4644 default: llvm_unreachable("Unknown atomicrmw operation"); 4645 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4646 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4647 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4648 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4649 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4650 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4651 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4652 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4653 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4654 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4655 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4656 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4657 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4658 } 4659 AtomicOrdering Ordering = I.getOrdering(); 4660 SyncScope::ID SSID = I.getSyncScopeID(); 4661 4662 SDValue InChain = getRoot(); 4663 4664 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4665 auto Alignment = DAG.getEVTAlignment(MemVT); 4666 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4667 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4668 4669 MachineFunction &MF = DAG.getMachineFunction(); 4670 MachineMemOperand *MMO = 4671 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4672 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4673 nullptr, SSID, Ordering); 4674 4675 SDValue L = 4676 DAG.getAtomic(NT, dl, MemVT, InChain, 4677 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4678 MMO); 4679 4680 SDValue OutChain = L.getValue(1); 4681 4682 setValue(&I, L); 4683 DAG.setRoot(OutChain); 4684 } 4685 4686 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4687 SDLoc dl = getCurSDLoc(); 4688 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4689 SDValue Ops[3]; 4690 Ops[0] = getRoot(); 4691 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4692 TLI.getFenceOperandTy(DAG.getDataLayout())); 4693 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4694 TLI.getFenceOperandTy(DAG.getDataLayout())); 4695 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4696 } 4697 4698 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4699 SDLoc dl = getCurSDLoc(); 4700 AtomicOrdering Order = I.getOrdering(); 4701 SyncScope::ID SSID = I.getSyncScopeID(); 4702 4703 SDValue InChain = getRoot(); 4704 4705 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4706 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4707 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4708 4709 if (!TLI.supportsUnalignedAtomics() && 4710 I.getAlignment() < MemVT.getSizeInBits() / 8) 4711 report_fatal_error("Cannot generate unaligned atomic load"); 4712 4713 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4714 4715 MachineMemOperand *MMO = 4716 DAG.getMachineFunction(). 4717 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4718 Flags, MemVT.getStoreSize(), 4719 I.getAlignment() ? I.getAlignment() : 4720 DAG.getEVTAlignment(MemVT), 4721 AAMDNodes(), nullptr, SSID, Order); 4722 4723 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4724 4725 SDValue Ptr = getValue(I.getPointerOperand()); 4726 4727 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4728 // TODO: Once this is better exercised by tests, it should be merged with 4729 // the normal path for loads to prevent future divergence. 4730 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4731 if (MemVT != VT) 4732 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4733 4734 setValue(&I, L); 4735 SDValue OutChain = L.getValue(1); 4736 if (!I.isUnordered()) 4737 DAG.setRoot(OutChain); 4738 else 4739 PendingLoads.push_back(OutChain); 4740 return; 4741 } 4742 4743 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4744 Ptr, MMO); 4745 4746 SDValue OutChain = L.getValue(1); 4747 if (MemVT != VT) 4748 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4749 4750 setValue(&I, L); 4751 DAG.setRoot(OutChain); 4752 } 4753 4754 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4755 SDLoc dl = getCurSDLoc(); 4756 4757 AtomicOrdering Ordering = I.getOrdering(); 4758 SyncScope::ID SSID = I.getSyncScopeID(); 4759 4760 SDValue InChain = getRoot(); 4761 4762 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4763 EVT MemVT = 4764 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4765 4766 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4767 report_fatal_error("Cannot generate unaligned atomic store"); 4768 4769 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4770 4771 MachineFunction &MF = DAG.getMachineFunction(); 4772 MachineMemOperand *MMO = 4773 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4774 MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(), 4775 nullptr, SSID, Ordering); 4776 4777 SDValue Val = getValue(I.getValueOperand()); 4778 if (Val.getValueType() != MemVT) 4779 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4780 SDValue Ptr = getValue(I.getPointerOperand()); 4781 4782 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4783 // TODO: Once this is better exercised by tests, it should be merged with 4784 // the normal path for stores to prevent future divergence. 4785 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4786 DAG.setRoot(S); 4787 return; 4788 } 4789 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4790 Ptr, Val, MMO); 4791 4792 4793 DAG.setRoot(OutChain); 4794 } 4795 4796 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4797 /// node. 4798 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4799 unsigned Intrinsic) { 4800 // Ignore the callsite's attributes. A specific call site may be marked with 4801 // readnone, but the lowering code will expect the chain based on the 4802 // definition. 4803 const Function *F = I.getCalledFunction(); 4804 bool HasChain = !F->doesNotAccessMemory(); 4805 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4806 4807 // Build the operand list. 4808 SmallVector<SDValue, 8> Ops; 4809 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4810 if (OnlyLoad) { 4811 // We don't need to serialize loads against other loads. 4812 Ops.push_back(DAG.getRoot()); 4813 } else { 4814 Ops.push_back(getRoot()); 4815 } 4816 } 4817 4818 // Info is set by getTgtMemInstrinsic 4819 TargetLowering::IntrinsicInfo Info; 4820 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4821 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4822 DAG.getMachineFunction(), 4823 Intrinsic); 4824 4825 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4826 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4827 Info.opc == ISD::INTRINSIC_W_CHAIN) 4828 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4829 TLI.getPointerTy(DAG.getDataLayout()))); 4830 4831 // Add all operands of the call to the operand list. 4832 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4833 const Value *Arg = I.getArgOperand(i); 4834 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4835 Ops.push_back(getValue(Arg)); 4836 continue; 4837 } 4838 4839 // Use TargetConstant instead of a regular constant for immarg. 4840 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4841 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4842 assert(CI->getBitWidth() <= 64 && 4843 "large intrinsic immediates not handled"); 4844 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4845 } else { 4846 Ops.push_back( 4847 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4848 } 4849 } 4850 4851 SmallVector<EVT, 4> ValueVTs; 4852 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4853 4854 if (HasChain) 4855 ValueVTs.push_back(MVT::Other); 4856 4857 SDVTList VTs = DAG.getVTList(ValueVTs); 4858 4859 // Create the node. 4860 SDValue Result; 4861 if (IsTgtIntrinsic) { 4862 // This is target intrinsic that touches memory 4863 AAMDNodes AAInfo; 4864 I.getAAMetadata(AAInfo); 4865 Result = DAG.getMemIntrinsicNode( 4866 Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4867 MachinePointerInfo(Info.ptrVal, Info.offset), 4868 Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo); 4869 } else if (!HasChain) { 4870 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4871 } else if (!I.getType()->isVoidTy()) { 4872 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4873 } else { 4874 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4875 } 4876 4877 if (HasChain) { 4878 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4879 if (OnlyLoad) 4880 PendingLoads.push_back(Chain); 4881 else 4882 DAG.setRoot(Chain); 4883 } 4884 4885 if (!I.getType()->isVoidTy()) { 4886 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4887 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4888 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4889 } else 4890 Result = lowerRangeToAssertZExt(DAG, I, Result); 4891 4892 setValue(&I, Result); 4893 } 4894 } 4895 4896 /// GetSignificand - Get the significand and build it into a floating-point 4897 /// number with exponent of 1: 4898 /// 4899 /// Op = (Op & 0x007fffff) | 0x3f800000; 4900 /// 4901 /// where Op is the hexadecimal representation of floating point value. 4902 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4903 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4904 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4905 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4906 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4907 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4908 } 4909 4910 /// GetExponent - Get the exponent: 4911 /// 4912 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4913 /// 4914 /// where Op is the hexadecimal representation of floating point value. 4915 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4916 const TargetLowering &TLI, const SDLoc &dl) { 4917 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4918 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4919 SDValue t1 = DAG.getNode( 4920 ISD::SRL, dl, MVT::i32, t0, 4921 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4922 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4923 DAG.getConstant(127, dl, MVT::i32)); 4924 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4925 } 4926 4927 /// getF32Constant - Get 32-bit floating point constant. 4928 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4929 const SDLoc &dl) { 4930 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4931 MVT::f32); 4932 } 4933 4934 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4935 SelectionDAG &DAG) { 4936 // TODO: What fast-math-flags should be set on the floating-point nodes? 4937 4938 // IntegerPartOfX = ((int32_t)(t0); 4939 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4940 4941 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4942 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4943 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4944 4945 // IntegerPartOfX <<= 23; 4946 IntegerPartOfX = DAG.getNode( 4947 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4948 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4949 DAG.getDataLayout()))); 4950 4951 SDValue TwoToFractionalPartOfX; 4952 if (LimitFloatPrecision <= 6) { 4953 // For floating-point precision of 6: 4954 // 4955 // TwoToFractionalPartOfX = 4956 // 0.997535578f + 4957 // (0.735607626f + 0.252464424f * x) * x; 4958 // 4959 // error 0.0144103317, which is 6 bits 4960 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4961 getF32Constant(DAG, 0x3e814304, dl)); 4962 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4963 getF32Constant(DAG, 0x3f3c50c8, dl)); 4964 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4965 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4966 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4967 } else if (LimitFloatPrecision <= 12) { 4968 // For floating-point precision of 12: 4969 // 4970 // TwoToFractionalPartOfX = 4971 // 0.999892986f + 4972 // (0.696457318f + 4973 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4974 // 4975 // error 0.000107046256, which is 13 to 14 bits 4976 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4977 getF32Constant(DAG, 0x3da235e3, dl)); 4978 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4979 getF32Constant(DAG, 0x3e65b8f3, dl)); 4980 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4981 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4982 getF32Constant(DAG, 0x3f324b07, dl)); 4983 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4984 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4985 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4986 } else { // LimitFloatPrecision <= 18 4987 // For floating-point precision of 18: 4988 // 4989 // TwoToFractionalPartOfX = 4990 // 0.999999982f + 4991 // (0.693148872f + 4992 // (0.240227044f + 4993 // (0.554906021e-1f + 4994 // (0.961591928e-2f + 4995 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4996 // error 2.47208000*10^(-7), which is better than 18 bits 4997 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4998 getF32Constant(DAG, 0x3924b03e, dl)); 4999 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5000 getF32Constant(DAG, 0x3ab24b87, dl)); 5001 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5002 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5003 getF32Constant(DAG, 0x3c1d8c17, dl)); 5004 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5005 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5006 getF32Constant(DAG, 0x3d634a1d, dl)); 5007 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5008 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5009 getF32Constant(DAG, 0x3e75fe14, dl)); 5010 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5011 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5012 getF32Constant(DAG, 0x3f317234, dl)); 5013 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5014 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5015 getF32Constant(DAG, 0x3f800000, dl)); 5016 } 5017 5018 // Add the exponent into the result in integer domain. 5019 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5020 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5021 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5022 } 5023 5024 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5025 /// limited-precision mode. 5026 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5027 const TargetLowering &TLI) { 5028 if (Op.getValueType() == MVT::f32 && 5029 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5030 5031 // Put the exponent in the right bit position for later addition to the 5032 // final result: 5033 // 5034 // t0 = Op * log2(e) 5035 5036 // TODO: What fast-math-flags should be set here? 5037 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5038 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5039 return getLimitedPrecisionExp2(t0, dl, DAG); 5040 } 5041 5042 // No special expansion. 5043 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 5044 } 5045 5046 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5047 /// limited-precision mode. 5048 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5049 const TargetLowering &TLI) { 5050 // TODO: What fast-math-flags should be set on the floating-point nodes? 5051 5052 if (Op.getValueType() == MVT::f32 && 5053 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5054 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5055 5056 // Scale the exponent by log(2). 5057 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5058 SDValue LogOfExponent = 5059 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5060 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5061 5062 // Get the significand and build it into a floating-point number with 5063 // exponent of 1. 5064 SDValue X = GetSignificand(DAG, Op1, dl); 5065 5066 SDValue LogOfMantissa; 5067 if (LimitFloatPrecision <= 6) { 5068 // For floating-point precision of 6: 5069 // 5070 // LogofMantissa = 5071 // -1.1609546f + 5072 // (1.4034025f - 0.23903021f * x) * x; 5073 // 5074 // error 0.0034276066, which is better than 8 bits 5075 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5076 getF32Constant(DAG, 0xbe74c456, dl)); 5077 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5078 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5079 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5080 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5081 getF32Constant(DAG, 0x3f949a29, dl)); 5082 } else if (LimitFloatPrecision <= 12) { 5083 // For floating-point precision of 12: 5084 // 5085 // LogOfMantissa = 5086 // -1.7417939f + 5087 // (2.8212026f + 5088 // (-1.4699568f + 5089 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5090 // 5091 // error 0.000061011436, which is 14 bits 5092 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5093 getF32Constant(DAG, 0xbd67b6d6, dl)); 5094 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5095 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5096 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5097 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5098 getF32Constant(DAG, 0x3fbc278b, dl)); 5099 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5100 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5101 getF32Constant(DAG, 0x40348e95, dl)); 5102 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5103 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5104 getF32Constant(DAG, 0x3fdef31a, dl)); 5105 } else { // LimitFloatPrecision <= 18 5106 // For floating-point precision of 18: 5107 // 5108 // LogOfMantissa = 5109 // -2.1072184f + 5110 // (4.2372794f + 5111 // (-3.7029485f + 5112 // (2.2781945f + 5113 // (-0.87823314f + 5114 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5115 // 5116 // error 0.0000023660568, which is better than 18 bits 5117 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5118 getF32Constant(DAG, 0xbc91e5ac, dl)); 5119 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5120 getF32Constant(DAG, 0x3e4350aa, dl)); 5121 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5122 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5123 getF32Constant(DAG, 0x3f60d3e3, dl)); 5124 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5125 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5126 getF32Constant(DAG, 0x4011cdf0, dl)); 5127 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5128 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5129 getF32Constant(DAG, 0x406cfd1c, dl)); 5130 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5131 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5132 getF32Constant(DAG, 0x408797cb, dl)); 5133 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5134 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5135 getF32Constant(DAG, 0x4006dcab, dl)); 5136 } 5137 5138 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5139 } 5140 5141 // No special expansion. 5142 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5143 } 5144 5145 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5146 /// limited-precision mode. 5147 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5148 const TargetLowering &TLI) { 5149 // TODO: What fast-math-flags should be set on the floating-point nodes? 5150 5151 if (Op.getValueType() == MVT::f32 && 5152 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5153 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5154 5155 // Get the exponent. 5156 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5157 5158 // Get the significand and build it into a floating-point number with 5159 // exponent of 1. 5160 SDValue X = GetSignificand(DAG, Op1, dl); 5161 5162 // Different possible minimax approximations of significand in 5163 // floating-point for various degrees of accuracy over [1,2]. 5164 SDValue Log2ofMantissa; 5165 if (LimitFloatPrecision <= 6) { 5166 // For floating-point precision of 6: 5167 // 5168 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5169 // 5170 // error 0.0049451742, which is more than 7 bits 5171 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5172 getF32Constant(DAG, 0xbeb08fe0, dl)); 5173 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5174 getF32Constant(DAG, 0x40019463, dl)); 5175 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5176 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5177 getF32Constant(DAG, 0x3fd6633d, dl)); 5178 } else if (LimitFloatPrecision <= 12) { 5179 // For floating-point precision of 12: 5180 // 5181 // Log2ofMantissa = 5182 // -2.51285454f + 5183 // (4.07009056f + 5184 // (-2.12067489f + 5185 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5186 // 5187 // error 0.0000876136000, which is better than 13 bits 5188 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5189 getF32Constant(DAG, 0xbda7262e, dl)); 5190 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5191 getF32Constant(DAG, 0x3f25280b, dl)); 5192 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5193 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5194 getF32Constant(DAG, 0x4007b923, dl)); 5195 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5196 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5197 getF32Constant(DAG, 0x40823e2f, dl)); 5198 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5199 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5200 getF32Constant(DAG, 0x4020d29c, dl)); 5201 } else { // LimitFloatPrecision <= 18 5202 // For floating-point precision of 18: 5203 // 5204 // Log2ofMantissa = 5205 // -3.0400495f + 5206 // (6.1129976f + 5207 // (-5.3420409f + 5208 // (3.2865683f + 5209 // (-1.2669343f + 5210 // (0.27515199f - 5211 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5212 // 5213 // error 0.0000018516, which is better than 18 bits 5214 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5215 getF32Constant(DAG, 0xbcd2769e, dl)); 5216 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5217 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5218 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5219 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5220 getF32Constant(DAG, 0x3fa22ae7, dl)); 5221 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5222 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5223 getF32Constant(DAG, 0x40525723, dl)); 5224 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5225 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5226 getF32Constant(DAG, 0x40aaf200, dl)); 5227 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5228 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5229 getF32Constant(DAG, 0x40c39dad, dl)); 5230 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5231 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5232 getF32Constant(DAG, 0x4042902c, dl)); 5233 } 5234 5235 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5236 } 5237 5238 // No special expansion. 5239 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5240 } 5241 5242 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5243 /// limited-precision mode. 5244 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5245 const TargetLowering &TLI) { 5246 // TODO: What fast-math-flags should be set on the floating-point nodes? 5247 5248 if (Op.getValueType() == MVT::f32 && 5249 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5250 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5251 5252 // Scale the exponent by log10(2) [0.30102999f]. 5253 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5254 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5255 getF32Constant(DAG, 0x3e9a209a, dl)); 5256 5257 // Get the significand and build it into a floating-point number with 5258 // exponent of 1. 5259 SDValue X = GetSignificand(DAG, Op1, dl); 5260 5261 SDValue Log10ofMantissa; 5262 if (LimitFloatPrecision <= 6) { 5263 // For floating-point precision of 6: 5264 // 5265 // Log10ofMantissa = 5266 // -0.50419619f + 5267 // (0.60948995f - 0.10380950f * x) * x; 5268 // 5269 // error 0.0014886165, which is 6 bits 5270 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5271 getF32Constant(DAG, 0xbdd49a13, dl)); 5272 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5273 getF32Constant(DAG, 0x3f1c0789, dl)); 5274 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5275 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5276 getF32Constant(DAG, 0x3f011300, dl)); 5277 } else if (LimitFloatPrecision <= 12) { 5278 // For floating-point precision of 12: 5279 // 5280 // Log10ofMantissa = 5281 // -0.64831180f + 5282 // (0.91751397f + 5283 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5284 // 5285 // error 0.00019228036, which is better than 12 bits 5286 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5287 getF32Constant(DAG, 0x3d431f31, dl)); 5288 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5289 getF32Constant(DAG, 0x3ea21fb2, dl)); 5290 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5291 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5292 getF32Constant(DAG, 0x3f6ae232, dl)); 5293 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5294 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5295 getF32Constant(DAG, 0x3f25f7c3, dl)); 5296 } else { // LimitFloatPrecision <= 18 5297 // For floating-point precision of 18: 5298 // 5299 // Log10ofMantissa = 5300 // -0.84299375f + 5301 // (1.5327582f + 5302 // (-1.0688956f + 5303 // (0.49102474f + 5304 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5305 // 5306 // error 0.0000037995730, which is better than 18 bits 5307 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5308 getF32Constant(DAG, 0x3c5d51ce, dl)); 5309 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5310 getF32Constant(DAG, 0x3e00685a, dl)); 5311 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5312 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5313 getF32Constant(DAG, 0x3efb6798, dl)); 5314 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5315 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5316 getF32Constant(DAG, 0x3f88d192, dl)); 5317 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5318 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5319 getF32Constant(DAG, 0x3fc4316c, dl)); 5320 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5321 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5322 getF32Constant(DAG, 0x3f57ce70, dl)); 5323 } 5324 5325 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5326 } 5327 5328 // No special expansion. 5329 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5330 } 5331 5332 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5333 /// limited-precision mode. 5334 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5335 const TargetLowering &TLI) { 5336 if (Op.getValueType() == MVT::f32 && 5337 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5338 return getLimitedPrecisionExp2(Op, dl, DAG); 5339 5340 // No special expansion. 5341 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5342 } 5343 5344 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5345 /// limited-precision mode with x == 10.0f. 5346 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5347 SelectionDAG &DAG, const TargetLowering &TLI) { 5348 bool IsExp10 = false; 5349 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5350 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5351 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5352 APFloat Ten(10.0f); 5353 IsExp10 = LHSC->isExactlyValue(Ten); 5354 } 5355 } 5356 5357 // TODO: What fast-math-flags should be set on the FMUL node? 5358 if (IsExp10) { 5359 // Put the exponent in the right bit position for later addition to the 5360 // final result: 5361 // 5362 // #define LOG2OF10 3.3219281f 5363 // t0 = Op * LOG2OF10; 5364 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5365 getF32Constant(DAG, 0x40549a78, dl)); 5366 return getLimitedPrecisionExp2(t0, dl, DAG); 5367 } 5368 5369 // No special expansion. 5370 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5371 } 5372 5373 /// ExpandPowI - Expand a llvm.powi intrinsic. 5374 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5375 SelectionDAG &DAG) { 5376 // If RHS is a constant, we can expand this out to a multiplication tree, 5377 // otherwise we end up lowering to a call to __powidf2 (for example). When 5378 // optimizing for size, we only want to do this if the expansion would produce 5379 // a small number of multiplies, otherwise we do the full expansion. 5380 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5381 // Get the exponent as a positive value. 5382 unsigned Val = RHSC->getSExtValue(); 5383 if ((int)Val < 0) Val = -Val; 5384 5385 // powi(x, 0) -> 1.0 5386 if (Val == 0) 5387 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5388 5389 bool OptForSize = DAG.shouldOptForSize(); 5390 if (!OptForSize || 5391 // If optimizing for size, don't insert too many multiplies. 5392 // This inserts up to 5 multiplies. 5393 countPopulation(Val) + Log2_32(Val) < 7) { 5394 // We use the simple binary decomposition method to generate the multiply 5395 // sequence. There are more optimal ways to do this (for example, 5396 // powi(x,15) generates one more multiply than it should), but this has 5397 // the benefit of being both really simple and much better than a libcall. 5398 SDValue Res; // Logically starts equal to 1.0 5399 SDValue CurSquare = LHS; 5400 // TODO: Intrinsics should have fast-math-flags that propagate to these 5401 // nodes. 5402 while (Val) { 5403 if (Val & 1) { 5404 if (Res.getNode()) 5405 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5406 else 5407 Res = CurSquare; // 1.0*CurSquare. 5408 } 5409 5410 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5411 CurSquare, CurSquare); 5412 Val >>= 1; 5413 } 5414 5415 // If the original was negative, invert the result, producing 1/(x*x*x). 5416 if (RHSC->getSExtValue() < 0) 5417 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5418 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5419 return Res; 5420 } 5421 } 5422 5423 // Otherwise, expand to a libcall. 5424 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5425 } 5426 5427 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5428 SDValue LHS, SDValue RHS, SDValue Scale, 5429 SelectionDAG &DAG, const TargetLowering &TLI) { 5430 EVT VT = LHS.getValueType(); 5431 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5432 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5433 LLVMContext &Ctx = *DAG.getContext(); 5434 5435 // If the type is legal but the operation isn't, this node might survive all 5436 // the way to operation legalization. If we end up there and we do not have 5437 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5438 // node. 5439 5440 // Coax the legalizer into expanding the node during type legalization instead 5441 // by bumping the size by one bit. This will force it to Promote, enabling the 5442 // early expansion and avoiding the need to expand later. 5443 5444 // We don't have to do this if Scale is 0; that can always be expanded, unless 5445 // it's a saturating signed operation. Those can experience true integer 5446 // division overflow, a case which we must avoid. 5447 5448 // FIXME: We wouldn't have to do this (or any of the early 5449 // expansion/promotion) if it was possible to expand a libcall of an 5450 // illegal type during operation legalization. But it's not, so things 5451 // get a bit hacky. 5452 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5453 if ((ScaleInt > 0 || (Saturating && Signed)) && 5454 (TLI.isTypeLegal(VT) || 5455 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5456 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5457 Opcode, VT, ScaleInt); 5458 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5459 EVT PromVT; 5460 if (VT.isScalarInteger()) 5461 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5462 else if (VT.isVector()) { 5463 PromVT = VT.getVectorElementType(); 5464 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5465 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5466 } else 5467 llvm_unreachable("Wrong VT for DIVFIX?"); 5468 if (Signed) { 5469 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5470 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5471 } else { 5472 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5473 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5474 } 5475 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5476 // For saturating operations, we need to shift up the LHS to get the 5477 // proper saturation width, and then shift down again afterwards. 5478 if (Saturating) 5479 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5480 DAG.getConstant(1, DL, ShiftTy)); 5481 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5482 if (Saturating) 5483 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5484 DAG.getConstant(1, DL, ShiftTy)); 5485 return DAG.getZExtOrTrunc(Res, DL, VT); 5486 } 5487 } 5488 5489 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5490 } 5491 5492 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5493 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5494 static void 5495 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5496 const SDValue &N) { 5497 switch (N.getOpcode()) { 5498 case ISD::CopyFromReg: { 5499 SDValue Op = N.getOperand(1); 5500 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5501 Op.getValueType().getSizeInBits()); 5502 return; 5503 } 5504 case ISD::BITCAST: 5505 case ISD::AssertZext: 5506 case ISD::AssertSext: 5507 case ISD::TRUNCATE: 5508 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5509 return; 5510 case ISD::BUILD_PAIR: 5511 case ISD::BUILD_VECTOR: 5512 case ISD::CONCAT_VECTORS: 5513 for (SDValue Op : N->op_values()) 5514 getUnderlyingArgRegs(Regs, Op); 5515 return; 5516 default: 5517 return; 5518 } 5519 } 5520 5521 /// If the DbgValueInst is a dbg_value of a function argument, create the 5522 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5523 /// instruction selection, they will be inserted to the entry BB. 5524 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5525 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5526 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5527 const Argument *Arg = dyn_cast<Argument>(V); 5528 if (!Arg) 5529 return false; 5530 5531 if (!IsDbgDeclare) { 5532 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5533 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5534 // the entry block. 5535 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5536 if (!IsInEntryBlock) 5537 return false; 5538 5539 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5540 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5541 // variable that also is a param. 5542 // 5543 // Although, if we are at the top of the entry block already, we can still 5544 // emit using ArgDbgValue. This might catch some situations when the 5545 // dbg.value refers to an argument that isn't used in the entry block, so 5546 // any CopyToReg node would be optimized out and the only way to express 5547 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5548 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5549 // we should only emit as ArgDbgValue if the Variable is an argument to the 5550 // current function, and the dbg.value intrinsic is found in the entry 5551 // block. 5552 bool VariableIsFunctionInputArg = Variable->isParameter() && 5553 !DL->getInlinedAt(); 5554 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5555 if (!IsInPrologue && !VariableIsFunctionInputArg) 5556 return false; 5557 5558 // Here we assume that a function argument on IR level only can be used to 5559 // describe one input parameter on source level. If we for example have 5560 // source code like this 5561 // 5562 // struct A { long x, y; }; 5563 // void foo(struct A a, long b) { 5564 // ... 5565 // b = a.x; 5566 // ... 5567 // } 5568 // 5569 // and IR like this 5570 // 5571 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5572 // entry: 5573 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5574 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5575 // call void @llvm.dbg.value(metadata i32 %b, "b", 5576 // ... 5577 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5578 // ... 5579 // 5580 // then the last dbg.value is describing a parameter "b" using a value that 5581 // is an argument. But since we already has used %a1 to describe a parameter 5582 // we should not handle that last dbg.value here (that would result in an 5583 // incorrect hoisting of the DBG_VALUE to the function entry). 5584 // Notice that we allow one dbg.value per IR level argument, to accommodate 5585 // for the situation with fragments above. 5586 if (VariableIsFunctionInputArg) { 5587 unsigned ArgNo = Arg->getArgNo(); 5588 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5589 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5590 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5591 return false; 5592 FuncInfo.DescribedArgs.set(ArgNo); 5593 } 5594 } 5595 5596 MachineFunction &MF = DAG.getMachineFunction(); 5597 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5598 5599 bool IsIndirect = false; 5600 Optional<MachineOperand> Op; 5601 // Some arguments' frame index is recorded during argument lowering. 5602 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5603 if (FI != std::numeric_limits<int>::max()) 5604 Op = MachineOperand::CreateFI(FI); 5605 5606 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5607 if (!Op && N.getNode()) { 5608 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5609 Register Reg; 5610 if (ArgRegsAndSizes.size() == 1) 5611 Reg = ArgRegsAndSizes.front().first; 5612 5613 if (Reg && Reg.isVirtual()) { 5614 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5615 Register PR = RegInfo.getLiveInPhysReg(Reg); 5616 if (PR) 5617 Reg = PR; 5618 } 5619 if (Reg) { 5620 Op = MachineOperand::CreateReg(Reg, false); 5621 IsIndirect = IsDbgDeclare; 5622 } 5623 } 5624 5625 if (!Op && N.getNode()) { 5626 // Check if frame index is available. 5627 SDValue LCandidate = peekThroughBitcasts(N); 5628 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5629 if (FrameIndexSDNode *FINode = 5630 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5631 Op = MachineOperand::CreateFI(FINode->getIndex()); 5632 } 5633 5634 if (!Op) { 5635 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5636 auto splitMultiRegDbgValue 5637 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5638 unsigned Offset = 0; 5639 for (auto RegAndSize : SplitRegs) { 5640 // If the expression is already a fragment, the current register 5641 // offset+size might extend beyond the fragment. In this case, only 5642 // the register bits that are inside the fragment are relevant. 5643 int RegFragmentSizeInBits = RegAndSize.second; 5644 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5645 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5646 // The register is entirely outside the expression fragment, 5647 // so is irrelevant for debug info. 5648 if (Offset >= ExprFragmentSizeInBits) 5649 break; 5650 // The register is partially outside the expression fragment, only 5651 // the low bits within the fragment are relevant for debug info. 5652 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5653 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5654 } 5655 } 5656 5657 auto FragmentExpr = DIExpression::createFragmentExpression( 5658 Expr, Offset, RegFragmentSizeInBits); 5659 Offset += RegAndSize.second; 5660 // If a valid fragment expression cannot be created, the variable's 5661 // correct value cannot be determined and so it is set as Undef. 5662 if (!FragmentExpr) { 5663 SDDbgValue *SDV = DAG.getConstantDbgValue( 5664 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5665 DAG.AddDbgValue(SDV, nullptr, false); 5666 continue; 5667 } 5668 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5669 FuncInfo.ArgDbgValues.push_back( 5670 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5671 RegAndSize.first, Variable, *FragmentExpr)); 5672 } 5673 }; 5674 5675 // Check if ValueMap has reg number. 5676 DenseMap<const Value *, unsigned>::const_iterator 5677 VMI = FuncInfo.ValueMap.find(V); 5678 if (VMI != FuncInfo.ValueMap.end()) { 5679 const auto &TLI = DAG.getTargetLoweringInfo(); 5680 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5681 V->getType(), getABIRegCopyCC(V)); 5682 if (RFV.occupiesMultipleRegs()) { 5683 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5684 return true; 5685 } 5686 5687 Op = MachineOperand::CreateReg(VMI->second, false); 5688 IsIndirect = IsDbgDeclare; 5689 } else if (ArgRegsAndSizes.size() > 1) { 5690 // This was split due to the calling convention, and no virtual register 5691 // mapping exists for the value. 5692 splitMultiRegDbgValue(ArgRegsAndSizes); 5693 return true; 5694 } 5695 } 5696 5697 if (!Op) 5698 return false; 5699 5700 assert(Variable->isValidLocationForIntrinsic(DL) && 5701 "Expected inlined-at fields to agree"); 5702 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5703 FuncInfo.ArgDbgValues.push_back( 5704 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5705 *Op, Variable, Expr)); 5706 5707 return true; 5708 } 5709 5710 /// Return the appropriate SDDbgValue based on N. 5711 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5712 DILocalVariable *Variable, 5713 DIExpression *Expr, 5714 const DebugLoc &dl, 5715 unsigned DbgSDNodeOrder) { 5716 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5717 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5718 // stack slot locations. 5719 // 5720 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5721 // debug values here after optimization: 5722 // 5723 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5724 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5725 // 5726 // Both describe the direct values of their associated variables. 5727 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5728 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5729 } 5730 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5731 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5732 } 5733 5734 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5735 switch (Intrinsic) { 5736 case Intrinsic::smul_fix: 5737 return ISD::SMULFIX; 5738 case Intrinsic::umul_fix: 5739 return ISD::UMULFIX; 5740 case Intrinsic::smul_fix_sat: 5741 return ISD::SMULFIXSAT; 5742 case Intrinsic::umul_fix_sat: 5743 return ISD::UMULFIXSAT; 5744 case Intrinsic::sdiv_fix: 5745 return ISD::SDIVFIX; 5746 case Intrinsic::udiv_fix: 5747 return ISD::UDIVFIX; 5748 case Intrinsic::sdiv_fix_sat: 5749 return ISD::SDIVFIXSAT; 5750 case Intrinsic::udiv_fix_sat: 5751 return ISD::UDIVFIXSAT; 5752 default: 5753 llvm_unreachable("Unhandled fixed point intrinsic"); 5754 } 5755 } 5756 5757 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5758 const char *FunctionName) { 5759 assert(FunctionName && "FunctionName must not be nullptr"); 5760 SDValue Callee = DAG.getExternalSymbol( 5761 FunctionName, 5762 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5763 LowerCallTo(&I, Callee, I.isTailCall()); 5764 } 5765 5766 /// Lower the call to the specified intrinsic function. 5767 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5768 unsigned Intrinsic) { 5769 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5770 SDLoc sdl = getCurSDLoc(); 5771 DebugLoc dl = getCurDebugLoc(); 5772 SDValue Res; 5773 5774 switch (Intrinsic) { 5775 default: 5776 // By default, turn this into a target intrinsic node. 5777 visitTargetIntrinsic(I, Intrinsic); 5778 return; 5779 case Intrinsic::vscale: { 5780 match(&I, m_VScale(DAG.getDataLayout())); 5781 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5782 setValue(&I, 5783 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5784 return; 5785 } 5786 case Intrinsic::vastart: visitVAStart(I); return; 5787 case Intrinsic::vaend: visitVAEnd(I); return; 5788 case Intrinsic::vacopy: visitVACopy(I); return; 5789 case Intrinsic::returnaddress: 5790 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5791 TLI.getPointerTy(DAG.getDataLayout()), 5792 getValue(I.getArgOperand(0)))); 5793 return; 5794 case Intrinsic::addressofreturnaddress: 5795 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5796 TLI.getPointerTy(DAG.getDataLayout()))); 5797 return; 5798 case Intrinsic::sponentry: 5799 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5800 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5801 return; 5802 case Intrinsic::frameaddress: 5803 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5804 TLI.getFrameIndexTy(DAG.getDataLayout()), 5805 getValue(I.getArgOperand(0)))); 5806 return; 5807 case Intrinsic::read_register: { 5808 Value *Reg = I.getArgOperand(0); 5809 SDValue Chain = getRoot(); 5810 SDValue RegName = 5811 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5812 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5813 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5814 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5815 setValue(&I, Res); 5816 DAG.setRoot(Res.getValue(1)); 5817 return; 5818 } 5819 case Intrinsic::write_register: { 5820 Value *Reg = I.getArgOperand(0); 5821 Value *RegValue = I.getArgOperand(1); 5822 SDValue Chain = getRoot(); 5823 SDValue RegName = 5824 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5825 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5826 RegName, getValue(RegValue))); 5827 return; 5828 } 5829 case Intrinsic::memcpy: { 5830 const auto &MCI = cast<MemCpyInst>(I); 5831 SDValue Op1 = getValue(I.getArgOperand(0)); 5832 SDValue Op2 = getValue(I.getArgOperand(1)); 5833 SDValue Op3 = getValue(I.getArgOperand(2)); 5834 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5835 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5836 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5837 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5838 bool isVol = MCI.isVolatile(); 5839 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5840 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5841 // node. 5842 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5843 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5844 /* AlwaysInline */ false, isTC, 5845 MachinePointerInfo(I.getArgOperand(0)), 5846 MachinePointerInfo(I.getArgOperand(1))); 5847 updateDAGForMaybeTailCall(MC); 5848 return; 5849 } 5850 case Intrinsic::memcpy_inline: { 5851 const auto &MCI = cast<MemCpyInlineInst>(I); 5852 SDValue Dst = getValue(I.getArgOperand(0)); 5853 SDValue Src = getValue(I.getArgOperand(1)); 5854 SDValue Size = getValue(I.getArgOperand(2)); 5855 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5856 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5857 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5858 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5859 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5860 bool isVol = MCI.isVolatile(); 5861 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5862 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5863 // node. 5864 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5865 /* AlwaysInline */ true, isTC, 5866 MachinePointerInfo(I.getArgOperand(0)), 5867 MachinePointerInfo(I.getArgOperand(1))); 5868 updateDAGForMaybeTailCall(MC); 5869 return; 5870 } 5871 case Intrinsic::memset: { 5872 const auto &MSI = cast<MemSetInst>(I); 5873 SDValue Op1 = getValue(I.getArgOperand(0)); 5874 SDValue Op2 = getValue(I.getArgOperand(1)); 5875 SDValue Op3 = getValue(I.getArgOperand(2)); 5876 // @llvm.memset defines 0 and 1 to both mean no alignment. 5877 Align Alignment = MSI.getDestAlign().valueOrOne(); 5878 bool isVol = MSI.isVolatile(); 5879 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5880 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5881 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5882 MachinePointerInfo(I.getArgOperand(0))); 5883 updateDAGForMaybeTailCall(MS); 5884 return; 5885 } 5886 case Intrinsic::memmove: { 5887 const auto &MMI = cast<MemMoveInst>(I); 5888 SDValue Op1 = getValue(I.getArgOperand(0)); 5889 SDValue Op2 = getValue(I.getArgOperand(1)); 5890 SDValue Op3 = getValue(I.getArgOperand(2)); 5891 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5892 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5893 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5894 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5895 bool isVol = MMI.isVolatile(); 5896 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5897 // FIXME: Support passing different dest/src alignments to the memmove DAG 5898 // node. 5899 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5900 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5901 isTC, MachinePointerInfo(I.getArgOperand(0)), 5902 MachinePointerInfo(I.getArgOperand(1))); 5903 updateDAGForMaybeTailCall(MM); 5904 return; 5905 } 5906 case Intrinsic::memcpy_element_unordered_atomic: { 5907 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5908 SDValue Dst = getValue(MI.getRawDest()); 5909 SDValue Src = getValue(MI.getRawSource()); 5910 SDValue Length = getValue(MI.getLength()); 5911 5912 unsigned DstAlign = MI.getDestAlignment(); 5913 unsigned SrcAlign = MI.getSourceAlignment(); 5914 Type *LengthTy = MI.getLength()->getType(); 5915 unsigned ElemSz = MI.getElementSizeInBytes(); 5916 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5917 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5918 SrcAlign, Length, LengthTy, ElemSz, isTC, 5919 MachinePointerInfo(MI.getRawDest()), 5920 MachinePointerInfo(MI.getRawSource())); 5921 updateDAGForMaybeTailCall(MC); 5922 return; 5923 } 5924 case Intrinsic::memmove_element_unordered_atomic: { 5925 auto &MI = cast<AtomicMemMoveInst>(I); 5926 SDValue Dst = getValue(MI.getRawDest()); 5927 SDValue Src = getValue(MI.getRawSource()); 5928 SDValue Length = getValue(MI.getLength()); 5929 5930 unsigned DstAlign = MI.getDestAlignment(); 5931 unsigned SrcAlign = MI.getSourceAlignment(); 5932 Type *LengthTy = MI.getLength()->getType(); 5933 unsigned ElemSz = MI.getElementSizeInBytes(); 5934 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5935 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5936 SrcAlign, Length, LengthTy, ElemSz, isTC, 5937 MachinePointerInfo(MI.getRawDest()), 5938 MachinePointerInfo(MI.getRawSource())); 5939 updateDAGForMaybeTailCall(MC); 5940 return; 5941 } 5942 case Intrinsic::memset_element_unordered_atomic: { 5943 auto &MI = cast<AtomicMemSetInst>(I); 5944 SDValue Dst = getValue(MI.getRawDest()); 5945 SDValue Val = getValue(MI.getValue()); 5946 SDValue Length = getValue(MI.getLength()); 5947 5948 unsigned DstAlign = MI.getDestAlignment(); 5949 Type *LengthTy = MI.getLength()->getType(); 5950 unsigned ElemSz = MI.getElementSizeInBytes(); 5951 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5952 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5953 LengthTy, ElemSz, isTC, 5954 MachinePointerInfo(MI.getRawDest())); 5955 updateDAGForMaybeTailCall(MC); 5956 return; 5957 } 5958 case Intrinsic::dbg_addr: 5959 case Intrinsic::dbg_declare: { 5960 const auto &DI = cast<DbgVariableIntrinsic>(I); 5961 DILocalVariable *Variable = DI.getVariable(); 5962 DIExpression *Expression = DI.getExpression(); 5963 dropDanglingDebugInfo(Variable, Expression); 5964 assert(Variable && "Missing variable"); 5965 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5966 << "\n"); 5967 // Check if address has undef value. 5968 const Value *Address = DI.getVariableLocation(); 5969 if (!Address || isa<UndefValue>(Address) || 5970 (Address->use_empty() && !isa<Argument>(Address))) { 5971 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5972 << " (bad/undef/unused-arg address)\n"); 5973 return; 5974 } 5975 5976 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5977 5978 // Check if this variable can be described by a frame index, typically 5979 // either as a static alloca or a byval parameter. 5980 int FI = std::numeric_limits<int>::max(); 5981 if (const auto *AI = 5982 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5983 if (AI->isStaticAlloca()) { 5984 auto I = FuncInfo.StaticAllocaMap.find(AI); 5985 if (I != FuncInfo.StaticAllocaMap.end()) 5986 FI = I->second; 5987 } 5988 } else if (const auto *Arg = dyn_cast<Argument>( 5989 Address->stripInBoundsConstantOffsets())) { 5990 FI = FuncInfo.getArgumentFrameIndex(Arg); 5991 } 5992 5993 // llvm.dbg.addr is control dependent and always generates indirect 5994 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5995 // the MachineFunction variable table. 5996 if (FI != std::numeric_limits<int>::max()) { 5997 if (Intrinsic == Intrinsic::dbg_addr) { 5998 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5999 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 6000 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 6001 } else { 6002 LLVM_DEBUG(dbgs() << "Skipping " << DI 6003 << " (variable info stashed in MF side table)\n"); 6004 } 6005 return; 6006 } 6007 6008 SDValue &N = NodeMap[Address]; 6009 if (!N.getNode() && isa<Argument>(Address)) 6010 // Check unused arguments map. 6011 N = UnusedArgNodeMap[Address]; 6012 SDDbgValue *SDV; 6013 if (N.getNode()) { 6014 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6015 Address = BCI->getOperand(0); 6016 // Parameters are handled specially. 6017 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6018 if (isParameter && FINode) { 6019 // Byval parameter. We have a frame index at this point. 6020 SDV = 6021 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6022 /*IsIndirect*/ true, dl, SDNodeOrder); 6023 } else if (isa<Argument>(Address)) { 6024 // Address is an argument, so try to emit its dbg value using 6025 // virtual register info from the FuncInfo.ValueMap. 6026 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6027 return; 6028 } else { 6029 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6030 true, dl, SDNodeOrder); 6031 } 6032 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 6033 } else { 6034 // If Address is an argument then try to emit its dbg value using 6035 // virtual register info from the FuncInfo.ValueMap. 6036 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6037 N)) { 6038 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6039 << " (could not emit func-arg dbg_value)\n"); 6040 } 6041 } 6042 return; 6043 } 6044 case Intrinsic::dbg_label: { 6045 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6046 DILabel *Label = DI.getLabel(); 6047 assert(Label && "Missing label"); 6048 6049 SDDbgLabel *SDV; 6050 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6051 DAG.AddDbgLabel(SDV); 6052 return; 6053 } 6054 case Intrinsic::dbg_value: { 6055 const DbgValueInst &DI = cast<DbgValueInst>(I); 6056 assert(DI.getVariable() && "Missing variable"); 6057 6058 DILocalVariable *Variable = DI.getVariable(); 6059 DIExpression *Expression = DI.getExpression(); 6060 dropDanglingDebugInfo(Variable, Expression); 6061 const Value *V = DI.getValue(); 6062 if (!V) 6063 return; 6064 6065 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 6066 SDNodeOrder)) 6067 return; 6068 6069 // TODO: Dangling debug info will eventually either be resolved or produce 6070 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 6071 // between the original dbg.value location and its resolved DBG_VALUE, which 6072 // we should ideally fill with an extra Undef DBG_VALUE. 6073 6074 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 6075 return; 6076 } 6077 6078 case Intrinsic::eh_typeid_for: { 6079 // Find the type id for the given typeinfo. 6080 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6081 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6082 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6083 setValue(&I, Res); 6084 return; 6085 } 6086 6087 case Intrinsic::eh_return_i32: 6088 case Intrinsic::eh_return_i64: 6089 DAG.getMachineFunction().setCallsEHReturn(true); 6090 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6091 MVT::Other, 6092 getControlRoot(), 6093 getValue(I.getArgOperand(0)), 6094 getValue(I.getArgOperand(1)))); 6095 return; 6096 case Intrinsic::eh_unwind_init: 6097 DAG.getMachineFunction().setCallsUnwindInit(true); 6098 return; 6099 case Intrinsic::eh_dwarf_cfa: 6100 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6101 TLI.getPointerTy(DAG.getDataLayout()), 6102 getValue(I.getArgOperand(0)))); 6103 return; 6104 case Intrinsic::eh_sjlj_callsite: { 6105 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6106 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6107 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6108 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6109 6110 MMI.setCurrentCallSite(CI->getZExtValue()); 6111 return; 6112 } 6113 case Intrinsic::eh_sjlj_functioncontext: { 6114 // Get and store the index of the function context. 6115 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6116 AllocaInst *FnCtx = 6117 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6118 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6119 MFI.setFunctionContextIndex(FI); 6120 return; 6121 } 6122 case Intrinsic::eh_sjlj_setjmp: { 6123 SDValue Ops[2]; 6124 Ops[0] = getRoot(); 6125 Ops[1] = getValue(I.getArgOperand(0)); 6126 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6127 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6128 setValue(&I, Op.getValue(0)); 6129 DAG.setRoot(Op.getValue(1)); 6130 return; 6131 } 6132 case Intrinsic::eh_sjlj_longjmp: 6133 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6134 getRoot(), getValue(I.getArgOperand(0)))); 6135 return; 6136 case Intrinsic::eh_sjlj_setup_dispatch: 6137 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6138 getRoot())); 6139 return; 6140 case Intrinsic::masked_gather: 6141 visitMaskedGather(I); 6142 return; 6143 case Intrinsic::masked_load: 6144 visitMaskedLoad(I); 6145 return; 6146 case Intrinsic::masked_scatter: 6147 visitMaskedScatter(I); 6148 return; 6149 case Intrinsic::masked_store: 6150 visitMaskedStore(I); 6151 return; 6152 case Intrinsic::masked_expandload: 6153 visitMaskedLoad(I, true /* IsExpanding */); 6154 return; 6155 case Intrinsic::masked_compressstore: 6156 visitMaskedStore(I, true /* IsCompressing */); 6157 return; 6158 case Intrinsic::powi: 6159 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6160 getValue(I.getArgOperand(1)), DAG)); 6161 return; 6162 case Intrinsic::log: 6163 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6164 return; 6165 case Intrinsic::log2: 6166 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6167 return; 6168 case Intrinsic::log10: 6169 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6170 return; 6171 case Intrinsic::exp: 6172 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6173 return; 6174 case Intrinsic::exp2: 6175 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6176 return; 6177 case Intrinsic::pow: 6178 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6179 getValue(I.getArgOperand(1)), DAG, TLI)); 6180 return; 6181 case Intrinsic::sqrt: 6182 case Intrinsic::fabs: 6183 case Intrinsic::sin: 6184 case Intrinsic::cos: 6185 case Intrinsic::floor: 6186 case Intrinsic::ceil: 6187 case Intrinsic::trunc: 6188 case Intrinsic::rint: 6189 case Intrinsic::nearbyint: 6190 case Intrinsic::round: 6191 case Intrinsic::canonicalize: { 6192 unsigned Opcode; 6193 switch (Intrinsic) { 6194 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6195 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6196 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6197 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6198 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6199 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6200 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6201 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6202 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6203 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6204 case Intrinsic::round: Opcode = ISD::FROUND; break; 6205 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6206 } 6207 6208 setValue(&I, DAG.getNode(Opcode, sdl, 6209 getValue(I.getArgOperand(0)).getValueType(), 6210 getValue(I.getArgOperand(0)))); 6211 return; 6212 } 6213 case Intrinsic::lround: 6214 case Intrinsic::llround: 6215 case Intrinsic::lrint: 6216 case Intrinsic::llrint: { 6217 unsigned Opcode; 6218 switch (Intrinsic) { 6219 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6220 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6221 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6222 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6223 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6224 } 6225 6226 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6227 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6228 getValue(I.getArgOperand(0)))); 6229 return; 6230 } 6231 case Intrinsic::minnum: 6232 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6233 getValue(I.getArgOperand(0)).getValueType(), 6234 getValue(I.getArgOperand(0)), 6235 getValue(I.getArgOperand(1)))); 6236 return; 6237 case Intrinsic::maxnum: 6238 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6239 getValue(I.getArgOperand(0)).getValueType(), 6240 getValue(I.getArgOperand(0)), 6241 getValue(I.getArgOperand(1)))); 6242 return; 6243 case Intrinsic::minimum: 6244 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6245 getValue(I.getArgOperand(0)).getValueType(), 6246 getValue(I.getArgOperand(0)), 6247 getValue(I.getArgOperand(1)))); 6248 return; 6249 case Intrinsic::maximum: 6250 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6251 getValue(I.getArgOperand(0)).getValueType(), 6252 getValue(I.getArgOperand(0)), 6253 getValue(I.getArgOperand(1)))); 6254 return; 6255 case Intrinsic::copysign: 6256 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6257 getValue(I.getArgOperand(0)).getValueType(), 6258 getValue(I.getArgOperand(0)), 6259 getValue(I.getArgOperand(1)))); 6260 return; 6261 case Intrinsic::fma: 6262 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6263 getValue(I.getArgOperand(0)).getValueType(), 6264 getValue(I.getArgOperand(0)), 6265 getValue(I.getArgOperand(1)), 6266 getValue(I.getArgOperand(2)))); 6267 return; 6268 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6269 case Intrinsic::INTRINSIC: 6270 #include "llvm/IR/ConstrainedOps.def" 6271 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(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)))); 6282 } else { 6283 // TODO: Intrinsic calls should have fast-math-flags. 6284 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6285 getValue(I.getArgOperand(0)).getValueType(), 6286 getValue(I.getArgOperand(0)), 6287 getValue(I.getArgOperand(1))); 6288 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6289 getValue(I.getArgOperand(0)).getValueType(), 6290 Mul, 6291 getValue(I.getArgOperand(2))); 6292 setValue(&I, Add); 6293 } 6294 return; 6295 } 6296 case Intrinsic::convert_to_fp16: 6297 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6298 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6299 getValue(I.getArgOperand(0)), 6300 DAG.getTargetConstant(0, sdl, 6301 MVT::i32)))); 6302 return; 6303 case Intrinsic::convert_from_fp16: 6304 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6305 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6306 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6307 getValue(I.getArgOperand(0))))); 6308 return; 6309 case Intrinsic::pcmarker: { 6310 SDValue Tmp = getValue(I.getArgOperand(0)); 6311 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6312 return; 6313 } 6314 case Intrinsic::readcyclecounter: { 6315 SDValue Op = getRoot(); 6316 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6317 DAG.getVTList(MVT::i64, MVT::Other), Op); 6318 setValue(&I, Res); 6319 DAG.setRoot(Res.getValue(1)); 6320 return; 6321 } 6322 case Intrinsic::bitreverse: 6323 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6324 getValue(I.getArgOperand(0)).getValueType(), 6325 getValue(I.getArgOperand(0)))); 6326 return; 6327 case Intrinsic::bswap: 6328 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6329 getValue(I.getArgOperand(0)).getValueType(), 6330 getValue(I.getArgOperand(0)))); 6331 return; 6332 case Intrinsic::cttz: { 6333 SDValue Arg = getValue(I.getArgOperand(0)); 6334 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6335 EVT Ty = Arg.getValueType(); 6336 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6337 sdl, Ty, Arg)); 6338 return; 6339 } 6340 case Intrinsic::ctlz: { 6341 SDValue Arg = getValue(I.getArgOperand(0)); 6342 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6343 EVT Ty = Arg.getValueType(); 6344 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6345 sdl, Ty, Arg)); 6346 return; 6347 } 6348 case Intrinsic::ctpop: { 6349 SDValue Arg = getValue(I.getArgOperand(0)); 6350 EVT Ty = Arg.getValueType(); 6351 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6352 return; 6353 } 6354 case Intrinsic::fshl: 6355 case Intrinsic::fshr: { 6356 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6357 SDValue X = getValue(I.getArgOperand(0)); 6358 SDValue Y = getValue(I.getArgOperand(1)); 6359 SDValue Z = getValue(I.getArgOperand(2)); 6360 EVT VT = X.getValueType(); 6361 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6362 SDValue Zero = DAG.getConstant(0, sdl, VT); 6363 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6364 6365 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6366 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6367 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6368 return; 6369 } 6370 6371 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6372 // avoid the select that is necessary in the general case to filter out 6373 // the 0-shift possibility that leads to UB. 6374 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6375 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6376 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6377 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6378 return; 6379 } 6380 6381 // Some targets only rotate one way. Try the opposite direction. 6382 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6383 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6384 // Negate the shift amount because it is safe to ignore the high bits. 6385 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6386 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6387 return; 6388 } 6389 6390 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6391 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6392 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6393 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6394 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6395 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6396 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6397 return; 6398 } 6399 6400 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6401 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6402 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6403 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6404 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6405 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6406 6407 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6408 // and that is undefined. We must compare and select to avoid UB. 6409 EVT CCVT = MVT::i1; 6410 if (VT.isVector()) 6411 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6412 6413 // For fshl, 0-shift returns the 1st arg (X). 6414 // For fshr, 0-shift returns the 2nd arg (Y). 6415 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6416 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6417 return; 6418 } 6419 case Intrinsic::sadd_sat: { 6420 SDValue Op1 = getValue(I.getArgOperand(0)); 6421 SDValue Op2 = getValue(I.getArgOperand(1)); 6422 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6423 return; 6424 } 6425 case Intrinsic::uadd_sat: { 6426 SDValue Op1 = getValue(I.getArgOperand(0)); 6427 SDValue Op2 = getValue(I.getArgOperand(1)); 6428 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6429 return; 6430 } 6431 case Intrinsic::ssub_sat: { 6432 SDValue Op1 = getValue(I.getArgOperand(0)); 6433 SDValue Op2 = getValue(I.getArgOperand(1)); 6434 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6435 return; 6436 } 6437 case Intrinsic::usub_sat: { 6438 SDValue Op1 = getValue(I.getArgOperand(0)); 6439 SDValue Op2 = getValue(I.getArgOperand(1)); 6440 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6441 return; 6442 } 6443 case Intrinsic::smul_fix: 6444 case Intrinsic::umul_fix: 6445 case Intrinsic::smul_fix_sat: 6446 case Intrinsic::umul_fix_sat: { 6447 SDValue Op1 = getValue(I.getArgOperand(0)); 6448 SDValue Op2 = getValue(I.getArgOperand(1)); 6449 SDValue Op3 = getValue(I.getArgOperand(2)); 6450 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6451 Op1.getValueType(), Op1, Op2, Op3)); 6452 return; 6453 } 6454 case Intrinsic::sdiv_fix: 6455 case Intrinsic::udiv_fix: 6456 case Intrinsic::sdiv_fix_sat: 6457 case Intrinsic::udiv_fix_sat: { 6458 SDValue Op1 = getValue(I.getArgOperand(0)); 6459 SDValue Op2 = getValue(I.getArgOperand(1)); 6460 SDValue Op3 = getValue(I.getArgOperand(2)); 6461 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6462 Op1, Op2, Op3, DAG, TLI)); 6463 return; 6464 } 6465 case Intrinsic::stacksave: { 6466 SDValue Op = getRoot(); 6467 Res = DAG.getNode( 6468 ISD::STACKSAVE, sdl, 6469 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6470 setValue(&I, Res); 6471 DAG.setRoot(Res.getValue(1)); 6472 return; 6473 } 6474 case Intrinsic::stackrestore: 6475 Res = getValue(I.getArgOperand(0)); 6476 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6477 return; 6478 case Intrinsic::get_dynamic_area_offset: { 6479 SDValue Op = getRoot(); 6480 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6481 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6482 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6483 // target. 6484 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6485 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6486 " intrinsic!"); 6487 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6488 Op); 6489 DAG.setRoot(Op); 6490 setValue(&I, Res); 6491 return; 6492 } 6493 case Intrinsic::stackguard: { 6494 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6495 MachineFunction &MF = DAG.getMachineFunction(); 6496 const Module &M = *MF.getFunction().getParent(); 6497 SDValue Chain = getRoot(); 6498 if (TLI.useLoadStackGuardNode()) { 6499 Res = getLoadStackGuard(DAG, sdl, Chain); 6500 } else { 6501 const Value *Global = TLI.getSDagStackGuard(M); 6502 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6503 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6504 MachinePointerInfo(Global, 0), Align, 6505 MachineMemOperand::MOVolatile); 6506 } 6507 if (TLI.useStackGuardXorFP()) 6508 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6509 DAG.setRoot(Chain); 6510 setValue(&I, Res); 6511 return; 6512 } 6513 case Intrinsic::stackprotector: { 6514 // Emit code into the DAG to store the stack guard onto the stack. 6515 MachineFunction &MF = DAG.getMachineFunction(); 6516 MachineFrameInfo &MFI = MF.getFrameInfo(); 6517 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6518 SDValue Src, Chain = getRoot(); 6519 6520 if (TLI.useLoadStackGuardNode()) 6521 Src = getLoadStackGuard(DAG, sdl, Chain); 6522 else 6523 Src = getValue(I.getArgOperand(0)); // The guard's value. 6524 6525 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6526 6527 int FI = FuncInfo.StaticAllocaMap[Slot]; 6528 MFI.setStackProtectorIndex(FI); 6529 6530 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6531 6532 // Store the stack protector onto the stack. 6533 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6534 DAG.getMachineFunction(), FI), 6535 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6536 setValue(&I, Res); 6537 DAG.setRoot(Res); 6538 return; 6539 } 6540 case Intrinsic::objectsize: 6541 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6542 6543 case Intrinsic::is_constant: 6544 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6545 6546 case Intrinsic::annotation: 6547 case Intrinsic::ptr_annotation: 6548 case Intrinsic::launder_invariant_group: 6549 case Intrinsic::strip_invariant_group: 6550 // Drop the intrinsic, but forward the value 6551 setValue(&I, getValue(I.getOperand(0))); 6552 return; 6553 case Intrinsic::assume: 6554 case Intrinsic::var_annotation: 6555 case Intrinsic::sideeffect: 6556 // Discard annotate attributes, assumptions, and artificial side-effects. 6557 return; 6558 6559 case Intrinsic::codeview_annotation: { 6560 // Emit a label associated with this metadata. 6561 MachineFunction &MF = DAG.getMachineFunction(); 6562 MCSymbol *Label = 6563 MF.getMMI().getContext().createTempSymbol("annotation", true); 6564 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6565 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6566 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6567 DAG.setRoot(Res); 6568 return; 6569 } 6570 6571 case Intrinsic::init_trampoline: { 6572 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6573 6574 SDValue Ops[6]; 6575 Ops[0] = getRoot(); 6576 Ops[1] = getValue(I.getArgOperand(0)); 6577 Ops[2] = getValue(I.getArgOperand(1)); 6578 Ops[3] = getValue(I.getArgOperand(2)); 6579 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6580 Ops[5] = DAG.getSrcValue(F); 6581 6582 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6583 6584 DAG.setRoot(Res); 6585 return; 6586 } 6587 case Intrinsic::adjust_trampoline: 6588 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6589 TLI.getPointerTy(DAG.getDataLayout()), 6590 getValue(I.getArgOperand(0)))); 6591 return; 6592 case Intrinsic::gcroot: { 6593 assert(DAG.getMachineFunction().getFunction().hasGC() && 6594 "only valid in functions with gc specified, enforced by Verifier"); 6595 assert(GFI && "implied by previous"); 6596 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6597 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6598 6599 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6600 GFI->addStackRoot(FI->getIndex(), TypeMap); 6601 return; 6602 } 6603 case Intrinsic::gcread: 6604 case Intrinsic::gcwrite: 6605 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6606 case Intrinsic::flt_rounds: 6607 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6608 setValue(&I, Res); 6609 DAG.setRoot(Res.getValue(1)); 6610 return; 6611 6612 case Intrinsic::expect: 6613 // Just replace __builtin_expect(exp, c) with EXP. 6614 setValue(&I, getValue(I.getArgOperand(0))); 6615 return; 6616 6617 case Intrinsic::debugtrap: 6618 case Intrinsic::trap: { 6619 StringRef TrapFuncName = 6620 I.getAttributes() 6621 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6622 .getValueAsString(); 6623 if (TrapFuncName.empty()) { 6624 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6625 ISD::TRAP : ISD::DEBUGTRAP; 6626 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6627 return; 6628 } 6629 TargetLowering::ArgListTy Args; 6630 6631 TargetLowering::CallLoweringInfo CLI(DAG); 6632 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6633 CallingConv::C, I.getType(), 6634 DAG.getExternalSymbol(TrapFuncName.data(), 6635 TLI.getPointerTy(DAG.getDataLayout())), 6636 std::move(Args)); 6637 6638 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6639 DAG.setRoot(Result.second); 6640 return; 6641 } 6642 6643 case Intrinsic::uadd_with_overflow: 6644 case Intrinsic::sadd_with_overflow: 6645 case Intrinsic::usub_with_overflow: 6646 case Intrinsic::ssub_with_overflow: 6647 case Intrinsic::umul_with_overflow: 6648 case Intrinsic::smul_with_overflow: { 6649 ISD::NodeType Op; 6650 switch (Intrinsic) { 6651 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6652 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6653 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6654 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6655 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6656 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6657 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6658 } 6659 SDValue Op1 = getValue(I.getArgOperand(0)); 6660 SDValue Op2 = getValue(I.getArgOperand(1)); 6661 6662 EVT ResultVT = Op1.getValueType(); 6663 EVT OverflowVT = MVT::i1; 6664 if (ResultVT.isVector()) 6665 OverflowVT = EVT::getVectorVT( 6666 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6667 6668 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6669 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6670 return; 6671 } 6672 case Intrinsic::prefetch: { 6673 SDValue Ops[5]; 6674 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6675 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6676 Ops[0] = DAG.getRoot(); 6677 Ops[1] = getValue(I.getArgOperand(0)); 6678 Ops[2] = getValue(I.getArgOperand(1)); 6679 Ops[3] = getValue(I.getArgOperand(2)); 6680 Ops[4] = getValue(I.getArgOperand(3)); 6681 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6682 DAG.getVTList(MVT::Other), Ops, 6683 EVT::getIntegerVT(*Context, 8), 6684 MachinePointerInfo(I.getArgOperand(0)), 6685 0, /* align */ 6686 Flags); 6687 6688 // Chain the prefetch in parallell with any pending loads, to stay out of 6689 // the way of later optimizations. 6690 PendingLoads.push_back(Result); 6691 Result = getRoot(); 6692 DAG.setRoot(Result); 6693 return; 6694 } 6695 case Intrinsic::lifetime_start: 6696 case Intrinsic::lifetime_end: { 6697 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6698 // Stack coloring is not enabled in O0, discard region information. 6699 if (TM.getOptLevel() == CodeGenOpt::None) 6700 return; 6701 6702 const int64_t ObjectSize = 6703 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6704 Value *const ObjectPtr = I.getArgOperand(1); 6705 SmallVector<const Value *, 4> Allocas; 6706 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6707 6708 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6709 E = Allocas.end(); Object != E; ++Object) { 6710 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6711 6712 // Could not find an Alloca. 6713 if (!LifetimeObject) 6714 continue; 6715 6716 // First check that the Alloca is static, otherwise it won't have a 6717 // valid frame index. 6718 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6719 if (SI == FuncInfo.StaticAllocaMap.end()) 6720 return; 6721 6722 const int FrameIndex = SI->second; 6723 int64_t Offset; 6724 if (GetPointerBaseWithConstantOffset( 6725 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6726 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6727 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6728 Offset); 6729 DAG.setRoot(Res); 6730 } 6731 return; 6732 } 6733 case Intrinsic::invariant_start: 6734 // Discard region information. 6735 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6736 return; 6737 case Intrinsic::invariant_end: 6738 // Discard region information. 6739 return; 6740 case Intrinsic::clear_cache: 6741 /// FunctionName may be null. 6742 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6743 lowerCallToExternalSymbol(I, FunctionName); 6744 return; 6745 case Intrinsic::donothing: 6746 // ignore 6747 return; 6748 case Intrinsic::experimental_stackmap: 6749 visitStackmap(I); 6750 return; 6751 case Intrinsic::experimental_patchpoint_void: 6752 case Intrinsic::experimental_patchpoint_i64: 6753 visitPatchpoint(&I); 6754 return; 6755 case Intrinsic::experimental_gc_statepoint: 6756 LowerStatepoint(ImmutableStatepoint(&I)); 6757 return; 6758 case Intrinsic::experimental_gc_result: 6759 visitGCResult(cast<GCResultInst>(I)); 6760 return; 6761 case Intrinsic::experimental_gc_relocate: 6762 visitGCRelocate(cast<GCRelocateInst>(I)); 6763 return; 6764 case Intrinsic::instrprof_increment: 6765 llvm_unreachable("instrprof failed to lower an increment"); 6766 case Intrinsic::instrprof_value_profile: 6767 llvm_unreachable("instrprof failed to lower a value profiling call"); 6768 case Intrinsic::localescape: { 6769 MachineFunction &MF = DAG.getMachineFunction(); 6770 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6771 6772 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6773 // is the same on all targets. 6774 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6775 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6776 if (isa<ConstantPointerNull>(Arg)) 6777 continue; // Skip null pointers. They represent a hole in index space. 6778 AllocaInst *Slot = cast<AllocaInst>(Arg); 6779 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6780 "can only escape static allocas"); 6781 int FI = FuncInfo.StaticAllocaMap[Slot]; 6782 MCSymbol *FrameAllocSym = 6783 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6784 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6785 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6786 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6787 .addSym(FrameAllocSym) 6788 .addFrameIndex(FI); 6789 } 6790 6791 return; 6792 } 6793 6794 case Intrinsic::localrecover: { 6795 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6796 MachineFunction &MF = DAG.getMachineFunction(); 6797 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6798 6799 // Get the symbol that defines the frame offset. 6800 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6801 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6802 unsigned IdxVal = 6803 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6804 MCSymbol *FrameAllocSym = 6805 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6806 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6807 6808 // Create a MCSymbol for the label to avoid any target lowering 6809 // that would make this PC relative. 6810 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6811 SDValue OffsetVal = 6812 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6813 6814 // Add the offset to the FP. 6815 Value *FP = I.getArgOperand(1); 6816 SDValue FPVal = getValue(FP); 6817 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6818 setValue(&I, Add); 6819 6820 return; 6821 } 6822 6823 case Intrinsic::eh_exceptionpointer: 6824 case Intrinsic::eh_exceptioncode: { 6825 // Get the exception pointer vreg, copy from it, and resize it to fit. 6826 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6827 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6828 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6829 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6830 SDValue N = 6831 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6832 if (Intrinsic == Intrinsic::eh_exceptioncode) 6833 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6834 setValue(&I, N); 6835 return; 6836 } 6837 case Intrinsic::xray_customevent: { 6838 // Here we want to make sure that the intrinsic behaves as if it has a 6839 // specific calling convention, and only for x86_64. 6840 // FIXME: Support other platforms later. 6841 const auto &Triple = DAG.getTarget().getTargetTriple(); 6842 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6843 return; 6844 6845 SDLoc DL = getCurSDLoc(); 6846 SmallVector<SDValue, 8> Ops; 6847 6848 // We want to say that we always want the arguments in registers. 6849 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6850 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6851 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6852 SDValue Chain = getRoot(); 6853 Ops.push_back(LogEntryVal); 6854 Ops.push_back(StrSizeVal); 6855 Ops.push_back(Chain); 6856 6857 // We need to enforce the calling convention for the callsite, so that 6858 // argument ordering is enforced correctly, and that register allocation can 6859 // see that some registers may be assumed clobbered and have to preserve 6860 // them across calls to the intrinsic. 6861 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6862 DL, NodeTys, Ops); 6863 SDValue patchableNode = SDValue(MN, 0); 6864 DAG.setRoot(patchableNode); 6865 setValue(&I, patchableNode); 6866 return; 6867 } 6868 case Intrinsic::xray_typedevent: { 6869 // Here we want to make sure that the intrinsic behaves as if it has a 6870 // specific calling convention, and only for x86_64. 6871 // FIXME: Support other platforms later. 6872 const auto &Triple = DAG.getTarget().getTargetTriple(); 6873 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6874 return; 6875 6876 SDLoc DL = getCurSDLoc(); 6877 SmallVector<SDValue, 8> Ops; 6878 6879 // We want to say that we always want the arguments in registers. 6880 // It's unclear to me how manipulating the selection DAG here forces callers 6881 // to provide arguments in registers instead of on the stack. 6882 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6883 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6884 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6885 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6886 SDValue Chain = getRoot(); 6887 Ops.push_back(LogTypeId); 6888 Ops.push_back(LogEntryVal); 6889 Ops.push_back(StrSizeVal); 6890 Ops.push_back(Chain); 6891 6892 // We need to enforce the calling convention for the callsite, so that 6893 // argument ordering is enforced correctly, and that register allocation can 6894 // see that some registers may be assumed clobbered and have to preserve 6895 // them across calls to the intrinsic. 6896 MachineSDNode *MN = DAG.getMachineNode( 6897 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6898 SDValue patchableNode = SDValue(MN, 0); 6899 DAG.setRoot(patchableNode); 6900 setValue(&I, patchableNode); 6901 return; 6902 } 6903 case Intrinsic::experimental_deoptimize: 6904 LowerDeoptimizeCall(&I); 6905 return; 6906 6907 case Intrinsic::experimental_vector_reduce_v2_fadd: 6908 case Intrinsic::experimental_vector_reduce_v2_fmul: 6909 case Intrinsic::experimental_vector_reduce_add: 6910 case Intrinsic::experimental_vector_reduce_mul: 6911 case Intrinsic::experimental_vector_reduce_and: 6912 case Intrinsic::experimental_vector_reduce_or: 6913 case Intrinsic::experimental_vector_reduce_xor: 6914 case Intrinsic::experimental_vector_reduce_smax: 6915 case Intrinsic::experimental_vector_reduce_smin: 6916 case Intrinsic::experimental_vector_reduce_umax: 6917 case Intrinsic::experimental_vector_reduce_umin: 6918 case Intrinsic::experimental_vector_reduce_fmax: 6919 case Intrinsic::experimental_vector_reduce_fmin: 6920 visitVectorReduce(I, Intrinsic); 6921 return; 6922 6923 case Intrinsic::icall_branch_funnel: { 6924 SmallVector<SDValue, 16> Ops; 6925 Ops.push_back(getValue(I.getArgOperand(0))); 6926 6927 int64_t Offset; 6928 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6929 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6930 if (!Base) 6931 report_fatal_error( 6932 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6933 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6934 6935 struct BranchFunnelTarget { 6936 int64_t Offset; 6937 SDValue Target; 6938 }; 6939 SmallVector<BranchFunnelTarget, 8> Targets; 6940 6941 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6942 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6943 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6944 if (ElemBase != Base) 6945 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6946 "to the same GlobalValue"); 6947 6948 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6949 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6950 if (!GA) 6951 report_fatal_error( 6952 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6953 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6954 GA->getGlobal(), getCurSDLoc(), 6955 Val.getValueType(), GA->getOffset())}); 6956 } 6957 llvm::sort(Targets, 6958 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6959 return T1.Offset < T2.Offset; 6960 }); 6961 6962 for (auto &T : Targets) { 6963 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6964 Ops.push_back(T.Target); 6965 } 6966 6967 Ops.push_back(DAG.getRoot()); // Chain 6968 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6969 getCurSDLoc(), MVT::Other, Ops), 6970 0); 6971 DAG.setRoot(N); 6972 setValue(&I, N); 6973 HasTailCall = true; 6974 return; 6975 } 6976 6977 case Intrinsic::wasm_landingpad_index: 6978 // Information this intrinsic contained has been transferred to 6979 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6980 // delete it now. 6981 return; 6982 6983 case Intrinsic::aarch64_settag: 6984 case Intrinsic::aarch64_settag_zero: { 6985 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6986 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6987 SDValue Val = TSI.EmitTargetCodeForSetTag( 6988 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6989 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6990 ZeroMemory); 6991 DAG.setRoot(Val); 6992 setValue(&I, Val); 6993 return; 6994 } 6995 case Intrinsic::ptrmask: { 6996 SDValue Ptr = getValue(I.getOperand(0)); 6997 SDValue Const = getValue(I.getOperand(1)); 6998 6999 EVT DestVT = 7000 EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7001 7002 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr, 7003 DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT))); 7004 return; 7005 } 7006 } 7007 } 7008 7009 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7010 const ConstrainedFPIntrinsic &FPI) { 7011 SDLoc sdl = getCurSDLoc(); 7012 7013 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7014 SmallVector<EVT, 4> ValueVTs; 7015 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7016 ValueVTs.push_back(MVT::Other); // Out chain 7017 7018 // We do not need to serialize constrained FP intrinsics against 7019 // each other or against (nonvolatile) loads, so they can be 7020 // chained like loads. 7021 SDValue Chain = DAG.getRoot(); 7022 SmallVector<SDValue, 4> Opers; 7023 Opers.push_back(Chain); 7024 if (FPI.isUnaryOp()) { 7025 Opers.push_back(getValue(FPI.getArgOperand(0))); 7026 } else if (FPI.isTernaryOp()) { 7027 Opers.push_back(getValue(FPI.getArgOperand(0))); 7028 Opers.push_back(getValue(FPI.getArgOperand(1))); 7029 Opers.push_back(getValue(FPI.getArgOperand(2))); 7030 } else { 7031 Opers.push_back(getValue(FPI.getArgOperand(0))); 7032 Opers.push_back(getValue(FPI.getArgOperand(1))); 7033 } 7034 7035 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7036 assert(Result.getNode()->getNumValues() == 2); 7037 7038 // Push node to the appropriate list so that future instructions can be 7039 // chained up correctly. 7040 SDValue OutChain = Result.getValue(1); 7041 switch (EB) { 7042 case fp::ExceptionBehavior::ebIgnore: 7043 // The only reason why ebIgnore nodes still need to be chained is that 7044 // they might depend on the current rounding mode, and therefore must 7045 // not be moved across instruction that may change that mode. 7046 LLVM_FALLTHROUGH; 7047 case fp::ExceptionBehavior::ebMayTrap: 7048 // These must not be moved across calls or instructions that may change 7049 // floating-point exception masks. 7050 PendingConstrainedFP.push_back(OutChain); 7051 break; 7052 case fp::ExceptionBehavior::ebStrict: 7053 // These must not be moved across calls or instructions that may change 7054 // floating-point exception masks or read floating-point exception flags. 7055 // In addition, they cannot be optimized out even if unused. 7056 PendingConstrainedFPStrict.push_back(OutChain); 7057 break; 7058 } 7059 }; 7060 7061 SDVTList VTs = DAG.getVTList(ValueVTs); 7062 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7063 7064 SDNodeFlags Flags; 7065 if (EB == fp::ExceptionBehavior::ebIgnore) 7066 Flags.setNoFPExcept(true); 7067 7068 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7069 Flags.copyFMF(*FPOp); 7070 7071 unsigned Opcode; 7072 switch (FPI.getIntrinsicID()) { 7073 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7074 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7075 case Intrinsic::INTRINSIC: \ 7076 Opcode = ISD::STRICT_##DAGN; \ 7077 break; 7078 #include "llvm/IR/ConstrainedOps.def" 7079 case Intrinsic::experimental_constrained_fmuladd: { 7080 Opcode = ISD::STRICT_FMA; 7081 // Break fmuladd into fmul and fadd. 7082 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7083 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7084 ValueVTs[0])) { 7085 Opers.pop_back(); 7086 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7087 pushOutChain(Mul, EB); 7088 Opcode = ISD::STRICT_FADD; 7089 Opers.clear(); 7090 Opers.push_back(Mul.getValue(1)); 7091 Opers.push_back(Mul.getValue(0)); 7092 Opers.push_back(getValue(FPI.getArgOperand(2))); 7093 } 7094 break; 7095 } 7096 } 7097 7098 // A few strict DAG nodes carry additional operands that are not 7099 // set up by the default code above. 7100 switch (Opcode) { 7101 default: break; 7102 case ISD::STRICT_FP_ROUND: 7103 Opers.push_back( 7104 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7105 break; 7106 case ISD::STRICT_FSETCC: 7107 case ISD::STRICT_FSETCCS: { 7108 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7109 Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate()))); 7110 break; 7111 } 7112 } 7113 7114 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7115 pushOutChain(Result, EB); 7116 7117 SDValue FPResult = Result.getValue(0); 7118 setValue(&FPI, FPResult); 7119 } 7120 7121 std::pair<SDValue, SDValue> 7122 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7123 const BasicBlock *EHPadBB) { 7124 MachineFunction &MF = DAG.getMachineFunction(); 7125 MachineModuleInfo &MMI = MF.getMMI(); 7126 MCSymbol *BeginLabel = nullptr; 7127 7128 if (EHPadBB) { 7129 // Insert a label before the invoke call to mark the try range. This can be 7130 // used to detect deletion of the invoke via the MachineModuleInfo. 7131 BeginLabel = MMI.getContext().createTempSymbol(); 7132 7133 // For SjLj, keep track of which landing pads go with which invokes 7134 // so as to maintain the ordering of pads in the LSDA. 7135 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7136 if (CallSiteIndex) { 7137 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7138 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7139 7140 // Now that the call site is handled, stop tracking it. 7141 MMI.setCurrentCallSite(0); 7142 } 7143 7144 // Both PendingLoads and PendingExports must be flushed here; 7145 // this call might not return. 7146 (void)getRoot(); 7147 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7148 7149 CLI.setChain(getRoot()); 7150 } 7151 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7152 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7153 7154 assert((CLI.IsTailCall || Result.second.getNode()) && 7155 "Non-null chain expected with non-tail call!"); 7156 assert((Result.second.getNode() || !Result.first.getNode()) && 7157 "Null value expected with tail call!"); 7158 7159 if (!Result.second.getNode()) { 7160 // As a special case, a null chain means that a tail call has been emitted 7161 // and the DAG root is already updated. 7162 HasTailCall = true; 7163 7164 // Since there's no actual continuation from this block, nothing can be 7165 // relying on us setting vregs for them. 7166 PendingExports.clear(); 7167 } else { 7168 DAG.setRoot(Result.second); 7169 } 7170 7171 if (EHPadBB) { 7172 // Insert a label at the end of the invoke call to mark the try range. This 7173 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7174 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7175 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7176 7177 // Inform MachineModuleInfo of range. 7178 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7179 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7180 // actually use outlined funclets and their LSDA info style. 7181 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7182 assert(CLI.CS); 7183 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7184 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 7185 BeginLabel, EndLabel); 7186 } else if (!isScopedEHPersonality(Pers)) { 7187 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7188 } 7189 } 7190 7191 return Result; 7192 } 7193 7194 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 7195 bool isTailCall, 7196 const BasicBlock *EHPadBB) { 7197 auto &DL = DAG.getDataLayout(); 7198 FunctionType *FTy = CS.getFunctionType(); 7199 Type *RetTy = CS.getType(); 7200 7201 TargetLowering::ArgListTy Args; 7202 Args.reserve(CS.arg_size()); 7203 7204 const Value *SwiftErrorVal = nullptr; 7205 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7206 7207 if (isTailCall) { 7208 // Avoid emitting tail calls in functions with the disable-tail-calls 7209 // attribute. 7210 auto *Caller = CS.getInstruction()->getParent()->getParent(); 7211 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7212 "true") 7213 isTailCall = false; 7214 7215 // We can't tail call inside a function with a swifterror argument. Lowering 7216 // does not support this yet. It would have to move into the swifterror 7217 // register before the call. 7218 if (TLI.supportSwiftError() && 7219 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7220 isTailCall = false; 7221 } 7222 7223 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 7224 i != e; ++i) { 7225 TargetLowering::ArgListEntry Entry; 7226 const Value *V = *i; 7227 7228 // Skip empty types 7229 if (V->getType()->isEmptyTy()) 7230 continue; 7231 7232 SDValue ArgNode = getValue(V); 7233 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7234 7235 Entry.setAttributes(&CS, i - CS.arg_begin()); 7236 7237 // Use swifterror virtual register as input to the call. 7238 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7239 SwiftErrorVal = V; 7240 // We find the virtual register for the actual swifterror argument. 7241 // Instead of using the Value, we use the virtual register instead. 7242 Entry.Node = DAG.getRegister( 7243 SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V), 7244 EVT(TLI.getPointerTy(DL))); 7245 } 7246 7247 Args.push_back(Entry); 7248 7249 // If we have an explicit sret argument that is an Instruction, (i.e., it 7250 // might point to function-local memory), we can't meaningfully tail-call. 7251 if (Entry.IsSRet && isa<Instruction>(V)) 7252 isTailCall = false; 7253 } 7254 7255 // If call site has a cfguardtarget operand bundle, create and add an 7256 // additional ArgListEntry. 7257 if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7258 TargetLowering::ArgListEntry Entry; 7259 Value *V = Bundle->Inputs[0]; 7260 SDValue ArgNode = getValue(V); 7261 Entry.Node = ArgNode; 7262 Entry.Ty = V->getType(); 7263 Entry.IsCFGuardTarget = true; 7264 Args.push_back(Entry); 7265 } 7266 7267 // Check if target-independent constraints permit a tail call here. 7268 // Target-dependent constraints are checked within TLI->LowerCallTo. 7269 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 7270 isTailCall = false; 7271 7272 // Disable tail calls if there is an swifterror argument. Targets have not 7273 // been updated to support tail calls. 7274 if (TLI.supportSwiftError() && SwiftErrorVal) 7275 isTailCall = false; 7276 7277 TargetLowering::CallLoweringInfo CLI(DAG); 7278 CLI.setDebugLoc(getCurSDLoc()) 7279 .setChain(getRoot()) 7280 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 7281 .setTailCall(isTailCall) 7282 .setConvergent(CS.isConvergent()); 7283 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7284 7285 if (Result.first.getNode()) { 7286 const Instruction *Inst = CS.getInstruction(); 7287 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 7288 setValue(Inst, Result.first); 7289 } 7290 7291 // The last element of CLI.InVals has the SDValue for swifterror return. 7292 // Here we copy it to a virtual register and update SwiftErrorMap for 7293 // book-keeping. 7294 if (SwiftErrorVal && TLI.supportSwiftError()) { 7295 // Get the last element of InVals. 7296 SDValue Src = CLI.InVals.back(); 7297 Register VReg = SwiftError.getOrCreateVRegDefAt( 7298 CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal); 7299 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7300 DAG.setRoot(CopyNode); 7301 } 7302 } 7303 7304 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7305 SelectionDAGBuilder &Builder) { 7306 // Check to see if this load can be trivially constant folded, e.g. if the 7307 // input is from a string literal. 7308 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7309 // Cast pointer to the type we really want to load. 7310 Type *LoadTy = 7311 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7312 if (LoadVT.isVector()) 7313 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7314 7315 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7316 PointerType::getUnqual(LoadTy)); 7317 7318 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7319 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7320 return Builder.getValue(LoadCst); 7321 } 7322 7323 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7324 // still constant memory, the input chain can be the entry node. 7325 SDValue Root; 7326 bool ConstantMemory = false; 7327 7328 // Do not serialize (non-volatile) loads of constant memory with anything. 7329 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7330 Root = Builder.DAG.getEntryNode(); 7331 ConstantMemory = true; 7332 } else { 7333 // Do not serialize non-volatile loads against each other. 7334 Root = Builder.DAG.getRoot(); 7335 } 7336 7337 SDValue Ptr = Builder.getValue(PtrVal); 7338 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7339 Ptr, MachinePointerInfo(PtrVal), 7340 /* Alignment = */ 1); 7341 7342 if (!ConstantMemory) 7343 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7344 return LoadVal; 7345 } 7346 7347 /// Record the value for an instruction that produces an integer result, 7348 /// converting the type where necessary. 7349 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7350 SDValue Value, 7351 bool IsSigned) { 7352 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7353 I.getType(), true); 7354 if (IsSigned) 7355 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7356 else 7357 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7358 setValue(&I, Value); 7359 } 7360 7361 /// See if we can lower a memcmp call into an optimized form. If so, return 7362 /// true and lower it. Otherwise return false, and it will be lowered like a 7363 /// normal call. 7364 /// The caller already checked that \p I calls the appropriate LibFunc with a 7365 /// correct prototype. 7366 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7367 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7368 const Value *Size = I.getArgOperand(2); 7369 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7370 if (CSize && CSize->getZExtValue() == 0) { 7371 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7372 I.getType(), true); 7373 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7374 return true; 7375 } 7376 7377 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7378 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7379 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7380 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7381 if (Res.first.getNode()) { 7382 processIntegerCallValue(I, Res.first, true); 7383 PendingLoads.push_back(Res.second); 7384 return true; 7385 } 7386 7387 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7388 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7389 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7390 return false; 7391 7392 // If the target has a fast compare for the given size, it will return a 7393 // preferred load type for that size. Require that the load VT is legal and 7394 // that the target supports unaligned loads of that type. Otherwise, return 7395 // INVALID. 7396 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7397 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7398 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7399 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7400 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7401 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7402 // TODO: Check alignment of src and dest ptrs. 7403 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7404 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7405 if (!TLI.isTypeLegal(LVT) || 7406 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7407 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7408 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7409 } 7410 7411 return LVT; 7412 }; 7413 7414 // This turns into unaligned loads. We only do this if the target natively 7415 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7416 // we'll only produce a small number of byte loads. 7417 MVT LoadVT; 7418 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7419 switch (NumBitsToCompare) { 7420 default: 7421 return false; 7422 case 16: 7423 LoadVT = MVT::i16; 7424 break; 7425 case 32: 7426 LoadVT = MVT::i32; 7427 break; 7428 case 64: 7429 case 128: 7430 case 256: 7431 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7432 break; 7433 } 7434 7435 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7436 return false; 7437 7438 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7439 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7440 7441 // Bitcast to a wide integer type if the loads are vectors. 7442 if (LoadVT.isVector()) { 7443 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7444 LoadL = DAG.getBitcast(CmpVT, LoadL); 7445 LoadR = DAG.getBitcast(CmpVT, LoadR); 7446 } 7447 7448 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7449 processIntegerCallValue(I, Cmp, false); 7450 return true; 7451 } 7452 7453 /// See if we can lower a memchr call into an optimized form. If so, return 7454 /// true and lower it. Otherwise return false, and it will be lowered like a 7455 /// normal call. 7456 /// The caller already checked that \p I calls the appropriate LibFunc with a 7457 /// correct prototype. 7458 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7459 const Value *Src = I.getArgOperand(0); 7460 const Value *Char = I.getArgOperand(1); 7461 const Value *Length = I.getArgOperand(2); 7462 7463 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7464 std::pair<SDValue, SDValue> Res = 7465 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7466 getValue(Src), getValue(Char), getValue(Length), 7467 MachinePointerInfo(Src)); 7468 if (Res.first.getNode()) { 7469 setValue(&I, Res.first); 7470 PendingLoads.push_back(Res.second); 7471 return true; 7472 } 7473 7474 return false; 7475 } 7476 7477 /// See if we can lower a mempcpy call into an optimized form. If so, return 7478 /// true and lower it. Otherwise return false, and it will be lowered like a 7479 /// normal call. 7480 /// The caller already checked that \p I calls the appropriate LibFunc with a 7481 /// correct prototype. 7482 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7483 SDValue Dst = getValue(I.getArgOperand(0)); 7484 SDValue Src = getValue(I.getArgOperand(1)); 7485 SDValue Size = getValue(I.getArgOperand(2)); 7486 7487 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7488 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7489 // DAG::getMemcpy needs Alignment to be defined. 7490 Align Alignment = assumeAligned(std::min(DstAlign, SrcAlign)); 7491 7492 bool isVol = false; 7493 SDLoc sdl = getCurSDLoc(); 7494 7495 // In the mempcpy context we need to pass in a false value for isTailCall 7496 // because the return pointer needs to be adjusted by the size of 7497 // the copied memory. 7498 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7499 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7500 /*isTailCall=*/false, 7501 MachinePointerInfo(I.getArgOperand(0)), 7502 MachinePointerInfo(I.getArgOperand(1))); 7503 assert(MC.getNode() != nullptr && 7504 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7505 DAG.setRoot(MC); 7506 7507 // Check if Size needs to be truncated or extended. 7508 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7509 7510 // Adjust return pointer to point just past the last dst byte. 7511 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7512 Dst, Size); 7513 setValue(&I, DstPlusSize); 7514 return true; 7515 } 7516 7517 /// See if we can lower a strcpy call into an optimized form. If so, return 7518 /// true and lower it, otherwise return false and it will be lowered like a 7519 /// normal call. 7520 /// The caller already checked that \p I calls the appropriate LibFunc with a 7521 /// correct prototype. 7522 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7523 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7524 7525 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7526 std::pair<SDValue, SDValue> Res = 7527 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7528 getValue(Arg0), getValue(Arg1), 7529 MachinePointerInfo(Arg0), 7530 MachinePointerInfo(Arg1), isStpcpy); 7531 if (Res.first.getNode()) { 7532 setValue(&I, Res.first); 7533 DAG.setRoot(Res.second); 7534 return true; 7535 } 7536 7537 return false; 7538 } 7539 7540 /// See if we can lower a strcmp call into an optimized form. If so, return 7541 /// true and lower it, otherwise return false and it will be lowered like a 7542 /// normal call. 7543 /// The caller already checked that \p I calls the appropriate LibFunc with a 7544 /// correct prototype. 7545 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7546 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7547 7548 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7549 std::pair<SDValue, SDValue> Res = 7550 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7551 getValue(Arg0), getValue(Arg1), 7552 MachinePointerInfo(Arg0), 7553 MachinePointerInfo(Arg1)); 7554 if (Res.first.getNode()) { 7555 processIntegerCallValue(I, Res.first, true); 7556 PendingLoads.push_back(Res.second); 7557 return true; 7558 } 7559 7560 return false; 7561 } 7562 7563 /// See if we can lower a strlen call into an optimized form. If so, return 7564 /// true and lower it, otherwise return false and it will be lowered like a 7565 /// normal call. 7566 /// The caller already checked that \p I calls the appropriate LibFunc with a 7567 /// correct prototype. 7568 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7569 const Value *Arg0 = I.getArgOperand(0); 7570 7571 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7572 std::pair<SDValue, SDValue> Res = 7573 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7574 getValue(Arg0), MachinePointerInfo(Arg0)); 7575 if (Res.first.getNode()) { 7576 processIntegerCallValue(I, Res.first, false); 7577 PendingLoads.push_back(Res.second); 7578 return true; 7579 } 7580 7581 return false; 7582 } 7583 7584 /// See if we can lower a strnlen call into an optimized form. If so, return 7585 /// true and lower it, otherwise return false and it will be lowered like a 7586 /// normal call. 7587 /// The caller already checked that \p I calls the appropriate LibFunc with a 7588 /// correct prototype. 7589 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7590 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7591 7592 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7593 std::pair<SDValue, SDValue> Res = 7594 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7595 getValue(Arg0), getValue(Arg1), 7596 MachinePointerInfo(Arg0)); 7597 if (Res.first.getNode()) { 7598 processIntegerCallValue(I, Res.first, false); 7599 PendingLoads.push_back(Res.second); 7600 return true; 7601 } 7602 7603 return false; 7604 } 7605 7606 /// See if we can lower a unary floating-point operation into an SDNode with 7607 /// the specified Opcode. If so, return true and lower it, otherwise return 7608 /// false and it will be lowered like a normal call. 7609 /// The caller already checked that \p I calls the appropriate LibFunc with a 7610 /// correct prototype. 7611 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7612 unsigned Opcode) { 7613 // We already checked this call's prototype; verify it doesn't modify errno. 7614 if (!I.onlyReadsMemory()) 7615 return false; 7616 7617 SDValue Tmp = getValue(I.getArgOperand(0)); 7618 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7619 return true; 7620 } 7621 7622 /// See if we can lower a binary floating-point operation into an SDNode with 7623 /// the specified Opcode. If so, return true and lower it. Otherwise return 7624 /// false, and it will be lowered like a normal call. 7625 /// The caller already checked that \p I calls the appropriate LibFunc with a 7626 /// correct prototype. 7627 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7628 unsigned Opcode) { 7629 // We already checked this call's prototype; verify it doesn't modify errno. 7630 if (!I.onlyReadsMemory()) 7631 return false; 7632 7633 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7634 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7635 EVT VT = Tmp0.getValueType(); 7636 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7637 return true; 7638 } 7639 7640 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7641 // Handle inline assembly differently. 7642 if (isa<InlineAsm>(I.getCalledValue())) { 7643 visitInlineAsm(&I); 7644 return; 7645 } 7646 7647 if (Function *F = I.getCalledFunction()) { 7648 if (F->isDeclaration()) { 7649 // Is this an LLVM intrinsic or a target-specific intrinsic? 7650 unsigned IID = F->getIntrinsicID(); 7651 if (!IID) 7652 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7653 IID = II->getIntrinsicID(F); 7654 7655 if (IID) { 7656 visitIntrinsicCall(I, IID); 7657 return; 7658 } 7659 } 7660 7661 // Check for well-known libc/libm calls. If the function is internal, it 7662 // can't be a library call. Don't do the check if marked as nobuiltin for 7663 // some reason or the call site requires strict floating point semantics. 7664 LibFunc Func; 7665 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7666 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7667 LibInfo->hasOptimizedCodeGen(Func)) { 7668 switch (Func) { 7669 default: break; 7670 case LibFunc_copysign: 7671 case LibFunc_copysignf: 7672 case LibFunc_copysignl: 7673 // We already checked this call's prototype; verify it doesn't modify 7674 // errno. 7675 if (I.onlyReadsMemory()) { 7676 SDValue LHS = getValue(I.getArgOperand(0)); 7677 SDValue RHS = getValue(I.getArgOperand(1)); 7678 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7679 LHS.getValueType(), LHS, RHS)); 7680 return; 7681 } 7682 break; 7683 case LibFunc_fabs: 7684 case LibFunc_fabsf: 7685 case LibFunc_fabsl: 7686 if (visitUnaryFloatCall(I, ISD::FABS)) 7687 return; 7688 break; 7689 case LibFunc_fmin: 7690 case LibFunc_fminf: 7691 case LibFunc_fminl: 7692 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7693 return; 7694 break; 7695 case LibFunc_fmax: 7696 case LibFunc_fmaxf: 7697 case LibFunc_fmaxl: 7698 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7699 return; 7700 break; 7701 case LibFunc_sin: 7702 case LibFunc_sinf: 7703 case LibFunc_sinl: 7704 if (visitUnaryFloatCall(I, ISD::FSIN)) 7705 return; 7706 break; 7707 case LibFunc_cos: 7708 case LibFunc_cosf: 7709 case LibFunc_cosl: 7710 if (visitUnaryFloatCall(I, ISD::FCOS)) 7711 return; 7712 break; 7713 case LibFunc_sqrt: 7714 case LibFunc_sqrtf: 7715 case LibFunc_sqrtl: 7716 case LibFunc_sqrt_finite: 7717 case LibFunc_sqrtf_finite: 7718 case LibFunc_sqrtl_finite: 7719 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7720 return; 7721 break; 7722 case LibFunc_floor: 7723 case LibFunc_floorf: 7724 case LibFunc_floorl: 7725 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7726 return; 7727 break; 7728 case LibFunc_nearbyint: 7729 case LibFunc_nearbyintf: 7730 case LibFunc_nearbyintl: 7731 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7732 return; 7733 break; 7734 case LibFunc_ceil: 7735 case LibFunc_ceilf: 7736 case LibFunc_ceill: 7737 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7738 return; 7739 break; 7740 case LibFunc_rint: 7741 case LibFunc_rintf: 7742 case LibFunc_rintl: 7743 if (visitUnaryFloatCall(I, ISD::FRINT)) 7744 return; 7745 break; 7746 case LibFunc_round: 7747 case LibFunc_roundf: 7748 case LibFunc_roundl: 7749 if (visitUnaryFloatCall(I, ISD::FROUND)) 7750 return; 7751 break; 7752 case LibFunc_trunc: 7753 case LibFunc_truncf: 7754 case LibFunc_truncl: 7755 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7756 return; 7757 break; 7758 case LibFunc_log2: 7759 case LibFunc_log2f: 7760 case LibFunc_log2l: 7761 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7762 return; 7763 break; 7764 case LibFunc_exp2: 7765 case LibFunc_exp2f: 7766 case LibFunc_exp2l: 7767 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7768 return; 7769 break; 7770 case LibFunc_memcmp: 7771 if (visitMemCmpCall(I)) 7772 return; 7773 break; 7774 case LibFunc_mempcpy: 7775 if (visitMemPCpyCall(I)) 7776 return; 7777 break; 7778 case LibFunc_memchr: 7779 if (visitMemChrCall(I)) 7780 return; 7781 break; 7782 case LibFunc_strcpy: 7783 if (visitStrCpyCall(I, false)) 7784 return; 7785 break; 7786 case LibFunc_stpcpy: 7787 if (visitStrCpyCall(I, true)) 7788 return; 7789 break; 7790 case LibFunc_strcmp: 7791 if (visitStrCmpCall(I)) 7792 return; 7793 break; 7794 case LibFunc_strlen: 7795 if (visitStrLenCall(I)) 7796 return; 7797 break; 7798 case LibFunc_strnlen: 7799 if (visitStrNLenCall(I)) 7800 return; 7801 break; 7802 } 7803 } 7804 } 7805 7806 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7807 // have to do anything here to lower funclet bundles. 7808 // CFGuardTarget bundles are lowered in LowerCallTo. 7809 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 7810 LLVMContext::OB_funclet, 7811 LLVMContext::OB_cfguardtarget}) && 7812 "Cannot lower calls with arbitrary operand bundles!"); 7813 7814 SDValue Callee = getValue(I.getCalledValue()); 7815 7816 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7817 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7818 else 7819 // Check if we can potentially perform a tail call. More detailed checking 7820 // is be done within LowerCallTo, after more information about the call is 7821 // known. 7822 LowerCallTo(&I, Callee, I.isTailCall()); 7823 } 7824 7825 namespace { 7826 7827 /// AsmOperandInfo - This contains information for each constraint that we are 7828 /// lowering. 7829 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7830 public: 7831 /// CallOperand - If this is the result output operand or a clobber 7832 /// this is null, otherwise it is the incoming operand to the CallInst. 7833 /// This gets modified as the asm is processed. 7834 SDValue CallOperand; 7835 7836 /// AssignedRegs - If this is a register or register class operand, this 7837 /// contains the set of register corresponding to the operand. 7838 RegsForValue AssignedRegs; 7839 7840 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7841 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7842 } 7843 7844 /// Whether or not this operand accesses memory 7845 bool hasMemory(const TargetLowering &TLI) const { 7846 // Indirect operand accesses access memory. 7847 if (isIndirect) 7848 return true; 7849 7850 for (const auto &Code : Codes) 7851 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7852 return true; 7853 7854 return false; 7855 } 7856 7857 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7858 /// corresponds to. If there is no Value* for this operand, it returns 7859 /// MVT::Other. 7860 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7861 const DataLayout &DL) const { 7862 if (!CallOperandVal) return MVT::Other; 7863 7864 if (isa<BasicBlock>(CallOperandVal)) 7865 return TLI.getPointerTy(DL); 7866 7867 llvm::Type *OpTy = CallOperandVal->getType(); 7868 7869 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7870 // If this is an indirect operand, the operand is a pointer to the 7871 // accessed type. 7872 if (isIndirect) { 7873 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7874 if (!PtrTy) 7875 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7876 OpTy = PtrTy->getElementType(); 7877 } 7878 7879 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7880 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7881 if (STy->getNumElements() == 1) 7882 OpTy = STy->getElementType(0); 7883 7884 // If OpTy is not a single value, it may be a struct/union that we 7885 // can tile with integers. 7886 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7887 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7888 switch (BitSize) { 7889 default: break; 7890 case 1: 7891 case 8: 7892 case 16: 7893 case 32: 7894 case 64: 7895 case 128: 7896 OpTy = IntegerType::get(Context, BitSize); 7897 break; 7898 } 7899 } 7900 7901 return TLI.getValueType(DL, OpTy, true); 7902 } 7903 }; 7904 7905 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7906 7907 } // end anonymous namespace 7908 7909 /// Make sure that the output operand \p OpInfo and its corresponding input 7910 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7911 /// out). 7912 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7913 SDISelAsmOperandInfo &MatchingOpInfo, 7914 SelectionDAG &DAG) { 7915 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7916 return; 7917 7918 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7919 const auto &TLI = DAG.getTargetLoweringInfo(); 7920 7921 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7922 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7923 OpInfo.ConstraintVT); 7924 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7925 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7926 MatchingOpInfo.ConstraintVT); 7927 if ((OpInfo.ConstraintVT.isInteger() != 7928 MatchingOpInfo.ConstraintVT.isInteger()) || 7929 (MatchRC.second != InputRC.second)) { 7930 // FIXME: error out in a more elegant fashion 7931 report_fatal_error("Unsupported asm: input constraint" 7932 " with a matching output constraint of" 7933 " incompatible type!"); 7934 } 7935 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7936 } 7937 7938 /// Get a direct memory input to behave well as an indirect operand. 7939 /// This may introduce stores, hence the need for a \p Chain. 7940 /// \return The (possibly updated) chain. 7941 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7942 SDISelAsmOperandInfo &OpInfo, 7943 SelectionDAG &DAG) { 7944 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7945 7946 // If we don't have an indirect input, put it in the constpool if we can, 7947 // otherwise spill it to a stack slot. 7948 // TODO: This isn't quite right. We need to handle these according to 7949 // the addressing mode that the constraint wants. Also, this may take 7950 // an additional register for the computation and we don't want that 7951 // either. 7952 7953 // If the operand is a float, integer, or vector constant, spill to a 7954 // constant pool entry to get its address. 7955 const Value *OpVal = OpInfo.CallOperandVal; 7956 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7957 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7958 OpInfo.CallOperand = DAG.getConstantPool( 7959 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7960 return Chain; 7961 } 7962 7963 // Otherwise, create a stack slot and emit a store to it before the asm. 7964 Type *Ty = OpVal->getType(); 7965 auto &DL = DAG.getDataLayout(); 7966 uint64_t TySize = DL.getTypeAllocSize(Ty); 7967 unsigned Align = DL.getPrefTypeAlignment(Ty); 7968 MachineFunction &MF = DAG.getMachineFunction(); 7969 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7970 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7971 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7972 MachinePointerInfo::getFixedStack(MF, SSFI), 7973 TLI.getMemValueType(DL, Ty)); 7974 OpInfo.CallOperand = StackSlot; 7975 7976 return Chain; 7977 } 7978 7979 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7980 /// specified operand. We prefer to assign virtual registers, to allow the 7981 /// register allocator to handle the assignment process. However, if the asm 7982 /// uses features that we can't model on machineinstrs, we have SDISel do the 7983 /// allocation. This produces generally horrible, but correct, code. 7984 /// 7985 /// OpInfo describes the operand 7986 /// RefOpInfo describes the matching operand if any, the operand otherwise 7987 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7988 SDISelAsmOperandInfo &OpInfo, 7989 SDISelAsmOperandInfo &RefOpInfo) { 7990 LLVMContext &Context = *DAG.getContext(); 7991 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7992 7993 MachineFunction &MF = DAG.getMachineFunction(); 7994 SmallVector<unsigned, 4> Regs; 7995 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7996 7997 // No work to do for memory operations. 7998 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7999 return; 8000 8001 // If this is a constraint for a single physreg, or a constraint for a 8002 // register class, find it. 8003 unsigned AssignedReg; 8004 const TargetRegisterClass *RC; 8005 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8006 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8007 // RC is unset only on failure. Return immediately. 8008 if (!RC) 8009 return; 8010 8011 // Get the actual register value type. This is important, because the user 8012 // may have asked for (e.g.) the AX register in i32 type. We need to 8013 // remember that AX is actually i16 to get the right extension. 8014 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8015 8016 if (OpInfo.ConstraintVT != MVT::Other) { 8017 // If this is an FP operand in an integer register (or visa versa), or more 8018 // generally if the operand value disagrees with the register class we plan 8019 // to stick it in, fix the operand type. 8020 // 8021 // If this is an input value, the bitcast to the new type is done now. 8022 // Bitcast for output value is done at the end of visitInlineAsm(). 8023 if ((OpInfo.Type == InlineAsm::isOutput || 8024 OpInfo.Type == InlineAsm::isInput) && 8025 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8026 // Try to convert to the first EVT that the reg class contains. If the 8027 // types are identical size, use a bitcast to convert (e.g. two differing 8028 // vector types). Note: output bitcast is done at the end of 8029 // visitInlineAsm(). 8030 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8031 // Exclude indirect inputs while they are unsupported because the code 8032 // to perform the load is missing and thus OpInfo.CallOperand still 8033 // refers to the input address rather than the pointed-to value. 8034 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8035 OpInfo.CallOperand = 8036 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8037 OpInfo.ConstraintVT = RegVT; 8038 // If the operand is an FP value and we want it in integer registers, 8039 // use the corresponding integer type. This turns an f64 value into 8040 // i64, which can be passed with two i32 values on a 32-bit machine. 8041 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8042 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8043 if (OpInfo.Type == InlineAsm::isInput) 8044 OpInfo.CallOperand = 8045 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8046 OpInfo.ConstraintVT = VT; 8047 } 8048 } 8049 } 8050 8051 // No need to allocate a matching input constraint since the constraint it's 8052 // matching to has already been allocated. 8053 if (OpInfo.isMatchingInputConstraint()) 8054 return; 8055 8056 EVT ValueVT = OpInfo.ConstraintVT; 8057 if (OpInfo.ConstraintVT == MVT::Other) 8058 ValueVT = RegVT; 8059 8060 // Initialize NumRegs. 8061 unsigned NumRegs = 1; 8062 if (OpInfo.ConstraintVT != MVT::Other) 8063 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8064 8065 // If this is a constraint for a specific physical register, like {r17}, 8066 // assign it now. 8067 8068 // If this associated to a specific register, initialize iterator to correct 8069 // place. If virtual, make sure we have enough registers 8070 8071 // Initialize iterator if necessary 8072 TargetRegisterClass::iterator I = RC->begin(); 8073 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8074 8075 // Do not check for single registers. 8076 if (AssignedReg) { 8077 for (; *I != AssignedReg; ++I) 8078 assert(I != RC->end() && "AssignedReg should be member of RC"); 8079 } 8080 8081 for (; NumRegs; --NumRegs, ++I) { 8082 assert(I != RC->end() && "Ran out of registers to allocate!"); 8083 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8084 Regs.push_back(R); 8085 } 8086 8087 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8088 } 8089 8090 static unsigned 8091 findMatchingInlineAsmOperand(unsigned OperandNo, 8092 const std::vector<SDValue> &AsmNodeOperands) { 8093 // Scan until we find the definition we already emitted of this operand. 8094 unsigned CurOp = InlineAsm::Op_FirstOperand; 8095 for (; OperandNo; --OperandNo) { 8096 // Advance to the next operand. 8097 unsigned OpFlag = 8098 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8099 assert((InlineAsm::isRegDefKind(OpFlag) || 8100 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8101 InlineAsm::isMemKind(OpFlag)) && 8102 "Skipped past definitions?"); 8103 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8104 } 8105 return CurOp; 8106 } 8107 8108 namespace { 8109 8110 class ExtraFlags { 8111 unsigned Flags = 0; 8112 8113 public: 8114 explicit ExtraFlags(ImmutableCallSite CS) { 8115 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 8116 if (IA->hasSideEffects()) 8117 Flags |= InlineAsm::Extra_HasSideEffects; 8118 if (IA->isAlignStack()) 8119 Flags |= InlineAsm::Extra_IsAlignStack; 8120 if (CS.isConvergent()) 8121 Flags |= InlineAsm::Extra_IsConvergent; 8122 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8123 } 8124 8125 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8126 // Ideally, we would only check against memory constraints. However, the 8127 // meaning of an Other constraint can be target-specific and we can't easily 8128 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8129 // for Other constraints as well. 8130 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8131 OpInfo.ConstraintType == TargetLowering::C_Other) { 8132 if (OpInfo.Type == InlineAsm::isInput) 8133 Flags |= InlineAsm::Extra_MayLoad; 8134 else if (OpInfo.Type == InlineAsm::isOutput) 8135 Flags |= InlineAsm::Extra_MayStore; 8136 else if (OpInfo.Type == InlineAsm::isClobber) 8137 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8138 } 8139 } 8140 8141 unsigned get() const { return Flags; } 8142 }; 8143 8144 } // end anonymous namespace 8145 8146 /// visitInlineAsm - Handle a call to an InlineAsm object. 8147 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 8148 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 8149 8150 /// ConstraintOperands - Information about all of the constraints. 8151 SDISelAsmOperandInfoVector ConstraintOperands; 8152 8153 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8154 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8155 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 8156 8157 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8158 // AsmDialect, MayLoad, MayStore). 8159 bool HasSideEffect = IA->hasSideEffects(); 8160 ExtraFlags ExtraInfo(CS); 8161 8162 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8163 unsigned ResNo = 0; // ResNo - The result number of the next output. 8164 unsigned NumMatchingOps = 0; 8165 for (auto &T : TargetConstraints) { 8166 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8167 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8168 8169 // Compute the value type for each operand. 8170 if (OpInfo.Type == InlineAsm::isInput || 8171 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8172 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 8173 8174 // Process the call argument. BasicBlocks are labels, currently appearing 8175 // only in asm's. 8176 const Instruction *I = CS.getInstruction(); 8177 if (isa<CallBrInst>(I) && 8178 ArgNo - 1 >= (cast<CallBrInst>(I)->getNumArgOperands() - 8179 cast<CallBrInst>(I)->getNumIndirectDests() - 8180 NumMatchingOps) && 8181 (NumMatchingOps == 0 || 8182 ArgNo - 1 < (cast<CallBrInst>(I)->getNumArgOperands() - 8183 NumMatchingOps))) { 8184 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8185 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8186 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8187 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8188 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8189 } else { 8190 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8191 } 8192 8193 OpInfo.ConstraintVT = 8194 OpInfo 8195 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8196 .getSimpleVT(); 8197 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8198 // The return value of the call is this value. As such, there is no 8199 // corresponding argument. 8200 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8201 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 8202 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8203 DAG.getDataLayout(), STy->getElementType(ResNo)); 8204 } else { 8205 assert(ResNo == 0 && "Asm only has one result!"); 8206 OpInfo.ConstraintVT = 8207 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 8208 } 8209 ++ResNo; 8210 } else { 8211 OpInfo.ConstraintVT = MVT::Other; 8212 } 8213 8214 if (OpInfo.hasMatchingInput()) 8215 ++NumMatchingOps; 8216 8217 if (!HasSideEffect) 8218 HasSideEffect = OpInfo.hasMemory(TLI); 8219 8220 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8221 // FIXME: Could we compute this on OpInfo rather than T? 8222 8223 // Compute the constraint code and ConstraintType to use. 8224 TLI.ComputeConstraintToUse(T, SDValue()); 8225 8226 if (T.ConstraintType == TargetLowering::C_Immediate && 8227 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8228 // We've delayed emitting a diagnostic like the "n" constraint because 8229 // inlining could cause an integer showing up. 8230 return emitInlineAsmError( 8231 CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an " 8232 "integer constant expression"); 8233 8234 ExtraInfo.update(T); 8235 } 8236 8237 8238 // We won't need to flush pending loads if this asm doesn't touch 8239 // memory and is nonvolatile. 8240 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8241 8242 bool IsCallBr = isa<CallBrInst>(CS.getInstruction()); 8243 if (IsCallBr) { 8244 // If this is a callbr we need to flush pending exports since inlineasm_br 8245 // is a terminator. We need to do this before nodes are glued to 8246 // the inlineasm_br node. 8247 Chain = getControlRoot(); 8248 } 8249 8250 // Second pass over the constraints: compute which constraint option to use. 8251 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8252 // If this is an output operand with a matching input operand, look up the 8253 // matching input. If their types mismatch, e.g. one is an integer, the 8254 // other is floating point, or their sizes are different, flag it as an 8255 // error. 8256 if (OpInfo.hasMatchingInput()) { 8257 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8258 patchMatchingInput(OpInfo, Input, DAG); 8259 } 8260 8261 // Compute the constraint code and ConstraintType to use. 8262 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8263 8264 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8265 OpInfo.Type == InlineAsm::isClobber) 8266 continue; 8267 8268 // If this is a memory input, and if the operand is not indirect, do what we 8269 // need to provide an address for the memory input. 8270 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8271 !OpInfo.isIndirect) { 8272 assert((OpInfo.isMultipleAlternative || 8273 (OpInfo.Type == InlineAsm::isInput)) && 8274 "Can only indirectify direct input operands!"); 8275 8276 // Memory operands really want the address of the value. 8277 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8278 8279 // There is no longer a Value* corresponding to this operand. 8280 OpInfo.CallOperandVal = nullptr; 8281 8282 // It is now an indirect operand. 8283 OpInfo.isIndirect = true; 8284 } 8285 8286 } 8287 8288 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8289 std::vector<SDValue> AsmNodeOperands; 8290 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8291 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8292 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 8293 8294 // If we have a !srcloc metadata node associated with it, we want to attach 8295 // this to the ultimately generated inline asm machineinstr. To do this, we 8296 // pass in the third operand as this (potentially null) inline asm MDNode. 8297 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 8298 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8299 8300 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8301 // bits as operand 3. 8302 AsmNodeOperands.push_back(DAG.getTargetConstant( 8303 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8304 8305 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8306 // this, assign virtual and physical registers for inputs and otput. 8307 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8308 // Assign Registers. 8309 SDISelAsmOperandInfo &RefOpInfo = 8310 OpInfo.isMatchingInputConstraint() 8311 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8312 : OpInfo; 8313 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8314 8315 switch (OpInfo.Type) { 8316 case InlineAsm::isOutput: 8317 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8318 unsigned ConstraintID = 8319 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8320 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8321 "Failed to convert memory constraint code to constraint id."); 8322 8323 // Add information to the INLINEASM node to know about this output. 8324 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8325 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8326 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8327 MVT::i32)); 8328 AsmNodeOperands.push_back(OpInfo.CallOperand); 8329 } else { 8330 // Otherwise, this outputs to a register (directly for C_Register / 8331 // C_RegisterClass, and a target-defined fashion for 8332 // C_Immediate/C_Other). Find a register that we can use. 8333 if (OpInfo.AssignedRegs.Regs.empty()) { 8334 emitInlineAsmError( 8335 CS, "couldn't allocate output register for constraint '" + 8336 Twine(OpInfo.ConstraintCode) + "'"); 8337 return; 8338 } 8339 8340 // Add information to the INLINEASM node to know that this register is 8341 // set. 8342 OpInfo.AssignedRegs.AddInlineAsmOperands( 8343 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8344 : InlineAsm::Kind_RegDef, 8345 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8346 } 8347 break; 8348 8349 case InlineAsm::isInput: { 8350 SDValue InOperandVal = OpInfo.CallOperand; 8351 8352 if (OpInfo.isMatchingInputConstraint()) { 8353 // If this is required to match an output register we have already set, 8354 // just use its register. 8355 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8356 AsmNodeOperands); 8357 unsigned OpFlag = 8358 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8359 if (InlineAsm::isRegDefKind(OpFlag) || 8360 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8361 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8362 if (OpInfo.isIndirect) { 8363 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8364 emitInlineAsmError(CS, "inline asm not supported yet:" 8365 " don't know how to handle tied " 8366 "indirect register inputs"); 8367 return; 8368 } 8369 8370 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8371 SmallVector<unsigned, 4> Regs; 8372 8373 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8374 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8375 MachineRegisterInfo &RegInfo = 8376 DAG.getMachineFunction().getRegInfo(); 8377 for (unsigned i = 0; i != NumRegs; ++i) 8378 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8379 } else { 8380 emitInlineAsmError(CS, "inline asm error: This value type register " 8381 "class is not natively supported!"); 8382 return; 8383 } 8384 8385 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8386 8387 SDLoc dl = getCurSDLoc(); 8388 // Use the produced MatchedRegs object to 8389 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8390 CS.getInstruction()); 8391 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8392 true, OpInfo.getMatchedOperand(), dl, 8393 DAG, AsmNodeOperands); 8394 break; 8395 } 8396 8397 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8398 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8399 "Unexpected number of operands"); 8400 // Add information to the INLINEASM node to know about this input. 8401 // See InlineAsm.h isUseOperandTiedToDef. 8402 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8403 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8404 OpInfo.getMatchedOperand()); 8405 AsmNodeOperands.push_back(DAG.getTargetConstant( 8406 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8407 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8408 break; 8409 } 8410 8411 // Treat indirect 'X' constraint as memory. 8412 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8413 OpInfo.isIndirect) 8414 OpInfo.ConstraintType = TargetLowering::C_Memory; 8415 8416 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8417 OpInfo.ConstraintType == TargetLowering::C_Other) { 8418 std::vector<SDValue> Ops; 8419 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8420 Ops, DAG); 8421 if (Ops.empty()) { 8422 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8423 if (isa<ConstantSDNode>(InOperandVal)) { 8424 emitInlineAsmError(CS, "value out of range for constraint '" + 8425 Twine(OpInfo.ConstraintCode) + "'"); 8426 return; 8427 } 8428 8429 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8430 Twine(OpInfo.ConstraintCode) + "'"); 8431 return; 8432 } 8433 8434 // Add information to the INLINEASM node to know about this input. 8435 unsigned ResOpType = 8436 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8437 AsmNodeOperands.push_back(DAG.getTargetConstant( 8438 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8439 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8440 break; 8441 } 8442 8443 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8444 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8445 assert(InOperandVal.getValueType() == 8446 TLI.getPointerTy(DAG.getDataLayout()) && 8447 "Memory operands expect pointer values"); 8448 8449 unsigned ConstraintID = 8450 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8451 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8452 "Failed to convert memory constraint code to constraint id."); 8453 8454 // Add information to the INLINEASM node to know about this input. 8455 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8456 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8457 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8458 getCurSDLoc(), 8459 MVT::i32)); 8460 AsmNodeOperands.push_back(InOperandVal); 8461 break; 8462 } 8463 8464 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8465 OpInfo.ConstraintType == TargetLowering::C_Register) && 8466 "Unknown constraint type!"); 8467 8468 // TODO: Support this. 8469 if (OpInfo.isIndirect) { 8470 emitInlineAsmError( 8471 CS, "Don't know how to handle indirect register inputs yet " 8472 "for constraint '" + 8473 Twine(OpInfo.ConstraintCode) + "'"); 8474 return; 8475 } 8476 8477 // Copy the input into the appropriate registers. 8478 if (OpInfo.AssignedRegs.Regs.empty()) { 8479 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8480 Twine(OpInfo.ConstraintCode) + "'"); 8481 return; 8482 } 8483 8484 SDLoc dl = getCurSDLoc(); 8485 8486 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8487 Chain, &Flag, CS.getInstruction()); 8488 8489 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8490 dl, DAG, AsmNodeOperands); 8491 break; 8492 } 8493 case InlineAsm::isClobber: 8494 // Add the clobbered value to the operand list, so that the register 8495 // allocator is aware that the physreg got clobbered. 8496 if (!OpInfo.AssignedRegs.Regs.empty()) 8497 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8498 false, 0, getCurSDLoc(), DAG, 8499 AsmNodeOperands); 8500 break; 8501 } 8502 } 8503 8504 // Finish up input operands. Set the input chain and add the flag last. 8505 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8506 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8507 8508 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8509 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8510 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8511 Flag = Chain.getValue(1); 8512 8513 // Do additional work to generate outputs. 8514 8515 SmallVector<EVT, 1> ResultVTs; 8516 SmallVector<SDValue, 1> ResultValues; 8517 SmallVector<SDValue, 8> OutChains; 8518 8519 llvm::Type *CSResultType = CS.getType(); 8520 ArrayRef<Type *> ResultTypes; 8521 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8522 ResultTypes = StructResult->elements(); 8523 else if (!CSResultType->isVoidTy()) 8524 ResultTypes = makeArrayRef(CSResultType); 8525 8526 auto CurResultType = ResultTypes.begin(); 8527 auto handleRegAssign = [&](SDValue V) { 8528 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8529 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8530 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8531 ++CurResultType; 8532 // If the type of the inline asm call site return value is different but has 8533 // same size as the type of the asm output bitcast it. One example of this 8534 // is for vectors with different width / number of elements. This can 8535 // happen for register classes that can contain multiple different value 8536 // types. The preg or vreg allocated may not have the same VT as was 8537 // expected. 8538 // 8539 // This can also happen for a return value that disagrees with the register 8540 // class it is put in, eg. a double in a general-purpose register on a 8541 // 32-bit machine. 8542 if (ResultVT != V.getValueType() && 8543 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8544 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8545 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8546 V.getValueType().isInteger()) { 8547 // If a result value was tied to an input value, the computed result 8548 // may have a wider width than the expected result. Extract the 8549 // relevant portion. 8550 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8551 } 8552 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8553 ResultVTs.push_back(ResultVT); 8554 ResultValues.push_back(V); 8555 }; 8556 8557 // Deal with output operands. 8558 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8559 if (OpInfo.Type == InlineAsm::isOutput) { 8560 SDValue Val; 8561 // Skip trivial output operands. 8562 if (OpInfo.AssignedRegs.Regs.empty()) 8563 continue; 8564 8565 switch (OpInfo.ConstraintType) { 8566 case TargetLowering::C_Register: 8567 case TargetLowering::C_RegisterClass: 8568 Val = OpInfo.AssignedRegs.getCopyFromRegs( 8569 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 8570 break; 8571 case TargetLowering::C_Immediate: 8572 case TargetLowering::C_Other: 8573 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8574 OpInfo, DAG); 8575 break; 8576 case TargetLowering::C_Memory: 8577 break; // Already handled. 8578 case TargetLowering::C_Unknown: 8579 assert(false && "Unexpected unknown constraint"); 8580 } 8581 8582 // Indirect output manifest as stores. Record output chains. 8583 if (OpInfo.isIndirect) { 8584 const Value *Ptr = OpInfo.CallOperandVal; 8585 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8586 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8587 MachinePointerInfo(Ptr)); 8588 OutChains.push_back(Store); 8589 } else { 8590 // generate CopyFromRegs to associated registers. 8591 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8592 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8593 for (const SDValue &V : Val->op_values()) 8594 handleRegAssign(V); 8595 } else 8596 handleRegAssign(Val); 8597 } 8598 } 8599 } 8600 8601 // Set results. 8602 if (!ResultValues.empty()) { 8603 assert(CurResultType == ResultTypes.end() && 8604 "Mismatch in number of ResultTypes"); 8605 assert(ResultValues.size() == ResultTypes.size() && 8606 "Mismatch in number of output operands in asm result"); 8607 8608 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8609 DAG.getVTList(ResultVTs), ResultValues); 8610 setValue(CS.getInstruction(), V); 8611 } 8612 8613 // Collect store chains. 8614 if (!OutChains.empty()) 8615 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8616 8617 // Only Update Root if inline assembly has a memory effect. 8618 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8619 DAG.setRoot(Chain); 8620 } 8621 8622 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8623 const Twine &Message) { 8624 LLVMContext &Ctx = *DAG.getContext(); 8625 Ctx.emitError(CS.getInstruction(), Message); 8626 8627 // Make sure we leave the DAG in a valid state 8628 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8629 SmallVector<EVT, 1> ValueVTs; 8630 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8631 8632 if (ValueVTs.empty()) 8633 return; 8634 8635 SmallVector<SDValue, 1> Ops; 8636 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8637 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8638 8639 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8640 } 8641 8642 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8643 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8644 MVT::Other, getRoot(), 8645 getValue(I.getArgOperand(0)), 8646 DAG.getSrcValue(I.getArgOperand(0)))); 8647 } 8648 8649 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8650 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8651 const DataLayout &DL = DAG.getDataLayout(); 8652 SDValue V = DAG.getVAArg( 8653 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8654 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8655 DL.getABITypeAlignment(I.getType())); 8656 DAG.setRoot(V.getValue(1)); 8657 8658 if (I.getType()->isPointerTy()) 8659 V = DAG.getPtrExtOrTrunc( 8660 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8661 setValue(&I, V); 8662 } 8663 8664 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8665 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8666 MVT::Other, getRoot(), 8667 getValue(I.getArgOperand(0)), 8668 DAG.getSrcValue(I.getArgOperand(0)))); 8669 } 8670 8671 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8672 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8673 MVT::Other, getRoot(), 8674 getValue(I.getArgOperand(0)), 8675 getValue(I.getArgOperand(1)), 8676 DAG.getSrcValue(I.getArgOperand(0)), 8677 DAG.getSrcValue(I.getArgOperand(1)))); 8678 } 8679 8680 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8681 const Instruction &I, 8682 SDValue Op) { 8683 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8684 if (!Range) 8685 return Op; 8686 8687 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8688 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8689 return Op; 8690 8691 APInt Lo = CR.getUnsignedMin(); 8692 if (!Lo.isMinValue()) 8693 return Op; 8694 8695 APInt Hi = CR.getUnsignedMax(); 8696 unsigned Bits = std::max(Hi.getActiveBits(), 8697 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8698 8699 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8700 8701 SDLoc SL = getCurSDLoc(); 8702 8703 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8704 DAG.getValueType(SmallVT)); 8705 unsigned NumVals = Op.getNode()->getNumValues(); 8706 if (NumVals == 1) 8707 return ZExt; 8708 8709 SmallVector<SDValue, 4> Ops; 8710 8711 Ops.push_back(ZExt); 8712 for (unsigned I = 1; I != NumVals; ++I) 8713 Ops.push_back(Op.getValue(I)); 8714 8715 return DAG.getMergeValues(Ops, SL); 8716 } 8717 8718 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8719 /// the call being lowered. 8720 /// 8721 /// This is a helper for lowering intrinsics that follow a target calling 8722 /// convention or require stack pointer adjustment. Only a subset of the 8723 /// intrinsic's operands need to participate in the calling convention. 8724 void SelectionDAGBuilder::populateCallLoweringInfo( 8725 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8726 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8727 bool IsPatchPoint) { 8728 TargetLowering::ArgListTy Args; 8729 Args.reserve(NumArgs); 8730 8731 // Populate the argument list. 8732 // Attributes for args start at offset 1, after the return attribute. 8733 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8734 ArgI != ArgE; ++ArgI) { 8735 const Value *V = Call->getOperand(ArgI); 8736 8737 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8738 8739 TargetLowering::ArgListEntry Entry; 8740 Entry.Node = getValue(V); 8741 Entry.Ty = V->getType(); 8742 Entry.setAttributes(Call, ArgI); 8743 Args.push_back(Entry); 8744 } 8745 8746 CLI.setDebugLoc(getCurSDLoc()) 8747 .setChain(getRoot()) 8748 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8749 .setDiscardResult(Call->use_empty()) 8750 .setIsPatchPoint(IsPatchPoint); 8751 } 8752 8753 /// Add a stack map intrinsic call's live variable operands to a stackmap 8754 /// or patchpoint target node's operand list. 8755 /// 8756 /// Constants are converted to TargetConstants purely as an optimization to 8757 /// avoid constant materialization and register allocation. 8758 /// 8759 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8760 /// generate addess computation nodes, and so FinalizeISel can convert the 8761 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8762 /// address materialization and register allocation, but may also be required 8763 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8764 /// alloca in the entry block, then the runtime may assume that the alloca's 8765 /// StackMap location can be read immediately after compilation and that the 8766 /// location is valid at any point during execution (this is similar to the 8767 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8768 /// only available in a register, then the runtime would need to trap when 8769 /// execution reaches the StackMap in order to read the alloca's location. 8770 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8771 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8772 SelectionDAGBuilder &Builder) { 8773 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8774 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8775 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8776 Ops.push_back( 8777 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8778 Ops.push_back( 8779 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8780 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8781 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8782 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8783 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8784 } else 8785 Ops.push_back(OpVal); 8786 } 8787 } 8788 8789 /// Lower llvm.experimental.stackmap directly to its target opcode. 8790 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8791 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8792 // [live variables...]) 8793 8794 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8795 8796 SDValue Chain, InFlag, Callee, NullPtr; 8797 SmallVector<SDValue, 32> Ops; 8798 8799 SDLoc DL = getCurSDLoc(); 8800 Callee = getValue(CI.getCalledValue()); 8801 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8802 8803 // The stackmap intrinsic only records the live variables (the arguments 8804 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8805 // intrinsic, this won't be lowered to a function call. This means we don't 8806 // have to worry about calling conventions and target specific lowering code. 8807 // Instead we perform the call lowering right here. 8808 // 8809 // chain, flag = CALLSEQ_START(chain, 0, 0) 8810 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8811 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8812 // 8813 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8814 InFlag = Chain.getValue(1); 8815 8816 // Add the <id> and <numBytes> constants. 8817 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8818 Ops.push_back(DAG.getTargetConstant( 8819 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8820 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8821 Ops.push_back(DAG.getTargetConstant( 8822 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8823 MVT::i32)); 8824 8825 // Push live variables for the stack map. 8826 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8827 8828 // We are not pushing any register mask info here on the operands list, 8829 // because the stackmap doesn't clobber anything. 8830 8831 // Push the chain and the glue flag. 8832 Ops.push_back(Chain); 8833 Ops.push_back(InFlag); 8834 8835 // Create the STACKMAP node. 8836 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8837 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8838 Chain = SDValue(SM, 0); 8839 InFlag = Chain.getValue(1); 8840 8841 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8842 8843 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8844 8845 // Set the root to the target-lowered call chain. 8846 DAG.setRoot(Chain); 8847 8848 // Inform the Frame Information that we have a stackmap in this function. 8849 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8850 } 8851 8852 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8853 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8854 const BasicBlock *EHPadBB) { 8855 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8856 // i32 <numBytes>, 8857 // i8* <target>, 8858 // i32 <numArgs>, 8859 // [Args...], 8860 // [live variables...]) 8861 8862 CallingConv::ID CC = CS.getCallingConv(); 8863 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8864 bool HasDef = !CS->getType()->isVoidTy(); 8865 SDLoc dl = getCurSDLoc(); 8866 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8867 8868 // Handle immediate and symbolic callees. 8869 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8870 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8871 /*isTarget=*/true); 8872 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8873 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8874 SDLoc(SymbolicCallee), 8875 SymbolicCallee->getValueType(0)); 8876 8877 // Get the real number of arguments participating in the call <numArgs> 8878 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8879 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8880 8881 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8882 // Intrinsics include all meta-operands up to but not including CC. 8883 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8884 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8885 "Not enough arguments provided to the patchpoint intrinsic"); 8886 8887 // For AnyRegCC the arguments are lowered later on manually. 8888 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8889 Type *ReturnTy = 8890 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8891 8892 TargetLowering::CallLoweringInfo CLI(DAG); 8893 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8894 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); 8895 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8896 8897 SDNode *CallEnd = Result.second.getNode(); 8898 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8899 CallEnd = CallEnd->getOperand(0).getNode(); 8900 8901 /// Get a call instruction from the call sequence chain. 8902 /// Tail calls are not allowed. 8903 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8904 "Expected a callseq node."); 8905 SDNode *Call = CallEnd->getOperand(0).getNode(); 8906 bool HasGlue = Call->getGluedNode(); 8907 8908 // Replace the target specific call node with the patchable intrinsic. 8909 SmallVector<SDValue, 8> Ops; 8910 8911 // Add the <id> and <numBytes> constants. 8912 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8913 Ops.push_back(DAG.getTargetConstant( 8914 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8915 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8916 Ops.push_back(DAG.getTargetConstant( 8917 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8918 MVT::i32)); 8919 8920 // Add the callee. 8921 Ops.push_back(Callee); 8922 8923 // Adjust <numArgs> to account for any arguments that have been passed on the 8924 // stack instead. 8925 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8926 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8927 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8928 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8929 8930 // Add the calling convention 8931 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8932 8933 // Add the arguments we omitted previously. The register allocator should 8934 // place these in any free register. 8935 if (IsAnyRegCC) 8936 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8937 Ops.push_back(getValue(CS.getArgument(i))); 8938 8939 // Push the arguments from the call instruction up to the register mask. 8940 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8941 Ops.append(Call->op_begin() + 2, e); 8942 8943 // Push live variables for the stack map. 8944 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8945 8946 // Push the register mask info. 8947 if (HasGlue) 8948 Ops.push_back(*(Call->op_end()-2)); 8949 else 8950 Ops.push_back(*(Call->op_end()-1)); 8951 8952 // Push the chain (this is originally the first operand of the call, but 8953 // becomes now the last or second to last operand). 8954 Ops.push_back(*(Call->op_begin())); 8955 8956 // Push the glue flag (last operand). 8957 if (HasGlue) 8958 Ops.push_back(*(Call->op_end()-1)); 8959 8960 SDVTList NodeTys; 8961 if (IsAnyRegCC && HasDef) { 8962 // Create the return types based on the intrinsic definition 8963 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8964 SmallVector<EVT, 3> ValueVTs; 8965 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8966 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8967 8968 // There is always a chain and a glue type at the end 8969 ValueVTs.push_back(MVT::Other); 8970 ValueVTs.push_back(MVT::Glue); 8971 NodeTys = DAG.getVTList(ValueVTs); 8972 } else 8973 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8974 8975 // Replace the target specific call node with a PATCHPOINT node. 8976 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8977 dl, NodeTys, Ops); 8978 8979 // Update the NodeMap. 8980 if (HasDef) { 8981 if (IsAnyRegCC) 8982 setValue(CS.getInstruction(), SDValue(MN, 0)); 8983 else 8984 setValue(CS.getInstruction(), Result.first); 8985 } 8986 8987 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8988 // call sequence. Furthermore the location of the chain and glue can change 8989 // when the AnyReg calling convention is used and the intrinsic returns a 8990 // value. 8991 if (IsAnyRegCC && HasDef) { 8992 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8993 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8994 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8995 } else 8996 DAG.ReplaceAllUsesWith(Call, MN); 8997 DAG.DeleteNode(Call); 8998 8999 // Inform the Frame Information that we have a patchpoint in this function. 9000 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9001 } 9002 9003 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9004 unsigned Intrinsic) { 9005 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9006 SDValue Op1 = getValue(I.getArgOperand(0)); 9007 SDValue Op2; 9008 if (I.getNumArgOperands() > 1) 9009 Op2 = getValue(I.getArgOperand(1)); 9010 SDLoc dl = getCurSDLoc(); 9011 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9012 SDValue Res; 9013 FastMathFlags FMF; 9014 if (isa<FPMathOperator>(I)) 9015 FMF = I.getFastMathFlags(); 9016 9017 switch (Intrinsic) { 9018 case Intrinsic::experimental_vector_reduce_v2_fadd: 9019 if (FMF.allowReassoc()) 9020 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9021 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 9022 else 9023 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 9024 break; 9025 case Intrinsic::experimental_vector_reduce_v2_fmul: 9026 if (FMF.allowReassoc()) 9027 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9028 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 9029 else 9030 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 9031 break; 9032 case Intrinsic::experimental_vector_reduce_add: 9033 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9034 break; 9035 case Intrinsic::experimental_vector_reduce_mul: 9036 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9037 break; 9038 case Intrinsic::experimental_vector_reduce_and: 9039 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9040 break; 9041 case Intrinsic::experimental_vector_reduce_or: 9042 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9043 break; 9044 case Intrinsic::experimental_vector_reduce_xor: 9045 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9046 break; 9047 case Intrinsic::experimental_vector_reduce_smax: 9048 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9049 break; 9050 case Intrinsic::experimental_vector_reduce_smin: 9051 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9052 break; 9053 case Intrinsic::experimental_vector_reduce_umax: 9054 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9055 break; 9056 case Intrinsic::experimental_vector_reduce_umin: 9057 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9058 break; 9059 case Intrinsic::experimental_vector_reduce_fmax: 9060 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 9061 break; 9062 case Intrinsic::experimental_vector_reduce_fmin: 9063 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 9064 break; 9065 default: 9066 llvm_unreachable("Unhandled vector reduce intrinsic"); 9067 } 9068 setValue(&I, Res); 9069 } 9070 9071 /// Returns an AttributeList representing the attributes applied to the return 9072 /// value of the given call. 9073 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9074 SmallVector<Attribute::AttrKind, 2> Attrs; 9075 if (CLI.RetSExt) 9076 Attrs.push_back(Attribute::SExt); 9077 if (CLI.RetZExt) 9078 Attrs.push_back(Attribute::ZExt); 9079 if (CLI.IsInReg) 9080 Attrs.push_back(Attribute::InReg); 9081 9082 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9083 Attrs); 9084 } 9085 9086 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9087 /// implementation, which just calls LowerCall. 9088 /// FIXME: When all targets are 9089 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9090 std::pair<SDValue, SDValue> 9091 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9092 // Handle the incoming return values from the call. 9093 CLI.Ins.clear(); 9094 Type *OrigRetTy = CLI.RetTy; 9095 SmallVector<EVT, 4> RetTys; 9096 SmallVector<uint64_t, 4> Offsets; 9097 auto &DL = CLI.DAG.getDataLayout(); 9098 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9099 9100 if (CLI.IsPostTypeLegalization) { 9101 // If we are lowering a libcall after legalization, split the return type. 9102 SmallVector<EVT, 4> OldRetTys; 9103 SmallVector<uint64_t, 4> OldOffsets; 9104 RetTys.swap(OldRetTys); 9105 Offsets.swap(OldOffsets); 9106 9107 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9108 EVT RetVT = OldRetTys[i]; 9109 uint64_t Offset = OldOffsets[i]; 9110 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9111 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9112 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9113 RetTys.append(NumRegs, RegisterVT); 9114 for (unsigned j = 0; j != NumRegs; ++j) 9115 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9116 } 9117 } 9118 9119 SmallVector<ISD::OutputArg, 4> Outs; 9120 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9121 9122 bool CanLowerReturn = 9123 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9124 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9125 9126 SDValue DemoteStackSlot; 9127 int DemoteStackIdx = -100; 9128 if (!CanLowerReturn) { 9129 // FIXME: equivalent assert? 9130 // assert(!CS.hasInAllocaArgument() && 9131 // "sret demotion is incompatible with inalloca"); 9132 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9133 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 9134 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9135 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 9136 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9137 DL.getAllocaAddrSpace()); 9138 9139 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9140 ArgListEntry Entry; 9141 Entry.Node = DemoteStackSlot; 9142 Entry.Ty = StackSlotPtrType; 9143 Entry.IsSExt = false; 9144 Entry.IsZExt = false; 9145 Entry.IsInReg = false; 9146 Entry.IsSRet = true; 9147 Entry.IsNest = false; 9148 Entry.IsByVal = false; 9149 Entry.IsReturned = false; 9150 Entry.IsSwiftSelf = false; 9151 Entry.IsSwiftError = false; 9152 Entry.IsCFGuardTarget = false; 9153 Entry.Alignment = Align; 9154 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9155 CLI.NumFixedArgs += 1; 9156 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9157 9158 // sret demotion isn't compatible with tail-calls, since the sret argument 9159 // points into the callers stack frame. 9160 CLI.IsTailCall = false; 9161 } else { 9162 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9163 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9164 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9165 ISD::ArgFlagsTy Flags; 9166 if (NeedsRegBlock) { 9167 Flags.setInConsecutiveRegs(); 9168 if (I == RetTys.size() - 1) 9169 Flags.setInConsecutiveRegsLast(); 9170 } 9171 EVT VT = RetTys[I]; 9172 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9173 CLI.CallConv, VT); 9174 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9175 CLI.CallConv, VT); 9176 for (unsigned i = 0; i != NumRegs; ++i) { 9177 ISD::InputArg MyFlags; 9178 MyFlags.Flags = Flags; 9179 MyFlags.VT = RegisterVT; 9180 MyFlags.ArgVT = VT; 9181 MyFlags.Used = CLI.IsReturnValueUsed; 9182 if (CLI.RetTy->isPointerTy()) { 9183 MyFlags.Flags.setPointer(); 9184 MyFlags.Flags.setPointerAddrSpace( 9185 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9186 } 9187 if (CLI.RetSExt) 9188 MyFlags.Flags.setSExt(); 9189 if (CLI.RetZExt) 9190 MyFlags.Flags.setZExt(); 9191 if (CLI.IsInReg) 9192 MyFlags.Flags.setInReg(); 9193 CLI.Ins.push_back(MyFlags); 9194 } 9195 } 9196 } 9197 9198 // We push in swifterror return as the last element of CLI.Ins. 9199 ArgListTy &Args = CLI.getArgs(); 9200 if (supportSwiftError()) { 9201 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9202 if (Args[i].IsSwiftError) { 9203 ISD::InputArg MyFlags; 9204 MyFlags.VT = getPointerTy(DL); 9205 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9206 MyFlags.Flags.setSwiftError(); 9207 CLI.Ins.push_back(MyFlags); 9208 } 9209 } 9210 } 9211 9212 // Handle all of the outgoing arguments. 9213 CLI.Outs.clear(); 9214 CLI.OutVals.clear(); 9215 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9216 SmallVector<EVT, 4> ValueVTs; 9217 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9218 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9219 Type *FinalType = Args[i].Ty; 9220 if (Args[i].IsByVal) 9221 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9222 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9223 FinalType, CLI.CallConv, CLI.IsVarArg); 9224 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9225 ++Value) { 9226 EVT VT = ValueVTs[Value]; 9227 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9228 SDValue Op = SDValue(Args[i].Node.getNode(), 9229 Args[i].Node.getResNo() + Value); 9230 ISD::ArgFlagsTy Flags; 9231 9232 // Certain targets (such as MIPS), may have a different ABI alignment 9233 // for a type depending on the context. Give the target a chance to 9234 // specify the alignment it wants. 9235 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9236 9237 if (Args[i].Ty->isPointerTy()) { 9238 Flags.setPointer(); 9239 Flags.setPointerAddrSpace( 9240 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9241 } 9242 if (Args[i].IsZExt) 9243 Flags.setZExt(); 9244 if (Args[i].IsSExt) 9245 Flags.setSExt(); 9246 if (Args[i].IsInReg) { 9247 // If we are using vectorcall calling convention, a structure that is 9248 // passed InReg - is surely an HVA 9249 if (CLI.CallConv == CallingConv::X86_VectorCall && 9250 isa<StructType>(FinalType)) { 9251 // The first value of a structure is marked 9252 if (0 == Value) 9253 Flags.setHvaStart(); 9254 Flags.setHva(); 9255 } 9256 // Set InReg Flag 9257 Flags.setInReg(); 9258 } 9259 if (Args[i].IsSRet) 9260 Flags.setSRet(); 9261 if (Args[i].IsSwiftSelf) 9262 Flags.setSwiftSelf(); 9263 if (Args[i].IsSwiftError) 9264 Flags.setSwiftError(); 9265 if (Args[i].IsCFGuardTarget) 9266 Flags.setCFGuardTarget(); 9267 if (Args[i].IsByVal) 9268 Flags.setByVal(); 9269 if (Args[i].IsInAlloca) { 9270 Flags.setInAlloca(); 9271 // Set the byval flag for CCAssignFn callbacks that don't know about 9272 // inalloca. This way we can know how many bytes we should've allocated 9273 // and how many bytes a callee cleanup function will pop. If we port 9274 // inalloca to more targets, we'll have to add custom inalloca handling 9275 // in the various CC lowering callbacks. 9276 Flags.setByVal(); 9277 } 9278 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9279 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9280 Type *ElementTy = Ty->getElementType(); 9281 9282 unsigned FrameSize = DL.getTypeAllocSize( 9283 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9284 Flags.setByValSize(FrameSize); 9285 9286 // info is not there but there are cases it cannot get right. 9287 unsigned FrameAlign; 9288 if (Args[i].Alignment) 9289 FrameAlign = Args[i].Alignment; 9290 else 9291 FrameAlign = getByValTypeAlignment(ElementTy, DL); 9292 Flags.setByValAlign(Align(FrameAlign)); 9293 } 9294 if (Args[i].IsNest) 9295 Flags.setNest(); 9296 if (NeedsRegBlock) 9297 Flags.setInConsecutiveRegs(); 9298 Flags.setOrigAlign(OriginalAlignment); 9299 9300 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9301 CLI.CallConv, VT); 9302 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9303 CLI.CallConv, VT); 9304 SmallVector<SDValue, 4> Parts(NumParts); 9305 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9306 9307 if (Args[i].IsSExt) 9308 ExtendKind = ISD::SIGN_EXTEND; 9309 else if (Args[i].IsZExt) 9310 ExtendKind = ISD::ZERO_EXTEND; 9311 9312 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9313 // for now. 9314 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9315 CanLowerReturn) { 9316 assert((CLI.RetTy == Args[i].Ty || 9317 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9318 CLI.RetTy->getPointerAddressSpace() == 9319 Args[i].Ty->getPointerAddressSpace())) && 9320 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9321 // Before passing 'returned' to the target lowering code, ensure that 9322 // either the register MVT and the actual EVT are the same size or that 9323 // the return value and argument are extended in the same way; in these 9324 // cases it's safe to pass the argument register value unchanged as the 9325 // return register value (although it's at the target's option whether 9326 // to do so) 9327 // TODO: allow code generation to take advantage of partially preserved 9328 // registers rather than clobbering the entire register when the 9329 // parameter extension method is not compatible with the return 9330 // extension method 9331 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9332 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9333 CLI.RetZExt == Args[i].IsZExt)) 9334 Flags.setReturned(); 9335 } 9336 9337 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 9338 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 9339 9340 for (unsigned j = 0; j != NumParts; ++j) { 9341 // if it isn't first piece, alignment must be 1 9342 // For scalable vectors the scalable part is currently handled 9343 // by individual targets, so we just use the known minimum size here. 9344 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9345 i < CLI.NumFixedArgs, i, 9346 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9347 if (NumParts > 1 && j == 0) 9348 MyFlags.Flags.setSplit(); 9349 else if (j != 0) { 9350 MyFlags.Flags.setOrigAlign(Align(1)); 9351 if (j == NumParts - 1) 9352 MyFlags.Flags.setSplitEnd(); 9353 } 9354 9355 CLI.Outs.push_back(MyFlags); 9356 CLI.OutVals.push_back(Parts[j]); 9357 } 9358 9359 if (NeedsRegBlock && Value == NumValues - 1) 9360 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9361 } 9362 } 9363 9364 SmallVector<SDValue, 4> InVals; 9365 CLI.Chain = LowerCall(CLI, InVals); 9366 9367 // Update CLI.InVals to use outside of this function. 9368 CLI.InVals = InVals; 9369 9370 // Verify that the target's LowerCall behaved as expected. 9371 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9372 "LowerCall didn't return a valid chain!"); 9373 assert((!CLI.IsTailCall || InVals.empty()) && 9374 "LowerCall emitted a return value for a tail call!"); 9375 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9376 "LowerCall didn't emit the correct number of values!"); 9377 9378 // For a tail call, the return value is merely live-out and there aren't 9379 // any nodes in the DAG representing it. Return a special value to 9380 // indicate that a tail call has been emitted and no more Instructions 9381 // should be processed in the current block. 9382 if (CLI.IsTailCall) { 9383 CLI.DAG.setRoot(CLI.Chain); 9384 return std::make_pair(SDValue(), SDValue()); 9385 } 9386 9387 #ifndef NDEBUG 9388 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9389 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9390 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9391 "LowerCall emitted a value with the wrong type!"); 9392 } 9393 #endif 9394 9395 SmallVector<SDValue, 4> ReturnValues; 9396 if (!CanLowerReturn) { 9397 // The instruction result is the result of loading from the 9398 // hidden sret parameter. 9399 SmallVector<EVT, 1> PVTs; 9400 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9401 9402 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9403 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9404 EVT PtrVT = PVTs[0]; 9405 9406 unsigned NumValues = RetTys.size(); 9407 ReturnValues.resize(NumValues); 9408 SmallVector<SDValue, 4> Chains(NumValues); 9409 9410 // An aggregate return value cannot wrap around the address space, so 9411 // offsets to its parts don't wrap either. 9412 SDNodeFlags Flags; 9413 Flags.setNoUnsignedWrap(true); 9414 9415 for (unsigned i = 0; i < NumValues; ++i) { 9416 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9417 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9418 PtrVT), Flags); 9419 SDValue L = CLI.DAG.getLoad( 9420 RetTys[i], CLI.DL, CLI.Chain, Add, 9421 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9422 DemoteStackIdx, Offsets[i]), 9423 /* Alignment = */ 1); 9424 ReturnValues[i] = L; 9425 Chains[i] = L.getValue(1); 9426 } 9427 9428 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9429 } else { 9430 // Collect the legal value parts into potentially illegal values 9431 // that correspond to the original function's return values. 9432 Optional<ISD::NodeType> AssertOp; 9433 if (CLI.RetSExt) 9434 AssertOp = ISD::AssertSext; 9435 else if (CLI.RetZExt) 9436 AssertOp = ISD::AssertZext; 9437 unsigned CurReg = 0; 9438 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9439 EVT VT = RetTys[I]; 9440 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9441 CLI.CallConv, VT); 9442 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9443 CLI.CallConv, VT); 9444 9445 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9446 NumRegs, RegisterVT, VT, nullptr, 9447 CLI.CallConv, AssertOp)); 9448 CurReg += NumRegs; 9449 } 9450 9451 // For a function returning void, there is no return value. We can't create 9452 // such a node, so we just return a null return value in that case. In 9453 // that case, nothing will actually look at the value. 9454 if (ReturnValues.empty()) 9455 return std::make_pair(SDValue(), CLI.Chain); 9456 } 9457 9458 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9459 CLI.DAG.getVTList(RetTys), ReturnValues); 9460 return std::make_pair(Res, CLI.Chain); 9461 } 9462 9463 void TargetLowering::LowerOperationWrapper(SDNode *N, 9464 SmallVectorImpl<SDValue> &Results, 9465 SelectionDAG &DAG) const { 9466 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9467 Results.push_back(Res); 9468 } 9469 9470 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9471 llvm_unreachable("LowerOperation not implemented for this target!"); 9472 } 9473 9474 void 9475 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9476 SDValue Op = getNonRegisterValue(V); 9477 assert((Op.getOpcode() != ISD::CopyFromReg || 9478 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9479 "Copy from a reg to the same reg!"); 9480 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9481 9482 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9483 // If this is an InlineAsm we have to match the registers required, not the 9484 // notional registers required by the type. 9485 9486 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9487 None); // This is not an ABI copy. 9488 SDValue Chain = DAG.getEntryNode(); 9489 9490 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9491 FuncInfo.PreferredExtendType.end()) 9492 ? ISD::ANY_EXTEND 9493 : FuncInfo.PreferredExtendType[V]; 9494 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9495 PendingExports.push_back(Chain); 9496 } 9497 9498 #include "llvm/CodeGen/SelectionDAGISel.h" 9499 9500 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9501 /// entry block, return true. This includes arguments used by switches, since 9502 /// the switch may expand into multiple basic blocks. 9503 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9504 // With FastISel active, we may be splitting blocks, so force creation 9505 // of virtual registers for all non-dead arguments. 9506 if (FastISel) 9507 return A->use_empty(); 9508 9509 const BasicBlock &Entry = A->getParent()->front(); 9510 for (const User *U : A->users()) 9511 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9512 return false; // Use not in entry block. 9513 9514 return true; 9515 } 9516 9517 using ArgCopyElisionMapTy = 9518 DenseMap<const Argument *, 9519 std::pair<const AllocaInst *, const StoreInst *>>; 9520 9521 /// Scan the entry block of the function in FuncInfo for arguments that look 9522 /// like copies into a local alloca. Record any copied arguments in 9523 /// ArgCopyElisionCandidates. 9524 static void 9525 findArgumentCopyElisionCandidates(const DataLayout &DL, 9526 FunctionLoweringInfo *FuncInfo, 9527 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9528 // Record the state of every static alloca used in the entry block. Argument 9529 // allocas are all used in the entry block, so we need approximately as many 9530 // entries as we have arguments. 9531 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9532 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9533 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9534 StaticAllocas.reserve(NumArgs * 2); 9535 9536 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9537 if (!V) 9538 return nullptr; 9539 V = V->stripPointerCasts(); 9540 const auto *AI = dyn_cast<AllocaInst>(V); 9541 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9542 return nullptr; 9543 auto Iter = StaticAllocas.insert({AI, Unknown}); 9544 return &Iter.first->second; 9545 }; 9546 9547 // Look for stores of arguments to static allocas. Look through bitcasts and 9548 // GEPs to handle type coercions, as long as the alloca is fully initialized 9549 // by the store. Any non-store use of an alloca escapes it and any subsequent 9550 // unanalyzed store might write it. 9551 // FIXME: Handle structs initialized with multiple stores. 9552 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9553 // Look for stores, and handle non-store uses conservatively. 9554 const auto *SI = dyn_cast<StoreInst>(&I); 9555 if (!SI) { 9556 // We will look through cast uses, so ignore them completely. 9557 if (I.isCast()) 9558 continue; 9559 // Ignore debug info intrinsics, they don't escape or store to allocas. 9560 if (isa<DbgInfoIntrinsic>(I)) 9561 continue; 9562 // This is an unknown instruction. Assume it escapes or writes to all 9563 // static alloca operands. 9564 for (const Use &U : I.operands()) { 9565 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9566 *Info = StaticAllocaInfo::Clobbered; 9567 } 9568 continue; 9569 } 9570 9571 // If the stored value is a static alloca, mark it as escaped. 9572 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9573 *Info = StaticAllocaInfo::Clobbered; 9574 9575 // Check if the destination is a static alloca. 9576 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9577 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9578 if (!Info) 9579 continue; 9580 const AllocaInst *AI = cast<AllocaInst>(Dst); 9581 9582 // Skip allocas that have been initialized or clobbered. 9583 if (*Info != StaticAllocaInfo::Unknown) 9584 continue; 9585 9586 // Check if the stored value is an argument, and that this store fully 9587 // initializes the alloca. Don't elide copies from the same argument twice. 9588 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9589 const auto *Arg = dyn_cast<Argument>(Val); 9590 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9591 Arg->getType()->isEmptyTy() || 9592 DL.getTypeStoreSize(Arg->getType()) != 9593 DL.getTypeAllocSize(AI->getAllocatedType()) || 9594 ArgCopyElisionCandidates.count(Arg)) { 9595 *Info = StaticAllocaInfo::Clobbered; 9596 continue; 9597 } 9598 9599 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9600 << '\n'); 9601 9602 // Mark this alloca and store for argument copy elision. 9603 *Info = StaticAllocaInfo::Elidable; 9604 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9605 9606 // Stop scanning if we've seen all arguments. This will happen early in -O0 9607 // builds, which is useful, because -O0 builds have large entry blocks and 9608 // many allocas. 9609 if (ArgCopyElisionCandidates.size() == NumArgs) 9610 break; 9611 } 9612 } 9613 9614 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9615 /// ArgVal is a load from a suitable fixed stack object. 9616 static void tryToElideArgumentCopy( 9617 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9618 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9619 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9620 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9621 SDValue ArgVal, bool &ArgHasUses) { 9622 // Check if this is a load from a fixed stack object. 9623 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9624 if (!LNode) 9625 return; 9626 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9627 if (!FINode) 9628 return; 9629 9630 // Check that the fixed stack object is the right size and alignment. 9631 // Look at the alignment that the user wrote on the alloca instead of looking 9632 // at the stack object. 9633 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9634 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9635 const AllocaInst *AI = ArgCopyIter->second.first; 9636 int FixedIndex = FINode->getIndex(); 9637 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9638 int OldIndex = AllocaIndex; 9639 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9640 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9641 LLVM_DEBUG( 9642 dbgs() << " argument copy elision failed due to bad fixed stack " 9643 "object size\n"); 9644 return; 9645 } 9646 unsigned RequiredAlignment = AI->getAlignment(); 9647 if (!RequiredAlignment) { 9648 RequiredAlignment = FuncInfo.MF->getDataLayout().getABITypeAlignment( 9649 AI->getAllocatedType()); 9650 } 9651 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9652 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9653 "greater than stack argument alignment (" 9654 << RequiredAlignment << " vs " 9655 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9656 return; 9657 } 9658 9659 // Perform the elision. Delete the old stack object and replace its only use 9660 // in the variable info map. Mark the stack object as mutable. 9661 LLVM_DEBUG({ 9662 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9663 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9664 << '\n'; 9665 }); 9666 MFI.RemoveStackObject(OldIndex); 9667 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9668 AllocaIndex = FixedIndex; 9669 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9670 Chains.push_back(ArgVal.getValue(1)); 9671 9672 // Avoid emitting code for the store implementing the copy. 9673 const StoreInst *SI = ArgCopyIter->second.second; 9674 ElidedArgCopyInstrs.insert(SI); 9675 9676 // Check for uses of the argument again so that we can avoid exporting ArgVal 9677 // if it is't used by anything other than the store. 9678 for (const Value *U : Arg.users()) { 9679 if (U != SI) { 9680 ArgHasUses = true; 9681 break; 9682 } 9683 } 9684 } 9685 9686 void SelectionDAGISel::LowerArguments(const Function &F) { 9687 SelectionDAG &DAG = SDB->DAG; 9688 SDLoc dl = SDB->getCurSDLoc(); 9689 const DataLayout &DL = DAG.getDataLayout(); 9690 SmallVector<ISD::InputArg, 16> Ins; 9691 9692 if (!FuncInfo->CanLowerReturn) { 9693 // Put in an sret pointer parameter before all the other parameters. 9694 SmallVector<EVT, 1> ValueVTs; 9695 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9696 F.getReturnType()->getPointerTo( 9697 DAG.getDataLayout().getAllocaAddrSpace()), 9698 ValueVTs); 9699 9700 // NOTE: Assuming that a pointer will never break down to more than one VT 9701 // or one register. 9702 ISD::ArgFlagsTy Flags; 9703 Flags.setSRet(); 9704 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9705 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9706 ISD::InputArg::NoArgIndex, 0); 9707 Ins.push_back(RetArg); 9708 } 9709 9710 // Look for stores of arguments to static allocas. Mark such arguments with a 9711 // flag to ask the target to give us the memory location of that argument if 9712 // available. 9713 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9714 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9715 ArgCopyElisionCandidates); 9716 9717 // Set up the incoming argument description vector. 9718 for (const Argument &Arg : F.args()) { 9719 unsigned ArgNo = Arg.getArgNo(); 9720 SmallVector<EVT, 4> ValueVTs; 9721 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9722 bool isArgValueUsed = !Arg.use_empty(); 9723 unsigned PartBase = 0; 9724 Type *FinalType = Arg.getType(); 9725 if (Arg.hasAttribute(Attribute::ByVal)) 9726 FinalType = Arg.getParamByValType(); 9727 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9728 FinalType, F.getCallingConv(), F.isVarArg()); 9729 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9730 Value != NumValues; ++Value) { 9731 EVT VT = ValueVTs[Value]; 9732 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9733 ISD::ArgFlagsTy Flags; 9734 9735 // Certain targets (such as MIPS), may have a different ABI alignment 9736 // for a type depending on the context. Give the target a chance to 9737 // specify the alignment it wants. 9738 const Align OriginalAlignment( 9739 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9740 9741 if (Arg.getType()->isPointerTy()) { 9742 Flags.setPointer(); 9743 Flags.setPointerAddrSpace( 9744 cast<PointerType>(Arg.getType())->getAddressSpace()); 9745 } 9746 if (Arg.hasAttribute(Attribute::ZExt)) 9747 Flags.setZExt(); 9748 if (Arg.hasAttribute(Attribute::SExt)) 9749 Flags.setSExt(); 9750 if (Arg.hasAttribute(Attribute::InReg)) { 9751 // If we are using vectorcall calling convention, a structure that is 9752 // passed InReg - is surely an HVA 9753 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9754 isa<StructType>(Arg.getType())) { 9755 // The first value of a structure is marked 9756 if (0 == Value) 9757 Flags.setHvaStart(); 9758 Flags.setHva(); 9759 } 9760 // Set InReg Flag 9761 Flags.setInReg(); 9762 } 9763 if (Arg.hasAttribute(Attribute::StructRet)) 9764 Flags.setSRet(); 9765 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9766 Flags.setSwiftSelf(); 9767 if (Arg.hasAttribute(Attribute::SwiftError)) 9768 Flags.setSwiftError(); 9769 if (Arg.hasAttribute(Attribute::ByVal)) 9770 Flags.setByVal(); 9771 if (Arg.hasAttribute(Attribute::InAlloca)) { 9772 Flags.setInAlloca(); 9773 // Set the byval flag for CCAssignFn callbacks that don't know about 9774 // inalloca. This way we can know how many bytes we should've allocated 9775 // and how many bytes a callee cleanup function will pop. If we port 9776 // inalloca to more targets, we'll have to add custom inalloca handling 9777 // in the various CC lowering callbacks. 9778 Flags.setByVal(); 9779 } 9780 if (F.getCallingConv() == CallingConv::X86_INTR) { 9781 // IA Interrupt passes frame (1st parameter) by value in the stack. 9782 if (ArgNo == 0) 9783 Flags.setByVal(); 9784 } 9785 if (Flags.isByVal() || Flags.isInAlloca()) { 9786 Type *ElementTy = Arg.getParamByValType(); 9787 9788 // For ByVal, size and alignment should be passed from FE. BE will 9789 // guess if this info is not there but there are cases it cannot get 9790 // right. 9791 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9792 Flags.setByValSize(FrameSize); 9793 9794 unsigned FrameAlign; 9795 if (Arg.getParamAlignment()) 9796 FrameAlign = Arg.getParamAlignment(); 9797 else 9798 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9799 Flags.setByValAlign(Align(FrameAlign)); 9800 } 9801 if (Arg.hasAttribute(Attribute::Nest)) 9802 Flags.setNest(); 9803 if (NeedsRegBlock) 9804 Flags.setInConsecutiveRegs(); 9805 Flags.setOrigAlign(OriginalAlignment); 9806 if (ArgCopyElisionCandidates.count(&Arg)) 9807 Flags.setCopyElisionCandidate(); 9808 if (Arg.hasAttribute(Attribute::Returned)) 9809 Flags.setReturned(); 9810 9811 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9812 *CurDAG->getContext(), F.getCallingConv(), VT); 9813 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9814 *CurDAG->getContext(), F.getCallingConv(), VT); 9815 for (unsigned i = 0; i != NumRegs; ++i) { 9816 // For scalable vectors, use the minimum size; individual targets 9817 // are responsible for handling scalable vector arguments and 9818 // return values. 9819 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9820 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9821 if (NumRegs > 1 && i == 0) 9822 MyFlags.Flags.setSplit(); 9823 // if it isn't first piece, alignment must be 1 9824 else if (i > 0) { 9825 MyFlags.Flags.setOrigAlign(Align(1)); 9826 if (i == NumRegs - 1) 9827 MyFlags.Flags.setSplitEnd(); 9828 } 9829 Ins.push_back(MyFlags); 9830 } 9831 if (NeedsRegBlock && Value == NumValues - 1) 9832 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9833 PartBase += VT.getStoreSize().getKnownMinSize(); 9834 } 9835 } 9836 9837 // Call the target to set up the argument values. 9838 SmallVector<SDValue, 8> InVals; 9839 SDValue NewRoot = TLI->LowerFormalArguments( 9840 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9841 9842 // Verify that the target's LowerFormalArguments behaved as expected. 9843 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9844 "LowerFormalArguments didn't return a valid chain!"); 9845 assert(InVals.size() == Ins.size() && 9846 "LowerFormalArguments didn't emit the correct number of values!"); 9847 LLVM_DEBUG({ 9848 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9849 assert(InVals[i].getNode() && 9850 "LowerFormalArguments emitted a null value!"); 9851 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9852 "LowerFormalArguments emitted a value with the wrong type!"); 9853 } 9854 }); 9855 9856 // Update the DAG with the new chain value resulting from argument lowering. 9857 DAG.setRoot(NewRoot); 9858 9859 // Set up the argument values. 9860 unsigned i = 0; 9861 if (!FuncInfo->CanLowerReturn) { 9862 // Create a virtual register for the sret pointer, and put in a copy 9863 // from the sret argument into it. 9864 SmallVector<EVT, 1> ValueVTs; 9865 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9866 F.getReturnType()->getPointerTo( 9867 DAG.getDataLayout().getAllocaAddrSpace()), 9868 ValueVTs); 9869 MVT VT = ValueVTs[0].getSimpleVT(); 9870 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9871 Optional<ISD::NodeType> AssertOp = None; 9872 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9873 nullptr, F.getCallingConv(), AssertOp); 9874 9875 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9876 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9877 Register SRetReg = 9878 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9879 FuncInfo->DemoteRegister = SRetReg; 9880 NewRoot = 9881 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9882 DAG.setRoot(NewRoot); 9883 9884 // i indexes lowered arguments. Bump it past the hidden sret argument. 9885 ++i; 9886 } 9887 9888 SmallVector<SDValue, 4> Chains; 9889 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9890 for (const Argument &Arg : F.args()) { 9891 SmallVector<SDValue, 4> ArgValues; 9892 SmallVector<EVT, 4> ValueVTs; 9893 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9894 unsigned NumValues = ValueVTs.size(); 9895 if (NumValues == 0) 9896 continue; 9897 9898 bool ArgHasUses = !Arg.use_empty(); 9899 9900 // Elide the copying store if the target loaded this argument from a 9901 // suitable fixed stack object. 9902 if (Ins[i].Flags.isCopyElisionCandidate()) { 9903 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9904 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9905 InVals[i], ArgHasUses); 9906 } 9907 9908 // If this argument is unused then remember its value. It is used to generate 9909 // debugging information. 9910 bool isSwiftErrorArg = 9911 TLI->supportSwiftError() && 9912 Arg.hasAttribute(Attribute::SwiftError); 9913 if (!ArgHasUses && !isSwiftErrorArg) { 9914 SDB->setUnusedArgValue(&Arg, InVals[i]); 9915 9916 // Also remember any frame index for use in FastISel. 9917 if (FrameIndexSDNode *FI = 9918 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9919 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9920 } 9921 9922 for (unsigned Val = 0; Val != NumValues; ++Val) { 9923 EVT VT = ValueVTs[Val]; 9924 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9925 F.getCallingConv(), VT); 9926 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9927 *CurDAG->getContext(), F.getCallingConv(), VT); 9928 9929 // Even an apparent 'unused' swifterror argument needs to be returned. So 9930 // we do generate a copy for it that can be used on return from the 9931 // function. 9932 if (ArgHasUses || isSwiftErrorArg) { 9933 Optional<ISD::NodeType> AssertOp; 9934 if (Arg.hasAttribute(Attribute::SExt)) 9935 AssertOp = ISD::AssertSext; 9936 else if (Arg.hasAttribute(Attribute::ZExt)) 9937 AssertOp = ISD::AssertZext; 9938 9939 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9940 PartVT, VT, nullptr, 9941 F.getCallingConv(), AssertOp)); 9942 } 9943 9944 i += NumParts; 9945 } 9946 9947 // We don't need to do anything else for unused arguments. 9948 if (ArgValues.empty()) 9949 continue; 9950 9951 // Note down frame index. 9952 if (FrameIndexSDNode *FI = 9953 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9954 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9955 9956 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9957 SDB->getCurSDLoc()); 9958 9959 SDB->setValue(&Arg, Res); 9960 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9961 // We want to associate the argument with the frame index, among 9962 // involved operands, that correspond to the lowest address. The 9963 // getCopyFromParts function, called earlier, is swapping the order of 9964 // the operands to BUILD_PAIR depending on endianness. The result of 9965 // that swapping is that the least significant bits of the argument will 9966 // be in the first operand of the BUILD_PAIR node, and the most 9967 // significant bits will be in the second operand. 9968 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9969 if (LoadSDNode *LNode = 9970 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9971 if (FrameIndexSDNode *FI = 9972 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9973 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9974 } 9975 9976 // Analyses past this point are naive and don't expect an assertion. 9977 if (Res.getOpcode() == ISD::AssertZext) 9978 Res = Res.getOperand(0); 9979 9980 // Update the SwiftErrorVRegDefMap. 9981 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9982 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9983 if (Register::isVirtualRegister(Reg)) 9984 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9985 Reg); 9986 } 9987 9988 // If this argument is live outside of the entry block, insert a copy from 9989 // wherever we got it to the vreg that other BB's will reference it as. 9990 if (Res.getOpcode() == ISD::CopyFromReg) { 9991 // If we can, though, try to skip creating an unnecessary vreg. 9992 // FIXME: This isn't very clean... it would be nice to make this more 9993 // general. 9994 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9995 if (Register::isVirtualRegister(Reg)) { 9996 FuncInfo->ValueMap[&Arg] = Reg; 9997 continue; 9998 } 9999 } 10000 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10001 FuncInfo->InitializeRegForValue(&Arg); 10002 SDB->CopyToExportRegsIfNeeded(&Arg); 10003 } 10004 } 10005 10006 if (!Chains.empty()) { 10007 Chains.push_back(NewRoot); 10008 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10009 } 10010 10011 DAG.setRoot(NewRoot); 10012 10013 assert(i == InVals.size() && "Argument register count mismatch!"); 10014 10015 // If any argument copy elisions occurred and we have debug info, update the 10016 // stale frame indices used in the dbg.declare variable info table. 10017 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10018 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10019 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10020 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10021 if (I != ArgCopyElisionFrameIndexMap.end()) 10022 VI.Slot = I->second; 10023 } 10024 } 10025 10026 // Finally, if the target has anything special to do, allow it to do so. 10027 emitFunctionEntryCode(); 10028 } 10029 10030 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10031 /// ensure constants are generated when needed. Remember the virtual registers 10032 /// that need to be added to the Machine PHI nodes as input. We cannot just 10033 /// directly add them, because expansion might result in multiple MBB's for one 10034 /// BB. As such, the start of the BB might correspond to a different MBB than 10035 /// the end. 10036 void 10037 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10038 const Instruction *TI = LLVMBB->getTerminator(); 10039 10040 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10041 10042 // Check PHI nodes in successors that expect a value to be available from this 10043 // block. 10044 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10045 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10046 if (!isa<PHINode>(SuccBB->begin())) continue; 10047 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10048 10049 // If this terminator has multiple identical successors (common for 10050 // switches), only handle each succ once. 10051 if (!SuccsHandled.insert(SuccMBB).second) 10052 continue; 10053 10054 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10055 10056 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10057 // nodes and Machine PHI nodes, but the incoming operands have not been 10058 // emitted yet. 10059 for (const PHINode &PN : SuccBB->phis()) { 10060 // Ignore dead phi's. 10061 if (PN.use_empty()) 10062 continue; 10063 10064 // Skip empty types 10065 if (PN.getType()->isEmptyTy()) 10066 continue; 10067 10068 unsigned Reg; 10069 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10070 10071 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10072 unsigned &RegOut = ConstantsOut[C]; 10073 if (RegOut == 0) { 10074 RegOut = FuncInfo.CreateRegs(C); 10075 CopyValueToVirtualRegister(C, RegOut); 10076 } 10077 Reg = RegOut; 10078 } else { 10079 DenseMap<const Value *, unsigned>::iterator I = 10080 FuncInfo.ValueMap.find(PHIOp); 10081 if (I != FuncInfo.ValueMap.end()) 10082 Reg = I->second; 10083 else { 10084 assert(isa<AllocaInst>(PHIOp) && 10085 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10086 "Didn't codegen value into a register!??"); 10087 Reg = FuncInfo.CreateRegs(PHIOp); 10088 CopyValueToVirtualRegister(PHIOp, Reg); 10089 } 10090 } 10091 10092 // Remember that this register needs to added to the machine PHI node as 10093 // the input for this MBB. 10094 SmallVector<EVT, 4> ValueVTs; 10095 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10096 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10097 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10098 EVT VT = ValueVTs[vti]; 10099 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10100 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10101 FuncInfo.PHINodesToUpdate.push_back( 10102 std::make_pair(&*MBBI++, Reg + i)); 10103 Reg += NumRegisters; 10104 } 10105 } 10106 } 10107 10108 ConstantsOut.clear(); 10109 } 10110 10111 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10112 /// is 0. 10113 MachineBasicBlock * 10114 SelectionDAGBuilder::StackProtectorDescriptor:: 10115 AddSuccessorMBB(const BasicBlock *BB, 10116 MachineBasicBlock *ParentMBB, 10117 bool IsLikely, 10118 MachineBasicBlock *SuccMBB) { 10119 // If SuccBB has not been created yet, create it. 10120 if (!SuccMBB) { 10121 MachineFunction *MF = ParentMBB->getParent(); 10122 MachineFunction::iterator BBI(ParentMBB); 10123 SuccMBB = MF->CreateMachineBasicBlock(BB); 10124 MF->insert(++BBI, SuccMBB); 10125 } 10126 // Add it as a successor of ParentMBB. 10127 ParentMBB->addSuccessor( 10128 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10129 return SuccMBB; 10130 } 10131 10132 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10133 MachineFunction::iterator I(MBB); 10134 if (++I == FuncInfo.MF->end()) 10135 return nullptr; 10136 return &*I; 10137 } 10138 10139 /// During lowering new call nodes can be created (such as memset, etc.). 10140 /// Those will become new roots of the current DAG, but complications arise 10141 /// when they are tail calls. In such cases, the call lowering will update 10142 /// the root, but the builder still needs to know that a tail call has been 10143 /// lowered in order to avoid generating an additional return. 10144 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10145 // If the node is null, we do have a tail call. 10146 if (MaybeTC.getNode() != nullptr) 10147 DAG.setRoot(MaybeTC); 10148 else 10149 HasTailCall = true; 10150 } 10151 10152 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10153 MachineBasicBlock *SwitchMBB, 10154 MachineBasicBlock *DefaultMBB) { 10155 MachineFunction *CurMF = FuncInfo.MF; 10156 MachineBasicBlock *NextMBB = nullptr; 10157 MachineFunction::iterator BBI(W.MBB); 10158 if (++BBI != FuncInfo.MF->end()) 10159 NextMBB = &*BBI; 10160 10161 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10162 10163 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10164 10165 if (Size == 2 && W.MBB == SwitchMBB) { 10166 // If any two of the cases has the same destination, and if one value 10167 // is the same as the other, but has one bit unset that the other has set, 10168 // use bit manipulation to do two compares at once. For example: 10169 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10170 // TODO: This could be extended to merge any 2 cases in switches with 3 10171 // cases. 10172 // TODO: Handle cases where W.CaseBB != SwitchBB. 10173 CaseCluster &Small = *W.FirstCluster; 10174 CaseCluster &Big = *W.LastCluster; 10175 10176 if (Small.Low == Small.High && Big.Low == Big.High && 10177 Small.MBB == Big.MBB) { 10178 const APInt &SmallValue = Small.Low->getValue(); 10179 const APInt &BigValue = Big.Low->getValue(); 10180 10181 // Check that there is only one bit different. 10182 APInt CommonBit = BigValue ^ SmallValue; 10183 if (CommonBit.isPowerOf2()) { 10184 SDValue CondLHS = getValue(Cond); 10185 EVT VT = CondLHS.getValueType(); 10186 SDLoc DL = getCurSDLoc(); 10187 10188 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10189 DAG.getConstant(CommonBit, DL, VT)); 10190 SDValue Cond = DAG.getSetCC( 10191 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10192 ISD::SETEQ); 10193 10194 // Update successor info. 10195 // Both Small and Big will jump to Small.BB, so we sum up the 10196 // probabilities. 10197 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10198 if (BPI) 10199 addSuccessorWithProb( 10200 SwitchMBB, DefaultMBB, 10201 // The default destination is the first successor in IR. 10202 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10203 else 10204 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10205 10206 // Insert the true branch. 10207 SDValue BrCond = 10208 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10209 DAG.getBasicBlock(Small.MBB)); 10210 // Insert the false branch. 10211 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10212 DAG.getBasicBlock(DefaultMBB)); 10213 10214 DAG.setRoot(BrCond); 10215 return; 10216 } 10217 } 10218 } 10219 10220 if (TM.getOptLevel() != CodeGenOpt::None) { 10221 // Here, we order cases by probability so the most likely case will be 10222 // checked first. However, two clusters can have the same probability in 10223 // which case their relative ordering is non-deterministic. So we use Low 10224 // as a tie-breaker as clusters are guaranteed to never overlap. 10225 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10226 [](const CaseCluster &a, const CaseCluster &b) { 10227 return a.Prob != b.Prob ? 10228 a.Prob > b.Prob : 10229 a.Low->getValue().slt(b.Low->getValue()); 10230 }); 10231 10232 // Rearrange the case blocks so that the last one falls through if possible 10233 // without changing the order of probabilities. 10234 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10235 --I; 10236 if (I->Prob > W.LastCluster->Prob) 10237 break; 10238 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10239 std::swap(*I, *W.LastCluster); 10240 break; 10241 } 10242 } 10243 } 10244 10245 // Compute total probability. 10246 BranchProbability DefaultProb = W.DefaultProb; 10247 BranchProbability UnhandledProbs = DefaultProb; 10248 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10249 UnhandledProbs += I->Prob; 10250 10251 MachineBasicBlock *CurMBB = W.MBB; 10252 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10253 bool FallthroughUnreachable = false; 10254 MachineBasicBlock *Fallthrough; 10255 if (I == W.LastCluster) { 10256 // For the last cluster, fall through to the default destination. 10257 Fallthrough = DefaultMBB; 10258 FallthroughUnreachable = isa<UnreachableInst>( 10259 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10260 } else { 10261 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10262 CurMF->insert(BBI, Fallthrough); 10263 // Put Cond in a virtual register to make it available from the new blocks. 10264 ExportFromCurrentBlock(Cond); 10265 } 10266 UnhandledProbs -= I->Prob; 10267 10268 switch (I->Kind) { 10269 case CC_JumpTable: { 10270 // FIXME: Optimize away range check based on pivot comparisons. 10271 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10272 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10273 10274 // The jump block hasn't been inserted yet; insert it here. 10275 MachineBasicBlock *JumpMBB = JT->MBB; 10276 CurMF->insert(BBI, JumpMBB); 10277 10278 auto JumpProb = I->Prob; 10279 auto FallthroughProb = UnhandledProbs; 10280 10281 // If the default statement is a target of the jump table, we evenly 10282 // distribute the default probability to successors of CurMBB. Also 10283 // update the probability on the edge from JumpMBB to Fallthrough. 10284 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10285 SE = JumpMBB->succ_end(); 10286 SI != SE; ++SI) { 10287 if (*SI == DefaultMBB) { 10288 JumpProb += DefaultProb / 2; 10289 FallthroughProb -= DefaultProb / 2; 10290 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10291 JumpMBB->normalizeSuccProbs(); 10292 break; 10293 } 10294 } 10295 10296 if (FallthroughUnreachable) { 10297 // Skip the range check if the fallthrough block is unreachable. 10298 JTH->OmitRangeCheck = true; 10299 } 10300 10301 if (!JTH->OmitRangeCheck) 10302 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10303 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10304 CurMBB->normalizeSuccProbs(); 10305 10306 // The jump table header will be inserted in our current block, do the 10307 // range check, and fall through to our fallthrough block. 10308 JTH->HeaderBB = CurMBB; 10309 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10310 10311 // If we're in the right place, emit the jump table header right now. 10312 if (CurMBB == SwitchMBB) { 10313 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10314 JTH->Emitted = true; 10315 } 10316 break; 10317 } 10318 case CC_BitTests: { 10319 // FIXME: Optimize away range check based on pivot comparisons. 10320 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10321 10322 // The bit test blocks haven't been inserted yet; insert them here. 10323 for (BitTestCase &BTC : BTB->Cases) 10324 CurMF->insert(BBI, BTC.ThisBB); 10325 10326 // Fill in fields of the BitTestBlock. 10327 BTB->Parent = CurMBB; 10328 BTB->Default = Fallthrough; 10329 10330 BTB->DefaultProb = UnhandledProbs; 10331 // If the cases in bit test don't form a contiguous range, we evenly 10332 // distribute the probability on the edge to Fallthrough to two 10333 // successors of CurMBB. 10334 if (!BTB->ContiguousRange) { 10335 BTB->Prob += DefaultProb / 2; 10336 BTB->DefaultProb -= DefaultProb / 2; 10337 } 10338 10339 if (FallthroughUnreachable) { 10340 // Skip the range check if the fallthrough block is unreachable. 10341 BTB->OmitRangeCheck = true; 10342 } 10343 10344 // If we're in the right place, emit the bit test header right now. 10345 if (CurMBB == SwitchMBB) { 10346 visitBitTestHeader(*BTB, SwitchMBB); 10347 BTB->Emitted = true; 10348 } 10349 break; 10350 } 10351 case CC_Range: { 10352 const Value *RHS, *LHS, *MHS; 10353 ISD::CondCode CC; 10354 if (I->Low == I->High) { 10355 // Check Cond == I->Low. 10356 CC = ISD::SETEQ; 10357 LHS = Cond; 10358 RHS=I->Low; 10359 MHS = nullptr; 10360 } else { 10361 // Check I->Low <= Cond <= I->High. 10362 CC = ISD::SETLE; 10363 LHS = I->Low; 10364 MHS = Cond; 10365 RHS = I->High; 10366 } 10367 10368 // If Fallthrough is unreachable, fold away the comparison. 10369 if (FallthroughUnreachable) 10370 CC = ISD::SETTRUE; 10371 10372 // The false probability is the sum of all unhandled cases. 10373 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10374 getCurSDLoc(), I->Prob, UnhandledProbs); 10375 10376 if (CurMBB == SwitchMBB) 10377 visitSwitchCase(CB, SwitchMBB); 10378 else 10379 SL->SwitchCases.push_back(CB); 10380 10381 break; 10382 } 10383 } 10384 CurMBB = Fallthrough; 10385 } 10386 } 10387 10388 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10389 CaseClusterIt First, 10390 CaseClusterIt Last) { 10391 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10392 if (X.Prob != CC.Prob) 10393 return X.Prob > CC.Prob; 10394 10395 // Ties are broken by comparing the case value. 10396 return X.Low->getValue().slt(CC.Low->getValue()); 10397 }); 10398 } 10399 10400 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10401 const SwitchWorkListItem &W, 10402 Value *Cond, 10403 MachineBasicBlock *SwitchMBB) { 10404 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10405 "Clusters not sorted?"); 10406 10407 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10408 10409 // Balance the tree based on branch probabilities to create a near-optimal (in 10410 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10411 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10412 CaseClusterIt LastLeft = W.FirstCluster; 10413 CaseClusterIt FirstRight = W.LastCluster; 10414 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10415 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10416 10417 // Move LastLeft and FirstRight towards each other from opposite directions to 10418 // find a partitioning of the clusters which balances the probability on both 10419 // sides. If LeftProb and RightProb are equal, alternate which side is 10420 // taken to ensure 0-probability nodes are distributed evenly. 10421 unsigned I = 0; 10422 while (LastLeft + 1 < FirstRight) { 10423 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10424 LeftProb += (++LastLeft)->Prob; 10425 else 10426 RightProb += (--FirstRight)->Prob; 10427 I++; 10428 } 10429 10430 while (true) { 10431 // Our binary search tree differs from a typical BST in that ours can have up 10432 // to three values in each leaf. The pivot selection above doesn't take that 10433 // into account, which means the tree might require more nodes and be less 10434 // efficient. We compensate for this here. 10435 10436 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10437 unsigned NumRight = W.LastCluster - FirstRight + 1; 10438 10439 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10440 // If one side has less than 3 clusters, and the other has more than 3, 10441 // consider taking a cluster from the other side. 10442 10443 if (NumLeft < NumRight) { 10444 // Consider moving the first cluster on the right to the left side. 10445 CaseCluster &CC = *FirstRight; 10446 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10447 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10448 if (LeftSideRank <= RightSideRank) { 10449 // Moving the cluster to the left does not demote it. 10450 ++LastLeft; 10451 ++FirstRight; 10452 continue; 10453 } 10454 } else { 10455 assert(NumRight < NumLeft); 10456 // Consider moving the last element on the left to the right side. 10457 CaseCluster &CC = *LastLeft; 10458 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10459 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10460 if (RightSideRank <= LeftSideRank) { 10461 // Moving the cluster to the right does not demot it. 10462 --LastLeft; 10463 --FirstRight; 10464 continue; 10465 } 10466 } 10467 } 10468 break; 10469 } 10470 10471 assert(LastLeft + 1 == FirstRight); 10472 assert(LastLeft >= W.FirstCluster); 10473 assert(FirstRight <= W.LastCluster); 10474 10475 // Use the first element on the right as pivot since we will make less-than 10476 // comparisons against it. 10477 CaseClusterIt PivotCluster = FirstRight; 10478 assert(PivotCluster > W.FirstCluster); 10479 assert(PivotCluster <= W.LastCluster); 10480 10481 CaseClusterIt FirstLeft = W.FirstCluster; 10482 CaseClusterIt LastRight = W.LastCluster; 10483 10484 const ConstantInt *Pivot = PivotCluster->Low; 10485 10486 // New blocks will be inserted immediately after the current one. 10487 MachineFunction::iterator BBI(W.MBB); 10488 ++BBI; 10489 10490 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10491 // we can branch to its destination directly if it's squeezed exactly in 10492 // between the known lower bound and Pivot - 1. 10493 MachineBasicBlock *LeftMBB; 10494 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10495 FirstLeft->Low == W.GE && 10496 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10497 LeftMBB = FirstLeft->MBB; 10498 } else { 10499 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10500 FuncInfo.MF->insert(BBI, LeftMBB); 10501 WorkList.push_back( 10502 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10503 // Put Cond in a virtual register to make it available from the new blocks. 10504 ExportFromCurrentBlock(Cond); 10505 } 10506 10507 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10508 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10509 // directly if RHS.High equals the current upper bound. 10510 MachineBasicBlock *RightMBB; 10511 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10512 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10513 RightMBB = FirstRight->MBB; 10514 } else { 10515 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10516 FuncInfo.MF->insert(BBI, RightMBB); 10517 WorkList.push_back( 10518 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10519 // Put Cond in a virtual register to make it available from the new blocks. 10520 ExportFromCurrentBlock(Cond); 10521 } 10522 10523 // Create the CaseBlock record that will be used to lower the branch. 10524 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10525 getCurSDLoc(), LeftProb, RightProb); 10526 10527 if (W.MBB == SwitchMBB) 10528 visitSwitchCase(CB, SwitchMBB); 10529 else 10530 SL->SwitchCases.push_back(CB); 10531 } 10532 10533 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10534 // from the swith statement. 10535 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10536 BranchProbability PeeledCaseProb) { 10537 if (PeeledCaseProb == BranchProbability::getOne()) 10538 return BranchProbability::getZero(); 10539 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10540 10541 uint32_t Numerator = CaseProb.getNumerator(); 10542 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10543 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10544 } 10545 10546 // Try to peel the top probability case if it exceeds the threshold. 10547 // Return current MachineBasicBlock for the switch statement if the peeling 10548 // does not occur. 10549 // If the peeling is performed, return the newly created MachineBasicBlock 10550 // for the peeled switch statement. Also update Clusters to remove the peeled 10551 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10552 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10553 const SwitchInst &SI, CaseClusterVector &Clusters, 10554 BranchProbability &PeeledCaseProb) { 10555 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10556 // Don't perform if there is only one cluster or optimizing for size. 10557 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10558 TM.getOptLevel() == CodeGenOpt::None || 10559 SwitchMBB->getParent()->getFunction().hasMinSize()) 10560 return SwitchMBB; 10561 10562 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10563 unsigned PeeledCaseIndex = 0; 10564 bool SwitchPeeled = false; 10565 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10566 CaseCluster &CC = Clusters[Index]; 10567 if (CC.Prob < TopCaseProb) 10568 continue; 10569 TopCaseProb = CC.Prob; 10570 PeeledCaseIndex = Index; 10571 SwitchPeeled = true; 10572 } 10573 if (!SwitchPeeled) 10574 return SwitchMBB; 10575 10576 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10577 << TopCaseProb << "\n"); 10578 10579 // Record the MBB for the peeled switch statement. 10580 MachineFunction::iterator BBI(SwitchMBB); 10581 ++BBI; 10582 MachineBasicBlock *PeeledSwitchMBB = 10583 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10584 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10585 10586 ExportFromCurrentBlock(SI.getCondition()); 10587 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10588 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10589 nullptr, nullptr, TopCaseProb.getCompl()}; 10590 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10591 10592 Clusters.erase(PeeledCaseIt); 10593 for (CaseCluster &CC : Clusters) { 10594 LLVM_DEBUG( 10595 dbgs() << "Scale the probablity for one cluster, before scaling: " 10596 << CC.Prob << "\n"); 10597 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10598 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10599 } 10600 PeeledCaseProb = TopCaseProb; 10601 return PeeledSwitchMBB; 10602 } 10603 10604 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10605 // Extract cases from the switch. 10606 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10607 CaseClusterVector Clusters; 10608 Clusters.reserve(SI.getNumCases()); 10609 for (auto I : SI.cases()) { 10610 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10611 const ConstantInt *CaseVal = I.getCaseValue(); 10612 BranchProbability Prob = 10613 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10614 : BranchProbability(1, SI.getNumCases() + 1); 10615 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10616 } 10617 10618 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10619 10620 // Cluster adjacent cases with the same destination. We do this at all 10621 // optimization levels because it's cheap to do and will make codegen faster 10622 // if there are many clusters. 10623 sortAndRangeify(Clusters); 10624 10625 // The branch probablity of the peeled case. 10626 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10627 MachineBasicBlock *PeeledSwitchMBB = 10628 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10629 10630 // If there is only the default destination, jump there directly. 10631 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10632 if (Clusters.empty()) { 10633 assert(PeeledSwitchMBB == SwitchMBB); 10634 SwitchMBB->addSuccessor(DefaultMBB); 10635 if (DefaultMBB != NextBlock(SwitchMBB)) { 10636 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10637 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10638 } 10639 return; 10640 } 10641 10642 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10643 SL->findBitTestClusters(Clusters, &SI); 10644 10645 LLVM_DEBUG({ 10646 dbgs() << "Case clusters: "; 10647 for (const CaseCluster &C : Clusters) { 10648 if (C.Kind == CC_JumpTable) 10649 dbgs() << "JT:"; 10650 if (C.Kind == CC_BitTests) 10651 dbgs() << "BT:"; 10652 10653 C.Low->getValue().print(dbgs(), true); 10654 if (C.Low != C.High) { 10655 dbgs() << '-'; 10656 C.High->getValue().print(dbgs(), true); 10657 } 10658 dbgs() << ' '; 10659 } 10660 dbgs() << '\n'; 10661 }); 10662 10663 assert(!Clusters.empty()); 10664 SwitchWorkList WorkList; 10665 CaseClusterIt First = Clusters.begin(); 10666 CaseClusterIt Last = Clusters.end() - 1; 10667 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10668 // Scale the branchprobability for DefaultMBB if the peel occurs and 10669 // DefaultMBB is not replaced. 10670 if (PeeledCaseProb != BranchProbability::getZero() && 10671 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10672 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10673 WorkList.push_back( 10674 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10675 10676 while (!WorkList.empty()) { 10677 SwitchWorkListItem W = WorkList.back(); 10678 WorkList.pop_back(); 10679 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10680 10681 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10682 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10683 // For optimized builds, lower large range as a balanced binary tree. 10684 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10685 continue; 10686 } 10687 10688 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10689 } 10690 } 10691 10692 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10693 SDNodeFlags Flags; 10694 10695 SDValue Op = getValue(I.getOperand(0)); 10696 if (I.getOperand(0)->getType()->isAggregateType()) { 10697 EVT VT = Op.getValueType(); 10698 SmallVector<SDValue, 1> Values; 10699 for (unsigned i = 0; i < Op.getNumOperands(); ++i) { 10700 SDValue Arg(Op.getNode(), i); 10701 SDValue UnNodeValue = DAG.getNode(ISD::FREEZE, getCurSDLoc(), VT, Arg, Flags); 10702 Values.push_back(UnNodeValue); 10703 } 10704 SDValue MergedValue = DAG.getMergeValues(Values, getCurSDLoc()); 10705 setValue(&I, MergedValue); 10706 } else { 10707 SDValue UnNodeValue = DAG.getNode(ISD::FREEZE, getCurSDLoc(), Op.getValueType(), 10708 Op, Flags); 10709 setValue(&I, UnNodeValue); 10710 } 10711 } 10712