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/CallingConv.h" 73 #include "llvm/IR/Constant.h" 74 #include "llvm/IR/ConstantRange.h" 75 #include "llvm/IR/Constants.h" 76 #include "llvm/IR/DataLayout.h" 77 #include "llvm/IR/DebugInfoMetadata.h" 78 #include "llvm/IR/DebugLoc.h" 79 #include "llvm/IR/DerivedTypes.h" 80 #include "llvm/IR/Function.h" 81 #include "llvm/IR/GetElementPtrTypeIterator.h" 82 #include "llvm/IR/InlineAsm.h" 83 #include "llvm/IR/InstrTypes.h" 84 #include "llvm/IR/Instruction.h" 85 #include "llvm/IR/Instructions.h" 86 #include "llvm/IR/IntrinsicInst.h" 87 #include "llvm/IR/Intrinsics.h" 88 #include "llvm/IR/IntrinsicsAArch64.h" 89 #include "llvm/IR/IntrinsicsWebAssembly.h" 90 #include "llvm/IR/LLVMContext.h" 91 #include "llvm/IR/Metadata.h" 92 #include "llvm/IR/Module.h" 93 #include "llvm/IR/Operator.h" 94 #include "llvm/IR/PatternMatch.h" 95 #include "llvm/IR/Statepoint.h" 96 #include "llvm/IR/Type.h" 97 #include "llvm/IR/User.h" 98 #include "llvm/IR/Value.h" 99 #include "llvm/MC/MCContext.h" 100 #include "llvm/MC/MCSymbol.h" 101 #include "llvm/Support/AtomicOrdering.h" 102 #include "llvm/Support/BranchProbability.h" 103 #include "llvm/Support/Casting.h" 104 #include "llvm/Support/CodeGen.h" 105 #include "llvm/Support/CommandLine.h" 106 #include "llvm/Support/Compiler.h" 107 #include "llvm/Support/Debug.h" 108 #include "llvm/Support/ErrorHandling.h" 109 #include "llvm/Support/MachineValueType.h" 110 #include "llvm/Support/MathExtras.h" 111 #include "llvm/Support/raw_ostream.h" 112 #include "llvm/Target/TargetIntrinsicInfo.h" 113 #include "llvm/Target/TargetMachine.h" 114 #include "llvm/Target/TargetOptions.h" 115 #include "llvm/Transforms/Utils/Local.h" 116 #include <algorithm> 117 #include <cassert> 118 #include <cstddef> 119 #include <cstdint> 120 #include <cstring> 121 #include <iterator> 122 #include <limits> 123 #include <numeric> 124 #include <tuple> 125 #include <utility> 126 #include <vector> 127 128 using namespace llvm; 129 using namespace PatternMatch; 130 using namespace SwitchCG; 131 132 #define DEBUG_TYPE "isel" 133 134 /// LimitFloatPrecision - Generate low-precision inline sequences for 135 /// some float libcalls (6, 8 or 12 bits). 136 static unsigned LimitFloatPrecision; 137 138 static cl::opt<unsigned, true> 139 LimitFPPrecision("limit-float-precision", 140 cl::desc("Generate low-precision inline sequences " 141 "for some float libcalls"), 142 cl::location(LimitFloatPrecision), cl::Hidden, 143 cl::init(0)); 144 145 static cl::opt<unsigned> SwitchPeelThreshold( 146 "switch-peel-threshold", cl::Hidden, cl::init(66), 147 cl::desc("Set the case probability threshold for peeling the case from a " 148 "switch statement. A value greater than 100 will void this " 149 "optimization")); 150 151 // Limit the width of DAG chains. This is important in general to prevent 152 // DAG-based analysis from blowing up. For example, alias analysis and 153 // load clustering may not complete in reasonable time. It is difficult to 154 // recognize and avoid this situation within each individual analysis, and 155 // future analyses are likely to have the same behavior. Limiting DAG width is 156 // the safe approach and will be especially important with global DAGs. 157 // 158 // MaxParallelChains default is arbitrarily high to avoid affecting 159 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 160 // sequence over this should have been converted to llvm.memcpy by the 161 // frontend. It is easy to induce this behavior with .ll code such as: 162 // %buffer = alloca [4096 x i8] 163 // %data = load [4096 x i8]* %argPtr 164 // store [4096 x i8] %data, [4096 x i8]* %buffer 165 static const unsigned MaxParallelChains = 64; 166 167 // Return the calling convention if the Value passed requires ABI mangling as it 168 // is a parameter to a function or a return value from a function which is not 169 // an intrinsic. 170 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 171 if (auto *R = dyn_cast<ReturnInst>(V)) 172 return R->getParent()->getParent()->getCallingConv(); 173 174 if (auto *CI = dyn_cast<CallInst>(V)) { 175 const bool IsInlineAsm = CI->isInlineAsm(); 176 const bool IsIndirectFunctionCall = 177 !IsInlineAsm && !CI->getCalledFunction(); 178 179 // It is possible that the call instruction is an inline asm statement or an 180 // indirect function call in which case the return value of 181 // getCalledFunction() would be nullptr. 182 const bool IsInstrinsicCall = 183 !IsInlineAsm && !IsIndirectFunctionCall && 184 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 185 186 if (!IsInlineAsm && !IsInstrinsicCall) 187 return CI->getCallingConv(); 188 } 189 190 return None; 191 } 192 193 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 194 const SDValue *Parts, unsigned NumParts, 195 MVT PartVT, EVT ValueVT, const Value *V, 196 Optional<CallingConv::ID> CC); 197 198 /// getCopyFromParts - Create a value that contains the specified legal parts 199 /// combined into the value they represent. If the parts combine to a type 200 /// larger than ValueVT then AssertOp can be used to specify whether the extra 201 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 202 /// (ISD::AssertSext). 203 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 204 const SDValue *Parts, unsigned NumParts, 205 MVT PartVT, EVT ValueVT, const Value *V, 206 Optional<CallingConv::ID> CC = None, 207 Optional<ISD::NodeType> AssertOp = None) { 208 if (ValueVT.isVector()) 209 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 210 CC); 211 212 assert(NumParts > 0 && "No parts to assemble!"); 213 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 214 SDValue Val = Parts[0]; 215 216 if (NumParts > 1) { 217 // Assemble the value from multiple parts. 218 if (ValueVT.isInteger()) { 219 unsigned PartBits = PartVT.getSizeInBits(); 220 unsigned ValueBits = ValueVT.getSizeInBits(); 221 222 // Assemble the power of 2 part. 223 unsigned RoundParts = 224 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 225 unsigned RoundBits = PartBits * RoundParts; 226 EVT RoundVT = RoundBits == ValueBits ? 227 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 228 SDValue Lo, Hi; 229 230 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 231 232 if (RoundParts > 2) { 233 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 234 PartVT, HalfVT, V); 235 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 236 RoundParts / 2, PartVT, HalfVT, V); 237 } else { 238 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 239 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 240 } 241 242 if (DAG.getDataLayout().isBigEndian()) 243 std::swap(Lo, Hi); 244 245 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 246 247 if (RoundParts < NumParts) { 248 // Assemble the trailing non-power-of-2 part. 249 unsigned OddParts = NumParts - RoundParts; 250 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 251 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 252 OddVT, V, CC); 253 254 // Combine the round and odd parts. 255 Lo = Val; 256 if (DAG.getDataLayout().isBigEndian()) 257 std::swap(Lo, Hi); 258 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 259 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 260 Hi = 261 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 262 DAG.getConstant(Lo.getValueSizeInBits(), DL, 263 TLI.getPointerTy(DAG.getDataLayout()))); 264 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 265 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 266 } 267 } else if (PartVT.isFloatingPoint()) { 268 // FP split into multiple FP parts (for ppcf128) 269 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 270 "Unexpected split"); 271 SDValue Lo, Hi; 272 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 273 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 274 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 275 std::swap(Lo, Hi); 276 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 277 } else { 278 // FP split into integer parts (soft fp) 279 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 280 !PartVT.isVector() && "Unexpected split"); 281 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 282 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 283 } 284 } 285 286 // There is now one part, held in Val. Correct it to match ValueVT. 287 // PartEVT is the type of the register class that holds the value. 288 // ValueVT is the type of the inline asm operation. 289 EVT PartEVT = Val.getValueType(); 290 291 if (PartEVT == ValueVT) 292 return Val; 293 294 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 295 ValueVT.bitsLT(PartEVT)) { 296 // For an FP value in an integer part, we need to truncate to the right 297 // width first. 298 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 299 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 300 } 301 302 // Handle types that have the same size. 303 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 304 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 305 306 // Handle types with different sizes. 307 if (PartEVT.isInteger() && ValueVT.isInteger()) { 308 if (ValueVT.bitsLT(PartEVT)) { 309 // For a truncate, see if we have any information to 310 // indicate whether the truncated bits will always be 311 // zero or sign-extension. 312 if (AssertOp.hasValue()) 313 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 314 DAG.getValueType(ValueVT)); 315 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 316 } 317 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 318 } 319 320 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 321 // FP_ROUND's are always exact here. 322 if (ValueVT.bitsLT(Val.getValueType())) 323 return DAG.getNode( 324 ISD::FP_ROUND, DL, ValueVT, Val, 325 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 326 327 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 328 } 329 330 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 331 // then truncating. 332 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 333 ValueVT.bitsLT(PartEVT)) { 334 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 335 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 336 } 337 338 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 339 } 340 341 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 342 const Twine &ErrMsg) { 343 const Instruction *I = dyn_cast_or_null<Instruction>(V); 344 if (!V) 345 return Ctx.emitError(ErrMsg); 346 347 const char *AsmError = ", possible invalid constraint for vector type"; 348 if (const CallInst *CI = dyn_cast<CallInst>(I)) 349 if (CI->isInlineAsm()) 350 return Ctx.emitError(I, ErrMsg + AsmError); 351 352 return Ctx.emitError(I, ErrMsg); 353 } 354 355 /// getCopyFromPartsVector - Create a value that contains the specified legal 356 /// parts combined into the value they represent. If the parts combine to a 357 /// type larger than ValueVT then AssertOp can be used to specify whether the 358 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 359 /// ValueVT (ISD::AssertSext). 360 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 361 const SDValue *Parts, unsigned NumParts, 362 MVT PartVT, EVT ValueVT, const Value *V, 363 Optional<CallingConv::ID> CallConv) { 364 assert(ValueVT.isVector() && "Not a vector value"); 365 assert(NumParts > 0 && "No parts to assemble!"); 366 const bool IsABIRegCopy = CallConv.hasValue(); 367 368 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 369 SDValue Val = Parts[0]; 370 371 // Handle a multi-element vector. 372 if (NumParts > 1) { 373 EVT IntermediateVT; 374 MVT RegisterVT; 375 unsigned NumIntermediates; 376 unsigned NumRegs; 377 378 if (IsABIRegCopy) { 379 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 380 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 381 NumIntermediates, RegisterVT); 382 } else { 383 NumRegs = 384 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 385 NumIntermediates, RegisterVT); 386 } 387 388 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 389 NumParts = NumRegs; // Silence a compiler warning. 390 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 391 assert(RegisterVT.getSizeInBits() == 392 Parts[0].getSimpleValueType().getSizeInBits() && 393 "Part type sizes don't match!"); 394 395 // Assemble the parts into intermediate operands. 396 SmallVector<SDValue, 8> Ops(NumIntermediates); 397 if (NumIntermediates == NumParts) { 398 // If the register was not expanded, truncate or copy the value, 399 // as appropriate. 400 for (unsigned i = 0; i != NumParts; ++i) 401 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 402 PartVT, IntermediateVT, V); 403 } else if (NumParts > 0) { 404 // If the intermediate type was expanded, build the intermediate 405 // operands from the parts. 406 assert(NumParts % NumIntermediates == 0 && 407 "Must expand into a divisible number of parts!"); 408 unsigned Factor = NumParts / NumIntermediates; 409 for (unsigned i = 0; i != NumIntermediates; ++i) 410 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 411 PartVT, IntermediateVT, V); 412 } 413 414 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 415 // intermediate operands. 416 EVT BuiltVectorTy = 417 IntermediateVT.isVector() 418 ? EVT::getVectorVT( 419 *DAG.getContext(), IntermediateVT.getScalarType(), 420 IntermediateVT.getVectorElementCount() * NumParts) 421 : EVT::getVectorVT(*DAG.getContext(), 422 IntermediateVT.getScalarType(), 423 NumIntermediates); 424 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 425 : ISD::BUILD_VECTOR, 426 DL, BuiltVectorTy, Ops); 427 } 428 429 // There is now one part, held in Val. Correct it to match ValueVT. 430 EVT PartEVT = Val.getValueType(); 431 432 if (PartEVT == ValueVT) 433 return Val; 434 435 if (PartEVT.isVector()) { 436 // If the element type of the source/dest vectors are the same, but the 437 // parts vector has more elements than the value vector, then we have a 438 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 439 // elements we want. 440 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 441 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 442 "Cannot narrow, it would be a lossy transformation"); 443 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 444 DAG.getVectorIdxConstant(0, DL)); 445 } 446 447 // Vector/Vector bitcast. 448 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 449 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 450 451 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 452 "Cannot handle this kind of promotion"); 453 // Promoted vector extract 454 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 455 456 } 457 458 // Trivial bitcast if the types are the same size and the destination 459 // vector type is legal. 460 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 461 TLI.isTypeLegal(ValueVT)) 462 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 463 464 if (ValueVT.getVectorNumElements() != 1) { 465 // Certain ABIs require that vectors are passed as integers. For vectors 466 // are the same size, this is an obvious bitcast. 467 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 468 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 469 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 470 // Bitcast Val back the original type and extract the corresponding 471 // vector we want. 472 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 473 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 474 ValueVT.getVectorElementType(), Elts); 475 Val = DAG.getBitcast(WiderVecType, Val); 476 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 477 DAG.getVectorIdxConstant(0, DL)); 478 } 479 480 diagnosePossiblyInvalidConstraint( 481 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 482 return DAG.getUNDEF(ValueVT); 483 } 484 485 // Handle cases such as i8 -> <1 x i1> 486 EVT ValueSVT = ValueVT.getVectorElementType(); 487 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 488 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 489 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 490 else 491 Val = ValueVT.isFloatingPoint() 492 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 493 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 494 } 495 496 return DAG.getBuildVector(ValueVT, DL, Val); 497 } 498 499 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 500 SDValue Val, SDValue *Parts, unsigned NumParts, 501 MVT PartVT, const Value *V, 502 Optional<CallingConv::ID> CallConv); 503 504 /// getCopyToParts - Create a series of nodes that contain the specified value 505 /// split into legal parts. If the parts contain more bits than Val, then, for 506 /// integers, ExtendKind can be used to specify how to generate the extra bits. 507 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 508 SDValue *Parts, unsigned NumParts, MVT PartVT, 509 const Value *V, 510 Optional<CallingConv::ID> CallConv = None, 511 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 512 EVT ValueVT = Val.getValueType(); 513 514 // Handle the vector case separately. 515 if (ValueVT.isVector()) 516 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 517 CallConv); 518 519 unsigned PartBits = PartVT.getSizeInBits(); 520 unsigned OrigNumParts = NumParts; 521 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 522 "Copying to an illegal type!"); 523 524 if (NumParts == 0) 525 return; 526 527 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 528 EVT PartEVT = PartVT; 529 if (PartEVT == ValueVT) { 530 assert(NumParts == 1 && "No-op copy with multiple parts!"); 531 Parts[0] = Val; 532 return; 533 } 534 535 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 536 // If the parts cover more bits than the value has, promote the value. 537 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 538 assert(NumParts == 1 && "Do not know what to promote to!"); 539 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 540 } else { 541 if (ValueVT.isFloatingPoint()) { 542 // FP values need to be bitcast, then extended if they are being put 543 // into a larger container. 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 545 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 546 } 547 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 548 ValueVT.isInteger() && 549 "Unknown mismatch!"); 550 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 551 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 552 if (PartVT == MVT::x86mmx) 553 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 554 } 555 } else if (PartBits == ValueVT.getSizeInBits()) { 556 // Different types of the same size. 557 assert(NumParts == 1 && PartEVT != ValueVT); 558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 559 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 560 // If the parts cover less bits than value has, truncate the value. 561 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 562 ValueVT.isInteger() && 563 "Unknown mismatch!"); 564 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 565 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 566 if (PartVT == MVT::x86mmx) 567 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 568 } 569 570 // The value may have changed - recompute ValueVT. 571 ValueVT = Val.getValueType(); 572 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 573 "Failed to tile the value with PartVT!"); 574 575 if (NumParts == 1) { 576 if (PartEVT != ValueVT) { 577 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 578 "scalar-to-vector conversion failed"); 579 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 580 } 581 582 Parts[0] = Val; 583 return; 584 } 585 586 // Expand the value into multiple parts. 587 if (NumParts & (NumParts - 1)) { 588 // The number of parts is not a power of 2. Split off and copy the tail. 589 assert(PartVT.isInteger() && ValueVT.isInteger() && 590 "Do not know what to expand to!"); 591 unsigned RoundParts = 1 << Log2_32(NumParts); 592 unsigned RoundBits = RoundParts * PartBits; 593 unsigned OddParts = NumParts - RoundParts; 594 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 595 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 596 597 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 598 CallConv); 599 600 if (DAG.getDataLayout().isBigEndian()) 601 // The odd parts were reversed by getCopyToParts - unreverse them. 602 std::reverse(Parts + RoundParts, Parts + NumParts); 603 604 NumParts = RoundParts; 605 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 606 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 607 } 608 609 // The number of parts is a power of 2. Repeatedly bisect the value using 610 // EXTRACT_ELEMENT. 611 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 612 EVT::getIntegerVT(*DAG.getContext(), 613 ValueVT.getSizeInBits()), 614 Val); 615 616 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 617 for (unsigned i = 0; i < NumParts; i += StepSize) { 618 unsigned ThisBits = StepSize * PartBits / 2; 619 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 620 SDValue &Part0 = Parts[i]; 621 SDValue &Part1 = Parts[i+StepSize/2]; 622 623 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 624 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 625 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 626 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 627 628 if (ThisBits == PartBits && ThisVT != PartVT) { 629 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 630 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 631 } 632 } 633 } 634 635 if (DAG.getDataLayout().isBigEndian()) 636 std::reverse(Parts, Parts + OrigNumParts); 637 } 638 639 static SDValue widenVectorToPartType(SelectionDAG &DAG, 640 SDValue Val, const SDLoc &DL, EVT PartVT) { 641 if (!PartVT.isVector()) 642 return SDValue(); 643 644 EVT ValueVT = Val.getValueType(); 645 unsigned PartNumElts = PartVT.getVectorNumElements(); 646 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 647 if (PartNumElts > ValueNumElts && 648 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 649 EVT ElementVT = PartVT.getVectorElementType(); 650 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 651 // undef elements. 652 SmallVector<SDValue, 16> Ops; 653 DAG.ExtractVectorElements(Val, Ops); 654 SDValue EltUndef = DAG.getUNDEF(ElementVT); 655 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 656 Ops.push_back(EltUndef); 657 658 // FIXME: Use CONCAT for 2x -> 4x. 659 return DAG.getBuildVector(PartVT, DL, Ops); 660 } 661 662 return SDValue(); 663 } 664 665 /// getCopyToPartsVector - Create a series of nodes that contain the specified 666 /// value split into legal parts. 667 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 668 SDValue Val, SDValue *Parts, unsigned NumParts, 669 MVT PartVT, const Value *V, 670 Optional<CallingConv::ID> CallConv) { 671 EVT ValueVT = Val.getValueType(); 672 assert(ValueVT.isVector() && "Not a vector"); 673 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 674 const bool IsABIRegCopy = CallConv.hasValue(); 675 676 if (NumParts == 1) { 677 EVT PartEVT = PartVT; 678 if (PartEVT == ValueVT) { 679 // Nothing to do. 680 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 681 // Bitconvert vector->vector case. 682 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 683 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 684 Val = Widened; 685 } else if (PartVT.isVector() && 686 PartEVT.getVectorElementType().bitsGE( 687 ValueVT.getVectorElementType()) && 688 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 689 690 // Promoted vector extract 691 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 692 } else { 693 if (ValueVT.getVectorNumElements() == 1) { 694 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 695 DAG.getVectorIdxConstant(0, DL)); 696 } else { 697 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 698 "lossy conversion of vector to scalar type"); 699 EVT IntermediateType = 700 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 701 Val = DAG.getBitcast(IntermediateType, Val); 702 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 703 } 704 } 705 706 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 707 Parts[0] = Val; 708 return; 709 } 710 711 // Handle a multi-element vector. 712 EVT IntermediateVT; 713 MVT RegisterVT; 714 unsigned NumIntermediates; 715 unsigned NumRegs; 716 if (IsABIRegCopy) { 717 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 718 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 719 NumIntermediates, RegisterVT); 720 } else { 721 NumRegs = 722 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 723 NumIntermediates, RegisterVT); 724 } 725 726 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 727 NumParts = NumRegs; // Silence a compiler warning. 728 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 729 730 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 731 IntermediateVT.getVectorNumElements() : 1; 732 733 // Convert the vector to the appropriate type if necessary. 734 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 735 736 EVT BuiltVectorTy = EVT::getVectorVT( 737 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 738 if (ValueVT != BuiltVectorTy) { 739 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 740 Val = Widened; 741 742 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 743 } 744 745 // Split the vector into intermediate operands. 746 SmallVector<SDValue, 8> Ops(NumIntermediates); 747 for (unsigned i = 0; i != NumIntermediates; ++i) { 748 if (IntermediateVT.isVector()) { 749 Ops[i] = 750 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 751 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 752 } else { 753 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 754 DAG.getVectorIdxConstant(i, DL)); 755 } 756 } 757 758 // Split the intermediate operands into legal parts. 759 if (NumParts == NumIntermediates) { 760 // If the register was not expanded, promote or copy the value, 761 // as appropriate. 762 for (unsigned i = 0; i != NumParts; ++i) 763 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 764 } else if (NumParts > 0) { 765 // If the intermediate type was expanded, split each the value into 766 // legal parts. 767 assert(NumIntermediates != 0 && "division by zero"); 768 assert(NumParts % NumIntermediates == 0 && 769 "Must expand into a divisible number of parts!"); 770 unsigned Factor = NumParts / NumIntermediates; 771 for (unsigned i = 0; i != NumIntermediates; ++i) 772 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 773 CallConv); 774 } 775 } 776 777 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 778 EVT valuevt, Optional<CallingConv::ID> CC) 779 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 780 RegCount(1, regs.size()), CallConv(CC) {} 781 782 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 783 const DataLayout &DL, unsigned Reg, Type *Ty, 784 Optional<CallingConv::ID> CC) { 785 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 786 787 CallConv = CC; 788 789 for (EVT ValueVT : ValueVTs) { 790 unsigned NumRegs = 791 isABIMangled() 792 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 793 : TLI.getNumRegisters(Context, ValueVT); 794 MVT RegisterVT = 795 isABIMangled() 796 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 797 : TLI.getRegisterType(Context, ValueVT); 798 for (unsigned i = 0; i != NumRegs; ++i) 799 Regs.push_back(Reg + i); 800 RegVTs.push_back(RegisterVT); 801 RegCount.push_back(NumRegs); 802 Reg += NumRegs; 803 } 804 } 805 806 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 807 FunctionLoweringInfo &FuncInfo, 808 const SDLoc &dl, SDValue &Chain, 809 SDValue *Flag, const Value *V) const { 810 // A Value with type {} or [0 x %t] needs no registers. 811 if (ValueVTs.empty()) 812 return SDValue(); 813 814 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 815 816 // Assemble the legal parts into the final values. 817 SmallVector<SDValue, 4> Values(ValueVTs.size()); 818 SmallVector<SDValue, 8> Parts; 819 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 820 // Copy the legal parts from the registers. 821 EVT ValueVT = ValueVTs[Value]; 822 unsigned NumRegs = RegCount[Value]; 823 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 824 *DAG.getContext(), 825 CallConv.getValue(), RegVTs[Value]) 826 : RegVTs[Value]; 827 828 Parts.resize(NumRegs); 829 for (unsigned i = 0; i != NumRegs; ++i) { 830 SDValue P; 831 if (!Flag) { 832 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 833 } else { 834 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 835 *Flag = P.getValue(2); 836 } 837 838 Chain = P.getValue(1); 839 Parts[i] = P; 840 841 // If the source register was virtual and if we know something about it, 842 // add an assert node. 843 if (!Register::isVirtualRegister(Regs[Part + i]) || 844 !RegisterVT.isInteger()) 845 continue; 846 847 const FunctionLoweringInfo::LiveOutInfo *LOI = 848 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 849 if (!LOI) 850 continue; 851 852 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 853 unsigned NumSignBits = LOI->NumSignBits; 854 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 855 856 if (NumZeroBits == RegSize) { 857 // The current value is a zero. 858 // Explicitly express that as it would be easier for 859 // optimizations to kick in. 860 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 861 continue; 862 } 863 864 // FIXME: We capture more information than the dag can represent. For 865 // now, just use the tightest assertzext/assertsext possible. 866 bool isSExt; 867 EVT FromVT(MVT::Other); 868 if (NumZeroBits) { 869 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 870 isSExt = false; 871 } else if (NumSignBits > 1) { 872 FromVT = 873 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 874 isSExt = true; 875 } else { 876 continue; 877 } 878 // Add an assertion node. 879 assert(FromVT != MVT::Other); 880 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 881 RegisterVT, P, DAG.getValueType(FromVT)); 882 } 883 884 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 885 RegisterVT, ValueVT, V, CallConv); 886 Part += NumRegs; 887 Parts.clear(); 888 } 889 890 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 891 } 892 893 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 894 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 895 const Value *V, 896 ISD::NodeType PreferredExtendType) const { 897 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 898 ISD::NodeType ExtendKind = PreferredExtendType; 899 900 // Get the list of the values's legal parts. 901 unsigned NumRegs = Regs.size(); 902 SmallVector<SDValue, 8> Parts(NumRegs); 903 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 904 unsigned NumParts = RegCount[Value]; 905 906 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 907 *DAG.getContext(), 908 CallConv.getValue(), RegVTs[Value]) 909 : RegVTs[Value]; 910 911 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 912 ExtendKind = ISD::ZERO_EXTEND; 913 914 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 915 NumParts, RegisterVT, V, CallConv, ExtendKind); 916 Part += NumParts; 917 } 918 919 // Copy the parts into the registers. 920 SmallVector<SDValue, 8> Chains(NumRegs); 921 for (unsigned i = 0; i != NumRegs; ++i) { 922 SDValue Part; 923 if (!Flag) { 924 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 925 } else { 926 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 927 *Flag = Part.getValue(1); 928 } 929 930 Chains[i] = Part.getValue(0); 931 } 932 933 if (NumRegs == 1 || Flag) 934 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 935 // flagged to it. That is the CopyToReg nodes and the user are considered 936 // a single scheduling unit. If we create a TokenFactor and return it as 937 // chain, then the TokenFactor is both a predecessor (operand) of the 938 // user as well as a successor (the TF operands are flagged to the user). 939 // c1, f1 = CopyToReg 940 // c2, f2 = CopyToReg 941 // c3 = TokenFactor c1, c2 942 // ... 943 // = op c3, ..., f2 944 Chain = Chains[NumRegs-1]; 945 else 946 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 947 } 948 949 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 950 unsigned MatchingIdx, const SDLoc &dl, 951 SelectionDAG &DAG, 952 std::vector<SDValue> &Ops) const { 953 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 954 955 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 956 if (HasMatching) 957 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 958 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 959 // Put the register class of the virtual registers in the flag word. That 960 // way, later passes can recompute register class constraints for inline 961 // assembly as well as normal instructions. 962 // Don't do this for tied operands that can use the regclass information 963 // from the def. 964 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 965 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 966 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 967 } 968 969 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 970 Ops.push_back(Res); 971 972 if (Code == InlineAsm::Kind_Clobber) { 973 // Clobbers should always have a 1:1 mapping with registers, and may 974 // reference registers that have illegal (e.g. vector) types. Hence, we 975 // shouldn't try to apply any sort of splitting logic to them. 976 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 977 "No 1:1 mapping from clobbers to regs?"); 978 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 979 (void)SP; 980 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 981 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 982 assert( 983 (Regs[I] != SP || 984 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 985 "If we clobbered the stack pointer, MFI should know about it."); 986 } 987 return; 988 } 989 990 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 991 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 992 MVT RegisterVT = RegVTs[Value]; 993 for (unsigned i = 0; i != NumRegs; ++i) { 994 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 995 unsigned TheReg = Regs[Reg++]; 996 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 997 } 998 } 999 } 1000 1001 SmallVector<std::pair<unsigned, unsigned>, 4> 1002 RegsForValue::getRegsAndSizes() const { 1003 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 1004 unsigned I = 0; 1005 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1006 unsigned RegCount = std::get<0>(CountAndVT); 1007 MVT RegisterVT = std::get<1>(CountAndVT); 1008 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1009 for (unsigned E = I + RegCount; I != E; ++I) 1010 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1011 } 1012 return OutVec; 1013 } 1014 1015 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1016 const TargetLibraryInfo *li) { 1017 AA = aa; 1018 GFI = gfi; 1019 LibInfo = li; 1020 DL = &DAG.getDataLayout(); 1021 Context = DAG.getContext(); 1022 LPadToCallSiteMap.clear(); 1023 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1024 } 1025 1026 void SelectionDAGBuilder::clear() { 1027 NodeMap.clear(); 1028 UnusedArgNodeMap.clear(); 1029 PendingLoads.clear(); 1030 PendingExports.clear(); 1031 PendingConstrainedFP.clear(); 1032 PendingConstrainedFPStrict.clear(); 1033 CurInst = nullptr; 1034 HasTailCall = false; 1035 SDNodeOrder = LowestSDNodeOrder; 1036 StatepointLowering.clear(); 1037 } 1038 1039 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1040 DanglingDebugInfoMap.clear(); 1041 } 1042 1043 // Update DAG root to include dependencies on Pending chains. 1044 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1045 SDValue Root = DAG.getRoot(); 1046 1047 if (Pending.empty()) 1048 return Root; 1049 1050 // Add current root to PendingChains, unless we already indirectly 1051 // depend on it. 1052 if (Root.getOpcode() != ISD::EntryToken) { 1053 unsigned i = 0, e = Pending.size(); 1054 for (; i != e; ++i) { 1055 assert(Pending[i].getNode()->getNumOperands() > 1); 1056 if (Pending[i].getNode()->getOperand(0) == Root) 1057 break; // Don't add the root if we already indirectly depend on it. 1058 } 1059 1060 if (i == e) 1061 Pending.push_back(Root); 1062 } 1063 1064 if (Pending.size() == 1) 1065 Root = Pending[0]; 1066 else 1067 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1068 1069 DAG.setRoot(Root); 1070 Pending.clear(); 1071 return Root; 1072 } 1073 1074 SDValue SelectionDAGBuilder::getMemoryRoot() { 1075 return updateRoot(PendingLoads); 1076 } 1077 1078 SDValue SelectionDAGBuilder::getRoot() { 1079 // Chain up all pending constrained intrinsics together with all 1080 // pending loads, by simply appending them to PendingLoads and 1081 // then calling getMemoryRoot(). 1082 PendingLoads.reserve(PendingLoads.size() + 1083 PendingConstrainedFP.size() + 1084 PendingConstrainedFPStrict.size()); 1085 PendingLoads.append(PendingConstrainedFP.begin(), 1086 PendingConstrainedFP.end()); 1087 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1088 PendingConstrainedFPStrict.end()); 1089 PendingConstrainedFP.clear(); 1090 PendingConstrainedFPStrict.clear(); 1091 return getMemoryRoot(); 1092 } 1093 1094 SDValue SelectionDAGBuilder::getControlRoot() { 1095 // We need to emit pending fpexcept.strict constrained intrinsics, 1096 // so append them to the PendingExports list. 1097 PendingExports.append(PendingConstrainedFPStrict.begin(), 1098 PendingConstrainedFPStrict.end()); 1099 PendingConstrainedFPStrict.clear(); 1100 return updateRoot(PendingExports); 1101 } 1102 1103 void SelectionDAGBuilder::visit(const Instruction &I) { 1104 // Set up outgoing PHI node register values before emitting the terminator. 1105 if (I.isTerminator()) { 1106 HandlePHINodesInSuccessorBlocks(I.getParent()); 1107 } 1108 1109 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1110 if (!isa<DbgInfoIntrinsic>(I)) 1111 ++SDNodeOrder; 1112 1113 CurInst = &I; 1114 1115 visit(I.getOpcode(), I); 1116 1117 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1118 // ConstrainedFPIntrinsics handle their own FMF. 1119 if (!isa<ConstrainedFPIntrinsic>(&I)) { 1120 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1121 // maps to this instruction. 1122 // TODO: We could handle all flags (nsw, etc) here. 1123 // TODO: If an IR instruction maps to >1 node, only the final node will have 1124 // flags set. 1125 if (SDNode *Node = getNodeForIRValue(&I)) { 1126 SDNodeFlags IncomingFlags; 1127 IncomingFlags.copyFMF(*FPMO); 1128 if (!Node->getFlags().isDefined()) 1129 Node->setFlags(IncomingFlags); 1130 else 1131 Node->intersectFlagsWith(IncomingFlags); 1132 } 1133 } 1134 } 1135 1136 if (!I.isTerminator() && !HasTailCall && 1137 !isStatepoint(&I)) // statepoints handle their exports internally 1138 CopyToExportRegsIfNeeded(&I); 1139 1140 CurInst = nullptr; 1141 } 1142 1143 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1144 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1145 } 1146 1147 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1148 // Note: this doesn't use InstVisitor, because it has to work with 1149 // ConstantExpr's in addition to instructions. 1150 switch (Opcode) { 1151 default: llvm_unreachable("Unknown instruction type encountered!"); 1152 // Build the switch statement using the Instruction.def file. 1153 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1154 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1155 #include "llvm/IR/Instruction.def" 1156 } 1157 } 1158 1159 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1160 const DIExpression *Expr) { 1161 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1162 const DbgValueInst *DI = DDI.getDI(); 1163 DIVariable *DanglingVariable = DI->getVariable(); 1164 DIExpression *DanglingExpr = DI->getExpression(); 1165 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1166 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1167 return true; 1168 } 1169 return false; 1170 }; 1171 1172 for (auto &DDIMI : DanglingDebugInfoMap) { 1173 DanglingDebugInfoVector &DDIV = DDIMI.second; 1174 1175 // If debug info is to be dropped, run it through final checks to see 1176 // whether it can be salvaged. 1177 for (auto &DDI : DDIV) 1178 if (isMatchingDbgValue(DDI)) 1179 salvageUnresolvedDbgValue(DDI); 1180 1181 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1182 } 1183 } 1184 1185 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1186 // generate the debug data structures now that we've seen its definition. 1187 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1188 SDValue Val) { 1189 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1190 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1191 return; 1192 1193 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1194 for (auto &DDI : DDIV) { 1195 const DbgValueInst *DI = DDI.getDI(); 1196 assert(DI && "Ill-formed DanglingDebugInfo"); 1197 DebugLoc dl = DDI.getdl(); 1198 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1199 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1200 DILocalVariable *Variable = DI->getVariable(); 1201 DIExpression *Expr = DI->getExpression(); 1202 assert(Variable->isValidLocationForIntrinsic(dl) && 1203 "Expected inlined-at fields to agree"); 1204 SDDbgValue *SDV; 1205 if (Val.getNode()) { 1206 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1207 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1208 // we couldn't resolve it directly when examining the DbgValue intrinsic 1209 // in the first place we should not be more successful here). Unless we 1210 // have some test case that prove this to be correct we should avoid 1211 // calling EmitFuncArgumentDbgValue here. 1212 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1213 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1214 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1215 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1216 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1217 // inserted after the definition of Val when emitting the instructions 1218 // after ISel. An alternative could be to teach 1219 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1220 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1221 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1222 << ValSDNodeOrder << "\n"); 1223 SDV = getDbgValue(Val, Variable, Expr, dl, 1224 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1225 DAG.AddDbgValue(SDV, Val.getNode(), false); 1226 } else 1227 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1228 << "in EmitFuncArgumentDbgValue\n"); 1229 } else { 1230 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1231 auto Undef = 1232 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1233 auto SDV = 1234 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1235 DAG.AddDbgValue(SDV, nullptr, false); 1236 } 1237 } 1238 DDIV.clear(); 1239 } 1240 1241 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1242 Value *V = DDI.getDI()->getValue(); 1243 DILocalVariable *Var = DDI.getDI()->getVariable(); 1244 DIExpression *Expr = DDI.getDI()->getExpression(); 1245 DebugLoc DL = DDI.getdl(); 1246 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1247 unsigned SDOrder = DDI.getSDNodeOrder(); 1248 1249 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1250 // that DW_OP_stack_value is desired. 1251 assert(isa<DbgValueInst>(DDI.getDI())); 1252 bool StackValue = true; 1253 1254 // Can this Value can be encoded without any further work? 1255 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1256 return; 1257 1258 // Attempt to salvage back through as many instructions as possible. Bail if 1259 // a non-instruction is seen, such as a constant expression or global 1260 // variable. FIXME: Further work could recover those too. 1261 while (isa<Instruction>(V)) { 1262 Instruction &VAsInst = *cast<Instruction>(V); 1263 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1264 1265 // If we cannot salvage any further, and haven't yet found a suitable debug 1266 // expression, bail out. 1267 if (!NewExpr) 1268 break; 1269 1270 // New value and expr now represent this debuginfo. 1271 V = VAsInst.getOperand(0); 1272 Expr = NewExpr; 1273 1274 // Some kind of simplification occurred: check whether the operand of the 1275 // salvaged debug expression can be encoded in this DAG. 1276 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1277 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1278 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1279 return; 1280 } 1281 } 1282 1283 // This was the final opportunity to salvage this debug information, and it 1284 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1285 // any earlier variable location. 1286 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1287 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1288 DAG.AddDbgValue(SDV, nullptr, false); 1289 1290 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1291 << "\n"); 1292 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1293 << "\n"); 1294 } 1295 1296 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1297 DIExpression *Expr, DebugLoc dl, 1298 DebugLoc InstDL, unsigned Order) { 1299 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1300 SDDbgValue *SDV; 1301 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1302 isa<ConstantPointerNull>(V)) { 1303 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1304 DAG.AddDbgValue(SDV, nullptr, false); 1305 return true; 1306 } 1307 1308 // If the Value is a frame index, we can create a FrameIndex debug value 1309 // without relying on the DAG at all. 1310 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1311 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1312 if (SI != FuncInfo.StaticAllocaMap.end()) { 1313 auto SDV = 1314 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1315 /*IsIndirect*/ false, dl, SDNodeOrder); 1316 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1317 // is still available even if the SDNode gets optimized out. 1318 DAG.AddDbgValue(SDV, nullptr, false); 1319 return true; 1320 } 1321 } 1322 1323 // Do not use getValue() in here; we don't want to generate code at 1324 // this point if it hasn't been done yet. 1325 SDValue N = NodeMap[V]; 1326 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1327 N = UnusedArgNodeMap[V]; 1328 if (N.getNode()) { 1329 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1330 return true; 1331 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1332 DAG.AddDbgValue(SDV, N.getNode(), false); 1333 return true; 1334 } 1335 1336 // Special rules apply for the first dbg.values of parameter variables in a 1337 // function. Identify them by the fact they reference Argument Values, that 1338 // they're parameters, and they are parameters of the current function. We 1339 // need to let them dangle until they get an SDNode. 1340 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1341 !InstDL.getInlinedAt(); 1342 if (!IsParamOfFunc) { 1343 // The value is not used in this block yet (or it would have an SDNode). 1344 // We still want the value to appear for the user if possible -- if it has 1345 // an associated VReg, we can refer to that instead. 1346 auto VMI = FuncInfo.ValueMap.find(V); 1347 if (VMI != FuncInfo.ValueMap.end()) { 1348 unsigned Reg = VMI->second; 1349 // If this is a PHI node, it may be split up into several MI PHI nodes 1350 // (in FunctionLoweringInfo::set). 1351 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1352 V->getType(), None); 1353 if (RFV.occupiesMultipleRegs()) { 1354 unsigned Offset = 0; 1355 unsigned BitsToDescribe = 0; 1356 if (auto VarSize = Var->getSizeInBits()) 1357 BitsToDescribe = *VarSize; 1358 if (auto Fragment = Expr->getFragmentInfo()) 1359 BitsToDescribe = Fragment->SizeInBits; 1360 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1361 unsigned RegisterSize = RegAndSize.second; 1362 // Bail out if all bits are described already. 1363 if (Offset >= BitsToDescribe) 1364 break; 1365 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1366 ? BitsToDescribe - Offset 1367 : RegisterSize; 1368 auto FragmentExpr = DIExpression::createFragmentExpression( 1369 Expr, Offset, FragmentSize); 1370 if (!FragmentExpr) 1371 continue; 1372 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1373 false, dl, SDNodeOrder); 1374 DAG.AddDbgValue(SDV, nullptr, false); 1375 Offset += RegisterSize; 1376 } 1377 } else { 1378 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1379 DAG.AddDbgValue(SDV, nullptr, false); 1380 } 1381 return true; 1382 } 1383 } 1384 1385 return false; 1386 } 1387 1388 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1389 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1390 for (auto &Pair : DanglingDebugInfoMap) 1391 for (auto &DDI : Pair.second) 1392 salvageUnresolvedDbgValue(DDI); 1393 clearDanglingDebugInfo(); 1394 } 1395 1396 /// getCopyFromRegs - If there was virtual register allocated for the value V 1397 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1398 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1399 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1400 SDValue Result; 1401 1402 if (It != FuncInfo.ValueMap.end()) { 1403 Register InReg = It->second; 1404 1405 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1406 DAG.getDataLayout(), InReg, Ty, 1407 None); // This is not an ABI copy. 1408 SDValue Chain = DAG.getEntryNode(); 1409 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1410 V); 1411 resolveDanglingDebugInfo(V, Result); 1412 } 1413 1414 return Result; 1415 } 1416 1417 /// getValue - Return an SDValue for the given Value. 1418 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1419 // If we already have an SDValue for this value, use it. It's important 1420 // to do this first, so that we don't create a CopyFromReg if we already 1421 // have a regular SDValue. 1422 SDValue &N = NodeMap[V]; 1423 if (N.getNode()) return N; 1424 1425 // If there's a virtual register allocated and initialized for this 1426 // value, use it. 1427 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1428 return copyFromReg; 1429 1430 // Otherwise create a new SDValue and remember it. 1431 SDValue Val = getValueImpl(V); 1432 NodeMap[V] = Val; 1433 resolveDanglingDebugInfo(V, Val); 1434 return Val; 1435 } 1436 1437 /// getNonRegisterValue - Return an SDValue for the given Value, but 1438 /// don't look in FuncInfo.ValueMap for a virtual register. 1439 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1440 // If we already have an SDValue for this value, use it. 1441 SDValue &N = NodeMap[V]; 1442 if (N.getNode()) { 1443 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1444 // Remove the debug location from the node as the node is about to be used 1445 // in a location which may differ from the original debug location. This 1446 // is relevant to Constant and ConstantFP nodes because they can appear 1447 // as constant expressions inside PHI nodes. 1448 N->setDebugLoc(DebugLoc()); 1449 } 1450 return N; 1451 } 1452 1453 // Otherwise create a new SDValue and remember it. 1454 SDValue Val = getValueImpl(V); 1455 NodeMap[V] = Val; 1456 resolveDanglingDebugInfo(V, Val); 1457 return Val; 1458 } 1459 1460 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1461 /// Create an SDValue for the given value. 1462 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1463 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1464 1465 if (const Constant *C = dyn_cast<Constant>(V)) { 1466 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1467 1468 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1469 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1470 1471 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1472 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1473 1474 if (isa<ConstantPointerNull>(C)) { 1475 unsigned AS = V->getType()->getPointerAddressSpace(); 1476 return DAG.getConstant(0, getCurSDLoc(), 1477 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1478 } 1479 1480 if (match(C, m_VScale(DAG.getDataLayout()))) 1481 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1482 1483 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1484 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1485 1486 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1487 return DAG.getUNDEF(VT); 1488 1489 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1490 visit(CE->getOpcode(), *CE); 1491 SDValue N1 = NodeMap[V]; 1492 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1493 return N1; 1494 } 1495 1496 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1497 SmallVector<SDValue, 4> Constants; 1498 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1499 OI != OE; ++OI) { 1500 SDNode *Val = getValue(*OI).getNode(); 1501 // If the operand is an empty aggregate, there are no values. 1502 if (!Val) continue; 1503 // Add each leaf value from the operand to the Constants list 1504 // to form a flattened list of all the values. 1505 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1506 Constants.push_back(SDValue(Val, i)); 1507 } 1508 1509 return DAG.getMergeValues(Constants, getCurSDLoc()); 1510 } 1511 1512 if (const ConstantDataSequential *CDS = 1513 dyn_cast<ConstantDataSequential>(C)) { 1514 SmallVector<SDValue, 4> Ops; 1515 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1516 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1517 // Add each leaf value from the operand to the Constants list 1518 // to form a flattened list of all the values. 1519 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1520 Ops.push_back(SDValue(Val, i)); 1521 } 1522 1523 if (isa<ArrayType>(CDS->getType())) 1524 return DAG.getMergeValues(Ops, getCurSDLoc()); 1525 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1526 } 1527 1528 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1529 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1530 "Unknown struct or array constant!"); 1531 1532 SmallVector<EVT, 4> ValueVTs; 1533 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1534 unsigned NumElts = ValueVTs.size(); 1535 if (NumElts == 0) 1536 return SDValue(); // empty struct 1537 SmallVector<SDValue, 4> Constants(NumElts); 1538 for (unsigned i = 0; i != NumElts; ++i) { 1539 EVT EltVT = ValueVTs[i]; 1540 if (isa<UndefValue>(C)) 1541 Constants[i] = DAG.getUNDEF(EltVT); 1542 else if (EltVT.isFloatingPoint()) 1543 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1544 else 1545 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1546 } 1547 1548 return DAG.getMergeValues(Constants, getCurSDLoc()); 1549 } 1550 1551 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1552 return DAG.getBlockAddress(BA, VT); 1553 1554 VectorType *VecTy = cast<VectorType>(V->getType()); 1555 1556 // Now that we know the number and type of the elements, get that number of 1557 // elements into the Ops array based on what kind of constant it is. 1558 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1559 SmallVector<SDValue, 16> Ops; 1560 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1561 for (unsigned i = 0; i != NumElements; ++i) 1562 Ops.push_back(getValue(CV->getOperand(i))); 1563 1564 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1565 } else if (isa<ConstantAggregateZero>(C)) { 1566 EVT EltVT = 1567 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1568 1569 SDValue Op; 1570 if (EltVT.isFloatingPoint()) 1571 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1572 else 1573 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1574 1575 if (isa<ScalableVectorType>(VecTy)) 1576 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1577 else { 1578 SmallVector<SDValue, 16> Ops; 1579 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1580 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1581 } 1582 } 1583 llvm_unreachable("Unknown vector constant"); 1584 } 1585 1586 // If this is a static alloca, generate it as the frameindex instead of 1587 // computation. 1588 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1589 DenseMap<const AllocaInst*, int>::iterator SI = 1590 FuncInfo.StaticAllocaMap.find(AI); 1591 if (SI != FuncInfo.StaticAllocaMap.end()) 1592 return DAG.getFrameIndex(SI->second, 1593 TLI.getFrameIndexTy(DAG.getDataLayout())); 1594 } 1595 1596 // If this is an instruction which fast-isel has deferred, select it now. 1597 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1598 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1599 1600 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1601 Inst->getType(), getABIRegCopyCC(V)); 1602 SDValue Chain = DAG.getEntryNode(); 1603 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1604 } 1605 1606 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1607 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1608 } 1609 llvm_unreachable("Can't get register for value!"); 1610 } 1611 1612 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1613 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1614 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1615 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1616 bool IsSEH = isAsynchronousEHPersonality(Pers); 1617 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1618 if (!IsSEH) 1619 CatchPadMBB->setIsEHScopeEntry(); 1620 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1621 if (IsMSVCCXX || IsCoreCLR) 1622 CatchPadMBB->setIsEHFuncletEntry(); 1623 } 1624 1625 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1626 // Update machine-CFG edge. 1627 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1628 FuncInfo.MBB->addSuccessor(TargetMBB); 1629 1630 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1631 bool IsSEH = isAsynchronousEHPersonality(Pers); 1632 if (IsSEH) { 1633 // If this is not a fall-through branch or optimizations are switched off, 1634 // emit the branch. 1635 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1636 TM.getOptLevel() == CodeGenOpt::None) 1637 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1638 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1639 return; 1640 } 1641 1642 // Figure out the funclet membership for the catchret's successor. 1643 // This will be used by the FuncletLayout pass to determine how to order the 1644 // BB's. 1645 // A 'catchret' returns to the outer scope's color. 1646 Value *ParentPad = I.getCatchSwitchParentPad(); 1647 const BasicBlock *SuccessorColor; 1648 if (isa<ConstantTokenNone>(ParentPad)) 1649 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1650 else 1651 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1652 assert(SuccessorColor && "No parent funclet for catchret!"); 1653 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1654 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1655 1656 // Create the terminator node. 1657 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1658 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1659 DAG.getBasicBlock(SuccessorColorMBB)); 1660 DAG.setRoot(Ret); 1661 } 1662 1663 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1664 // Don't emit any special code for the cleanuppad instruction. It just marks 1665 // the start of an EH scope/funclet. 1666 FuncInfo.MBB->setIsEHScopeEntry(); 1667 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1668 if (Pers != EHPersonality::Wasm_CXX) { 1669 FuncInfo.MBB->setIsEHFuncletEntry(); 1670 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1671 } 1672 } 1673 1674 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1675 // the control flow always stops at the single catch pad, as it does for a 1676 // cleanup pad. In case the exception caught is not of the types the catch pad 1677 // catches, it will be rethrown by a rethrow. 1678 static void findWasmUnwindDestinations( 1679 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1680 BranchProbability Prob, 1681 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1682 &UnwindDests) { 1683 while (EHPadBB) { 1684 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1685 if (isa<CleanupPadInst>(Pad)) { 1686 // Stop on cleanup pads. 1687 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1688 UnwindDests.back().first->setIsEHScopeEntry(); 1689 break; 1690 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1691 // Add the catchpad handlers to the possible destinations. We don't 1692 // continue to the unwind destination of the catchswitch for wasm. 1693 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1694 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1695 UnwindDests.back().first->setIsEHScopeEntry(); 1696 } 1697 break; 1698 } else { 1699 continue; 1700 } 1701 } 1702 } 1703 1704 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1705 /// many places it could ultimately go. In the IR, we have a single unwind 1706 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1707 /// This function skips over imaginary basic blocks that hold catchswitch 1708 /// instructions, and finds all the "real" machine 1709 /// basic block destinations. As those destinations may not be successors of 1710 /// EHPadBB, here we also calculate the edge probability to those destinations. 1711 /// The passed-in Prob is the edge probability to EHPadBB. 1712 static void findUnwindDestinations( 1713 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1714 BranchProbability Prob, 1715 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1716 &UnwindDests) { 1717 EHPersonality Personality = 1718 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1719 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1720 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1721 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1722 bool IsSEH = isAsynchronousEHPersonality(Personality); 1723 1724 if (IsWasmCXX) { 1725 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1726 assert(UnwindDests.size() <= 1 && 1727 "There should be at most one unwind destination for wasm"); 1728 return; 1729 } 1730 1731 while (EHPadBB) { 1732 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1733 BasicBlock *NewEHPadBB = nullptr; 1734 if (isa<LandingPadInst>(Pad)) { 1735 // Stop on landingpads. They are not funclets. 1736 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1737 break; 1738 } else if (isa<CleanupPadInst>(Pad)) { 1739 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1740 // personalities. 1741 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1742 UnwindDests.back().first->setIsEHScopeEntry(); 1743 UnwindDests.back().first->setIsEHFuncletEntry(); 1744 break; 1745 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1746 // Add the catchpad handlers to the possible destinations. 1747 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1748 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1749 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1750 if (IsMSVCCXX || IsCoreCLR) 1751 UnwindDests.back().first->setIsEHFuncletEntry(); 1752 if (!IsSEH) 1753 UnwindDests.back().first->setIsEHScopeEntry(); 1754 } 1755 NewEHPadBB = CatchSwitch->getUnwindDest(); 1756 } else { 1757 continue; 1758 } 1759 1760 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1761 if (BPI && NewEHPadBB) 1762 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1763 EHPadBB = NewEHPadBB; 1764 } 1765 } 1766 1767 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1768 // Update successor info. 1769 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1770 auto UnwindDest = I.getUnwindDest(); 1771 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1772 BranchProbability UnwindDestProb = 1773 (BPI && UnwindDest) 1774 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1775 : BranchProbability::getZero(); 1776 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1777 for (auto &UnwindDest : UnwindDests) { 1778 UnwindDest.first->setIsEHPad(); 1779 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1780 } 1781 FuncInfo.MBB->normalizeSuccProbs(); 1782 1783 // Create the terminator node. 1784 SDValue Ret = 1785 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1786 DAG.setRoot(Ret); 1787 } 1788 1789 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1790 report_fatal_error("visitCatchSwitch not yet implemented!"); 1791 } 1792 1793 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1794 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1795 auto &DL = DAG.getDataLayout(); 1796 SDValue Chain = getControlRoot(); 1797 SmallVector<ISD::OutputArg, 8> Outs; 1798 SmallVector<SDValue, 8> OutVals; 1799 1800 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1801 // lower 1802 // 1803 // %val = call <ty> @llvm.experimental.deoptimize() 1804 // ret <ty> %val 1805 // 1806 // differently. 1807 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1808 LowerDeoptimizingReturn(); 1809 return; 1810 } 1811 1812 if (!FuncInfo.CanLowerReturn) { 1813 unsigned DemoteReg = FuncInfo.DemoteRegister; 1814 const Function *F = I.getParent()->getParent(); 1815 1816 // Emit a store of the return value through the virtual register. 1817 // Leave Outs empty so that LowerReturn won't try to load return 1818 // registers the usual way. 1819 SmallVector<EVT, 1> PtrValueVTs; 1820 ComputeValueVTs(TLI, DL, 1821 F->getReturnType()->getPointerTo( 1822 DAG.getDataLayout().getAllocaAddrSpace()), 1823 PtrValueVTs); 1824 1825 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1826 DemoteReg, PtrValueVTs[0]); 1827 SDValue RetOp = getValue(I.getOperand(0)); 1828 1829 SmallVector<EVT, 4> ValueVTs, MemVTs; 1830 SmallVector<uint64_t, 4> Offsets; 1831 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1832 &Offsets); 1833 unsigned NumValues = ValueVTs.size(); 1834 1835 SmallVector<SDValue, 4> Chains(NumValues); 1836 for (unsigned i = 0; i != NumValues; ++i) { 1837 // An aggregate return value cannot wrap around the address space, so 1838 // offsets to its parts don't wrap either. 1839 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1840 1841 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1842 if (MemVTs[i] != ValueVTs[i]) 1843 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1844 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val, 1845 // FIXME: better loc info would be nice. 1846 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1847 } 1848 1849 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1850 MVT::Other, Chains); 1851 } else if (I.getNumOperands() != 0) { 1852 SmallVector<EVT, 4> ValueVTs; 1853 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1854 unsigned NumValues = ValueVTs.size(); 1855 if (NumValues) { 1856 SDValue RetOp = getValue(I.getOperand(0)); 1857 1858 const Function *F = I.getParent()->getParent(); 1859 1860 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1861 I.getOperand(0)->getType(), F->getCallingConv(), 1862 /*IsVarArg*/ false); 1863 1864 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1865 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1866 Attribute::SExt)) 1867 ExtendKind = ISD::SIGN_EXTEND; 1868 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1869 Attribute::ZExt)) 1870 ExtendKind = ISD::ZERO_EXTEND; 1871 1872 LLVMContext &Context = F->getContext(); 1873 bool RetInReg = F->getAttributes().hasAttribute( 1874 AttributeList::ReturnIndex, Attribute::InReg); 1875 1876 for (unsigned j = 0; j != NumValues; ++j) { 1877 EVT VT = ValueVTs[j]; 1878 1879 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1880 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1881 1882 CallingConv::ID CC = F->getCallingConv(); 1883 1884 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1885 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1886 SmallVector<SDValue, 4> Parts(NumParts); 1887 getCopyToParts(DAG, getCurSDLoc(), 1888 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1889 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1890 1891 // 'inreg' on function refers to return value 1892 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1893 if (RetInReg) 1894 Flags.setInReg(); 1895 1896 if (I.getOperand(0)->getType()->isPointerTy()) { 1897 Flags.setPointer(); 1898 Flags.setPointerAddrSpace( 1899 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1900 } 1901 1902 if (NeedsRegBlock) { 1903 Flags.setInConsecutiveRegs(); 1904 if (j == NumValues - 1) 1905 Flags.setInConsecutiveRegsLast(); 1906 } 1907 1908 // Propagate extension type if any 1909 if (ExtendKind == ISD::SIGN_EXTEND) 1910 Flags.setSExt(); 1911 else if (ExtendKind == ISD::ZERO_EXTEND) 1912 Flags.setZExt(); 1913 1914 for (unsigned i = 0; i < NumParts; ++i) { 1915 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1916 VT, /*isfixed=*/true, 0, 0)); 1917 OutVals.push_back(Parts[i]); 1918 } 1919 } 1920 } 1921 } 1922 1923 // Push in swifterror virtual register as the last element of Outs. This makes 1924 // sure swifterror virtual register will be returned in the swifterror 1925 // physical register. 1926 const Function *F = I.getParent()->getParent(); 1927 if (TLI.supportSwiftError() && 1928 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1929 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1930 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1931 Flags.setSwiftError(); 1932 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1933 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1934 true /*isfixed*/, 1 /*origidx*/, 1935 0 /*partOffs*/)); 1936 // Create SDNode for the swifterror virtual register. 1937 OutVals.push_back( 1938 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1939 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1940 EVT(TLI.getPointerTy(DL)))); 1941 } 1942 1943 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1944 CallingConv::ID CallConv = 1945 DAG.getMachineFunction().getFunction().getCallingConv(); 1946 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1947 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1948 1949 // Verify that the target's LowerReturn behaved as expected. 1950 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1951 "LowerReturn didn't return a valid chain!"); 1952 1953 // Update the DAG with the new chain value resulting from return lowering. 1954 DAG.setRoot(Chain); 1955 } 1956 1957 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1958 /// created for it, emit nodes to copy the value into the virtual 1959 /// registers. 1960 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1961 // Skip empty types 1962 if (V->getType()->isEmptyTy()) 1963 return; 1964 1965 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 1966 if (VMI != FuncInfo.ValueMap.end()) { 1967 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1968 CopyValueToVirtualRegister(V, VMI->second); 1969 } 1970 } 1971 1972 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1973 /// the current basic block, add it to ValueMap now so that we'll get a 1974 /// CopyTo/FromReg. 1975 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1976 // No need to export constants. 1977 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1978 1979 // Already exported? 1980 if (FuncInfo.isExportedInst(V)) return; 1981 1982 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1983 CopyValueToVirtualRegister(V, Reg); 1984 } 1985 1986 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1987 const BasicBlock *FromBB) { 1988 // The operands of the setcc have to be in this block. We don't know 1989 // how to export them from some other block. 1990 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1991 // Can export from current BB. 1992 if (VI->getParent() == FromBB) 1993 return true; 1994 1995 // Is already exported, noop. 1996 return FuncInfo.isExportedInst(V); 1997 } 1998 1999 // If this is an argument, we can export it if the BB is the entry block or 2000 // if it is already exported. 2001 if (isa<Argument>(V)) { 2002 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2003 return true; 2004 2005 // Otherwise, can only export this if it is already exported. 2006 return FuncInfo.isExportedInst(V); 2007 } 2008 2009 // Otherwise, constants can always be exported. 2010 return true; 2011 } 2012 2013 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2014 BranchProbability 2015 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2016 const MachineBasicBlock *Dst) const { 2017 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2018 const BasicBlock *SrcBB = Src->getBasicBlock(); 2019 const BasicBlock *DstBB = Dst->getBasicBlock(); 2020 if (!BPI) { 2021 // If BPI is not available, set the default probability as 1 / N, where N is 2022 // the number of successors. 2023 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2024 return BranchProbability(1, SuccSize); 2025 } 2026 return BPI->getEdgeProbability(SrcBB, DstBB); 2027 } 2028 2029 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2030 MachineBasicBlock *Dst, 2031 BranchProbability Prob) { 2032 if (!FuncInfo.BPI) 2033 Src->addSuccessorWithoutProb(Dst); 2034 else { 2035 if (Prob.isUnknown()) 2036 Prob = getEdgeProbability(Src, Dst); 2037 Src->addSuccessor(Dst, Prob); 2038 } 2039 } 2040 2041 static bool InBlock(const Value *V, const BasicBlock *BB) { 2042 if (const Instruction *I = dyn_cast<Instruction>(V)) 2043 return I->getParent() == BB; 2044 return true; 2045 } 2046 2047 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2048 /// This function emits a branch and is used at the leaves of an OR or an 2049 /// AND operator tree. 2050 void 2051 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2052 MachineBasicBlock *TBB, 2053 MachineBasicBlock *FBB, 2054 MachineBasicBlock *CurBB, 2055 MachineBasicBlock *SwitchBB, 2056 BranchProbability TProb, 2057 BranchProbability FProb, 2058 bool InvertCond) { 2059 const BasicBlock *BB = CurBB->getBasicBlock(); 2060 2061 // If the leaf of the tree is a comparison, merge the condition into 2062 // the caseblock. 2063 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2064 // The operands of the cmp have to be in this block. We don't know 2065 // how to export them from some other block. If this is the first block 2066 // of the sequence, no exporting is needed. 2067 if (CurBB == SwitchBB || 2068 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2069 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2070 ISD::CondCode Condition; 2071 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2072 ICmpInst::Predicate Pred = 2073 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2074 Condition = getICmpCondCode(Pred); 2075 } else { 2076 const FCmpInst *FC = cast<FCmpInst>(Cond); 2077 FCmpInst::Predicate Pred = 2078 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2079 Condition = getFCmpCondCode(Pred); 2080 if (TM.Options.NoNaNsFPMath) 2081 Condition = getFCmpCodeWithoutNaN(Condition); 2082 } 2083 2084 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2085 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2086 SL->SwitchCases.push_back(CB); 2087 return; 2088 } 2089 } 2090 2091 // Create a CaseBlock record representing this branch. 2092 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2093 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2094 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2095 SL->SwitchCases.push_back(CB); 2096 } 2097 2098 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2099 MachineBasicBlock *TBB, 2100 MachineBasicBlock *FBB, 2101 MachineBasicBlock *CurBB, 2102 MachineBasicBlock *SwitchBB, 2103 Instruction::BinaryOps Opc, 2104 BranchProbability TProb, 2105 BranchProbability FProb, 2106 bool InvertCond) { 2107 // Skip over not part of the tree and remember to invert op and operands at 2108 // next level. 2109 Value *NotCond; 2110 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2111 InBlock(NotCond, CurBB->getBasicBlock())) { 2112 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2113 !InvertCond); 2114 return; 2115 } 2116 2117 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2118 // Compute the effective opcode for Cond, taking into account whether it needs 2119 // to be inverted, e.g. 2120 // and (not (or A, B)), C 2121 // gets lowered as 2122 // and (and (not A, not B), C) 2123 unsigned BOpc = 0; 2124 if (BOp) { 2125 BOpc = BOp->getOpcode(); 2126 if (InvertCond) { 2127 if (BOpc == Instruction::And) 2128 BOpc = Instruction::Or; 2129 else if (BOpc == Instruction::Or) 2130 BOpc = Instruction::And; 2131 } 2132 } 2133 2134 // If this node is not part of the or/and tree, emit it as a branch. 2135 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2136 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2137 BOp->getParent() != CurBB->getBasicBlock() || 2138 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2139 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2140 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2141 TProb, FProb, InvertCond); 2142 return; 2143 } 2144 2145 // Create TmpBB after CurBB. 2146 MachineFunction::iterator BBI(CurBB); 2147 MachineFunction &MF = DAG.getMachineFunction(); 2148 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2149 CurBB->getParent()->insert(++BBI, TmpBB); 2150 2151 if (Opc == Instruction::Or) { 2152 // Codegen X | Y as: 2153 // BB1: 2154 // jmp_if_X TBB 2155 // jmp TmpBB 2156 // TmpBB: 2157 // jmp_if_Y TBB 2158 // jmp FBB 2159 // 2160 2161 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2162 // The requirement is that 2163 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2164 // = TrueProb for original BB. 2165 // Assuming the original probabilities are A and B, one choice is to set 2166 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2167 // A/(1+B) and 2B/(1+B). This choice assumes that 2168 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2169 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2170 // TmpBB, but the math is more complicated. 2171 2172 auto NewTrueProb = TProb / 2; 2173 auto NewFalseProb = TProb / 2 + FProb; 2174 // Emit the LHS condition. 2175 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2176 NewTrueProb, NewFalseProb, InvertCond); 2177 2178 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2179 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2180 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2181 // Emit the RHS condition into TmpBB. 2182 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2183 Probs[0], Probs[1], InvertCond); 2184 } else { 2185 assert(Opc == Instruction::And && "Unknown merge op!"); 2186 // Codegen X & Y as: 2187 // BB1: 2188 // jmp_if_X TmpBB 2189 // jmp FBB 2190 // TmpBB: 2191 // jmp_if_Y TBB 2192 // jmp FBB 2193 // 2194 // This requires creation of TmpBB after CurBB. 2195 2196 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2197 // The requirement is that 2198 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2199 // = FalseProb for original BB. 2200 // Assuming the original probabilities are A and B, one choice is to set 2201 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2202 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2203 // TrueProb for BB1 * FalseProb for TmpBB. 2204 2205 auto NewTrueProb = TProb + FProb / 2; 2206 auto NewFalseProb = FProb / 2; 2207 // Emit the LHS condition. 2208 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2209 NewTrueProb, NewFalseProb, InvertCond); 2210 2211 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2212 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2213 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2214 // Emit the RHS condition into TmpBB. 2215 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2216 Probs[0], Probs[1], InvertCond); 2217 } 2218 } 2219 2220 /// If the set of cases should be emitted as a series of branches, return true. 2221 /// If we should emit this as a bunch of and/or'd together conditions, return 2222 /// false. 2223 bool 2224 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2225 if (Cases.size() != 2) return true; 2226 2227 // If this is two comparisons of the same values or'd or and'd together, they 2228 // will get folded into a single comparison, so don't emit two blocks. 2229 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2230 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2231 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2232 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2233 return false; 2234 } 2235 2236 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2237 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2238 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2239 Cases[0].CC == Cases[1].CC && 2240 isa<Constant>(Cases[0].CmpRHS) && 2241 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2242 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2243 return false; 2244 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2245 return false; 2246 } 2247 2248 return true; 2249 } 2250 2251 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2252 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2253 2254 // Update machine-CFG edges. 2255 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2256 2257 if (I.isUnconditional()) { 2258 // Update machine-CFG edges. 2259 BrMBB->addSuccessor(Succ0MBB); 2260 2261 // If this is not a fall-through branch or optimizations are switched off, 2262 // emit the branch. 2263 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2264 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2265 MVT::Other, getControlRoot(), 2266 DAG.getBasicBlock(Succ0MBB))); 2267 2268 return; 2269 } 2270 2271 // If this condition is one of the special cases we handle, do special stuff 2272 // now. 2273 const Value *CondVal = I.getCondition(); 2274 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2275 2276 // If this is a series of conditions that are or'd or and'd together, emit 2277 // this as a sequence of branches instead of setcc's with and/or operations. 2278 // As long as jumps are not expensive, this should improve performance. 2279 // For example, instead of something like: 2280 // cmp A, B 2281 // C = seteq 2282 // cmp D, E 2283 // F = setle 2284 // or C, F 2285 // jnz foo 2286 // Emit: 2287 // cmp A, B 2288 // je foo 2289 // cmp D, E 2290 // jle foo 2291 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2292 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2293 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2294 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2295 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2296 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2297 Opcode, 2298 getEdgeProbability(BrMBB, Succ0MBB), 2299 getEdgeProbability(BrMBB, Succ1MBB), 2300 /*InvertCond=*/false); 2301 // If the compares in later blocks need to use values not currently 2302 // exported from this block, export them now. This block should always 2303 // be the first entry. 2304 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2305 2306 // Allow some cases to be rejected. 2307 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2308 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2309 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2310 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2311 } 2312 2313 // Emit the branch for this block. 2314 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2315 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2316 return; 2317 } 2318 2319 // Okay, we decided not to do this, remove any inserted MBB's and clear 2320 // SwitchCases. 2321 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2322 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2323 2324 SL->SwitchCases.clear(); 2325 } 2326 } 2327 2328 // Create a CaseBlock record representing this branch. 2329 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2330 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2331 2332 // Use visitSwitchCase to actually insert the fast branch sequence for this 2333 // cond branch. 2334 visitSwitchCase(CB, BrMBB); 2335 } 2336 2337 /// visitSwitchCase - Emits the necessary code to represent a single node in 2338 /// the binary search tree resulting from lowering a switch instruction. 2339 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2340 MachineBasicBlock *SwitchBB) { 2341 SDValue Cond; 2342 SDValue CondLHS = getValue(CB.CmpLHS); 2343 SDLoc dl = CB.DL; 2344 2345 if (CB.CC == ISD::SETTRUE) { 2346 // Branch or fall through to TrueBB. 2347 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2348 SwitchBB->normalizeSuccProbs(); 2349 if (CB.TrueBB != NextBlock(SwitchBB)) { 2350 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2351 DAG.getBasicBlock(CB.TrueBB))); 2352 } 2353 return; 2354 } 2355 2356 auto &TLI = DAG.getTargetLoweringInfo(); 2357 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2358 2359 // Build the setcc now. 2360 if (!CB.CmpMHS) { 2361 // Fold "(X == true)" to X and "(X == false)" to !X to 2362 // handle common cases produced by branch lowering. 2363 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2364 CB.CC == ISD::SETEQ) 2365 Cond = CondLHS; 2366 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2367 CB.CC == ISD::SETEQ) { 2368 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2369 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2370 } else { 2371 SDValue CondRHS = getValue(CB.CmpRHS); 2372 2373 // If a pointer's DAG type is larger than its memory type then the DAG 2374 // values are zero-extended. This breaks signed comparisons so truncate 2375 // back to the underlying type before doing the compare. 2376 if (CondLHS.getValueType() != MemVT) { 2377 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2378 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2379 } 2380 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2381 } 2382 } else { 2383 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2384 2385 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2386 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2387 2388 SDValue CmpOp = getValue(CB.CmpMHS); 2389 EVT VT = CmpOp.getValueType(); 2390 2391 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2392 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2393 ISD::SETLE); 2394 } else { 2395 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2396 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2397 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2398 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2399 } 2400 } 2401 2402 // Update successor info 2403 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2404 // TrueBB and FalseBB are always different unless the incoming IR is 2405 // degenerate. This only happens when running llc on weird IR. 2406 if (CB.TrueBB != CB.FalseBB) 2407 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2408 SwitchBB->normalizeSuccProbs(); 2409 2410 // If the lhs block is the next block, invert the condition so that we can 2411 // fall through to the lhs instead of the rhs block. 2412 if (CB.TrueBB == NextBlock(SwitchBB)) { 2413 std::swap(CB.TrueBB, CB.FalseBB); 2414 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2415 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2416 } 2417 2418 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2419 MVT::Other, getControlRoot(), Cond, 2420 DAG.getBasicBlock(CB.TrueBB)); 2421 2422 // Insert the false branch. Do this even if it's a fall through branch, 2423 // this makes it easier to do DAG optimizations which require inverting 2424 // the branch condition. 2425 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2426 DAG.getBasicBlock(CB.FalseBB)); 2427 2428 DAG.setRoot(BrCond); 2429 } 2430 2431 /// visitJumpTable - Emit JumpTable node in the current MBB 2432 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2433 // Emit the code for the jump table 2434 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2435 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2436 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2437 JT.Reg, PTy); 2438 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2439 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2440 MVT::Other, Index.getValue(1), 2441 Table, Index); 2442 DAG.setRoot(BrJumpTable); 2443 } 2444 2445 /// visitJumpTableHeader - This function emits necessary code to produce index 2446 /// in the JumpTable from switch case. 2447 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2448 JumpTableHeader &JTH, 2449 MachineBasicBlock *SwitchBB) { 2450 SDLoc dl = getCurSDLoc(); 2451 2452 // Subtract the lowest switch case value from the value being switched on. 2453 SDValue SwitchOp = getValue(JTH.SValue); 2454 EVT VT = SwitchOp.getValueType(); 2455 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2456 DAG.getConstant(JTH.First, dl, VT)); 2457 2458 // The SDNode we just created, which holds the value being switched on minus 2459 // the smallest case value, needs to be copied to a virtual register so it 2460 // can be used as an index into the jump table in a subsequent basic block. 2461 // This value may be smaller or larger than the target's pointer type, and 2462 // therefore require extension or truncating. 2463 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2464 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2465 2466 unsigned JumpTableReg = 2467 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2468 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2469 JumpTableReg, SwitchOp); 2470 JT.Reg = JumpTableReg; 2471 2472 if (!JTH.OmitRangeCheck) { 2473 // Emit the range check for the jump table, and branch to the default block 2474 // for the switch statement if the value being switched on exceeds the 2475 // largest case in the switch. 2476 SDValue CMP = DAG.getSetCC( 2477 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2478 Sub.getValueType()), 2479 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2480 2481 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2482 MVT::Other, CopyTo, CMP, 2483 DAG.getBasicBlock(JT.Default)); 2484 2485 // Avoid emitting unnecessary branches to the next block. 2486 if (JT.MBB != NextBlock(SwitchBB)) 2487 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2488 DAG.getBasicBlock(JT.MBB)); 2489 2490 DAG.setRoot(BrCond); 2491 } else { 2492 // Avoid emitting unnecessary branches to the next block. 2493 if (JT.MBB != NextBlock(SwitchBB)) 2494 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2495 DAG.getBasicBlock(JT.MBB))); 2496 else 2497 DAG.setRoot(CopyTo); 2498 } 2499 } 2500 2501 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2502 /// variable if there exists one. 2503 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2504 SDValue &Chain) { 2505 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2506 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2507 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2508 MachineFunction &MF = DAG.getMachineFunction(); 2509 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2510 MachineSDNode *Node = 2511 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2512 if (Global) { 2513 MachinePointerInfo MPInfo(Global); 2514 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2515 MachineMemOperand::MODereferenceable; 2516 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2517 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2518 DAG.setNodeMemRefs(Node, {MemRef}); 2519 } 2520 if (PtrTy != PtrMemTy) 2521 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2522 return SDValue(Node, 0); 2523 } 2524 2525 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2526 /// tail spliced into a stack protector check success bb. 2527 /// 2528 /// For a high level explanation of how this fits into the stack protector 2529 /// generation see the comment on the declaration of class 2530 /// StackProtectorDescriptor. 2531 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2532 MachineBasicBlock *ParentBB) { 2533 2534 // First create the loads to the guard/stack slot for the comparison. 2535 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2536 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2537 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2538 2539 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2540 int FI = MFI.getStackProtectorIndex(); 2541 2542 SDValue Guard; 2543 SDLoc dl = getCurSDLoc(); 2544 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2545 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2546 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2547 2548 // Generate code to load the content of the guard slot. 2549 SDValue GuardVal = DAG.getLoad( 2550 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2551 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2552 MachineMemOperand::MOVolatile); 2553 2554 if (TLI.useStackGuardXorFP()) 2555 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2556 2557 // Retrieve guard check function, nullptr if instrumentation is inlined. 2558 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2559 // The target provides a guard check function to validate the guard value. 2560 // Generate a call to that function with the content of the guard slot as 2561 // argument. 2562 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2563 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2564 2565 TargetLowering::ArgListTy Args; 2566 TargetLowering::ArgListEntry Entry; 2567 Entry.Node = GuardVal; 2568 Entry.Ty = FnTy->getParamType(0); 2569 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2570 Entry.IsInReg = true; 2571 Args.push_back(Entry); 2572 2573 TargetLowering::CallLoweringInfo CLI(DAG); 2574 CLI.setDebugLoc(getCurSDLoc()) 2575 .setChain(DAG.getEntryNode()) 2576 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2577 getValue(GuardCheckFn), std::move(Args)); 2578 2579 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2580 DAG.setRoot(Result.second); 2581 return; 2582 } 2583 2584 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2585 // Otherwise, emit a volatile load to retrieve the stack guard value. 2586 SDValue Chain = DAG.getEntryNode(); 2587 if (TLI.useLoadStackGuardNode()) { 2588 Guard = getLoadStackGuard(DAG, dl, Chain); 2589 } else { 2590 const Value *IRGuard = TLI.getSDagStackGuard(M); 2591 SDValue GuardPtr = getValue(IRGuard); 2592 2593 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2594 MachinePointerInfo(IRGuard, 0), Align, 2595 MachineMemOperand::MOVolatile); 2596 } 2597 2598 // Perform the comparison via a getsetcc. 2599 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2600 *DAG.getContext(), 2601 Guard.getValueType()), 2602 Guard, GuardVal, ISD::SETNE); 2603 2604 // If the guard/stackslot do not equal, branch to failure MBB. 2605 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2606 MVT::Other, GuardVal.getOperand(0), 2607 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2608 // Otherwise branch to success MBB. 2609 SDValue Br = DAG.getNode(ISD::BR, dl, 2610 MVT::Other, BrCond, 2611 DAG.getBasicBlock(SPD.getSuccessMBB())); 2612 2613 DAG.setRoot(Br); 2614 } 2615 2616 /// Codegen the failure basic block for a stack protector check. 2617 /// 2618 /// A failure stack protector machine basic block consists simply of a call to 2619 /// __stack_chk_fail(). 2620 /// 2621 /// For a high level explanation of how this fits into the stack protector 2622 /// generation see the comment on the declaration of class 2623 /// StackProtectorDescriptor. 2624 void 2625 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2626 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2627 TargetLowering::MakeLibCallOptions CallOptions; 2628 CallOptions.setDiscardResult(true); 2629 SDValue Chain = 2630 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2631 None, CallOptions, getCurSDLoc()).second; 2632 // On PS4, the "return address" must still be within the calling function, 2633 // even if it's at the very end, so emit an explicit TRAP here. 2634 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2635 if (TM.getTargetTriple().isPS4CPU()) 2636 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2637 2638 DAG.setRoot(Chain); 2639 } 2640 2641 /// visitBitTestHeader - This function emits necessary code to produce value 2642 /// suitable for "bit tests" 2643 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2644 MachineBasicBlock *SwitchBB) { 2645 SDLoc dl = getCurSDLoc(); 2646 2647 // Subtract the minimum value. 2648 SDValue SwitchOp = getValue(B.SValue); 2649 EVT VT = SwitchOp.getValueType(); 2650 SDValue RangeSub = 2651 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2652 2653 // Determine the type of the test operands. 2654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2655 bool UsePtrType = false; 2656 if (!TLI.isTypeLegal(VT)) { 2657 UsePtrType = true; 2658 } else { 2659 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2660 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2661 // Switch table case range are encoded into series of masks. 2662 // Just use pointer type, it's guaranteed to fit. 2663 UsePtrType = true; 2664 break; 2665 } 2666 } 2667 SDValue Sub = RangeSub; 2668 if (UsePtrType) { 2669 VT = TLI.getPointerTy(DAG.getDataLayout()); 2670 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2671 } 2672 2673 B.RegVT = VT.getSimpleVT(); 2674 B.Reg = FuncInfo.CreateReg(B.RegVT); 2675 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2676 2677 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2678 2679 if (!B.OmitRangeCheck) 2680 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2681 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2682 SwitchBB->normalizeSuccProbs(); 2683 2684 SDValue Root = CopyTo; 2685 if (!B.OmitRangeCheck) { 2686 // Conditional branch to the default block. 2687 SDValue RangeCmp = DAG.getSetCC(dl, 2688 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2689 RangeSub.getValueType()), 2690 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2691 ISD::SETUGT); 2692 2693 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2694 DAG.getBasicBlock(B.Default)); 2695 } 2696 2697 // Avoid emitting unnecessary branches to the next block. 2698 if (MBB != NextBlock(SwitchBB)) 2699 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2700 2701 DAG.setRoot(Root); 2702 } 2703 2704 /// visitBitTestCase - this function produces one "bit test" 2705 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2706 MachineBasicBlock* NextMBB, 2707 BranchProbability BranchProbToNext, 2708 unsigned Reg, 2709 BitTestCase &B, 2710 MachineBasicBlock *SwitchBB) { 2711 SDLoc dl = getCurSDLoc(); 2712 MVT VT = BB.RegVT; 2713 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2714 SDValue Cmp; 2715 unsigned PopCount = countPopulation(B.Mask); 2716 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2717 if (PopCount == 1) { 2718 // Testing for a single bit; just compare the shift count with what it 2719 // would need to be to shift a 1 bit in that position. 2720 Cmp = DAG.getSetCC( 2721 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2722 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2723 ISD::SETEQ); 2724 } else if (PopCount == BB.Range) { 2725 // There is only one zero bit in the range, test for it directly. 2726 Cmp = DAG.getSetCC( 2727 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2728 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2729 ISD::SETNE); 2730 } else { 2731 // Make desired shift 2732 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2733 DAG.getConstant(1, dl, VT), ShiftOp); 2734 2735 // Emit bit tests and jumps 2736 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2737 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2738 Cmp = DAG.getSetCC( 2739 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2740 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2741 } 2742 2743 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2744 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2745 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2746 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2747 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2748 // one as they are relative probabilities (and thus work more like weights), 2749 // and hence we need to normalize them to let the sum of them become one. 2750 SwitchBB->normalizeSuccProbs(); 2751 2752 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2753 MVT::Other, getControlRoot(), 2754 Cmp, DAG.getBasicBlock(B.TargetBB)); 2755 2756 // Avoid emitting unnecessary branches to the next block. 2757 if (NextMBB != NextBlock(SwitchBB)) 2758 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2759 DAG.getBasicBlock(NextMBB)); 2760 2761 DAG.setRoot(BrAnd); 2762 } 2763 2764 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2765 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2766 2767 // Retrieve successors. Look through artificial IR level blocks like 2768 // catchswitch for successors. 2769 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2770 const BasicBlock *EHPadBB = I.getSuccessor(1); 2771 2772 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2773 // have to do anything here to lower funclet bundles. 2774 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2775 LLVMContext::OB_funclet, 2776 LLVMContext::OB_cfguardtarget}) && 2777 "Cannot lower invokes with arbitrary operand bundles yet!"); 2778 2779 const Value *Callee(I.getCalledOperand()); 2780 const Function *Fn = dyn_cast<Function>(Callee); 2781 if (isa<InlineAsm>(Callee)) 2782 visitInlineAsm(I); 2783 else if (Fn && Fn->isIntrinsic()) { 2784 switch (Fn->getIntrinsicID()) { 2785 default: 2786 llvm_unreachable("Cannot invoke this intrinsic"); 2787 case Intrinsic::donothing: 2788 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2789 break; 2790 case Intrinsic::experimental_patchpoint_void: 2791 case Intrinsic::experimental_patchpoint_i64: 2792 visitPatchpoint(I, EHPadBB); 2793 break; 2794 case Intrinsic::experimental_gc_statepoint: 2795 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2796 break; 2797 case Intrinsic::wasm_rethrow_in_catch: { 2798 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2799 // special because it can be invoked, so we manually lower it to a DAG 2800 // node here. 2801 SmallVector<SDValue, 8> Ops; 2802 Ops.push_back(getRoot()); // inchain 2803 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2804 Ops.push_back( 2805 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2806 TLI.getPointerTy(DAG.getDataLayout()))); 2807 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2808 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2809 break; 2810 } 2811 } 2812 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2813 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2814 // Eventually we will support lowering the @llvm.experimental.deoptimize 2815 // intrinsic, and right now there are no plans to support other intrinsics 2816 // with deopt state. 2817 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2818 } else { 2819 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2820 } 2821 2822 // If the value of the invoke is used outside of its defining block, make it 2823 // available as a virtual register. 2824 // We already took care of the exported value for the statepoint instruction 2825 // during call to the LowerStatepoint. 2826 if (!isStatepoint(I)) { 2827 CopyToExportRegsIfNeeded(&I); 2828 } 2829 2830 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2831 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2832 BranchProbability EHPadBBProb = 2833 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2834 : BranchProbability::getZero(); 2835 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2836 2837 // Update successor info. 2838 addSuccessorWithProb(InvokeMBB, Return); 2839 for (auto &UnwindDest : UnwindDests) { 2840 UnwindDest.first->setIsEHPad(); 2841 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2842 } 2843 InvokeMBB->normalizeSuccProbs(); 2844 2845 // Drop into normal successor. 2846 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2847 DAG.getBasicBlock(Return))); 2848 } 2849 2850 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2851 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2852 2853 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2854 // have to do anything here to lower funclet bundles. 2855 assert(!I.hasOperandBundlesOtherThan( 2856 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2857 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2858 2859 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2860 visitInlineAsm(I); 2861 CopyToExportRegsIfNeeded(&I); 2862 2863 // Retrieve successors. 2864 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2865 Return->setInlineAsmBrDefaultTarget(); 2866 2867 // Update successor info. 2868 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2869 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2870 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2871 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2872 CallBrMBB->addInlineAsmBrIndirectTarget(Target); 2873 } 2874 CallBrMBB->normalizeSuccProbs(); 2875 2876 // Drop into default successor. 2877 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2878 MVT::Other, getControlRoot(), 2879 DAG.getBasicBlock(Return))); 2880 } 2881 2882 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2883 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2884 } 2885 2886 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2887 assert(FuncInfo.MBB->isEHPad() && 2888 "Call to landingpad not in landing pad!"); 2889 2890 // If there aren't registers to copy the values into (e.g., during SjLj 2891 // exceptions), then don't bother to create these DAG nodes. 2892 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2893 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2894 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2895 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2896 return; 2897 2898 // If landingpad's return type is token type, we don't create DAG nodes 2899 // for its exception pointer and selector value. The extraction of exception 2900 // pointer or selector value from token type landingpads is not currently 2901 // supported. 2902 if (LP.getType()->isTokenTy()) 2903 return; 2904 2905 SmallVector<EVT, 2> ValueVTs; 2906 SDLoc dl = getCurSDLoc(); 2907 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2908 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2909 2910 // Get the two live-in registers as SDValues. The physregs have already been 2911 // copied into virtual registers. 2912 SDValue Ops[2]; 2913 if (FuncInfo.ExceptionPointerVirtReg) { 2914 Ops[0] = DAG.getZExtOrTrunc( 2915 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2916 FuncInfo.ExceptionPointerVirtReg, 2917 TLI.getPointerTy(DAG.getDataLayout())), 2918 dl, ValueVTs[0]); 2919 } else { 2920 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2921 } 2922 Ops[1] = DAG.getZExtOrTrunc( 2923 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2924 FuncInfo.ExceptionSelectorVirtReg, 2925 TLI.getPointerTy(DAG.getDataLayout())), 2926 dl, ValueVTs[1]); 2927 2928 // Merge into one. 2929 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2930 DAG.getVTList(ValueVTs), Ops); 2931 setValue(&LP, Res); 2932 } 2933 2934 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2935 MachineBasicBlock *Last) { 2936 // Update JTCases. 2937 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2938 if (SL->JTCases[i].first.HeaderBB == First) 2939 SL->JTCases[i].first.HeaderBB = Last; 2940 2941 // Update BitTestCases. 2942 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2943 if (SL->BitTestCases[i].Parent == First) 2944 SL->BitTestCases[i].Parent = Last; 2945 2946 // SelectionDAGISel::FinishBasicBlock will add PHI operands for the 2947 // successors of the fallthrough block. Here, we add PHI operands for the 2948 // successors of the INLINEASM_BR block itself. 2949 if (First->getFirstTerminator()->getOpcode() == TargetOpcode::INLINEASM_BR) 2950 for (std::pair<MachineInstr *, unsigned> &pair : FuncInfo.PHINodesToUpdate) 2951 if (First->isSuccessor(pair.first->getParent())) 2952 MachineInstrBuilder(*First->getParent(), pair.first) 2953 .addReg(pair.second) 2954 .addMBB(First); 2955 } 2956 2957 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2958 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2959 2960 // Update machine-CFG edges with unique successors. 2961 SmallSet<BasicBlock*, 32> Done; 2962 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2963 BasicBlock *BB = I.getSuccessor(i); 2964 bool Inserted = Done.insert(BB).second; 2965 if (!Inserted) 2966 continue; 2967 2968 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2969 addSuccessorWithProb(IndirectBrMBB, Succ); 2970 } 2971 IndirectBrMBB->normalizeSuccProbs(); 2972 2973 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2974 MVT::Other, getControlRoot(), 2975 getValue(I.getAddress()))); 2976 } 2977 2978 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2979 if (!DAG.getTarget().Options.TrapUnreachable) 2980 return; 2981 2982 // We may be able to ignore unreachable behind a noreturn call. 2983 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2984 const BasicBlock &BB = *I.getParent(); 2985 if (&I != &BB.front()) { 2986 BasicBlock::const_iterator PredI = 2987 std::prev(BasicBlock::const_iterator(&I)); 2988 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2989 if (Call->doesNotReturn()) 2990 return; 2991 } 2992 } 2993 } 2994 2995 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2996 } 2997 2998 void SelectionDAGBuilder::visitFSub(const User &I) { 2999 // -0.0 - X --> fneg 3000 Type *Ty = I.getType(); 3001 if (isa<Constant>(I.getOperand(0)) && 3002 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 3003 SDValue Op2 = getValue(I.getOperand(1)); 3004 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 3005 Op2.getValueType(), Op2)); 3006 return; 3007 } 3008 3009 visitBinary(I, ISD::FSUB); 3010 } 3011 3012 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3013 SDNodeFlags Flags; 3014 3015 SDValue Op = getValue(I.getOperand(0)); 3016 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3017 Op, Flags); 3018 setValue(&I, UnNodeValue); 3019 } 3020 3021 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3022 SDNodeFlags Flags; 3023 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3024 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3025 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3026 } 3027 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3028 Flags.setExact(ExactOp->isExact()); 3029 } 3030 3031 SDValue Op1 = getValue(I.getOperand(0)); 3032 SDValue Op2 = getValue(I.getOperand(1)); 3033 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3034 Op1, Op2, Flags); 3035 setValue(&I, BinNodeValue); 3036 } 3037 3038 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3039 SDValue Op1 = getValue(I.getOperand(0)); 3040 SDValue Op2 = getValue(I.getOperand(1)); 3041 3042 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3043 Op1.getValueType(), DAG.getDataLayout()); 3044 3045 // Coerce the shift amount to the right type if we can. 3046 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3047 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3048 unsigned Op2Size = Op2.getValueSizeInBits(); 3049 SDLoc DL = getCurSDLoc(); 3050 3051 // If the operand is smaller than the shift count type, promote it. 3052 if (ShiftSize > Op2Size) 3053 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3054 3055 // If the operand is larger than the shift count type but the shift 3056 // count type has enough bits to represent any shift value, truncate 3057 // it now. This is a common case and it exposes the truncate to 3058 // optimization early. 3059 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3060 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3061 // Otherwise we'll need to temporarily settle for some other convenient 3062 // type. Type legalization will make adjustments once the shiftee is split. 3063 else 3064 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3065 } 3066 3067 bool nuw = false; 3068 bool nsw = false; 3069 bool exact = false; 3070 3071 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3072 3073 if (const OverflowingBinaryOperator *OFBinOp = 3074 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3075 nuw = OFBinOp->hasNoUnsignedWrap(); 3076 nsw = OFBinOp->hasNoSignedWrap(); 3077 } 3078 if (const PossiblyExactOperator *ExactOp = 3079 dyn_cast<const PossiblyExactOperator>(&I)) 3080 exact = ExactOp->isExact(); 3081 } 3082 SDNodeFlags Flags; 3083 Flags.setExact(exact); 3084 Flags.setNoSignedWrap(nsw); 3085 Flags.setNoUnsignedWrap(nuw); 3086 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3087 Flags); 3088 setValue(&I, Res); 3089 } 3090 3091 void SelectionDAGBuilder::visitSDiv(const User &I) { 3092 SDValue Op1 = getValue(I.getOperand(0)); 3093 SDValue Op2 = getValue(I.getOperand(1)); 3094 3095 SDNodeFlags Flags; 3096 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3097 cast<PossiblyExactOperator>(&I)->isExact()); 3098 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3099 Op2, Flags)); 3100 } 3101 3102 void SelectionDAGBuilder::visitICmp(const User &I) { 3103 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3104 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3105 predicate = IC->getPredicate(); 3106 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3107 predicate = ICmpInst::Predicate(IC->getPredicate()); 3108 SDValue Op1 = getValue(I.getOperand(0)); 3109 SDValue Op2 = getValue(I.getOperand(1)); 3110 ISD::CondCode Opcode = getICmpCondCode(predicate); 3111 3112 auto &TLI = DAG.getTargetLoweringInfo(); 3113 EVT MemVT = 3114 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3115 3116 // If a pointer's DAG type is larger than its memory type then the DAG values 3117 // are zero-extended. This breaks signed comparisons so truncate back to the 3118 // underlying type before doing the compare. 3119 if (Op1.getValueType() != MemVT) { 3120 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3121 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3122 } 3123 3124 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3125 I.getType()); 3126 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3127 } 3128 3129 void SelectionDAGBuilder::visitFCmp(const User &I) { 3130 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3131 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3132 predicate = FC->getPredicate(); 3133 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3134 predicate = FCmpInst::Predicate(FC->getPredicate()); 3135 SDValue Op1 = getValue(I.getOperand(0)); 3136 SDValue Op2 = getValue(I.getOperand(1)); 3137 3138 ISD::CondCode Condition = getFCmpCondCode(predicate); 3139 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3140 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3141 Condition = getFCmpCodeWithoutNaN(Condition); 3142 3143 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3144 I.getType()); 3145 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3146 } 3147 3148 // Check if the condition of the select has one use or two users that are both 3149 // selects with the same condition. 3150 static bool hasOnlySelectUsers(const Value *Cond) { 3151 return llvm::all_of(Cond->users(), [](const Value *V) { 3152 return isa<SelectInst>(V); 3153 }); 3154 } 3155 3156 void SelectionDAGBuilder::visitSelect(const User &I) { 3157 SmallVector<EVT, 4> ValueVTs; 3158 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3159 ValueVTs); 3160 unsigned NumValues = ValueVTs.size(); 3161 if (NumValues == 0) return; 3162 3163 SmallVector<SDValue, 4> Values(NumValues); 3164 SDValue Cond = getValue(I.getOperand(0)); 3165 SDValue LHSVal = getValue(I.getOperand(1)); 3166 SDValue RHSVal = getValue(I.getOperand(2)); 3167 SmallVector<SDValue, 1> BaseOps(1, Cond); 3168 ISD::NodeType OpCode = 3169 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3170 3171 bool IsUnaryAbs = false; 3172 3173 // Min/max matching is only viable if all output VTs are the same. 3174 if (is_splat(ValueVTs)) { 3175 EVT VT = ValueVTs[0]; 3176 LLVMContext &Ctx = *DAG.getContext(); 3177 auto &TLI = DAG.getTargetLoweringInfo(); 3178 3179 // We care about the legality of the operation after it has been type 3180 // legalized. 3181 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3182 VT = TLI.getTypeToTransformTo(Ctx, VT); 3183 3184 // If the vselect is legal, assume we want to leave this as a vector setcc + 3185 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3186 // min/max is legal on the scalar type. 3187 bool UseScalarMinMax = VT.isVector() && 3188 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3189 3190 Value *LHS, *RHS; 3191 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3192 ISD::NodeType Opc = ISD::DELETED_NODE; 3193 switch (SPR.Flavor) { 3194 case SPF_UMAX: Opc = ISD::UMAX; break; 3195 case SPF_UMIN: Opc = ISD::UMIN; break; 3196 case SPF_SMAX: Opc = ISD::SMAX; break; 3197 case SPF_SMIN: Opc = ISD::SMIN; break; 3198 case SPF_FMINNUM: 3199 switch (SPR.NaNBehavior) { 3200 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3201 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3202 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3203 case SPNB_RETURNS_ANY: { 3204 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3205 Opc = ISD::FMINNUM; 3206 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3207 Opc = ISD::FMINIMUM; 3208 else if (UseScalarMinMax) 3209 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3210 ISD::FMINNUM : ISD::FMINIMUM; 3211 break; 3212 } 3213 } 3214 break; 3215 case SPF_FMAXNUM: 3216 switch (SPR.NaNBehavior) { 3217 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3218 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3219 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3220 case SPNB_RETURNS_ANY: 3221 3222 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3223 Opc = ISD::FMAXNUM; 3224 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3225 Opc = ISD::FMAXIMUM; 3226 else if (UseScalarMinMax) 3227 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3228 ISD::FMAXNUM : ISD::FMAXIMUM; 3229 break; 3230 } 3231 break; 3232 case SPF_ABS: 3233 IsUnaryAbs = true; 3234 Opc = ISD::ABS; 3235 break; 3236 case SPF_NABS: 3237 // TODO: we need to produce sub(0, abs(X)). 3238 default: break; 3239 } 3240 3241 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3242 (TLI.isOperationLegalOrCustom(Opc, VT) || 3243 (UseScalarMinMax && 3244 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3245 // If the underlying comparison instruction is used by any other 3246 // instruction, the consumed instructions won't be destroyed, so it is 3247 // not profitable to convert to a min/max. 3248 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3249 OpCode = Opc; 3250 LHSVal = getValue(LHS); 3251 RHSVal = getValue(RHS); 3252 BaseOps.clear(); 3253 } 3254 3255 if (IsUnaryAbs) { 3256 OpCode = Opc; 3257 LHSVal = getValue(LHS); 3258 BaseOps.clear(); 3259 } 3260 } 3261 3262 if (IsUnaryAbs) { 3263 for (unsigned i = 0; i != NumValues; ++i) { 3264 Values[i] = 3265 DAG.getNode(OpCode, getCurSDLoc(), 3266 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3267 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3268 } 3269 } else { 3270 for (unsigned i = 0; i != NumValues; ++i) { 3271 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3272 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3273 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3274 Values[i] = DAG.getNode( 3275 OpCode, getCurSDLoc(), 3276 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3277 } 3278 } 3279 3280 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3281 DAG.getVTList(ValueVTs), Values)); 3282 } 3283 3284 void SelectionDAGBuilder::visitTrunc(const User &I) { 3285 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3286 SDValue N = getValue(I.getOperand(0)); 3287 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3288 I.getType()); 3289 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3290 } 3291 3292 void SelectionDAGBuilder::visitZExt(const User &I) { 3293 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3294 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3295 SDValue N = getValue(I.getOperand(0)); 3296 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3297 I.getType()); 3298 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3299 } 3300 3301 void SelectionDAGBuilder::visitSExt(const User &I) { 3302 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3303 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3304 SDValue N = getValue(I.getOperand(0)); 3305 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3306 I.getType()); 3307 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3308 } 3309 3310 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3311 // FPTrunc is never a no-op cast, no need to check 3312 SDValue N = getValue(I.getOperand(0)); 3313 SDLoc dl = getCurSDLoc(); 3314 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3315 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3316 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3317 DAG.getTargetConstant( 3318 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3319 } 3320 3321 void SelectionDAGBuilder::visitFPExt(const User &I) { 3322 // FPExt is never a no-op cast, no need to check 3323 SDValue N = getValue(I.getOperand(0)); 3324 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3325 I.getType()); 3326 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3327 } 3328 3329 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3330 // FPToUI is never a no-op cast, no need to check 3331 SDValue N = getValue(I.getOperand(0)); 3332 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3333 I.getType()); 3334 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3335 } 3336 3337 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3338 // FPToSI is never a no-op cast, no need to check 3339 SDValue N = getValue(I.getOperand(0)); 3340 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3341 I.getType()); 3342 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3343 } 3344 3345 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3346 // UIToFP is never a no-op cast, no need to check 3347 SDValue N = getValue(I.getOperand(0)); 3348 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3349 I.getType()); 3350 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3351 } 3352 3353 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3354 // SIToFP is never a no-op cast, no need to check 3355 SDValue N = getValue(I.getOperand(0)); 3356 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3357 I.getType()); 3358 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3359 } 3360 3361 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3362 // What to do depends on the size of the integer and the size of the pointer. 3363 // We can either truncate, zero extend, or no-op, accordingly. 3364 SDValue N = getValue(I.getOperand(0)); 3365 auto &TLI = DAG.getTargetLoweringInfo(); 3366 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3367 I.getType()); 3368 EVT PtrMemVT = 3369 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3370 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3371 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3372 setValue(&I, N); 3373 } 3374 3375 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3376 // What to do depends on the size of the integer and the size of the pointer. 3377 // We can either truncate, zero extend, or no-op, accordingly. 3378 SDValue N = getValue(I.getOperand(0)); 3379 auto &TLI = DAG.getTargetLoweringInfo(); 3380 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3381 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3382 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3383 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3384 setValue(&I, N); 3385 } 3386 3387 void SelectionDAGBuilder::visitBitCast(const User &I) { 3388 SDValue N = getValue(I.getOperand(0)); 3389 SDLoc dl = getCurSDLoc(); 3390 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3391 I.getType()); 3392 3393 // BitCast assures us that source and destination are the same size so this is 3394 // either a BITCAST or a no-op. 3395 if (DestVT != N.getValueType()) 3396 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3397 DestVT, N)); // convert types. 3398 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3399 // might fold any kind of constant expression to an integer constant and that 3400 // is not what we are looking for. Only recognize a bitcast of a genuine 3401 // constant integer as an opaque constant. 3402 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3403 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3404 /*isOpaque*/true)); 3405 else 3406 setValue(&I, N); // noop cast. 3407 } 3408 3409 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3410 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3411 const Value *SV = I.getOperand(0); 3412 SDValue N = getValue(SV); 3413 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3414 3415 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3416 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3417 3418 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3419 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3420 3421 setValue(&I, N); 3422 } 3423 3424 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3425 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3426 SDValue InVec = getValue(I.getOperand(0)); 3427 SDValue InVal = getValue(I.getOperand(1)); 3428 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3429 TLI.getVectorIdxTy(DAG.getDataLayout())); 3430 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3431 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3432 InVec, InVal, InIdx)); 3433 } 3434 3435 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3437 SDValue InVec = getValue(I.getOperand(0)); 3438 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3439 TLI.getVectorIdxTy(DAG.getDataLayout())); 3440 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3441 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3442 InVec, InIdx)); 3443 } 3444 3445 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3446 SDValue Src1 = getValue(I.getOperand(0)); 3447 SDValue Src2 = getValue(I.getOperand(1)); 3448 ArrayRef<int> Mask; 3449 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3450 Mask = SVI->getShuffleMask(); 3451 else 3452 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3453 SDLoc DL = getCurSDLoc(); 3454 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3455 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3456 EVT SrcVT = Src1.getValueType(); 3457 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3458 3459 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3460 VT.isScalableVector()) { 3461 // Canonical splat form of first element of first input vector. 3462 SDValue FirstElt = 3463 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3464 DAG.getVectorIdxConstant(0, DL)); 3465 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3466 return; 3467 } 3468 3469 // For now, we only handle splats for scalable vectors. 3470 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3471 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3472 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3473 3474 unsigned MaskNumElts = Mask.size(); 3475 3476 if (SrcNumElts == MaskNumElts) { 3477 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3478 return; 3479 } 3480 3481 // Normalize the shuffle vector since mask and vector length don't match. 3482 if (SrcNumElts < MaskNumElts) { 3483 // Mask is longer than the source vectors. We can use concatenate vector to 3484 // make the mask and vectors lengths match. 3485 3486 if (MaskNumElts % SrcNumElts == 0) { 3487 // Mask length is a multiple of the source vector length. 3488 // Check if the shuffle is some kind of concatenation of the input 3489 // vectors. 3490 unsigned NumConcat = MaskNumElts / SrcNumElts; 3491 bool IsConcat = true; 3492 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3493 for (unsigned i = 0; i != MaskNumElts; ++i) { 3494 int Idx = Mask[i]; 3495 if (Idx < 0) 3496 continue; 3497 // Ensure the indices in each SrcVT sized piece are sequential and that 3498 // the same source is used for the whole piece. 3499 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3500 (ConcatSrcs[i / SrcNumElts] >= 0 && 3501 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3502 IsConcat = false; 3503 break; 3504 } 3505 // Remember which source this index came from. 3506 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3507 } 3508 3509 // The shuffle is concatenating multiple vectors together. Just emit 3510 // a CONCAT_VECTORS operation. 3511 if (IsConcat) { 3512 SmallVector<SDValue, 8> ConcatOps; 3513 for (auto Src : ConcatSrcs) { 3514 if (Src < 0) 3515 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3516 else if (Src == 0) 3517 ConcatOps.push_back(Src1); 3518 else 3519 ConcatOps.push_back(Src2); 3520 } 3521 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3522 return; 3523 } 3524 } 3525 3526 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3527 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3528 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3529 PaddedMaskNumElts); 3530 3531 // Pad both vectors with undefs to make them the same length as the mask. 3532 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3533 3534 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3535 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3536 MOps1[0] = Src1; 3537 MOps2[0] = Src2; 3538 3539 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3540 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3541 3542 // Readjust mask for new input vector length. 3543 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3544 for (unsigned i = 0; i != MaskNumElts; ++i) { 3545 int Idx = Mask[i]; 3546 if (Idx >= (int)SrcNumElts) 3547 Idx -= SrcNumElts - PaddedMaskNumElts; 3548 MappedOps[i] = Idx; 3549 } 3550 3551 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3552 3553 // If the concatenated vector was padded, extract a subvector with the 3554 // correct number of elements. 3555 if (MaskNumElts != PaddedMaskNumElts) 3556 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3557 DAG.getVectorIdxConstant(0, DL)); 3558 3559 setValue(&I, Result); 3560 return; 3561 } 3562 3563 if (SrcNumElts > MaskNumElts) { 3564 // Analyze the access pattern of the vector to see if we can extract 3565 // two subvectors and do the shuffle. 3566 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3567 bool CanExtract = true; 3568 for (int Idx : Mask) { 3569 unsigned Input = 0; 3570 if (Idx < 0) 3571 continue; 3572 3573 if (Idx >= (int)SrcNumElts) { 3574 Input = 1; 3575 Idx -= SrcNumElts; 3576 } 3577 3578 // If all the indices come from the same MaskNumElts sized portion of 3579 // the sources we can use extract. Also make sure the extract wouldn't 3580 // extract past the end of the source. 3581 int NewStartIdx = alignDown(Idx, MaskNumElts); 3582 if (NewStartIdx + MaskNumElts > SrcNumElts || 3583 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3584 CanExtract = false; 3585 // Make sure we always update StartIdx as we use it to track if all 3586 // elements are undef. 3587 StartIdx[Input] = NewStartIdx; 3588 } 3589 3590 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3591 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3592 return; 3593 } 3594 if (CanExtract) { 3595 // Extract appropriate subvector and generate a vector shuffle 3596 for (unsigned Input = 0; Input < 2; ++Input) { 3597 SDValue &Src = Input == 0 ? Src1 : Src2; 3598 if (StartIdx[Input] < 0) 3599 Src = DAG.getUNDEF(VT); 3600 else { 3601 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3602 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3603 } 3604 } 3605 3606 // Calculate new mask. 3607 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3608 for (int &Idx : MappedOps) { 3609 if (Idx >= (int)SrcNumElts) 3610 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3611 else if (Idx >= 0) 3612 Idx -= StartIdx[0]; 3613 } 3614 3615 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3616 return; 3617 } 3618 } 3619 3620 // We can't use either concat vectors or extract subvectors so fall back to 3621 // replacing the shuffle with extract and build vector. 3622 // to insert and build vector. 3623 EVT EltVT = VT.getVectorElementType(); 3624 SmallVector<SDValue,8> Ops; 3625 for (int Idx : Mask) { 3626 SDValue Res; 3627 3628 if (Idx < 0) { 3629 Res = DAG.getUNDEF(EltVT); 3630 } else { 3631 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3632 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3633 3634 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3635 DAG.getVectorIdxConstant(Idx, DL)); 3636 } 3637 3638 Ops.push_back(Res); 3639 } 3640 3641 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3642 } 3643 3644 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3645 ArrayRef<unsigned> Indices; 3646 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3647 Indices = IV->getIndices(); 3648 else 3649 Indices = cast<ConstantExpr>(&I)->getIndices(); 3650 3651 const Value *Op0 = I.getOperand(0); 3652 const Value *Op1 = I.getOperand(1); 3653 Type *AggTy = I.getType(); 3654 Type *ValTy = Op1->getType(); 3655 bool IntoUndef = isa<UndefValue>(Op0); 3656 bool FromUndef = isa<UndefValue>(Op1); 3657 3658 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3659 3660 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3661 SmallVector<EVT, 4> AggValueVTs; 3662 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3663 SmallVector<EVT, 4> ValValueVTs; 3664 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3665 3666 unsigned NumAggValues = AggValueVTs.size(); 3667 unsigned NumValValues = ValValueVTs.size(); 3668 SmallVector<SDValue, 4> Values(NumAggValues); 3669 3670 // Ignore an insertvalue that produces an empty object 3671 if (!NumAggValues) { 3672 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3673 return; 3674 } 3675 3676 SDValue Agg = getValue(Op0); 3677 unsigned i = 0; 3678 // Copy the beginning value(s) from the original aggregate. 3679 for (; i != LinearIndex; ++i) 3680 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3681 SDValue(Agg.getNode(), Agg.getResNo() + i); 3682 // Copy values from the inserted value(s). 3683 if (NumValValues) { 3684 SDValue Val = getValue(Op1); 3685 for (; i != LinearIndex + NumValValues; ++i) 3686 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3687 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3688 } 3689 // Copy remaining value(s) from the original aggregate. 3690 for (; i != NumAggValues; ++i) 3691 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3692 SDValue(Agg.getNode(), Agg.getResNo() + i); 3693 3694 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3695 DAG.getVTList(AggValueVTs), Values)); 3696 } 3697 3698 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3699 ArrayRef<unsigned> Indices; 3700 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3701 Indices = EV->getIndices(); 3702 else 3703 Indices = cast<ConstantExpr>(&I)->getIndices(); 3704 3705 const Value *Op0 = I.getOperand(0); 3706 Type *AggTy = Op0->getType(); 3707 Type *ValTy = I.getType(); 3708 bool OutOfUndef = isa<UndefValue>(Op0); 3709 3710 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3711 3712 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3713 SmallVector<EVT, 4> ValValueVTs; 3714 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3715 3716 unsigned NumValValues = ValValueVTs.size(); 3717 3718 // Ignore a extractvalue that produces an empty object 3719 if (!NumValValues) { 3720 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3721 return; 3722 } 3723 3724 SmallVector<SDValue, 4> Values(NumValValues); 3725 3726 SDValue Agg = getValue(Op0); 3727 // Copy out the selected value(s). 3728 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3729 Values[i - LinearIndex] = 3730 OutOfUndef ? 3731 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3732 SDValue(Agg.getNode(), Agg.getResNo() + i); 3733 3734 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3735 DAG.getVTList(ValValueVTs), Values)); 3736 } 3737 3738 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3739 Value *Op0 = I.getOperand(0); 3740 // Note that the pointer operand may be a vector of pointers. Take the scalar 3741 // element which holds a pointer. 3742 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3743 SDValue N = getValue(Op0); 3744 SDLoc dl = getCurSDLoc(); 3745 auto &TLI = DAG.getTargetLoweringInfo(); 3746 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3747 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3748 3749 // Normalize Vector GEP - all scalar operands should be converted to the 3750 // splat vector. 3751 bool IsVectorGEP = I.getType()->isVectorTy(); 3752 ElementCount VectorElementCount = 3753 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3754 : ElementCount(0, false); 3755 3756 if (IsVectorGEP && !N.getValueType().isVector()) { 3757 LLVMContext &Context = *DAG.getContext(); 3758 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3759 if (VectorElementCount.Scalable) 3760 N = DAG.getSplatVector(VT, dl, N); 3761 else 3762 N = DAG.getSplatBuildVector(VT, dl, N); 3763 } 3764 3765 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3766 GTI != E; ++GTI) { 3767 const Value *Idx = GTI.getOperand(); 3768 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3769 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3770 if (Field) { 3771 // N = N + Offset 3772 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3773 3774 // In an inbounds GEP with an offset that is nonnegative even when 3775 // interpreted as signed, assume there is no unsigned overflow. 3776 SDNodeFlags Flags; 3777 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3778 Flags.setNoUnsignedWrap(true); 3779 3780 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3781 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3782 } 3783 } else { 3784 // IdxSize is the width of the arithmetic according to IR semantics. 3785 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3786 // (and fix up the result later). 3787 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3788 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3789 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3790 // We intentionally mask away the high bits here; ElementSize may not 3791 // fit in IdxTy. 3792 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3793 bool ElementScalable = ElementSize.isScalable(); 3794 3795 // If this is a scalar constant or a splat vector of constants, 3796 // handle it quickly. 3797 const auto *C = dyn_cast<Constant>(Idx); 3798 if (C && isa<VectorType>(C->getType())) 3799 C = C->getSplatValue(); 3800 3801 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3802 if (CI && CI->isZero()) 3803 continue; 3804 if (CI && !ElementScalable) { 3805 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3806 LLVMContext &Context = *DAG.getContext(); 3807 SDValue OffsVal; 3808 if (IsVectorGEP) 3809 OffsVal = DAG.getConstant( 3810 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3811 else 3812 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3813 3814 // In an inbounds GEP with an offset that is nonnegative even when 3815 // interpreted as signed, assume there is no unsigned overflow. 3816 SDNodeFlags Flags; 3817 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3818 Flags.setNoUnsignedWrap(true); 3819 3820 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3821 3822 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3823 continue; 3824 } 3825 3826 // N = N + Idx * ElementMul; 3827 SDValue IdxN = getValue(Idx); 3828 3829 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3830 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3831 VectorElementCount); 3832 if (VectorElementCount.Scalable) 3833 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3834 else 3835 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3836 } 3837 3838 // If the index is smaller or larger than intptr_t, truncate or extend 3839 // it. 3840 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3841 3842 if (ElementScalable) { 3843 EVT VScaleTy = N.getValueType().getScalarType(); 3844 SDValue VScale = DAG.getNode( 3845 ISD::VSCALE, dl, VScaleTy, 3846 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3847 if (IsVectorGEP) 3848 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3849 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3850 } else { 3851 // If this is a multiply by a power of two, turn it into a shl 3852 // immediately. This is a very common case. 3853 if (ElementMul != 1) { 3854 if (ElementMul.isPowerOf2()) { 3855 unsigned Amt = ElementMul.logBase2(); 3856 IdxN = DAG.getNode(ISD::SHL, dl, 3857 N.getValueType(), IdxN, 3858 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3859 } else { 3860 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3861 IdxN.getValueType()); 3862 IdxN = DAG.getNode(ISD::MUL, dl, 3863 N.getValueType(), IdxN, Scale); 3864 } 3865 } 3866 } 3867 3868 N = DAG.getNode(ISD::ADD, dl, 3869 N.getValueType(), N, IdxN); 3870 } 3871 } 3872 3873 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3874 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3875 3876 setValue(&I, N); 3877 } 3878 3879 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3880 // If this is a fixed sized alloca in the entry block of the function, 3881 // allocate it statically on the stack. 3882 if (FuncInfo.StaticAllocaMap.count(&I)) 3883 return; // getValue will auto-populate this. 3884 3885 SDLoc dl = getCurSDLoc(); 3886 Type *Ty = I.getAllocatedType(); 3887 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3888 auto &DL = DAG.getDataLayout(); 3889 uint64_t TySize = DL.getTypeAllocSize(Ty); 3890 MaybeAlign Alignment = max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3891 3892 SDValue AllocSize = getValue(I.getArraySize()); 3893 3894 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3895 if (AllocSize.getValueType() != IntPtr) 3896 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3897 3898 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3899 AllocSize, 3900 DAG.getConstant(TySize, dl, IntPtr)); 3901 3902 // Handle alignment. If the requested alignment is less than or equal to 3903 // the stack alignment, ignore it. If the size is greater than or equal to 3904 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3905 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3906 if (Alignment <= StackAlign) 3907 Alignment = None; 3908 3909 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3910 // Round the size of the allocation up to the stack alignment size 3911 // by add SA-1 to the size. This doesn't overflow because we're computing 3912 // an address inside an alloca. 3913 SDNodeFlags Flags; 3914 Flags.setNoUnsignedWrap(true); 3915 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3916 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3917 3918 // Mask out the low bits for alignment purposes. 3919 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3920 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3921 3922 SDValue Ops[] = { 3923 getRoot(), AllocSize, 3924 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 3925 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3926 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3927 setValue(&I, DSA); 3928 DAG.setRoot(DSA.getValue(1)); 3929 3930 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3931 } 3932 3933 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3934 if (I.isAtomic()) 3935 return visitAtomicLoad(I); 3936 3937 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3938 const Value *SV = I.getOperand(0); 3939 if (TLI.supportSwiftError()) { 3940 // Swifterror values can come from either a function parameter with 3941 // swifterror attribute or an alloca with swifterror attribute. 3942 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3943 if (Arg->hasSwiftErrorAttr()) 3944 return visitLoadFromSwiftError(I); 3945 } 3946 3947 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3948 if (Alloca->isSwiftError()) 3949 return visitLoadFromSwiftError(I); 3950 } 3951 } 3952 3953 SDValue Ptr = getValue(SV); 3954 3955 Type *Ty = I.getType(); 3956 Align Alignment = DL->getValueOrABITypeAlignment(I.getAlign(), Ty); 3957 3958 AAMDNodes AAInfo; 3959 I.getAAMetadata(AAInfo); 3960 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3961 3962 SmallVector<EVT, 4> ValueVTs, MemVTs; 3963 SmallVector<uint64_t, 4> Offsets; 3964 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 3965 unsigned NumValues = ValueVTs.size(); 3966 if (NumValues == 0) 3967 return; 3968 3969 bool isVolatile = I.isVolatile(); 3970 3971 SDValue Root; 3972 bool ConstantMemory = false; 3973 if (isVolatile) 3974 // Serialize volatile loads with other side effects. 3975 Root = getRoot(); 3976 else if (NumValues > MaxParallelChains) 3977 Root = getMemoryRoot(); 3978 else if (AA && 3979 AA->pointsToConstantMemory(MemoryLocation( 3980 SV, 3981 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3982 AAInfo))) { 3983 // Do not serialize (non-volatile) loads of constant memory with anything. 3984 Root = DAG.getEntryNode(); 3985 ConstantMemory = true; 3986 } else { 3987 // Do not serialize non-volatile loads against each other. 3988 Root = DAG.getRoot(); 3989 } 3990 3991 SDLoc dl = getCurSDLoc(); 3992 3993 if (isVolatile) 3994 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3995 3996 // An aggregate load cannot wrap around the address space, so offsets to its 3997 // parts don't wrap either. 3998 SDNodeFlags Flags; 3999 Flags.setNoUnsignedWrap(true); 4000 4001 SmallVector<SDValue, 4> Values(NumValues); 4002 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4003 EVT PtrVT = Ptr.getValueType(); 4004 4005 MachineMemOperand::Flags MMOFlags 4006 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4007 4008 unsigned ChainI = 0; 4009 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4010 // Serializing loads here may result in excessive register pressure, and 4011 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4012 // could recover a bit by hoisting nodes upward in the chain by recognizing 4013 // they are side-effect free or do not alias. The optimizer should really 4014 // avoid this case by converting large object/array copies to llvm.memcpy 4015 // (MaxParallelChains should always remain as failsafe). 4016 if (ChainI == MaxParallelChains) { 4017 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4018 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4019 makeArrayRef(Chains.data(), ChainI)); 4020 Root = Chain; 4021 ChainI = 0; 4022 } 4023 SDValue A = DAG.getNode(ISD::ADD, dl, 4024 PtrVT, Ptr, 4025 DAG.getConstant(Offsets[i], dl, PtrVT), 4026 Flags); 4027 4028 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4029 MachinePointerInfo(SV, Offsets[i]), Alignment, 4030 MMOFlags, AAInfo, Ranges); 4031 Chains[ChainI] = L.getValue(1); 4032 4033 if (MemVTs[i] != ValueVTs[i]) 4034 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4035 4036 Values[i] = L; 4037 } 4038 4039 if (!ConstantMemory) { 4040 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4041 makeArrayRef(Chains.data(), ChainI)); 4042 if (isVolatile) 4043 DAG.setRoot(Chain); 4044 else 4045 PendingLoads.push_back(Chain); 4046 } 4047 4048 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4049 DAG.getVTList(ValueVTs), Values)); 4050 } 4051 4052 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4053 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4054 "call visitStoreToSwiftError when backend supports swifterror"); 4055 4056 SmallVector<EVT, 4> ValueVTs; 4057 SmallVector<uint64_t, 4> Offsets; 4058 const Value *SrcV = I.getOperand(0); 4059 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4060 SrcV->getType(), ValueVTs, &Offsets); 4061 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4062 "expect a single EVT for swifterror"); 4063 4064 SDValue Src = getValue(SrcV); 4065 // Create a virtual register, then update the virtual register. 4066 Register VReg = 4067 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4068 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4069 // Chain can be getRoot or getControlRoot. 4070 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4071 SDValue(Src.getNode(), Src.getResNo())); 4072 DAG.setRoot(CopyNode); 4073 } 4074 4075 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4076 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4077 "call visitLoadFromSwiftError when backend supports swifterror"); 4078 4079 assert(!I.isVolatile() && 4080 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4081 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4082 "Support volatile, non temporal, invariant for load_from_swift_error"); 4083 4084 const Value *SV = I.getOperand(0); 4085 Type *Ty = I.getType(); 4086 AAMDNodes AAInfo; 4087 I.getAAMetadata(AAInfo); 4088 assert( 4089 (!AA || 4090 !AA->pointsToConstantMemory(MemoryLocation( 4091 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4092 AAInfo))) && 4093 "load_from_swift_error should not be constant memory"); 4094 4095 SmallVector<EVT, 4> ValueVTs; 4096 SmallVector<uint64_t, 4> Offsets; 4097 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4098 ValueVTs, &Offsets); 4099 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4100 "expect a single EVT for swifterror"); 4101 4102 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4103 SDValue L = DAG.getCopyFromReg( 4104 getRoot(), getCurSDLoc(), 4105 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4106 4107 setValue(&I, L); 4108 } 4109 4110 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4111 if (I.isAtomic()) 4112 return visitAtomicStore(I); 4113 4114 const Value *SrcV = I.getOperand(0); 4115 const Value *PtrV = I.getOperand(1); 4116 4117 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4118 if (TLI.supportSwiftError()) { 4119 // Swifterror values can come from either a function parameter with 4120 // swifterror attribute or an alloca with swifterror attribute. 4121 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4122 if (Arg->hasSwiftErrorAttr()) 4123 return visitStoreToSwiftError(I); 4124 } 4125 4126 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4127 if (Alloca->isSwiftError()) 4128 return visitStoreToSwiftError(I); 4129 } 4130 } 4131 4132 SmallVector<EVT, 4> ValueVTs, MemVTs; 4133 SmallVector<uint64_t, 4> Offsets; 4134 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4135 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4136 unsigned NumValues = ValueVTs.size(); 4137 if (NumValues == 0) 4138 return; 4139 4140 // Get the lowered operands. Note that we do this after 4141 // checking if NumResults is zero, because with zero results 4142 // the operands won't have values in the map. 4143 SDValue Src = getValue(SrcV); 4144 SDValue Ptr = getValue(PtrV); 4145 4146 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4147 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4148 SDLoc dl = getCurSDLoc(); 4149 Align Alignment = 4150 DL->getValueOrABITypeAlignment(I.getAlign(), SrcV->getType()); 4151 AAMDNodes AAInfo; 4152 I.getAAMetadata(AAInfo); 4153 4154 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4155 4156 // An aggregate load cannot wrap around the address space, so offsets to its 4157 // parts don't wrap either. 4158 SDNodeFlags Flags; 4159 Flags.setNoUnsignedWrap(true); 4160 4161 unsigned ChainI = 0; 4162 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4163 // See visitLoad comments. 4164 if (ChainI == MaxParallelChains) { 4165 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4166 makeArrayRef(Chains.data(), ChainI)); 4167 Root = Chain; 4168 ChainI = 0; 4169 } 4170 SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags); 4171 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4172 if (MemVTs[i] != ValueVTs[i]) 4173 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4174 SDValue St = 4175 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4176 Alignment, MMOFlags, AAInfo); 4177 Chains[ChainI] = St; 4178 } 4179 4180 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4181 makeArrayRef(Chains.data(), ChainI)); 4182 DAG.setRoot(StoreNode); 4183 } 4184 4185 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4186 bool IsCompressing) { 4187 SDLoc sdl = getCurSDLoc(); 4188 4189 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4190 MaybeAlign &Alignment) { 4191 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4192 Src0 = I.getArgOperand(0); 4193 Ptr = I.getArgOperand(1); 4194 Alignment = 4195 MaybeAlign(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()); 4196 Mask = I.getArgOperand(3); 4197 }; 4198 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4199 MaybeAlign &Alignment) { 4200 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4201 Src0 = I.getArgOperand(0); 4202 Ptr = I.getArgOperand(1); 4203 Mask = I.getArgOperand(2); 4204 Alignment = None; 4205 }; 4206 4207 Value *PtrOperand, *MaskOperand, *Src0Operand; 4208 MaybeAlign Alignment; 4209 if (IsCompressing) 4210 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4211 else 4212 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4213 4214 SDValue Ptr = getValue(PtrOperand); 4215 SDValue Src0 = getValue(Src0Operand); 4216 SDValue Mask = getValue(MaskOperand); 4217 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4218 4219 EVT VT = Src0.getValueType(); 4220 if (!Alignment) 4221 Alignment = DAG.getEVTAlign(VT); 4222 4223 AAMDNodes AAInfo; 4224 I.getAAMetadata(AAInfo); 4225 4226 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4227 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4228 // TODO: Make MachineMemOperands aware of scalable 4229 // vectors. 4230 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4231 SDValue StoreNode = 4232 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4233 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4234 DAG.setRoot(StoreNode); 4235 setValue(&I, StoreNode); 4236 } 4237 4238 // Get a uniform base for the Gather/Scatter intrinsic. 4239 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4240 // We try to represent it as a base pointer + vector of indices. 4241 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4242 // The first operand of the GEP may be a single pointer or a vector of pointers 4243 // Example: 4244 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4245 // or 4246 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4247 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4248 // 4249 // When the first GEP operand is a single pointer - it is the uniform base we 4250 // are looking for. If first operand of the GEP is a splat vector - we 4251 // extract the splat value and use it as a uniform base. 4252 // In all other cases the function returns 'false'. 4253 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4254 ISD::MemIndexType &IndexType, SDValue &Scale, 4255 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4256 SelectionDAG& DAG = SDB->DAG; 4257 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4258 const DataLayout &DL = DAG.getDataLayout(); 4259 4260 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4261 4262 // Handle splat constant pointer. 4263 if (auto *C = dyn_cast<Constant>(Ptr)) { 4264 C = C->getSplatValue(); 4265 if (!C) 4266 return false; 4267 4268 Base = SDB->getValue(C); 4269 4270 unsigned NumElts = cast<VectorType>(Ptr->getType())->getNumElements(); 4271 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4272 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4273 IndexType = ISD::SIGNED_SCALED; 4274 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4275 return true; 4276 } 4277 4278 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4279 if (!GEP || GEP->getParent() != CurBB) 4280 return false; 4281 4282 if (GEP->getNumOperands() != 2) 4283 return false; 4284 4285 const Value *BasePtr = GEP->getPointerOperand(); 4286 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4287 4288 // Make sure the base is scalar and the index is a vector. 4289 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4290 return false; 4291 4292 Base = SDB->getValue(BasePtr); 4293 Index = SDB->getValue(IndexVal); 4294 IndexType = ISD::SIGNED_SCALED; 4295 Scale = DAG.getTargetConstant( 4296 DL.getTypeAllocSize(GEP->getResultElementType()), 4297 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4298 return true; 4299 } 4300 4301 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4302 SDLoc sdl = getCurSDLoc(); 4303 4304 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4305 const Value *Ptr = I.getArgOperand(1); 4306 SDValue Src0 = getValue(I.getArgOperand(0)); 4307 SDValue Mask = getValue(I.getArgOperand(3)); 4308 EVT VT = Src0.getValueType(); 4309 MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()); 4310 if (!Alignment) 4311 Alignment = DAG.getEVTAlign(VT); 4312 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4313 4314 AAMDNodes AAInfo; 4315 I.getAAMetadata(AAInfo); 4316 4317 SDValue Base; 4318 SDValue Index; 4319 ISD::MemIndexType IndexType; 4320 SDValue Scale; 4321 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4322 I.getParent()); 4323 4324 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4325 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4326 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4327 // TODO: Make MachineMemOperands aware of scalable 4328 // vectors. 4329 MemoryLocation::UnknownSize, *Alignment, AAInfo); 4330 if (!UniformBase) { 4331 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4332 Index = getValue(Ptr); 4333 IndexType = ISD::SIGNED_SCALED; 4334 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4335 } 4336 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4337 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4338 Ops, MMO, IndexType); 4339 DAG.setRoot(Scatter); 4340 setValue(&I, Scatter); 4341 } 4342 4343 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4344 SDLoc sdl = getCurSDLoc(); 4345 4346 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4347 MaybeAlign &Alignment) { 4348 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4349 Ptr = I.getArgOperand(0); 4350 Alignment = 4351 MaybeAlign(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 4352 Mask = I.getArgOperand(2); 4353 Src0 = I.getArgOperand(3); 4354 }; 4355 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4356 MaybeAlign &Alignment) { 4357 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4358 Ptr = I.getArgOperand(0); 4359 Alignment = None; 4360 Mask = I.getArgOperand(1); 4361 Src0 = I.getArgOperand(2); 4362 }; 4363 4364 Value *PtrOperand, *MaskOperand, *Src0Operand; 4365 MaybeAlign Alignment; 4366 if (IsExpanding) 4367 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4368 else 4369 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4370 4371 SDValue Ptr = getValue(PtrOperand); 4372 SDValue Src0 = getValue(Src0Operand); 4373 SDValue Mask = getValue(MaskOperand); 4374 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4375 4376 EVT VT = Src0.getValueType(); 4377 if (!Alignment) 4378 Alignment = DAG.getEVTAlign(VT); 4379 4380 AAMDNodes AAInfo; 4381 I.getAAMetadata(AAInfo); 4382 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4383 4384 // Do not serialize masked loads of constant memory with anything. 4385 MemoryLocation ML; 4386 if (VT.isScalableVector()) 4387 ML = MemoryLocation(PtrOperand); 4388 else 4389 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4390 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4391 AAInfo); 4392 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4393 4394 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4395 4396 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4397 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4398 // TODO: Make MachineMemOperands aware of scalable 4399 // vectors. 4400 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4401 4402 SDValue Load = 4403 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4404 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4405 if (AddToChain) 4406 PendingLoads.push_back(Load.getValue(1)); 4407 setValue(&I, Load); 4408 } 4409 4410 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4411 SDLoc sdl = getCurSDLoc(); 4412 4413 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4414 const Value *Ptr = I.getArgOperand(0); 4415 SDValue Src0 = getValue(I.getArgOperand(3)); 4416 SDValue Mask = getValue(I.getArgOperand(2)); 4417 4418 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4419 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4420 MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 4421 if (!Alignment) 4422 Alignment = DAG.getEVTAlign(VT); 4423 4424 AAMDNodes AAInfo; 4425 I.getAAMetadata(AAInfo); 4426 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4427 4428 SDValue Root = DAG.getRoot(); 4429 SDValue Base; 4430 SDValue Index; 4431 ISD::MemIndexType IndexType; 4432 SDValue Scale; 4433 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4434 I.getParent()); 4435 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4436 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4437 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4438 // TODO: Make MachineMemOperands aware of scalable 4439 // vectors. 4440 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4441 4442 if (!UniformBase) { 4443 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4444 Index = getValue(Ptr); 4445 IndexType = ISD::SIGNED_SCALED; 4446 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4447 } 4448 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4449 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4450 Ops, MMO, IndexType); 4451 4452 PendingLoads.push_back(Gather.getValue(1)); 4453 setValue(&I, Gather); 4454 } 4455 4456 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4457 SDLoc dl = getCurSDLoc(); 4458 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4459 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4460 SyncScope::ID SSID = I.getSyncScopeID(); 4461 4462 SDValue InChain = getRoot(); 4463 4464 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4465 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4466 4467 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4468 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4469 4470 MachineFunction &MF = DAG.getMachineFunction(); 4471 MachineMemOperand *MMO = MF.getMachineMemOperand( 4472 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4473 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4474 FailureOrdering); 4475 4476 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4477 dl, MemVT, VTs, InChain, 4478 getValue(I.getPointerOperand()), 4479 getValue(I.getCompareOperand()), 4480 getValue(I.getNewValOperand()), MMO); 4481 4482 SDValue OutChain = L.getValue(2); 4483 4484 setValue(&I, L); 4485 DAG.setRoot(OutChain); 4486 } 4487 4488 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4489 SDLoc dl = getCurSDLoc(); 4490 ISD::NodeType NT; 4491 switch (I.getOperation()) { 4492 default: llvm_unreachable("Unknown atomicrmw operation"); 4493 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4494 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4495 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4496 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4497 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4498 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4499 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4500 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4501 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4502 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4503 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4504 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4505 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4506 } 4507 AtomicOrdering Ordering = I.getOrdering(); 4508 SyncScope::ID SSID = I.getSyncScopeID(); 4509 4510 SDValue InChain = getRoot(); 4511 4512 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4513 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4514 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4515 4516 MachineFunction &MF = DAG.getMachineFunction(); 4517 MachineMemOperand *MMO = MF.getMachineMemOperand( 4518 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4519 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4520 4521 SDValue L = 4522 DAG.getAtomic(NT, dl, MemVT, InChain, 4523 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4524 MMO); 4525 4526 SDValue OutChain = L.getValue(1); 4527 4528 setValue(&I, L); 4529 DAG.setRoot(OutChain); 4530 } 4531 4532 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4533 SDLoc dl = getCurSDLoc(); 4534 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4535 SDValue Ops[3]; 4536 Ops[0] = getRoot(); 4537 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4538 TLI.getFenceOperandTy(DAG.getDataLayout())); 4539 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4540 TLI.getFenceOperandTy(DAG.getDataLayout())); 4541 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4542 } 4543 4544 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4545 SDLoc dl = getCurSDLoc(); 4546 AtomicOrdering Order = I.getOrdering(); 4547 SyncScope::ID SSID = I.getSyncScopeID(); 4548 4549 SDValue InChain = getRoot(); 4550 4551 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4552 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4553 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4554 4555 if (!TLI.supportsUnalignedAtomics() && 4556 I.getAlignment() < MemVT.getSizeInBits() / 8) 4557 report_fatal_error("Cannot generate unaligned atomic load"); 4558 4559 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4560 4561 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4562 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4563 *I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4564 4565 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4566 4567 SDValue Ptr = getValue(I.getPointerOperand()); 4568 4569 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4570 // TODO: Once this is better exercised by tests, it should be merged with 4571 // the normal path for loads to prevent future divergence. 4572 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4573 if (MemVT != VT) 4574 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4575 4576 setValue(&I, L); 4577 SDValue OutChain = L.getValue(1); 4578 if (!I.isUnordered()) 4579 DAG.setRoot(OutChain); 4580 else 4581 PendingLoads.push_back(OutChain); 4582 return; 4583 } 4584 4585 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4586 Ptr, MMO); 4587 4588 SDValue OutChain = L.getValue(1); 4589 if (MemVT != VT) 4590 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4591 4592 setValue(&I, L); 4593 DAG.setRoot(OutChain); 4594 } 4595 4596 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4597 SDLoc dl = getCurSDLoc(); 4598 4599 AtomicOrdering Ordering = I.getOrdering(); 4600 SyncScope::ID SSID = I.getSyncScopeID(); 4601 4602 SDValue InChain = getRoot(); 4603 4604 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4605 EVT MemVT = 4606 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4607 4608 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4609 report_fatal_error("Cannot generate unaligned atomic store"); 4610 4611 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4612 4613 MachineFunction &MF = DAG.getMachineFunction(); 4614 MachineMemOperand *MMO = MF.getMachineMemOperand( 4615 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4616 *I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4617 4618 SDValue Val = getValue(I.getValueOperand()); 4619 if (Val.getValueType() != MemVT) 4620 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4621 SDValue Ptr = getValue(I.getPointerOperand()); 4622 4623 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4624 // TODO: Once this is better exercised by tests, it should be merged with 4625 // the normal path for stores to prevent future divergence. 4626 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4627 DAG.setRoot(S); 4628 return; 4629 } 4630 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4631 Ptr, Val, MMO); 4632 4633 4634 DAG.setRoot(OutChain); 4635 } 4636 4637 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4638 /// node. 4639 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4640 unsigned Intrinsic) { 4641 // Ignore the callsite's attributes. A specific call site may be marked with 4642 // readnone, but the lowering code will expect the chain based on the 4643 // definition. 4644 const Function *F = I.getCalledFunction(); 4645 bool HasChain = !F->doesNotAccessMemory(); 4646 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4647 4648 // Build the operand list. 4649 SmallVector<SDValue, 8> Ops; 4650 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4651 if (OnlyLoad) { 4652 // We don't need to serialize loads against other loads. 4653 Ops.push_back(DAG.getRoot()); 4654 } else { 4655 Ops.push_back(getRoot()); 4656 } 4657 } 4658 4659 // Info is set by getTgtMemInstrinsic 4660 TargetLowering::IntrinsicInfo Info; 4661 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4662 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4663 DAG.getMachineFunction(), 4664 Intrinsic); 4665 4666 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4667 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4668 Info.opc == ISD::INTRINSIC_W_CHAIN) 4669 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4670 TLI.getPointerTy(DAG.getDataLayout()))); 4671 4672 // Add all operands of the call to the operand list. 4673 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4674 const Value *Arg = I.getArgOperand(i); 4675 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4676 Ops.push_back(getValue(Arg)); 4677 continue; 4678 } 4679 4680 // Use TargetConstant instead of a regular constant for immarg. 4681 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4682 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4683 assert(CI->getBitWidth() <= 64 && 4684 "large intrinsic immediates not handled"); 4685 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4686 } else { 4687 Ops.push_back( 4688 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4689 } 4690 } 4691 4692 SmallVector<EVT, 4> ValueVTs; 4693 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4694 4695 if (HasChain) 4696 ValueVTs.push_back(MVT::Other); 4697 4698 SDVTList VTs = DAG.getVTList(ValueVTs); 4699 4700 // Create the node. 4701 SDValue Result; 4702 if (IsTgtIntrinsic) { 4703 // This is target intrinsic that touches memory 4704 AAMDNodes AAInfo; 4705 I.getAAMetadata(AAInfo); 4706 Result = 4707 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4708 MachinePointerInfo(Info.ptrVal, Info.offset), 4709 Info.align, Info.flags, Info.size, AAInfo); 4710 } else if (!HasChain) { 4711 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4712 } else if (!I.getType()->isVoidTy()) { 4713 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4714 } else { 4715 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4716 } 4717 4718 if (HasChain) { 4719 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4720 if (OnlyLoad) 4721 PendingLoads.push_back(Chain); 4722 else 4723 DAG.setRoot(Chain); 4724 } 4725 4726 if (!I.getType()->isVoidTy()) { 4727 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4728 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4729 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4730 } else 4731 Result = lowerRangeToAssertZExt(DAG, I, Result); 4732 4733 setValue(&I, Result); 4734 } 4735 } 4736 4737 /// GetSignificand - Get the significand and build it into a floating-point 4738 /// number with exponent of 1: 4739 /// 4740 /// Op = (Op & 0x007fffff) | 0x3f800000; 4741 /// 4742 /// where Op is the hexadecimal representation of floating point value. 4743 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4744 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4745 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4746 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4747 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4748 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4749 } 4750 4751 /// GetExponent - Get the exponent: 4752 /// 4753 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4754 /// 4755 /// where Op is the hexadecimal representation of floating point value. 4756 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4757 const TargetLowering &TLI, const SDLoc &dl) { 4758 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4759 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4760 SDValue t1 = DAG.getNode( 4761 ISD::SRL, dl, MVT::i32, t0, 4762 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4763 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4764 DAG.getConstant(127, dl, MVT::i32)); 4765 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4766 } 4767 4768 /// getF32Constant - Get 32-bit floating point constant. 4769 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4770 const SDLoc &dl) { 4771 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4772 MVT::f32); 4773 } 4774 4775 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4776 SelectionDAG &DAG) { 4777 // TODO: What fast-math-flags should be set on the floating-point nodes? 4778 4779 // IntegerPartOfX = ((int32_t)(t0); 4780 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4781 4782 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4783 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4784 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4785 4786 // IntegerPartOfX <<= 23; 4787 IntegerPartOfX = DAG.getNode( 4788 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4789 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4790 DAG.getDataLayout()))); 4791 4792 SDValue TwoToFractionalPartOfX; 4793 if (LimitFloatPrecision <= 6) { 4794 // For floating-point precision of 6: 4795 // 4796 // TwoToFractionalPartOfX = 4797 // 0.997535578f + 4798 // (0.735607626f + 0.252464424f * x) * x; 4799 // 4800 // error 0.0144103317, which is 6 bits 4801 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4802 getF32Constant(DAG, 0x3e814304, dl)); 4803 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4804 getF32Constant(DAG, 0x3f3c50c8, dl)); 4805 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4806 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4807 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4808 } else if (LimitFloatPrecision <= 12) { 4809 // For floating-point precision of 12: 4810 // 4811 // TwoToFractionalPartOfX = 4812 // 0.999892986f + 4813 // (0.696457318f + 4814 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4815 // 4816 // error 0.000107046256, which is 13 to 14 bits 4817 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4818 getF32Constant(DAG, 0x3da235e3, dl)); 4819 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4820 getF32Constant(DAG, 0x3e65b8f3, dl)); 4821 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4822 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4823 getF32Constant(DAG, 0x3f324b07, dl)); 4824 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4825 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4826 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4827 } else { // LimitFloatPrecision <= 18 4828 // For floating-point precision of 18: 4829 // 4830 // TwoToFractionalPartOfX = 4831 // 0.999999982f + 4832 // (0.693148872f + 4833 // (0.240227044f + 4834 // (0.554906021e-1f + 4835 // (0.961591928e-2f + 4836 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4837 // error 2.47208000*10^(-7), which is better than 18 bits 4838 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4839 getF32Constant(DAG, 0x3924b03e, dl)); 4840 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4841 getF32Constant(DAG, 0x3ab24b87, dl)); 4842 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4843 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4844 getF32Constant(DAG, 0x3c1d8c17, dl)); 4845 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4846 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4847 getF32Constant(DAG, 0x3d634a1d, dl)); 4848 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4849 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4850 getF32Constant(DAG, 0x3e75fe14, dl)); 4851 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4852 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4853 getF32Constant(DAG, 0x3f317234, dl)); 4854 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4855 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4856 getF32Constant(DAG, 0x3f800000, dl)); 4857 } 4858 4859 // Add the exponent into the result in integer domain. 4860 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4861 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4862 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4863 } 4864 4865 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4866 /// limited-precision mode. 4867 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4868 const TargetLowering &TLI) { 4869 if (Op.getValueType() == MVT::f32 && 4870 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4871 4872 // Put the exponent in the right bit position for later addition to the 4873 // final result: 4874 // 4875 // t0 = Op * log2(e) 4876 4877 // TODO: What fast-math-flags should be set here? 4878 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4879 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4880 return getLimitedPrecisionExp2(t0, dl, DAG); 4881 } 4882 4883 // No special expansion. 4884 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4885 } 4886 4887 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4888 /// limited-precision mode. 4889 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4890 const TargetLowering &TLI) { 4891 // TODO: What fast-math-flags should be set on the floating-point nodes? 4892 4893 if (Op.getValueType() == MVT::f32 && 4894 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4895 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4896 4897 // Scale the exponent by log(2). 4898 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4899 SDValue LogOfExponent = 4900 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4901 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 4902 4903 // Get the significand and build it into a floating-point number with 4904 // exponent of 1. 4905 SDValue X = GetSignificand(DAG, Op1, dl); 4906 4907 SDValue LogOfMantissa; 4908 if (LimitFloatPrecision <= 6) { 4909 // For floating-point precision of 6: 4910 // 4911 // LogofMantissa = 4912 // -1.1609546f + 4913 // (1.4034025f - 0.23903021f * x) * x; 4914 // 4915 // error 0.0034276066, which is better than 8 bits 4916 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4917 getF32Constant(DAG, 0xbe74c456, dl)); 4918 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4919 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4920 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4921 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4922 getF32Constant(DAG, 0x3f949a29, dl)); 4923 } else if (LimitFloatPrecision <= 12) { 4924 // For floating-point precision of 12: 4925 // 4926 // LogOfMantissa = 4927 // -1.7417939f + 4928 // (2.8212026f + 4929 // (-1.4699568f + 4930 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4931 // 4932 // error 0.000061011436, which is 14 bits 4933 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4934 getF32Constant(DAG, 0xbd67b6d6, dl)); 4935 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4936 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4937 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4938 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4939 getF32Constant(DAG, 0x3fbc278b, dl)); 4940 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4941 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4942 getF32Constant(DAG, 0x40348e95, dl)); 4943 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4944 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4945 getF32Constant(DAG, 0x3fdef31a, dl)); 4946 } else { // LimitFloatPrecision <= 18 4947 // For floating-point precision of 18: 4948 // 4949 // LogOfMantissa = 4950 // -2.1072184f + 4951 // (4.2372794f + 4952 // (-3.7029485f + 4953 // (2.2781945f + 4954 // (-0.87823314f + 4955 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4956 // 4957 // error 0.0000023660568, which is better than 18 bits 4958 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4959 getF32Constant(DAG, 0xbc91e5ac, dl)); 4960 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4961 getF32Constant(DAG, 0x3e4350aa, dl)); 4962 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4963 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4964 getF32Constant(DAG, 0x3f60d3e3, dl)); 4965 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4966 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4967 getF32Constant(DAG, 0x4011cdf0, dl)); 4968 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4969 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4970 getF32Constant(DAG, 0x406cfd1c, dl)); 4971 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4972 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4973 getF32Constant(DAG, 0x408797cb, dl)); 4974 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4975 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4976 getF32Constant(DAG, 0x4006dcab, dl)); 4977 } 4978 4979 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4980 } 4981 4982 // No special expansion. 4983 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4984 } 4985 4986 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4987 /// limited-precision mode. 4988 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4989 const TargetLowering &TLI) { 4990 // TODO: What fast-math-flags should be set on the floating-point nodes? 4991 4992 if (Op.getValueType() == MVT::f32 && 4993 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4994 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4995 4996 // Get the exponent. 4997 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4998 4999 // Get the significand and build it into a floating-point number with 5000 // exponent of 1. 5001 SDValue X = GetSignificand(DAG, Op1, dl); 5002 5003 // Different possible minimax approximations of significand in 5004 // floating-point for various degrees of accuracy over [1,2]. 5005 SDValue Log2ofMantissa; 5006 if (LimitFloatPrecision <= 6) { 5007 // For floating-point precision of 6: 5008 // 5009 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5010 // 5011 // error 0.0049451742, which is more than 7 bits 5012 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5013 getF32Constant(DAG, 0xbeb08fe0, dl)); 5014 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5015 getF32Constant(DAG, 0x40019463, dl)); 5016 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5017 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5018 getF32Constant(DAG, 0x3fd6633d, dl)); 5019 } else if (LimitFloatPrecision <= 12) { 5020 // For floating-point precision of 12: 5021 // 5022 // Log2ofMantissa = 5023 // -2.51285454f + 5024 // (4.07009056f + 5025 // (-2.12067489f + 5026 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5027 // 5028 // error 0.0000876136000, which is better than 13 bits 5029 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5030 getF32Constant(DAG, 0xbda7262e, dl)); 5031 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5032 getF32Constant(DAG, 0x3f25280b, dl)); 5033 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5034 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5035 getF32Constant(DAG, 0x4007b923, dl)); 5036 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5037 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5038 getF32Constant(DAG, 0x40823e2f, dl)); 5039 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5040 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5041 getF32Constant(DAG, 0x4020d29c, dl)); 5042 } else { // LimitFloatPrecision <= 18 5043 // For floating-point precision of 18: 5044 // 5045 // Log2ofMantissa = 5046 // -3.0400495f + 5047 // (6.1129976f + 5048 // (-5.3420409f + 5049 // (3.2865683f + 5050 // (-1.2669343f + 5051 // (0.27515199f - 5052 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5053 // 5054 // error 0.0000018516, which is better than 18 bits 5055 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5056 getF32Constant(DAG, 0xbcd2769e, dl)); 5057 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5058 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5059 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5060 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5061 getF32Constant(DAG, 0x3fa22ae7, dl)); 5062 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5063 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5064 getF32Constant(DAG, 0x40525723, dl)); 5065 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5066 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5067 getF32Constant(DAG, 0x40aaf200, dl)); 5068 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5069 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5070 getF32Constant(DAG, 0x40c39dad, dl)); 5071 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5072 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5073 getF32Constant(DAG, 0x4042902c, dl)); 5074 } 5075 5076 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5077 } 5078 5079 // No special expansion. 5080 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5081 } 5082 5083 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5084 /// limited-precision mode. 5085 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5086 const TargetLowering &TLI) { 5087 // TODO: What fast-math-flags should be set on the floating-point nodes? 5088 5089 if (Op.getValueType() == MVT::f32 && 5090 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5091 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5092 5093 // Scale the exponent by log10(2) [0.30102999f]. 5094 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5095 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5096 getF32Constant(DAG, 0x3e9a209a, dl)); 5097 5098 // Get the significand and build it into a floating-point number with 5099 // exponent of 1. 5100 SDValue X = GetSignificand(DAG, Op1, dl); 5101 5102 SDValue Log10ofMantissa; 5103 if (LimitFloatPrecision <= 6) { 5104 // For floating-point precision of 6: 5105 // 5106 // Log10ofMantissa = 5107 // -0.50419619f + 5108 // (0.60948995f - 0.10380950f * x) * x; 5109 // 5110 // error 0.0014886165, which is 6 bits 5111 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5112 getF32Constant(DAG, 0xbdd49a13, dl)); 5113 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5114 getF32Constant(DAG, 0x3f1c0789, dl)); 5115 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5116 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5117 getF32Constant(DAG, 0x3f011300, dl)); 5118 } else if (LimitFloatPrecision <= 12) { 5119 // For floating-point precision of 12: 5120 // 5121 // Log10ofMantissa = 5122 // -0.64831180f + 5123 // (0.91751397f + 5124 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5125 // 5126 // error 0.00019228036, which is better than 12 bits 5127 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5128 getF32Constant(DAG, 0x3d431f31, dl)); 5129 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5130 getF32Constant(DAG, 0x3ea21fb2, dl)); 5131 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5132 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5133 getF32Constant(DAG, 0x3f6ae232, dl)); 5134 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5135 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5136 getF32Constant(DAG, 0x3f25f7c3, dl)); 5137 } else { // LimitFloatPrecision <= 18 5138 // For floating-point precision of 18: 5139 // 5140 // Log10ofMantissa = 5141 // -0.84299375f + 5142 // (1.5327582f + 5143 // (-1.0688956f + 5144 // (0.49102474f + 5145 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5146 // 5147 // error 0.0000037995730, which is better than 18 bits 5148 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5149 getF32Constant(DAG, 0x3c5d51ce, dl)); 5150 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5151 getF32Constant(DAG, 0x3e00685a, dl)); 5152 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5153 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5154 getF32Constant(DAG, 0x3efb6798, dl)); 5155 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5156 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5157 getF32Constant(DAG, 0x3f88d192, dl)); 5158 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5159 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5160 getF32Constant(DAG, 0x3fc4316c, dl)); 5161 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5162 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5163 getF32Constant(DAG, 0x3f57ce70, dl)); 5164 } 5165 5166 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5167 } 5168 5169 // No special expansion. 5170 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5171 } 5172 5173 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5174 /// limited-precision mode. 5175 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5176 const TargetLowering &TLI) { 5177 if (Op.getValueType() == MVT::f32 && 5178 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5179 return getLimitedPrecisionExp2(Op, dl, DAG); 5180 5181 // No special expansion. 5182 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5183 } 5184 5185 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5186 /// limited-precision mode with x == 10.0f. 5187 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5188 SelectionDAG &DAG, const TargetLowering &TLI) { 5189 bool IsExp10 = false; 5190 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5191 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5192 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5193 APFloat Ten(10.0f); 5194 IsExp10 = LHSC->isExactlyValue(Ten); 5195 } 5196 } 5197 5198 // TODO: What fast-math-flags should be set on the FMUL node? 5199 if (IsExp10) { 5200 // Put the exponent in the right bit position for later addition to the 5201 // final result: 5202 // 5203 // #define LOG2OF10 3.3219281f 5204 // t0 = Op * LOG2OF10; 5205 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5206 getF32Constant(DAG, 0x40549a78, dl)); 5207 return getLimitedPrecisionExp2(t0, dl, DAG); 5208 } 5209 5210 // No special expansion. 5211 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5212 } 5213 5214 /// ExpandPowI - Expand a llvm.powi intrinsic. 5215 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5216 SelectionDAG &DAG) { 5217 // If RHS is a constant, we can expand this out to a multiplication tree, 5218 // otherwise we end up lowering to a call to __powidf2 (for example). When 5219 // optimizing for size, we only want to do this if the expansion would produce 5220 // a small number of multiplies, otherwise we do the full expansion. 5221 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5222 // Get the exponent as a positive value. 5223 unsigned Val = RHSC->getSExtValue(); 5224 if ((int)Val < 0) Val = -Val; 5225 5226 // powi(x, 0) -> 1.0 5227 if (Val == 0) 5228 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5229 5230 bool OptForSize = DAG.shouldOptForSize(); 5231 if (!OptForSize || 5232 // If optimizing for size, don't insert too many multiplies. 5233 // This inserts up to 5 multiplies. 5234 countPopulation(Val) + Log2_32(Val) < 7) { 5235 // We use the simple binary decomposition method to generate the multiply 5236 // sequence. There are more optimal ways to do this (for example, 5237 // powi(x,15) generates one more multiply than it should), but this has 5238 // the benefit of being both really simple and much better than a libcall. 5239 SDValue Res; // Logically starts equal to 1.0 5240 SDValue CurSquare = LHS; 5241 // TODO: Intrinsics should have fast-math-flags that propagate to these 5242 // nodes. 5243 while (Val) { 5244 if (Val & 1) { 5245 if (Res.getNode()) 5246 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5247 else 5248 Res = CurSquare; // 1.0*CurSquare. 5249 } 5250 5251 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5252 CurSquare, CurSquare); 5253 Val >>= 1; 5254 } 5255 5256 // If the original was negative, invert the result, producing 1/(x*x*x). 5257 if (RHSC->getSExtValue() < 0) 5258 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5259 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5260 return Res; 5261 } 5262 } 5263 5264 // Otherwise, expand to a libcall. 5265 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5266 } 5267 5268 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5269 SDValue LHS, SDValue RHS, SDValue Scale, 5270 SelectionDAG &DAG, const TargetLowering &TLI) { 5271 EVT VT = LHS.getValueType(); 5272 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5273 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5274 LLVMContext &Ctx = *DAG.getContext(); 5275 5276 // If the type is legal but the operation isn't, this node might survive all 5277 // the way to operation legalization. If we end up there and we do not have 5278 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5279 // node. 5280 5281 // Coax the legalizer into expanding the node during type legalization instead 5282 // by bumping the size by one bit. This will force it to Promote, enabling the 5283 // early expansion and avoiding the need to expand later. 5284 5285 // We don't have to do this if Scale is 0; that can always be expanded, unless 5286 // it's a saturating signed operation. Those can experience true integer 5287 // division overflow, a case which we must avoid. 5288 5289 // FIXME: We wouldn't have to do this (or any of the early 5290 // expansion/promotion) if it was possible to expand a libcall of an 5291 // illegal type during operation legalization. But it's not, so things 5292 // get a bit hacky. 5293 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5294 if ((ScaleInt > 0 || (Saturating && Signed)) && 5295 (TLI.isTypeLegal(VT) || 5296 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5297 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5298 Opcode, VT, ScaleInt); 5299 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5300 EVT PromVT; 5301 if (VT.isScalarInteger()) 5302 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5303 else if (VT.isVector()) { 5304 PromVT = VT.getVectorElementType(); 5305 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5306 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5307 } else 5308 llvm_unreachable("Wrong VT for DIVFIX?"); 5309 if (Signed) { 5310 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5311 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5312 } else { 5313 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5314 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5315 } 5316 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5317 // For saturating operations, we need to shift up the LHS to get the 5318 // proper saturation width, and then shift down again afterwards. 5319 if (Saturating) 5320 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5321 DAG.getConstant(1, DL, ShiftTy)); 5322 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5323 if (Saturating) 5324 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5325 DAG.getConstant(1, DL, ShiftTy)); 5326 return DAG.getZExtOrTrunc(Res, DL, VT); 5327 } 5328 } 5329 5330 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5331 } 5332 5333 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5334 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5335 static void 5336 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5337 const SDValue &N) { 5338 switch (N.getOpcode()) { 5339 case ISD::CopyFromReg: { 5340 SDValue Op = N.getOperand(1); 5341 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5342 Op.getValueType().getSizeInBits()); 5343 return; 5344 } 5345 case ISD::BITCAST: 5346 case ISD::AssertZext: 5347 case ISD::AssertSext: 5348 case ISD::TRUNCATE: 5349 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5350 return; 5351 case ISD::BUILD_PAIR: 5352 case ISD::BUILD_VECTOR: 5353 case ISD::CONCAT_VECTORS: 5354 for (SDValue Op : N->op_values()) 5355 getUnderlyingArgRegs(Regs, Op); 5356 return; 5357 default: 5358 return; 5359 } 5360 } 5361 5362 /// If the DbgValueInst is a dbg_value of a function argument, create the 5363 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5364 /// instruction selection, they will be inserted to the entry BB. 5365 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5366 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5367 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5368 const Argument *Arg = dyn_cast<Argument>(V); 5369 if (!Arg) 5370 return false; 5371 5372 if (!IsDbgDeclare) { 5373 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5374 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5375 // the entry block. 5376 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5377 if (!IsInEntryBlock) 5378 return false; 5379 5380 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5381 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5382 // variable that also is a param. 5383 // 5384 // Although, if we are at the top of the entry block already, we can still 5385 // emit using ArgDbgValue. This might catch some situations when the 5386 // dbg.value refers to an argument that isn't used in the entry block, so 5387 // any CopyToReg node would be optimized out and the only way to express 5388 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5389 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5390 // we should only emit as ArgDbgValue if the Variable is an argument to the 5391 // current function, and the dbg.value intrinsic is found in the entry 5392 // block. 5393 bool VariableIsFunctionInputArg = Variable->isParameter() && 5394 !DL->getInlinedAt(); 5395 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5396 if (!IsInPrologue && !VariableIsFunctionInputArg) 5397 return false; 5398 5399 // Here we assume that a function argument on IR level only can be used to 5400 // describe one input parameter on source level. If we for example have 5401 // source code like this 5402 // 5403 // struct A { long x, y; }; 5404 // void foo(struct A a, long b) { 5405 // ... 5406 // b = a.x; 5407 // ... 5408 // } 5409 // 5410 // and IR like this 5411 // 5412 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5413 // entry: 5414 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5415 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5416 // call void @llvm.dbg.value(metadata i32 %b, "b", 5417 // ... 5418 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5419 // ... 5420 // 5421 // then the last dbg.value is describing a parameter "b" using a value that 5422 // is an argument. But since we already has used %a1 to describe a parameter 5423 // we should not handle that last dbg.value here (that would result in an 5424 // incorrect hoisting of the DBG_VALUE to the function entry). 5425 // Notice that we allow one dbg.value per IR level argument, to accommodate 5426 // for the situation with fragments above. 5427 if (VariableIsFunctionInputArg) { 5428 unsigned ArgNo = Arg->getArgNo(); 5429 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5430 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5431 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5432 return false; 5433 FuncInfo.DescribedArgs.set(ArgNo); 5434 } 5435 } 5436 5437 MachineFunction &MF = DAG.getMachineFunction(); 5438 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5439 5440 bool IsIndirect = false; 5441 Optional<MachineOperand> Op; 5442 // Some arguments' frame index is recorded during argument lowering. 5443 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5444 if (FI != std::numeric_limits<int>::max()) 5445 Op = MachineOperand::CreateFI(FI); 5446 5447 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5448 if (!Op && N.getNode()) { 5449 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5450 Register Reg; 5451 if (ArgRegsAndSizes.size() == 1) 5452 Reg = ArgRegsAndSizes.front().first; 5453 5454 if (Reg && Reg.isVirtual()) { 5455 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5456 Register PR = RegInfo.getLiveInPhysReg(Reg); 5457 if (PR) 5458 Reg = PR; 5459 } 5460 if (Reg) { 5461 Op = MachineOperand::CreateReg(Reg, false); 5462 IsIndirect = IsDbgDeclare; 5463 } 5464 } 5465 5466 if (!Op && N.getNode()) { 5467 // Check if frame index is available. 5468 SDValue LCandidate = peekThroughBitcasts(N); 5469 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5470 if (FrameIndexSDNode *FINode = 5471 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5472 Op = MachineOperand::CreateFI(FINode->getIndex()); 5473 } 5474 5475 if (!Op) { 5476 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5477 auto splitMultiRegDbgValue 5478 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5479 unsigned Offset = 0; 5480 for (auto RegAndSize : SplitRegs) { 5481 // If the expression is already a fragment, the current register 5482 // offset+size might extend beyond the fragment. In this case, only 5483 // the register bits that are inside the fragment are relevant. 5484 int RegFragmentSizeInBits = RegAndSize.second; 5485 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5486 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5487 // The register is entirely outside the expression fragment, 5488 // so is irrelevant for debug info. 5489 if (Offset >= ExprFragmentSizeInBits) 5490 break; 5491 // The register is partially outside the expression fragment, only 5492 // the low bits within the fragment are relevant for debug info. 5493 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5494 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5495 } 5496 } 5497 5498 auto FragmentExpr = DIExpression::createFragmentExpression( 5499 Expr, Offset, RegFragmentSizeInBits); 5500 Offset += RegAndSize.second; 5501 // If a valid fragment expression cannot be created, the variable's 5502 // correct value cannot be determined and so it is set as Undef. 5503 if (!FragmentExpr) { 5504 SDDbgValue *SDV = DAG.getConstantDbgValue( 5505 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5506 DAG.AddDbgValue(SDV, nullptr, false); 5507 continue; 5508 } 5509 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5510 FuncInfo.ArgDbgValues.push_back( 5511 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5512 RegAndSize.first, Variable, *FragmentExpr)); 5513 } 5514 }; 5515 5516 // Check if ValueMap has reg number. 5517 DenseMap<const Value *, Register>::const_iterator 5518 VMI = FuncInfo.ValueMap.find(V); 5519 if (VMI != FuncInfo.ValueMap.end()) { 5520 const auto &TLI = DAG.getTargetLoweringInfo(); 5521 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5522 V->getType(), getABIRegCopyCC(V)); 5523 if (RFV.occupiesMultipleRegs()) { 5524 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5525 return true; 5526 } 5527 5528 Op = MachineOperand::CreateReg(VMI->second, false); 5529 IsIndirect = IsDbgDeclare; 5530 } else if (ArgRegsAndSizes.size() > 1) { 5531 // This was split due to the calling convention, and no virtual register 5532 // mapping exists for the value. 5533 splitMultiRegDbgValue(ArgRegsAndSizes); 5534 return true; 5535 } 5536 } 5537 5538 if (!Op) 5539 return false; 5540 5541 assert(Variable->isValidLocationForIntrinsic(DL) && 5542 "Expected inlined-at fields to agree"); 5543 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5544 FuncInfo.ArgDbgValues.push_back( 5545 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5546 *Op, Variable, Expr)); 5547 5548 return true; 5549 } 5550 5551 /// Return the appropriate SDDbgValue based on N. 5552 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5553 DILocalVariable *Variable, 5554 DIExpression *Expr, 5555 const DebugLoc &dl, 5556 unsigned DbgSDNodeOrder) { 5557 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5558 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5559 // stack slot locations. 5560 // 5561 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5562 // debug values here after optimization: 5563 // 5564 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5565 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5566 // 5567 // Both describe the direct values of their associated variables. 5568 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5569 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5570 } 5571 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5572 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5573 } 5574 5575 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5576 switch (Intrinsic) { 5577 case Intrinsic::smul_fix: 5578 return ISD::SMULFIX; 5579 case Intrinsic::umul_fix: 5580 return ISD::UMULFIX; 5581 case Intrinsic::smul_fix_sat: 5582 return ISD::SMULFIXSAT; 5583 case Intrinsic::umul_fix_sat: 5584 return ISD::UMULFIXSAT; 5585 case Intrinsic::sdiv_fix: 5586 return ISD::SDIVFIX; 5587 case Intrinsic::udiv_fix: 5588 return ISD::UDIVFIX; 5589 case Intrinsic::sdiv_fix_sat: 5590 return ISD::SDIVFIXSAT; 5591 case Intrinsic::udiv_fix_sat: 5592 return ISD::UDIVFIXSAT; 5593 default: 5594 llvm_unreachable("Unhandled fixed point intrinsic"); 5595 } 5596 } 5597 5598 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5599 const char *FunctionName) { 5600 assert(FunctionName && "FunctionName must not be nullptr"); 5601 SDValue Callee = DAG.getExternalSymbol( 5602 FunctionName, 5603 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5604 LowerCallTo(I, Callee, I.isTailCall()); 5605 } 5606 5607 /// Lower the call to the specified intrinsic function. 5608 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5609 unsigned Intrinsic) { 5610 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5611 SDLoc sdl = getCurSDLoc(); 5612 DebugLoc dl = getCurDebugLoc(); 5613 SDValue Res; 5614 5615 switch (Intrinsic) { 5616 default: 5617 // By default, turn this into a target intrinsic node. 5618 visitTargetIntrinsic(I, Intrinsic); 5619 return; 5620 case Intrinsic::vscale: { 5621 match(&I, m_VScale(DAG.getDataLayout())); 5622 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5623 setValue(&I, 5624 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5625 return; 5626 } 5627 case Intrinsic::vastart: visitVAStart(I); return; 5628 case Intrinsic::vaend: visitVAEnd(I); return; 5629 case Intrinsic::vacopy: visitVACopy(I); return; 5630 case Intrinsic::returnaddress: 5631 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5632 TLI.getPointerTy(DAG.getDataLayout()), 5633 getValue(I.getArgOperand(0)))); 5634 return; 5635 case Intrinsic::addressofreturnaddress: 5636 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5637 TLI.getPointerTy(DAG.getDataLayout()))); 5638 return; 5639 case Intrinsic::sponentry: 5640 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5641 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5642 return; 5643 case Intrinsic::frameaddress: 5644 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5645 TLI.getFrameIndexTy(DAG.getDataLayout()), 5646 getValue(I.getArgOperand(0)))); 5647 return; 5648 case Intrinsic::read_register: { 5649 Value *Reg = I.getArgOperand(0); 5650 SDValue Chain = getRoot(); 5651 SDValue RegName = 5652 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5653 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5654 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5655 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5656 setValue(&I, Res); 5657 DAG.setRoot(Res.getValue(1)); 5658 return; 5659 } 5660 case Intrinsic::write_register: { 5661 Value *Reg = I.getArgOperand(0); 5662 Value *RegValue = I.getArgOperand(1); 5663 SDValue Chain = getRoot(); 5664 SDValue RegName = 5665 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5666 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5667 RegName, getValue(RegValue))); 5668 return; 5669 } 5670 case Intrinsic::memcpy: { 5671 const auto &MCI = cast<MemCpyInst>(I); 5672 SDValue Op1 = getValue(I.getArgOperand(0)); 5673 SDValue Op2 = getValue(I.getArgOperand(1)); 5674 SDValue Op3 = getValue(I.getArgOperand(2)); 5675 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5676 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5677 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5678 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5679 bool isVol = MCI.isVolatile(); 5680 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5681 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5682 // node. 5683 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5684 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5685 /* AlwaysInline */ false, isTC, 5686 MachinePointerInfo(I.getArgOperand(0)), 5687 MachinePointerInfo(I.getArgOperand(1))); 5688 updateDAGForMaybeTailCall(MC); 5689 return; 5690 } 5691 case Intrinsic::memcpy_inline: { 5692 const auto &MCI = cast<MemCpyInlineInst>(I); 5693 SDValue Dst = getValue(I.getArgOperand(0)); 5694 SDValue Src = getValue(I.getArgOperand(1)); 5695 SDValue Size = getValue(I.getArgOperand(2)); 5696 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5697 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5698 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5699 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5700 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5701 bool isVol = MCI.isVolatile(); 5702 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5703 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5704 // node. 5705 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5706 /* AlwaysInline */ true, isTC, 5707 MachinePointerInfo(I.getArgOperand(0)), 5708 MachinePointerInfo(I.getArgOperand(1))); 5709 updateDAGForMaybeTailCall(MC); 5710 return; 5711 } 5712 case Intrinsic::memset: { 5713 const auto &MSI = cast<MemSetInst>(I); 5714 SDValue Op1 = getValue(I.getArgOperand(0)); 5715 SDValue Op2 = getValue(I.getArgOperand(1)); 5716 SDValue Op3 = getValue(I.getArgOperand(2)); 5717 // @llvm.memset defines 0 and 1 to both mean no alignment. 5718 Align Alignment = MSI.getDestAlign().valueOrOne(); 5719 bool isVol = MSI.isVolatile(); 5720 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5721 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5722 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5723 MachinePointerInfo(I.getArgOperand(0))); 5724 updateDAGForMaybeTailCall(MS); 5725 return; 5726 } 5727 case Intrinsic::memmove: { 5728 const auto &MMI = cast<MemMoveInst>(I); 5729 SDValue Op1 = getValue(I.getArgOperand(0)); 5730 SDValue Op2 = getValue(I.getArgOperand(1)); 5731 SDValue Op3 = getValue(I.getArgOperand(2)); 5732 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5733 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5734 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5735 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5736 bool isVol = MMI.isVolatile(); 5737 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5738 // FIXME: Support passing different dest/src alignments to the memmove DAG 5739 // node. 5740 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5741 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5742 isTC, MachinePointerInfo(I.getArgOperand(0)), 5743 MachinePointerInfo(I.getArgOperand(1))); 5744 updateDAGForMaybeTailCall(MM); 5745 return; 5746 } 5747 case Intrinsic::memcpy_element_unordered_atomic: { 5748 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5749 SDValue Dst = getValue(MI.getRawDest()); 5750 SDValue Src = getValue(MI.getRawSource()); 5751 SDValue Length = getValue(MI.getLength()); 5752 5753 unsigned DstAlign = MI.getDestAlignment(); 5754 unsigned SrcAlign = MI.getSourceAlignment(); 5755 Type *LengthTy = MI.getLength()->getType(); 5756 unsigned ElemSz = MI.getElementSizeInBytes(); 5757 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5758 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5759 SrcAlign, Length, LengthTy, ElemSz, isTC, 5760 MachinePointerInfo(MI.getRawDest()), 5761 MachinePointerInfo(MI.getRawSource())); 5762 updateDAGForMaybeTailCall(MC); 5763 return; 5764 } 5765 case Intrinsic::memmove_element_unordered_atomic: { 5766 auto &MI = cast<AtomicMemMoveInst>(I); 5767 SDValue Dst = getValue(MI.getRawDest()); 5768 SDValue Src = getValue(MI.getRawSource()); 5769 SDValue Length = getValue(MI.getLength()); 5770 5771 unsigned DstAlign = MI.getDestAlignment(); 5772 unsigned SrcAlign = MI.getSourceAlignment(); 5773 Type *LengthTy = MI.getLength()->getType(); 5774 unsigned ElemSz = MI.getElementSizeInBytes(); 5775 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5776 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5777 SrcAlign, Length, LengthTy, ElemSz, isTC, 5778 MachinePointerInfo(MI.getRawDest()), 5779 MachinePointerInfo(MI.getRawSource())); 5780 updateDAGForMaybeTailCall(MC); 5781 return; 5782 } 5783 case Intrinsic::memset_element_unordered_atomic: { 5784 auto &MI = cast<AtomicMemSetInst>(I); 5785 SDValue Dst = getValue(MI.getRawDest()); 5786 SDValue Val = getValue(MI.getValue()); 5787 SDValue Length = getValue(MI.getLength()); 5788 5789 unsigned DstAlign = MI.getDestAlignment(); 5790 Type *LengthTy = MI.getLength()->getType(); 5791 unsigned ElemSz = MI.getElementSizeInBytes(); 5792 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5793 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5794 LengthTy, ElemSz, isTC, 5795 MachinePointerInfo(MI.getRawDest())); 5796 updateDAGForMaybeTailCall(MC); 5797 return; 5798 } 5799 case Intrinsic::dbg_addr: 5800 case Intrinsic::dbg_declare: { 5801 const auto &DI = cast<DbgVariableIntrinsic>(I); 5802 DILocalVariable *Variable = DI.getVariable(); 5803 DIExpression *Expression = DI.getExpression(); 5804 dropDanglingDebugInfo(Variable, Expression); 5805 assert(Variable && "Missing variable"); 5806 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5807 << "\n"); 5808 // Check if address has undef value. 5809 const Value *Address = DI.getVariableLocation(); 5810 if (!Address || isa<UndefValue>(Address) || 5811 (Address->use_empty() && !isa<Argument>(Address))) { 5812 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5813 << " (bad/undef/unused-arg address)\n"); 5814 return; 5815 } 5816 5817 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5818 5819 // Check if this variable can be described by a frame index, typically 5820 // either as a static alloca or a byval parameter. 5821 int FI = std::numeric_limits<int>::max(); 5822 if (const auto *AI = 5823 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5824 if (AI->isStaticAlloca()) { 5825 auto I = FuncInfo.StaticAllocaMap.find(AI); 5826 if (I != FuncInfo.StaticAllocaMap.end()) 5827 FI = I->second; 5828 } 5829 } else if (const auto *Arg = dyn_cast<Argument>( 5830 Address->stripInBoundsConstantOffsets())) { 5831 FI = FuncInfo.getArgumentFrameIndex(Arg); 5832 } 5833 5834 // llvm.dbg.addr is control dependent and always generates indirect 5835 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5836 // the MachineFunction variable table. 5837 if (FI != std::numeric_limits<int>::max()) { 5838 if (Intrinsic == Intrinsic::dbg_addr) { 5839 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5840 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5841 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5842 } else { 5843 LLVM_DEBUG(dbgs() << "Skipping " << DI 5844 << " (variable info stashed in MF side table)\n"); 5845 } 5846 return; 5847 } 5848 5849 SDValue &N = NodeMap[Address]; 5850 if (!N.getNode() && isa<Argument>(Address)) 5851 // Check unused arguments map. 5852 N = UnusedArgNodeMap[Address]; 5853 SDDbgValue *SDV; 5854 if (N.getNode()) { 5855 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5856 Address = BCI->getOperand(0); 5857 // Parameters are handled specially. 5858 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5859 if (isParameter && FINode) { 5860 // Byval parameter. We have a frame index at this point. 5861 SDV = 5862 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5863 /*IsIndirect*/ true, dl, SDNodeOrder); 5864 } else if (isa<Argument>(Address)) { 5865 // Address is an argument, so try to emit its dbg value using 5866 // virtual register info from the FuncInfo.ValueMap. 5867 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5868 return; 5869 } else { 5870 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5871 true, dl, SDNodeOrder); 5872 } 5873 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5874 } else { 5875 // If Address is an argument then try to emit its dbg value using 5876 // virtual register info from the FuncInfo.ValueMap. 5877 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5878 N)) { 5879 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5880 << " (could not emit func-arg dbg_value)\n"); 5881 } 5882 } 5883 return; 5884 } 5885 case Intrinsic::dbg_label: { 5886 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5887 DILabel *Label = DI.getLabel(); 5888 assert(Label && "Missing label"); 5889 5890 SDDbgLabel *SDV; 5891 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5892 DAG.AddDbgLabel(SDV); 5893 return; 5894 } 5895 case Intrinsic::dbg_value: { 5896 const DbgValueInst &DI = cast<DbgValueInst>(I); 5897 assert(DI.getVariable() && "Missing variable"); 5898 5899 DILocalVariable *Variable = DI.getVariable(); 5900 DIExpression *Expression = DI.getExpression(); 5901 dropDanglingDebugInfo(Variable, Expression); 5902 const Value *V = DI.getValue(); 5903 if (!V) 5904 return; 5905 5906 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5907 SDNodeOrder)) 5908 return; 5909 5910 // TODO: Dangling debug info will eventually either be resolved or produce 5911 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5912 // between the original dbg.value location and its resolved DBG_VALUE, which 5913 // we should ideally fill with an extra Undef DBG_VALUE. 5914 5915 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5916 return; 5917 } 5918 5919 case Intrinsic::eh_typeid_for: { 5920 // Find the type id for the given typeinfo. 5921 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5922 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5923 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5924 setValue(&I, Res); 5925 return; 5926 } 5927 5928 case Intrinsic::eh_return_i32: 5929 case Intrinsic::eh_return_i64: 5930 DAG.getMachineFunction().setCallsEHReturn(true); 5931 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5932 MVT::Other, 5933 getControlRoot(), 5934 getValue(I.getArgOperand(0)), 5935 getValue(I.getArgOperand(1)))); 5936 return; 5937 case Intrinsic::eh_unwind_init: 5938 DAG.getMachineFunction().setCallsUnwindInit(true); 5939 return; 5940 case Intrinsic::eh_dwarf_cfa: 5941 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5942 TLI.getPointerTy(DAG.getDataLayout()), 5943 getValue(I.getArgOperand(0)))); 5944 return; 5945 case Intrinsic::eh_sjlj_callsite: { 5946 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5947 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5948 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5949 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5950 5951 MMI.setCurrentCallSite(CI->getZExtValue()); 5952 return; 5953 } 5954 case Intrinsic::eh_sjlj_functioncontext: { 5955 // Get and store the index of the function context. 5956 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5957 AllocaInst *FnCtx = 5958 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5959 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5960 MFI.setFunctionContextIndex(FI); 5961 return; 5962 } 5963 case Intrinsic::eh_sjlj_setjmp: { 5964 SDValue Ops[2]; 5965 Ops[0] = getRoot(); 5966 Ops[1] = getValue(I.getArgOperand(0)); 5967 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5968 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5969 setValue(&I, Op.getValue(0)); 5970 DAG.setRoot(Op.getValue(1)); 5971 return; 5972 } 5973 case Intrinsic::eh_sjlj_longjmp: 5974 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5975 getRoot(), getValue(I.getArgOperand(0)))); 5976 return; 5977 case Intrinsic::eh_sjlj_setup_dispatch: 5978 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5979 getRoot())); 5980 return; 5981 case Intrinsic::masked_gather: 5982 visitMaskedGather(I); 5983 return; 5984 case Intrinsic::masked_load: 5985 visitMaskedLoad(I); 5986 return; 5987 case Intrinsic::masked_scatter: 5988 visitMaskedScatter(I); 5989 return; 5990 case Intrinsic::masked_store: 5991 visitMaskedStore(I); 5992 return; 5993 case Intrinsic::masked_expandload: 5994 visitMaskedLoad(I, true /* IsExpanding */); 5995 return; 5996 case Intrinsic::masked_compressstore: 5997 visitMaskedStore(I, true /* IsCompressing */); 5998 return; 5999 case Intrinsic::powi: 6000 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6001 getValue(I.getArgOperand(1)), DAG)); 6002 return; 6003 case Intrinsic::log: 6004 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6005 return; 6006 case Intrinsic::log2: 6007 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6008 return; 6009 case Intrinsic::log10: 6010 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6011 return; 6012 case Intrinsic::exp: 6013 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6014 return; 6015 case Intrinsic::exp2: 6016 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6017 return; 6018 case Intrinsic::pow: 6019 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6020 getValue(I.getArgOperand(1)), DAG, TLI)); 6021 return; 6022 case Intrinsic::sqrt: 6023 case Intrinsic::fabs: 6024 case Intrinsic::sin: 6025 case Intrinsic::cos: 6026 case Intrinsic::floor: 6027 case Intrinsic::ceil: 6028 case Intrinsic::trunc: 6029 case Intrinsic::rint: 6030 case Intrinsic::nearbyint: 6031 case Intrinsic::round: 6032 case Intrinsic::canonicalize: { 6033 unsigned Opcode; 6034 switch (Intrinsic) { 6035 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6036 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6037 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6038 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6039 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6040 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6041 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6042 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6043 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6044 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6045 case Intrinsic::round: Opcode = ISD::FROUND; break; 6046 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6047 } 6048 6049 setValue(&I, DAG.getNode(Opcode, sdl, 6050 getValue(I.getArgOperand(0)).getValueType(), 6051 getValue(I.getArgOperand(0)))); 6052 return; 6053 } 6054 case Intrinsic::lround: 6055 case Intrinsic::llround: 6056 case Intrinsic::lrint: 6057 case Intrinsic::llrint: { 6058 unsigned Opcode; 6059 switch (Intrinsic) { 6060 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6061 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6062 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6063 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6064 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6065 } 6066 6067 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6068 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6069 getValue(I.getArgOperand(0)))); 6070 return; 6071 } 6072 case Intrinsic::minnum: 6073 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6074 getValue(I.getArgOperand(0)).getValueType(), 6075 getValue(I.getArgOperand(0)), 6076 getValue(I.getArgOperand(1)))); 6077 return; 6078 case Intrinsic::maxnum: 6079 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6080 getValue(I.getArgOperand(0)).getValueType(), 6081 getValue(I.getArgOperand(0)), 6082 getValue(I.getArgOperand(1)))); 6083 return; 6084 case Intrinsic::minimum: 6085 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6086 getValue(I.getArgOperand(0)).getValueType(), 6087 getValue(I.getArgOperand(0)), 6088 getValue(I.getArgOperand(1)))); 6089 return; 6090 case Intrinsic::maximum: 6091 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6092 getValue(I.getArgOperand(0)).getValueType(), 6093 getValue(I.getArgOperand(0)), 6094 getValue(I.getArgOperand(1)))); 6095 return; 6096 case Intrinsic::copysign: 6097 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6098 getValue(I.getArgOperand(0)).getValueType(), 6099 getValue(I.getArgOperand(0)), 6100 getValue(I.getArgOperand(1)))); 6101 return; 6102 case Intrinsic::fma: 6103 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6104 getValue(I.getArgOperand(0)).getValueType(), 6105 getValue(I.getArgOperand(0)), 6106 getValue(I.getArgOperand(1)), 6107 getValue(I.getArgOperand(2)))); 6108 return; 6109 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6110 case Intrinsic::INTRINSIC: 6111 #include "llvm/IR/ConstrainedOps.def" 6112 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6113 return; 6114 case Intrinsic::fmuladd: { 6115 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6116 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6117 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6118 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6119 getValue(I.getArgOperand(0)).getValueType(), 6120 getValue(I.getArgOperand(0)), 6121 getValue(I.getArgOperand(1)), 6122 getValue(I.getArgOperand(2)))); 6123 } else { 6124 // TODO: Intrinsic calls should have fast-math-flags. 6125 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6126 getValue(I.getArgOperand(0)).getValueType(), 6127 getValue(I.getArgOperand(0)), 6128 getValue(I.getArgOperand(1))); 6129 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6130 getValue(I.getArgOperand(0)).getValueType(), 6131 Mul, 6132 getValue(I.getArgOperand(2))); 6133 setValue(&I, Add); 6134 } 6135 return; 6136 } 6137 case Intrinsic::convert_to_fp16: 6138 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6139 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6140 getValue(I.getArgOperand(0)), 6141 DAG.getTargetConstant(0, sdl, 6142 MVT::i32)))); 6143 return; 6144 case Intrinsic::convert_from_fp16: 6145 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6146 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6147 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6148 getValue(I.getArgOperand(0))))); 6149 return; 6150 case Intrinsic::pcmarker: { 6151 SDValue Tmp = getValue(I.getArgOperand(0)); 6152 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6153 return; 6154 } 6155 case Intrinsic::readcyclecounter: { 6156 SDValue Op = getRoot(); 6157 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6158 DAG.getVTList(MVT::i64, MVT::Other), Op); 6159 setValue(&I, Res); 6160 DAG.setRoot(Res.getValue(1)); 6161 return; 6162 } 6163 case Intrinsic::bitreverse: 6164 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6165 getValue(I.getArgOperand(0)).getValueType(), 6166 getValue(I.getArgOperand(0)))); 6167 return; 6168 case Intrinsic::bswap: 6169 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6170 getValue(I.getArgOperand(0)).getValueType(), 6171 getValue(I.getArgOperand(0)))); 6172 return; 6173 case Intrinsic::cttz: { 6174 SDValue Arg = getValue(I.getArgOperand(0)); 6175 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6176 EVT Ty = Arg.getValueType(); 6177 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6178 sdl, Ty, Arg)); 6179 return; 6180 } 6181 case Intrinsic::ctlz: { 6182 SDValue Arg = getValue(I.getArgOperand(0)); 6183 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6184 EVT Ty = Arg.getValueType(); 6185 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6186 sdl, Ty, Arg)); 6187 return; 6188 } 6189 case Intrinsic::ctpop: { 6190 SDValue Arg = getValue(I.getArgOperand(0)); 6191 EVT Ty = Arg.getValueType(); 6192 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6193 return; 6194 } 6195 case Intrinsic::fshl: 6196 case Intrinsic::fshr: { 6197 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6198 SDValue X = getValue(I.getArgOperand(0)); 6199 SDValue Y = getValue(I.getArgOperand(1)); 6200 SDValue Z = getValue(I.getArgOperand(2)); 6201 EVT VT = X.getValueType(); 6202 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6203 SDValue Zero = DAG.getConstant(0, sdl, VT); 6204 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6205 6206 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6207 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6208 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6209 return; 6210 } 6211 6212 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6213 // avoid the select that is necessary in the general case to filter out 6214 // the 0-shift possibility that leads to UB. 6215 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6216 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6217 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6218 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6219 return; 6220 } 6221 6222 // Some targets only rotate one way. Try the opposite direction. 6223 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6224 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6225 // Negate the shift amount because it is safe to ignore the high bits. 6226 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6227 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6228 return; 6229 } 6230 6231 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6232 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6233 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6234 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6235 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6236 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6237 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6238 return; 6239 } 6240 6241 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6242 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6243 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6244 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6245 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6246 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6247 6248 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6249 // and that is undefined. We must compare and select to avoid UB. 6250 EVT CCVT = MVT::i1; 6251 if (VT.isVector()) 6252 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6253 6254 // For fshl, 0-shift returns the 1st arg (X). 6255 // For fshr, 0-shift returns the 2nd arg (Y). 6256 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6257 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6258 return; 6259 } 6260 case Intrinsic::sadd_sat: { 6261 SDValue Op1 = getValue(I.getArgOperand(0)); 6262 SDValue Op2 = getValue(I.getArgOperand(1)); 6263 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6264 return; 6265 } 6266 case Intrinsic::uadd_sat: { 6267 SDValue Op1 = getValue(I.getArgOperand(0)); 6268 SDValue Op2 = getValue(I.getArgOperand(1)); 6269 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6270 return; 6271 } 6272 case Intrinsic::ssub_sat: { 6273 SDValue Op1 = getValue(I.getArgOperand(0)); 6274 SDValue Op2 = getValue(I.getArgOperand(1)); 6275 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6276 return; 6277 } 6278 case Intrinsic::usub_sat: { 6279 SDValue Op1 = getValue(I.getArgOperand(0)); 6280 SDValue Op2 = getValue(I.getArgOperand(1)); 6281 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6282 return; 6283 } 6284 case Intrinsic::smul_fix: 6285 case Intrinsic::umul_fix: 6286 case Intrinsic::smul_fix_sat: 6287 case Intrinsic::umul_fix_sat: { 6288 SDValue Op1 = getValue(I.getArgOperand(0)); 6289 SDValue Op2 = getValue(I.getArgOperand(1)); 6290 SDValue Op3 = getValue(I.getArgOperand(2)); 6291 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6292 Op1.getValueType(), Op1, Op2, Op3)); 6293 return; 6294 } 6295 case Intrinsic::sdiv_fix: 6296 case Intrinsic::udiv_fix: 6297 case Intrinsic::sdiv_fix_sat: 6298 case Intrinsic::udiv_fix_sat: { 6299 SDValue Op1 = getValue(I.getArgOperand(0)); 6300 SDValue Op2 = getValue(I.getArgOperand(1)); 6301 SDValue Op3 = getValue(I.getArgOperand(2)); 6302 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6303 Op1, Op2, Op3, DAG, TLI)); 6304 return; 6305 } 6306 case Intrinsic::stacksave: { 6307 SDValue Op = getRoot(); 6308 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6309 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6310 setValue(&I, Res); 6311 DAG.setRoot(Res.getValue(1)); 6312 return; 6313 } 6314 case Intrinsic::stackrestore: 6315 Res = getValue(I.getArgOperand(0)); 6316 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6317 return; 6318 case Intrinsic::get_dynamic_area_offset: { 6319 SDValue Op = getRoot(); 6320 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6321 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6322 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6323 // target. 6324 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6325 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6326 " intrinsic!"); 6327 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6328 Op); 6329 DAG.setRoot(Op); 6330 setValue(&I, Res); 6331 return; 6332 } 6333 case Intrinsic::stackguard: { 6334 MachineFunction &MF = DAG.getMachineFunction(); 6335 const Module &M = *MF.getFunction().getParent(); 6336 SDValue Chain = getRoot(); 6337 if (TLI.useLoadStackGuardNode()) { 6338 Res = getLoadStackGuard(DAG, sdl, Chain); 6339 } else { 6340 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6341 const Value *Global = TLI.getSDagStackGuard(M); 6342 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6343 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6344 MachinePointerInfo(Global, 0), Align, 6345 MachineMemOperand::MOVolatile); 6346 } 6347 if (TLI.useStackGuardXorFP()) 6348 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6349 DAG.setRoot(Chain); 6350 setValue(&I, Res); 6351 return; 6352 } 6353 case Intrinsic::stackprotector: { 6354 // Emit code into the DAG to store the stack guard onto the stack. 6355 MachineFunction &MF = DAG.getMachineFunction(); 6356 MachineFrameInfo &MFI = MF.getFrameInfo(); 6357 SDValue Src, Chain = getRoot(); 6358 6359 if (TLI.useLoadStackGuardNode()) 6360 Src = getLoadStackGuard(DAG, sdl, Chain); 6361 else 6362 Src = getValue(I.getArgOperand(0)); // The guard's value. 6363 6364 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6365 6366 int FI = FuncInfo.StaticAllocaMap[Slot]; 6367 MFI.setStackProtectorIndex(FI); 6368 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6369 6370 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6371 6372 // Store the stack protector onto the stack. 6373 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6374 DAG.getMachineFunction(), FI), 6375 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6376 setValue(&I, Res); 6377 DAG.setRoot(Res); 6378 return; 6379 } 6380 case Intrinsic::objectsize: 6381 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6382 6383 case Intrinsic::is_constant: 6384 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6385 6386 case Intrinsic::annotation: 6387 case Intrinsic::ptr_annotation: 6388 case Intrinsic::launder_invariant_group: 6389 case Intrinsic::strip_invariant_group: 6390 // Drop the intrinsic, but forward the value 6391 setValue(&I, getValue(I.getOperand(0))); 6392 return; 6393 case Intrinsic::assume: 6394 case Intrinsic::var_annotation: 6395 case Intrinsic::sideeffect: 6396 // Discard annotate attributes, assumptions, and artificial side-effects. 6397 return; 6398 6399 case Intrinsic::codeview_annotation: { 6400 // Emit a label associated with this metadata. 6401 MachineFunction &MF = DAG.getMachineFunction(); 6402 MCSymbol *Label = 6403 MF.getMMI().getContext().createTempSymbol("annotation", true); 6404 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6405 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6406 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6407 DAG.setRoot(Res); 6408 return; 6409 } 6410 6411 case Intrinsic::init_trampoline: { 6412 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6413 6414 SDValue Ops[6]; 6415 Ops[0] = getRoot(); 6416 Ops[1] = getValue(I.getArgOperand(0)); 6417 Ops[2] = getValue(I.getArgOperand(1)); 6418 Ops[3] = getValue(I.getArgOperand(2)); 6419 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6420 Ops[5] = DAG.getSrcValue(F); 6421 6422 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6423 6424 DAG.setRoot(Res); 6425 return; 6426 } 6427 case Intrinsic::adjust_trampoline: 6428 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6429 TLI.getPointerTy(DAG.getDataLayout()), 6430 getValue(I.getArgOperand(0)))); 6431 return; 6432 case Intrinsic::gcroot: { 6433 assert(DAG.getMachineFunction().getFunction().hasGC() && 6434 "only valid in functions with gc specified, enforced by Verifier"); 6435 assert(GFI && "implied by previous"); 6436 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6437 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6438 6439 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6440 GFI->addStackRoot(FI->getIndex(), TypeMap); 6441 return; 6442 } 6443 case Intrinsic::gcread: 6444 case Intrinsic::gcwrite: 6445 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6446 case Intrinsic::flt_rounds: 6447 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6448 setValue(&I, Res); 6449 DAG.setRoot(Res.getValue(1)); 6450 return; 6451 6452 case Intrinsic::expect: 6453 // Just replace __builtin_expect(exp, c) with EXP. 6454 setValue(&I, getValue(I.getArgOperand(0))); 6455 return; 6456 6457 case Intrinsic::debugtrap: 6458 case Intrinsic::trap: { 6459 StringRef TrapFuncName = 6460 I.getAttributes() 6461 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6462 .getValueAsString(); 6463 if (TrapFuncName.empty()) { 6464 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6465 ISD::TRAP : ISD::DEBUGTRAP; 6466 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6467 return; 6468 } 6469 TargetLowering::ArgListTy Args; 6470 6471 TargetLowering::CallLoweringInfo CLI(DAG); 6472 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6473 CallingConv::C, I.getType(), 6474 DAG.getExternalSymbol(TrapFuncName.data(), 6475 TLI.getPointerTy(DAG.getDataLayout())), 6476 std::move(Args)); 6477 6478 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6479 DAG.setRoot(Result.second); 6480 return; 6481 } 6482 6483 case Intrinsic::uadd_with_overflow: 6484 case Intrinsic::sadd_with_overflow: 6485 case Intrinsic::usub_with_overflow: 6486 case Intrinsic::ssub_with_overflow: 6487 case Intrinsic::umul_with_overflow: 6488 case Intrinsic::smul_with_overflow: { 6489 ISD::NodeType Op; 6490 switch (Intrinsic) { 6491 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6492 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6493 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6494 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6495 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6496 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6497 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6498 } 6499 SDValue Op1 = getValue(I.getArgOperand(0)); 6500 SDValue Op2 = getValue(I.getArgOperand(1)); 6501 6502 EVT ResultVT = Op1.getValueType(); 6503 EVT OverflowVT = MVT::i1; 6504 if (ResultVT.isVector()) 6505 OverflowVT = EVT::getVectorVT( 6506 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6507 6508 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6509 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6510 return; 6511 } 6512 case Intrinsic::prefetch: { 6513 SDValue Ops[5]; 6514 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6515 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6516 Ops[0] = DAG.getRoot(); 6517 Ops[1] = getValue(I.getArgOperand(0)); 6518 Ops[2] = getValue(I.getArgOperand(1)); 6519 Ops[3] = getValue(I.getArgOperand(2)); 6520 Ops[4] = getValue(I.getArgOperand(3)); 6521 SDValue Result = DAG.getMemIntrinsicNode( 6522 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6523 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6524 /* align */ None, Flags); 6525 6526 // Chain the prefetch in parallell with any pending loads, to stay out of 6527 // the way of later optimizations. 6528 PendingLoads.push_back(Result); 6529 Result = getRoot(); 6530 DAG.setRoot(Result); 6531 return; 6532 } 6533 case Intrinsic::lifetime_start: 6534 case Intrinsic::lifetime_end: { 6535 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6536 // Stack coloring is not enabled in O0, discard region information. 6537 if (TM.getOptLevel() == CodeGenOpt::None) 6538 return; 6539 6540 const int64_t ObjectSize = 6541 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6542 Value *const ObjectPtr = I.getArgOperand(1); 6543 SmallVector<const Value *, 4> Allocas; 6544 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6545 6546 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6547 E = Allocas.end(); Object != E; ++Object) { 6548 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6549 6550 // Could not find an Alloca. 6551 if (!LifetimeObject) 6552 continue; 6553 6554 // First check that the Alloca is static, otherwise it won't have a 6555 // valid frame index. 6556 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6557 if (SI == FuncInfo.StaticAllocaMap.end()) 6558 return; 6559 6560 const int FrameIndex = SI->second; 6561 int64_t Offset; 6562 if (GetPointerBaseWithConstantOffset( 6563 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6564 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6565 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6566 Offset); 6567 DAG.setRoot(Res); 6568 } 6569 return; 6570 } 6571 case Intrinsic::invariant_start: 6572 // Discard region information. 6573 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6574 return; 6575 case Intrinsic::invariant_end: 6576 // Discard region information. 6577 return; 6578 case Intrinsic::clear_cache: 6579 /// FunctionName may be null. 6580 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6581 lowerCallToExternalSymbol(I, FunctionName); 6582 return; 6583 case Intrinsic::donothing: 6584 // ignore 6585 return; 6586 case Intrinsic::experimental_stackmap: 6587 visitStackmap(I); 6588 return; 6589 case Intrinsic::experimental_patchpoint_void: 6590 case Intrinsic::experimental_patchpoint_i64: 6591 visitPatchpoint(I); 6592 return; 6593 case Intrinsic::experimental_gc_statepoint: 6594 LowerStatepoint(ImmutableStatepoint(&I)); 6595 return; 6596 case Intrinsic::experimental_gc_result: 6597 visitGCResult(cast<GCResultInst>(I)); 6598 return; 6599 case Intrinsic::experimental_gc_relocate: 6600 visitGCRelocate(cast<GCRelocateInst>(I)); 6601 return; 6602 case Intrinsic::instrprof_increment: 6603 llvm_unreachable("instrprof failed to lower an increment"); 6604 case Intrinsic::instrprof_value_profile: 6605 llvm_unreachable("instrprof failed to lower a value profiling call"); 6606 case Intrinsic::localescape: { 6607 MachineFunction &MF = DAG.getMachineFunction(); 6608 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6609 6610 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6611 // is the same on all targets. 6612 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6613 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6614 if (isa<ConstantPointerNull>(Arg)) 6615 continue; // Skip null pointers. They represent a hole in index space. 6616 AllocaInst *Slot = cast<AllocaInst>(Arg); 6617 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6618 "can only escape static allocas"); 6619 int FI = FuncInfo.StaticAllocaMap[Slot]; 6620 MCSymbol *FrameAllocSym = 6621 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6622 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6623 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6624 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6625 .addSym(FrameAllocSym) 6626 .addFrameIndex(FI); 6627 } 6628 6629 return; 6630 } 6631 6632 case Intrinsic::localrecover: { 6633 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6634 MachineFunction &MF = DAG.getMachineFunction(); 6635 6636 // Get the symbol that defines the frame offset. 6637 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6638 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6639 unsigned IdxVal = 6640 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6641 MCSymbol *FrameAllocSym = 6642 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6643 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6644 6645 Value *FP = I.getArgOperand(1); 6646 SDValue FPVal = getValue(FP); 6647 EVT PtrVT = FPVal.getValueType(); 6648 6649 // Create a MCSymbol for the label to avoid any target lowering 6650 // that would make this PC relative. 6651 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6652 SDValue OffsetVal = 6653 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6654 6655 // Add the offset to the FP. 6656 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6657 setValue(&I, Add); 6658 6659 return; 6660 } 6661 6662 case Intrinsic::eh_exceptionpointer: 6663 case Intrinsic::eh_exceptioncode: { 6664 // Get the exception pointer vreg, copy from it, and resize it to fit. 6665 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6666 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6667 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6668 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6669 SDValue N = 6670 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6671 if (Intrinsic == Intrinsic::eh_exceptioncode) 6672 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6673 setValue(&I, N); 6674 return; 6675 } 6676 case Intrinsic::xray_customevent: { 6677 // Here we want to make sure that the intrinsic behaves as if it has a 6678 // specific calling convention, and only for x86_64. 6679 // FIXME: Support other platforms later. 6680 const auto &Triple = DAG.getTarget().getTargetTriple(); 6681 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6682 return; 6683 6684 SDLoc DL = getCurSDLoc(); 6685 SmallVector<SDValue, 8> Ops; 6686 6687 // We want to say that we always want the arguments in registers. 6688 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6689 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6690 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6691 SDValue Chain = getRoot(); 6692 Ops.push_back(LogEntryVal); 6693 Ops.push_back(StrSizeVal); 6694 Ops.push_back(Chain); 6695 6696 // We need to enforce the calling convention for the callsite, so that 6697 // argument ordering is enforced correctly, and that register allocation can 6698 // see that some registers may be assumed clobbered and have to preserve 6699 // them across calls to the intrinsic. 6700 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6701 DL, NodeTys, Ops); 6702 SDValue patchableNode = SDValue(MN, 0); 6703 DAG.setRoot(patchableNode); 6704 setValue(&I, patchableNode); 6705 return; 6706 } 6707 case Intrinsic::xray_typedevent: { 6708 // Here we want to make sure that the intrinsic behaves as if it has a 6709 // specific calling convention, and only for x86_64. 6710 // FIXME: Support other platforms later. 6711 const auto &Triple = DAG.getTarget().getTargetTriple(); 6712 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6713 return; 6714 6715 SDLoc DL = getCurSDLoc(); 6716 SmallVector<SDValue, 8> Ops; 6717 6718 // We want to say that we always want the arguments in registers. 6719 // It's unclear to me how manipulating the selection DAG here forces callers 6720 // to provide arguments in registers instead of on the stack. 6721 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6722 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6723 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6724 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6725 SDValue Chain = getRoot(); 6726 Ops.push_back(LogTypeId); 6727 Ops.push_back(LogEntryVal); 6728 Ops.push_back(StrSizeVal); 6729 Ops.push_back(Chain); 6730 6731 // We need to enforce the calling convention for the callsite, so that 6732 // argument ordering is enforced correctly, and that register allocation can 6733 // see that some registers may be assumed clobbered and have to preserve 6734 // them across calls to the intrinsic. 6735 MachineSDNode *MN = DAG.getMachineNode( 6736 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6737 SDValue patchableNode = SDValue(MN, 0); 6738 DAG.setRoot(patchableNode); 6739 setValue(&I, patchableNode); 6740 return; 6741 } 6742 case Intrinsic::experimental_deoptimize: 6743 LowerDeoptimizeCall(&I); 6744 return; 6745 6746 case Intrinsic::experimental_vector_reduce_v2_fadd: 6747 case Intrinsic::experimental_vector_reduce_v2_fmul: 6748 case Intrinsic::experimental_vector_reduce_add: 6749 case Intrinsic::experimental_vector_reduce_mul: 6750 case Intrinsic::experimental_vector_reduce_and: 6751 case Intrinsic::experimental_vector_reduce_or: 6752 case Intrinsic::experimental_vector_reduce_xor: 6753 case Intrinsic::experimental_vector_reduce_smax: 6754 case Intrinsic::experimental_vector_reduce_smin: 6755 case Intrinsic::experimental_vector_reduce_umax: 6756 case Intrinsic::experimental_vector_reduce_umin: 6757 case Intrinsic::experimental_vector_reduce_fmax: 6758 case Intrinsic::experimental_vector_reduce_fmin: 6759 visitVectorReduce(I, Intrinsic); 6760 return; 6761 6762 case Intrinsic::icall_branch_funnel: { 6763 SmallVector<SDValue, 16> Ops; 6764 Ops.push_back(getValue(I.getArgOperand(0))); 6765 6766 int64_t Offset; 6767 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6768 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6769 if (!Base) 6770 report_fatal_error( 6771 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6772 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6773 6774 struct BranchFunnelTarget { 6775 int64_t Offset; 6776 SDValue Target; 6777 }; 6778 SmallVector<BranchFunnelTarget, 8> Targets; 6779 6780 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6781 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6782 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6783 if (ElemBase != Base) 6784 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6785 "to the same GlobalValue"); 6786 6787 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6788 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6789 if (!GA) 6790 report_fatal_error( 6791 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6792 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6793 GA->getGlobal(), getCurSDLoc(), 6794 Val.getValueType(), GA->getOffset())}); 6795 } 6796 llvm::sort(Targets, 6797 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6798 return T1.Offset < T2.Offset; 6799 }); 6800 6801 for (auto &T : Targets) { 6802 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6803 Ops.push_back(T.Target); 6804 } 6805 6806 Ops.push_back(DAG.getRoot()); // Chain 6807 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6808 getCurSDLoc(), MVT::Other, Ops), 6809 0); 6810 DAG.setRoot(N); 6811 setValue(&I, N); 6812 HasTailCall = true; 6813 return; 6814 } 6815 6816 case Intrinsic::wasm_landingpad_index: 6817 // Information this intrinsic contained has been transferred to 6818 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6819 // delete it now. 6820 return; 6821 6822 case Intrinsic::aarch64_settag: 6823 case Intrinsic::aarch64_settag_zero: { 6824 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6825 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6826 SDValue Val = TSI.EmitTargetCodeForSetTag( 6827 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6828 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6829 ZeroMemory); 6830 DAG.setRoot(Val); 6831 setValue(&I, Val); 6832 return; 6833 } 6834 case Intrinsic::ptrmask: { 6835 SDValue Ptr = getValue(I.getOperand(0)); 6836 SDValue Const = getValue(I.getOperand(1)); 6837 6838 EVT DestVT = 6839 EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6840 6841 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr, 6842 DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT))); 6843 return; 6844 } 6845 } 6846 } 6847 6848 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6849 const ConstrainedFPIntrinsic &FPI) { 6850 SDLoc sdl = getCurSDLoc(); 6851 6852 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6853 SmallVector<EVT, 4> ValueVTs; 6854 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6855 ValueVTs.push_back(MVT::Other); // Out chain 6856 6857 // We do not need to serialize constrained FP intrinsics against 6858 // each other or against (nonvolatile) loads, so they can be 6859 // chained like loads. 6860 SDValue Chain = DAG.getRoot(); 6861 SmallVector<SDValue, 4> Opers; 6862 Opers.push_back(Chain); 6863 if (FPI.isUnaryOp()) { 6864 Opers.push_back(getValue(FPI.getArgOperand(0))); 6865 } else if (FPI.isTernaryOp()) { 6866 Opers.push_back(getValue(FPI.getArgOperand(0))); 6867 Opers.push_back(getValue(FPI.getArgOperand(1))); 6868 Opers.push_back(getValue(FPI.getArgOperand(2))); 6869 } else { 6870 Opers.push_back(getValue(FPI.getArgOperand(0))); 6871 Opers.push_back(getValue(FPI.getArgOperand(1))); 6872 } 6873 6874 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 6875 assert(Result.getNode()->getNumValues() == 2); 6876 6877 // Push node to the appropriate list so that future instructions can be 6878 // chained up correctly. 6879 SDValue OutChain = Result.getValue(1); 6880 switch (EB) { 6881 case fp::ExceptionBehavior::ebIgnore: 6882 // The only reason why ebIgnore nodes still need to be chained is that 6883 // they might depend on the current rounding mode, and therefore must 6884 // not be moved across instruction that may change that mode. 6885 LLVM_FALLTHROUGH; 6886 case fp::ExceptionBehavior::ebMayTrap: 6887 // These must not be moved across calls or instructions that may change 6888 // floating-point exception masks. 6889 PendingConstrainedFP.push_back(OutChain); 6890 break; 6891 case fp::ExceptionBehavior::ebStrict: 6892 // These must not be moved across calls or instructions that may change 6893 // floating-point exception masks or read floating-point exception flags. 6894 // In addition, they cannot be optimized out even if unused. 6895 PendingConstrainedFPStrict.push_back(OutChain); 6896 break; 6897 } 6898 }; 6899 6900 SDVTList VTs = DAG.getVTList(ValueVTs); 6901 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 6902 6903 SDNodeFlags Flags; 6904 if (EB == fp::ExceptionBehavior::ebIgnore) 6905 Flags.setNoFPExcept(true); 6906 6907 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 6908 Flags.copyFMF(*FPOp); 6909 6910 unsigned Opcode; 6911 switch (FPI.getIntrinsicID()) { 6912 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6913 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6914 case Intrinsic::INTRINSIC: \ 6915 Opcode = ISD::STRICT_##DAGN; \ 6916 break; 6917 #include "llvm/IR/ConstrainedOps.def" 6918 case Intrinsic::experimental_constrained_fmuladd: { 6919 Opcode = ISD::STRICT_FMA; 6920 // Break fmuladd into fmul and fadd. 6921 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 6922 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 6923 ValueVTs[0])) { 6924 Opers.pop_back(); 6925 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 6926 pushOutChain(Mul, EB); 6927 Opcode = ISD::STRICT_FADD; 6928 Opers.clear(); 6929 Opers.push_back(Mul.getValue(1)); 6930 Opers.push_back(Mul.getValue(0)); 6931 Opers.push_back(getValue(FPI.getArgOperand(2))); 6932 } 6933 break; 6934 } 6935 } 6936 6937 // A few strict DAG nodes carry additional operands that are not 6938 // set up by the default code above. 6939 switch (Opcode) { 6940 default: break; 6941 case ISD::STRICT_FP_ROUND: 6942 Opers.push_back( 6943 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 6944 break; 6945 case ISD::STRICT_FSETCC: 6946 case ISD::STRICT_FSETCCS: { 6947 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 6948 Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate()))); 6949 break; 6950 } 6951 } 6952 6953 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 6954 pushOutChain(Result, EB); 6955 6956 SDValue FPResult = Result.getValue(0); 6957 setValue(&FPI, FPResult); 6958 } 6959 6960 std::pair<SDValue, SDValue> 6961 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6962 const BasicBlock *EHPadBB) { 6963 MachineFunction &MF = DAG.getMachineFunction(); 6964 MachineModuleInfo &MMI = MF.getMMI(); 6965 MCSymbol *BeginLabel = nullptr; 6966 6967 if (EHPadBB) { 6968 // Insert a label before the invoke call to mark the try range. This can be 6969 // used to detect deletion of the invoke via the MachineModuleInfo. 6970 BeginLabel = MMI.getContext().createTempSymbol(); 6971 6972 // For SjLj, keep track of which landing pads go with which invokes 6973 // so as to maintain the ordering of pads in the LSDA. 6974 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6975 if (CallSiteIndex) { 6976 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6977 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6978 6979 // Now that the call site is handled, stop tracking it. 6980 MMI.setCurrentCallSite(0); 6981 } 6982 6983 // Both PendingLoads and PendingExports must be flushed here; 6984 // this call might not return. 6985 (void)getRoot(); 6986 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6987 6988 CLI.setChain(getRoot()); 6989 } 6990 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6991 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6992 6993 assert((CLI.IsTailCall || Result.second.getNode()) && 6994 "Non-null chain expected with non-tail call!"); 6995 assert((Result.second.getNode() || !Result.first.getNode()) && 6996 "Null value expected with tail call!"); 6997 6998 if (!Result.second.getNode()) { 6999 // As a special case, a null chain means that a tail call has been emitted 7000 // and the DAG root is already updated. 7001 HasTailCall = true; 7002 7003 // Since there's no actual continuation from this block, nothing can be 7004 // relying on us setting vregs for them. 7005 PendingExports.clear(); 7006 } else { 7007 DAG.setRoot(Result.second); 7008 } 7009 7010 if (EHPadBB) { 7011 // Insert a label at the end of the invoke call to mark the try range. This 7012 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7013 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7014 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7015 7016 // Inform MachineModuleInfo of range. 7017 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7018 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7019 // actually use outlined funclets and their LSDA info style. 7020 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7021 assert(CLI.CB); 7022 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7023 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel); 7024 } else if (!isScopedEHPersonality(Pers)) { 7025 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7026 } 7027 } 7028 7029 return Result; 7030 } 7031 7032 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7033 bool isTailCall, 7034 const BasicBlock *EHPadBB) { 7035 auto &DL = DAG.getDataLayout(); 7036 FunctionType *FTy = CB.getFunctionType(); 7037 Type *RetTy = CB.getType(); 7038 7039 TargetLowering::ArgListTy Args; 7040 Args.reserve(CB.arg_size()); 7041 7042 const Value *SwiftErrorVal = nullptr; 7043 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7044 7045 if (isTailCall) { 7046 // Avoid emitting tail calls in functions with the disable-tail-calls 7047 // attribute. 7048 auto *Caller = CB.getParent()->getParent(); 7049 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7050 "true") 7051 isTailCall = false; 7052 7053 // We can't tail call inside a function with a swifterror argument. Lowering 7054 // does not support this yet. It would have to move into the swifterror 7055 // register before the call. 7056 if (TLI.supportSwiftError() && 7057 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7058 isTailCall = false; 7059 } 7060 7061 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7062 TargetLowering::ArgListEntry Entry; 7063 const Value *V = *I; 7064 7065 // Skip empty types 7066 if (V->getType()->isEmptyTy()) 7067 continue; 7068 7069 SDValue ArgNode = getValue(V); 7070 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7071 7072 Entry.setAttributes(&CB, I - CB.arg_begin()); 7073 7074 // Use swifterror virtual register as input to the call. 7075 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7076 SwiftErrorVal = V; 7077 // We find the virtual register for the actual swifterror argument. 7078 // Instead of using the Value, we use the virtual register instead. 7079 Entry.Node = 7080 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7081 EVT(TLI.getPointerTy(DL))); 7082 } 7083 7084 Args.push_back(Entry); 7085 7086 // If we have an explicit sret argument that is an Instruction, (i.e., it 7087 // might point to function-local memory), we can't meaningfully tail-call. 7088 if (Entry.IsSRet && isa<Instruction>(V)) 7089 isTailCall = false; 7090 } 7091 7092 // If call site has a cfguardtarget operand bundle, create and add an 7093 // additional ArgListEntry. 7094 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7095 TargetLowering::ArgListEntry Entry; 7096 Value *V = Bundle->Inputs[0]; 7097 SDValue ArgNode = getValue(V); 7098 Entry.Node = ArgNode; 7099 Entry.Ty = V->getType(); 7100 Entry.IsCFGuardTarget = true; 7101 Args.push_back(Entry); 7102 } 7103 7104 // Check if target-independent constraints permit a tail call here. 7105 // Target-dependent constraints are checked within TLI->LowerCallTo. 7106 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7107 isTailCall = false; 7108 7109 // Disable tail calls if there is an swifterror argument. Targets have not 7110 // been updated to support tail calls. 7111 if (TLI.supportSwiftError() && SwiftErrorVal) 7112 isTailCall = false; 7113 7114 TargetLowering::CallLoweringInfo CLI(DAG); 7115 CLI.setDebugLoc(getCurSDLoc()) 7116 .setChain(getRoot()) 7117 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7118 .setTailCall(isTailCall) 7119 .setConvergent(CB.isConvergent()); 7120 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7121 7122 if (Result.first.getNode()) { 7123 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7124 setValue(&CB, Result.first); 7125 } 7126 7127 // The last element of CLI.InVals has the SDValue for swifterror return. 7128 // Here we copy it to a virtual register and update SwiftErrorMap for 7129 // book-keeping. 7130 if (SwiftErrorVal && TLI.supportSwiftError()) { 7131 // Get the last element of InVals. 7132 SDValue Src = CLI.InVals.back(); 7133 Register VReg = 7134 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7135 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7136 DAG.setRoot(CopyNode); 7137 } 7138 } 7139 7140 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7141 SelectionDAGBuilder &Builder) { 7142 // Check to see if this load can be trivially constant folded, e.g. if the 7143 // input is from a string literal. 7144 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7145 // Cast pointer to the type we really want to load. 7146 Type *LoadTy = 7147 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7148 if (LoadVT.isVector()) 7149 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7150 7151 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7152 PointerType::getUnqual(LoadTy)); 7153 7154 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7155 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7156 return Builder.getValue(LoadCst); 7157 } 7158 7159 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7160 // still constant memory, the input chain can be the entry node. 7161 SDValue Root; 7162 bool ConstantMemory = false; 7163 7164 // Do not serialize (non-volatile) loads of constant memory with anything. 7165 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7166 Root = Builder.DAG.getEntryNode(); 7167 ConstantMemory = true; 7168 } else { 7169 // Do not serialize non-volatile loads against each other. 7170 Root = Builder.DAG.getRoot(); 7171 } 7172 7173 SDValue Ptr = Builder.getValue(PtrVal); 7174 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7175 Ptr, MachinePointerInfo(PtrVal), 7176 /* Alignment = */ 1); 7177 7178 if (!ConstantMemory) 7179 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7180 return LoadVal; 7181 } 7182 7183 /// Record the value for an instruction that produces an integer result, 7184 /// converting the type where necessary. 7185 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7186 SDValue Value, 7187 bool IsSigned) { 7188 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7189 I.getType(), true); 7190 if (IsSigned) 7191 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7192 else 7193 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7194 setValue(&I, Value); 7195 } 7196 7197 /// See if we can lower a memcmp call into an optimized form. If so, return 7198 /// true and lower it. Otherwise return false, and it will be lowered like a 7199 /// normal call. 7200 /// The caller already checked that \p I calls the appropriate LibFunc with a 7201 /// correct prototype. 7202 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7203 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7204 const Value *Size = I.getArgOperand(2); 7205 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7206 if (CSize && CSize->getZExtValue() == 0) { 7207 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7208 I.getType(), true); 7209 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7210 return true; 7211 } 7212 7213 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7214 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7215 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7216 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7217 if (Res.first.getNode()) { 7218 processIntegerCallValue(I, Res.first, true); 7219 PendingLoads.push_back(Res.second); 7220 return true; 7221 } 7222 7223 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7224 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7225 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7226 return false; 7227 7228 // If the target has a fast compare for the given size, it will return a 7229 // preferred load type for that size. Require that the load VT is legal and 7230 // that the target supports unaligned loads of that type. Otherwise, return 7231 // INVALID. 7232 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7233 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7234 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7235 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7236 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7237 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7238 // TODO: Check alignment of src and dest ptrs. 7239 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7240 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7241 if (!TLI.isTypeLegal(LVT) || 7242 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7243 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7244 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7245 } 7246 7247 return LVT; 7248 }; 7249 7250 // This turns into unaligned loads. We only do this if the target natively 7251 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7252 // we'll only produce a small number of byte loads. 7253 MVT LoadVT; 7254 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7255 switch (NumBitsToCompare) { 7256 default: 7257 return false; 7258 case 16: 7259 LoadVT = MVT::i16; 7260 break; 7261 case 32: 7262 LoadVT = MVT::i32; 7263 break; 7264 case 64: 7265 case 128: 7266 case 256: 7267 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7268 break; 7269 } 7270 7271 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7272 return false; 7273 7274 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7275 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7276 7277 // Bitcast to a wide integer type if the loads are vectors. 7278 if (LoadVT.isVector()) { 7279 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7280 LoadL = DAG.getBitcast(CmpVT, LoadL); 7281 LoadR = DAG.getBitcast(CmpVT, LoadR); 7282 } 7283 7284 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7285 processIntegerCallValue(I, Cmp, false); 7286 return true; 7287 } 7288 7289 /// See if we can lower a memchr call into an optimized form. If so, return 7290 /// true and lower it. Otherwise return false, and it will be lowered like a 7291 /// normal call. 7292 /// The caller already checked that \p I calls the appropriate LibFunc with a 7293 /// correct prototype. 7294 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7295 const Value *Src = I.getArgOperand(0); 7296 const Value *Char = I.getArgOperand(1); 7297 const Value *Length = I.getArgOperand(2); 7298 7299 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7300 std::pair<SDValue, SDValue> Res = 7301 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7302 getValue(Src), getValue(Char), getValue(Length), 7303 MachinePointerInfo(Src)); 7304 if (Res.first.getNode()) { 7305 setValue(&I, Res.first); 7306 PendingLoads.push_back(Res.second); 7307 return true; 7308 } 7309 7310 return false; 7311 } 7312 7313 /// See if we can lower a mempcpy call into an optimized form. If so, return 7314 /// true and lower it. Otherwise return false, and it will be lowered like a 7315 /// normal call. 7316 /// The caller already checked that \p I calls the appropriate LibFunc with a 7317 /// correct prototype. 7318 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7319 SDValue Dst = getValue(I.getArgOperand(0)); 7320 SDValue Src = getValue(I.getArgOperand(1)); 7321 SDValue Size = getValue(I.getArgOperand(2)); 7322 7323 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7324 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7325 // DAG::getMemcpy needs Alignment to be defined. 7326 Align Alignment = std::min(DstAlign, SrcAlign); 7327 7328 bool isVol = false; 7329 SDLoc sdl = getCurSDLoc(); 7330 7331 // In the mempcpy context we need to pass in a false value for isTailCall 7332 // because the return pointer needs to be adjusted by the size of 7333 // the copied memory. 7334 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7335 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7336 /*isTailCall=*/false, 7337 MachinePointerInfo(I.getArgOperand(0)), 7338 MachinePointerInfo(I.getArgOperand(1))); 7339 assert(MC.getNode() != nullptr && 7340 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7341 DAG.setRoot(MC); 7342 7343 // Check if Size needs to be truncated or extended. 7344 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7345 7346 // Adjust return pointer to point just past the last dst byte. 7347 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7348 Dst, Size); 7349 setValue(&I, DstPlusSize); 7350 return true; 7351 } 7352 7353 /// See if we can lower a strcpy call into an optimized form. If so, return 7354 /// true and lower it, otherwise return false and it will be lowered like a 7355 /// normal call. 7356 /// The caller already checked that \p I calls the appropriate LibFunc with a 7357 /// correct prototype. 7358 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7359 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7360 7361 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7362 std::pair<SDValue, SDValue> Res = 7363 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7364 getValue(Arg0), getValue(Arg1), 7365 MachinePointerInfo(Arg0), 7366 MachinePointerInfo(Arg1), isStpcpy); 7367 if (Res.first.getNode()) { 7368 setValue(&I, Res.first); 7369 DAG.setRoot(Res.second); 7370 return true; 7371 } 7372 7373 return false; 7374 } 7375 7376 /// See if we can lower a strcmp call into an optimized form. If so, return 7377 /// true and lower it, otherwise return false and it will be lowered like a 7378 /// normal call. 7379 /// The caller already checked that \p I calls the appropriate LibFunc with a 7380 /// correct prototype. 7381 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7382 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7383 7384 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7385 std::pair<SDValue, SDValue> Res = 7386 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7387 getValue(Arg0), getValue(Arg1), 7388 MachinePointerInfo(Arg0), 7389 MachinePointerInfo(Arg1)); 7390 if (Res.first.getNode()) { 7391 processIntegerCallValue(I, Res.first, true); 7392 PendingLoads.push_back(Res.second); 7393 return true; 7394 } 7395 7396 return false; 7397 } 7398 7399 /// See if we can lower a strlen call into an optimized form. If so, return 7400 /// true and lower it, otherwise return false and it will be lowered like a 7401 /// normal call. 7402 /// The caller already checked that \p I calls the appropriate LibFunc with a 7403 /// correct prototype. 7404 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7405 const Value *Arg0 = I.getArgOperand(0); 7406 7407 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7408 std::pair<SDValue, SDValue> Res = 7409 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7410 getValue(Arg0), MachinePointerInfo(Arg0)); 7411 if (Res.first.getNode()) { 7412 processIntegerCallValue(I, Res.first, false); 7413 PendingLoads.push_back(Res.second); 7414 return true; 7415 } 7416 7417 return false; 7418 } 7419 7420 /// See if we can lower a strnlen call into an optimized form. If so, return 7421 /// true and lower it, otherwise return false and it will be lowered like a 7422 /// normal call. 7423 /// The caller already checked that \p I calls the appropriate LibFunc with a 7424 /// correct prototype. 7425 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7426 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7427 7428 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7429 std::pair<SDValue, SDValue> Res = 7430 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7431 getValue(Arg0), getValue(Arg1), 7432 MachinePointerInfo(Arg0)); 7433 if (Res.first.getNode()) { 7434 processIntegerCallValue(I, Res.first, false); 7435 PendingLoads.push_back(Res.second); 7436 return true; 7437 } 7438 7439 return false; 7440 } 7441 7442 /// See if we can lower a unary floating-point operation into an SDNode with 7443 /// the specified Opcode. If so, return true and lower it, otherwise return 7444 /// false and it will be lowered like a normal call. 7445 /// The caller already checked that \p I calls the appropriate LibFunc with a 7446 /// correct prototype. 7447 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7448 unsigned Opcode) { 7449 // We already checked this call's prototype; verify it doesn't modify errno. 7450 if (!I.onlyReadsMemory()) 7451 return false; 7452 7453 SDValue Tmp = getValue(I.getArgOperand(0)); 7454 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7455 return true; 7456 } 7457 7458 /// See if we can lower a binary floating-point operation into an SDNode with 7459 /// the specified Opcode. If so, return true and lower it. Otherwise return 7460 /// false, and it will be lowered like a normal call. 7461 /// The caller already checked that \p I calls the appropriate LibFunc with a 7462 /// correct prototype. 7463 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7464 unsigned Opcode) { 7465 // We already checked this call's prototype; verify it doesn't modify errno. 7466 if (!I.onlyReadsMemory()) 7467 return false; 7468 7469 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7470 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7471 EVT VT = Tmp0.getValueType(); 7472 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7473 return true; 7474 } 7475 7476 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7477 // Handle inline assembly differently. 7478 if (I.isInlineAsm()) { 7479 visitInlineAsm(I); 7480 return; 7481 } 7482 7483 if (Function *F = I.getCalledFunction()) { 7484 if (F->isDeclaration()) { 7485 // Is this an LLVM intrinsic or a target-specific intrinsic? 7486 unsigned IID = F->getIntrinsicID(); 7487 if (!IID) 7488 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7489 IID = II->getIntrinsicID(F); 7490 7491 if (IID) { 7492 visitIntrinsicCall(I, IID); 7493 return; 7494 } 7495 } 7496 7497 // Check for well-known libc/libm calls. If the function is internal, it 7498 // can't be a library call. Don't do the check if marked as nobuiltin for 7499 // some reason or the call site requires strict floating point semantics. 7500 LibFunc Func; 7501 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7502 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7503 LibInfo->hasOptimizedCodeGen(Func)) { 7504 switch (Func) { 7505 default: break; 7506 case LibFunc_copysign: 7507 case LibFunc_copysignf: 7508 case LibFunc_copysignl: 7509 // We already checked this call's prototype; verify it doesn't modify 7510 // errno. 7511 if (I.onlyReadsMemory()) { 7512 SDValue LHS = getValue(I.getArgOperand(0)); 7513 SDValue RHS = getValue(I.getArgOperand(1)); 7514 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7515 LHS.getValueType(), LHS, RHS)); 7516 return; 7517 } 7518 break; 7519 case LibFunc_fabs: 7520 case LibFunc_fabsf: 7521 case LibFunc_fabsl: 7522 if (visitUnaryFloatCall(I, ISD::FABS)) 7523 return; 7524 break; 7525 case LibFunc_fmin: 7526 case LibFunc_fminf: 7527 case LibFunc_fminl: 7528 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7529 return; 7530 break; 7531 case LibFunc_fmax: 7532 case LibFunc_fmaxf: 7533 case LibFunc_fmaxl: 7534 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7535 return; 7536 break; 7537 case LibFunc_sin: 7538 case LibFunc_sinf: 7539 case LibFunc_sinl: 7540 if (visitUnaryFloatCall(I, ISD::FSIN)) 7541 return; 7542 break; 7543 case LibFunc_cos: 7544 case LibFunc_cosf: 7545 case LibFunc_cosl: 7546 if (visitUnaryFloatCall(I, ISD::FCOS)) 7547 return; 7548 break; 7549 case LibFunc_sqrt: 7550 case LibFunc_sqrtf: 7551 case LibFunc_sqrtl: 7552 case LibFunc_sqrt_finite: 7553 case LibFunc_sqrtf_finite: 7554 case LibFunc_sqrtl_finite: 7555 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7556 return; 7557 break; 7558 case LibFunc_floor: 7559 case LibFunc_floorf: 7560 case LibFunc_floorl: 7561 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7562 return; 7563 break; 7564 case LibFunc_nearbyint: 7565 case LibFunc_nearbyintf: 7566 case LibFunc_nearbyintl: 7567 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7568 return; 7569 break; 7570 case LibFunc_ceil: 7571 case LibFunc_ceilf: 7572 case LibFunc_ceill: 7573 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7574 return; 7575 break; 7576 case LibFunc_rint: 7577 case LibFunc_rintf: 7578 case LibFunc_rintl: 7579 if (visitUnaryFloatCall(I, ISD::FRINT)) 7580 return; 7581 break; 7582 case LibFunc_round: 7583 case LibFunc_roundf: 7584 case LibFunc_roundl: 7585 if (visitUnaryFloatCall(I, ISD::FROUND)) 7586 return; 7587 break; 7588 case LibFunc_trunc: 7589 case LibFunc_truncf: 7590 case LibFunc_truncl: 7591 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7592 return; 7593 break; 7594 case LibFunc_log2: 7595 case LibFunc_log2f: 7596 case LibFunc_log2l: 7597 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7598 return; 7599 break; 7600 case LibFunc_exp2: 7601 case LibFunc_exp2f: 7602 case LibFunc_exp2l: 7603 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7604 return; 7605 break; 7606 case LibFunc_memcmp: 7607 if (visitMemCmpCall(I)) 7608 return; 7609 break; 7610 case LibFunc_mempcpy: 7611 if (visitMemPCpyCall(I)) 7612 return; 7613 break; 7614 case LibFunc_memchr: 7615 if (visitMemChrCall(I)) 7616 return; 7617 break; 7618 case LibFunc_strcpy: 7619 if (visitStrCpyCall(I, false)) 7620 return; 7621 break; 7622 case LibFunc_stpcpy: 7623 if (visitStrCpyCall(I, true)) 7624 return; 7625 break; 7626 case LibFunc_strcmp: 7627 if (visitStrCmpCall(I)) 7628 return; 7629 break; 7630 case LibFunc_strlen: 7631 if (visitStrLenCall(I)) 7632 return; 7633 break; 7634 case LibFunc_strnlen: 7635 if (visitStrNLenCall(I)) 7636 return; 7637 break; 7638 } 7639 } 7640 } 7641 7642 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7643 // have to do anything here to lower funclet bundles. 7644 // CFGuardTarget bundles are lowered in LowerCallTo. 7645 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 7646 LLVMContext::OB_funclet, 7647 LLVMContext::OB_cfguardtarget}) && 7648 "Cannot lower calls with arbitrary operand bundles!"); 7649 7650 SDValue Callee = getValue(I.getCalledOperand()); 7651 7652 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7653 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7654 else 7655 // Check if we can potentially perform a tail call. More detailed checking 7656 // is be done within LowerCallTo, after more information about the call is 7657 // known. 7658 LowerCallTo(I, Callee, I.isTailCall()); 7659 } 7660 7661 namespace { 7662 7663 /// AsmOperandInfo - This contains information for each constraint that we are 7664 /// lowering. 7665 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7666 public: 7667 /// CallOperand - If this is the result output operand or a clobber 7668 /// this is null, otherwise it is the incoming operand to the CallInst. 7669 /// This gets modified as the asm is processed. 7670 SDValue CallOperand; 7671 7672 /// AssignedRegs - If this is a register or register class operand, this 7673 /// contains the set of register corresponding to the operand. 7674 RegsForValue AssignedRegs; 7675 7676 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7677 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7678 } 7679 7680 /// Whether or not this operand accesses memory 7681 bool hasMemory(const TargetLowering &TLI) const { 7682 // Indirect operand accesses access memory. 7683 if (isIndirect) 7684 return true; 7685 7686 for (const auto &Code : Codes) 7687 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7688 return true; 7689 7690 return false; 7691 } 7692 7693 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7694 /// corresponds to. If there is no Value* for this operand, it returns 7695 /// MVT::Other. 7696 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7697 const DataLayout &DL) const { 7698 if (!CallOperandVal) return MVT::Other; 7699 7700 if (isa<BasicBlock>(CallOperandVal)) 7701 return TLI.getProgramPointerTy(DL); 7702 7703 llvm::Type *OpTy = CallOperandVal->getType(); 7704 7705 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7706 // If this is an indirect operand, the operand is a pointer to the 7707 // accessed type. 7708 if (isIndirect) { 7709 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7710 if (!PtrTy) 7711 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7712 OpTy = PtrTy->getElementType(); 7713 } 7714 7715 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7716 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7717 if (STy->getNumElements() == 1) 7718 OpTy = STy->getElementType(0); 7719 7720 // If OpTy is not a single value, it may be a struct/union that we 7721 // can tile with integers. 7722 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7723 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7724 switch (BitSize) { 7725 default: break; 7726 case 1: 7727 case 8: 7728 case 16: 7729 case 32: 7730 case 64: 7731 case 128: 7732 OpTy = IntegerType::get(Context, BitSize); 7733 break; 7734 } 7735 } 7736 7737 return TLI.getValueType(DL, OpTy, true); 7738 } 7739 }; 7740 7741 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7742 7743 } // end anonymous namespace 7744 7745 /// Make sure that the output operand \p OpInfo and its corresponding input 7746 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7747 /// out). 7748 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7749 SDISelAsmOperandInfo &MatchingOpInfo, 7750 SelectionDAG &DAG) { 7751 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7752 return; 7753 7754 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7755 const auto &TLI = DAG.getTargetLoweringInfo(); 7756 7757 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7758 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7759 OpInfo.ConstraintVT); 7760 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7761 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7762 MatchingOpInfo.ConstraintVT); 7763 if ((OpInfo.ConstraintVT.isInteger() != 7764 MatchingOpInfo.ConstraintVT.isInteger()) || 7765 (MatchRC.second != InputRC.second)) { 7766 // FIXME: error out in a more elegant fashion 7767 report_fatal_error("Unsupported asm: input constraint" 7768 " with a matching output constraint of" 7769 " incompatible type!"); 7770 } 7771 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7772 } 7773 7774 /// Get a direct memory input to behave well as an indirect operand. 7775 /// This may introduce stores, hence the need for a \p Chain. 7776 /// \return The (possibly updated) chain. 7777 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7778 SDISelAsmOperandInfo &OpInfo, 7779 SelectionDAG &DAG) { 7780 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7781 7782 // If we don't have an indirect input, put it in the constpool if we can, 7783 // otherwise spill it to a stack slot. 7784 // TODO: This isn't quite right. We need to handle these according to 7785 // the addressing mode that the constraint wants. Also, this may take 7786 // an additional register for the computation and we don't want that 7787 // either. 7788 7789 // If the operand is a float, integer, or vector constant, spill to a 7790 // constant pool entry to get its address. 7791 const Value *OpVal = OpInfo.CallOperandVal; 7792 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7793 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7794 OpInfo.CallOperand = DAG.getConstantPool( 7795 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7796 return Chain; 7797 } 7798 7799 // Otherwise, create a stack slot and emit a store to it before the asm. 7800 Type *Ty = OpVal->getType(); 7801 auto &DL = DAG.getDataLayout(); 7802 uint64_t TySize = DL.getTypeAllocSize(Ty); 7803 unsigned Align = DL.getPrefTypeAlignment(Ty); 7804 MachineFunction &MF = DAG.getMachineFunction(); 7805 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7806 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7807 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7808 MachinePointerInfo::getFixedStack(MF, SSFI), 7809 TLI.getMemValueType(DL, Ty)); 7810 OpInfo.CallOperand = StackSlot; 7811 7812 return Chain; 7813 } 7814 7815 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7816 /// specified operand. We prefer to assign virtual registers, to allow the 7817 /// register allocator to handle the assignment process. However, if the asm 7818 /// uses features that we can't model on machineinstrs, we have SDISel do the 7819 /// allocation. This produces generally horrible, but correct, code. 7820 /// 7821 /// OpInfo describes the operand 7822 /// RefOpInfo describes the matching operand if any, the operand otherwise 7823 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7824 SDISelAsmOperandInfo &OpInfo, 7825 SDISelAsmOperandInfo &RefOpInfo) { 7826 LLVMContext &Context = *DAG.getContext(); 7827 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7828 7829 MachineFunction &MF = DAG.getMachineFunction(); 7830 SmallVector<unsigned, 4> Regs; 7831 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7832 7833 // No work to do for memory operations. 7834 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7835 return; 7836 7837 // If this is a constraint for a single physreg, or a constraint for a 7838 // register class, find it. 7839 unsigned AssignedReg; 7840 const TargetRegisterClass *RC; 7841 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7842 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7843 // RC is unset only on failure. Return immediately. 7844 if (!RC) 7845 return; 7846 7847 // Get the actual register value type. This is important, because the user 7848 // may have asked for (e.g.) the AX register in i32 type. We need to 7849 // remember that AX is actually i16 to get the right extension. 7850 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7851 7852 if (OpInfo.ConstraintVT != MVT::Other) { 7853 // If this is an FP operand in an integer register (or visa versa), or more 7854 // generally if the operand value disagrees with the register class we plan 7855 // to stick it in, fix the operand type. 7856 // 7857 // If this is an input value, the bitcast to the new type is done now. 7858 // Bitcast for output value is done at the end of visitInlineAsm(). 7859 if ((OpInfo.Type == InlineAsm::isOutput || 7860 OpInfo.Type == InlineAsm::isInput) && 7861 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7862 // Try to convert to the first EVT that the reg class contains. If the 7863 // types are identical size, use a bitcast to convert (e.g. two differing 7864 // vector types). Note: output bitcast is done at the end of 7865 // visitInlineAsm(). 7866 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7867 // Exclude indirect inputs while they are unsupported because the code 7868 // to perform the load is missing and thus OpInfo.CallOperand still 7869 // refers to the input address rather than the pointed-to value. 7870 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7871 OpInfo.CallOperand = 7872 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7873 OpInfo.ConstraintVT = RegVT; 7874 // If the operand is an FP value and we want it in integer registers, 7875 // use the corresponding integer type. This turns an f64 value into 7876 // i64, which can be passed with two i32 values on a 32-bit machine. 7877 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7878 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7879 if (OpInfo.Type == InlineAsm::isInput) 7880 OpInfo.CallOperand = 7881 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7882 OpInfo.ConstraintVT = VT; 7883 } 7884 } 7885 } 7886 7887 // No need to allocate a matching input constraint since the constraint it's 7888 // matching to has already been allocated. 7889 if (OpInfo.isMatchingInputConstraint()) 7890 return; 7891 7892 EVT ValueVT = OpInfo.ConstraintVT; 7893 if (OpInfo.ConstraintVT == MVT::Other) 7894 ValueVT = RegVT; 7895 7896 // Initialize NumRegs. 7897 unsigned NumRegs = 1; 7898 if (OpInfo.ConstraintVT != MVT::Other) 7899 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7900 7901 // If this is a constraint for a specific physical register, like {r17}, 7902 // assign it now. 7903 7904 // If this associated to a specific register, initialize iterator to correct 7905 // place. If virtual, make sure we have enough registers 7906 7907 // Initialize iterator if necessary 7908 TargetRegisterClass::iterator I = RC->begin(); 7909 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7910 7911 // Do not check for single registers. 7912 if (AssignedReg) { 7913 for (; *I != AssignedReg; ++I) 7914 assert(I != RC->end() && "AssignedReg should be member of RC"); 7915 } 7916 7917 for (; NumRegs; --NumRegs, ++I) { 7918 assert(I != RC->end() && "Ran out of registers to allocate!"); 7919 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 7920 Regs.push_back(R); 7921 } 7922 7923 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7924 } 7925 7926 static unsigned 7927 findMatchingInlineAsmOperand(unsigned OperandNo, 7928 const std::vector<SDValue> &AsmNodeOperands) { 7929 // Scan until we find the definition we already emitted of this operand. 7930 unsigned CurOp = InlineAsm::Op_FirstOperand; 7931 for (; OperandNo; --OperandNo) { 7932 // Advance to the next operand. 7933 unsigned OpFlag = 7934 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7935 assert((InlineAsm::isRegDefKind(OpFlag) || 7936 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7937 InlineAsm::isMemKind(OpFlag)) && 7938 "Skipped past definitions?"); 7939 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7940 } 7941 return CurOp; 7942 } 7943 7944 namespace { 7945 7946 class ExtraFlags { 7947 unsigned Flags = 0; 7948 7949 public: 7950 explicit ExtraFlags(const CallBase &Call) { 7951 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 7952 if (IA->hasSideEffects()) 7953 Flags |= InlineAsm::Extra_HasSideEffects; 7954 if (IA->isAlignStack()) 7955 Flags |= InlineAsm::Extra_IsAlignStack; 7956 if (Call.isConvergent()) 7957 Flags |= InlineAsm::Extra_IsConvergent; 7958 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7959 } 7960 7961 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7962 // Ideally, we would only check against memory constraints. However, the 7963 // meaning of an Other constraint can be target-specific and we can't easily 7964 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7965 // for Other constraints as well. 7966 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7967 OpInfo.ConstraintType == TargetLowering::C_Other) { 7968 if (OpInfo.Type == InlineAsm::isInput) 7969 Flags |= InlineAsm::Extra_MayLoad; 7970 else if (OpInfo.Type == InlineAsm::isOutput) 7971 Flags |= InlineAsm::Extra_MayStore; 7972 else if (OpInfo.Type == InlineAsm::isClobber) 7973 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7974 } 7975 } 7976 7977 unsigned get() const { return Flags; } 7978 }; 7979 7980 } // end anonymous namespace 7981 7982 /// visitInlineAsm - Handle a call to an InlineAsm object. 7983 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 7984 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 7985 7986 /// ConstraintOperands - Information about all of the constraints. 7987 SDISelAsmOperandInfoVector ConstraintOperands; 7988 7989 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7990 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7991 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 7992 7993 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7994 // AsmDialect, MayLoad, MayStore). 7995 bool HasSideEffect = IA->hasSideEffects(); 7996 ExtraFlags ExtraInfo(Call); 7997 7998 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7999 unsigned ResNo = 0; // ResNo - The result number of the next output. 8000 unsigned NumMatchingOps = 0; 8001 for (auto &T : TargetConstraints) { 8002 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8003 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8004 8005 // Compute the value type for each operand. 8006 if (OpInfo.Type == InlineAsm::isInput || 8007 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8008 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8009 8010 // Process the call argument. BasicBlocks are labels, currently appearing 8011 // only in asm's. 8012 if (isa<CallBrInst>(Call) && 8013 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8014 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8015 NumMatchingOps) && 8016 (NumMatchingOps == 0 || 8017 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8018 NumMatchingOps))) { 8019 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8020 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8021 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8022 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8023 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8024 } else { 8025 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8026 } 8027 8028 OpInfo.ConstraintVT = 8029 OpInfo 8030 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8031 .getSimpleVT(); 8032 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8033 // The return value of the call is this value. As such, there is no 8034 // corresponding argument. 8035 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8036 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8037 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8038 DAG.getDataLayout(), STy->getElementType(ResNo)); 8039 } else { 8040 assert(ResNo == 0 && "Asm only has one result!"); 8041 OpInfo.ConstraintVT = 8042 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8043 } 8044 ++ResNo; 8045 } else { 8046 OpInfo.ConstraintVT = MVT::Other; 8047 } 8048 8049 if (OpInfo.hasMatchingInput()) 8050 ++NumMatchingOps; 8051 8052 if (!HasSideEffect) 8053 HasSideEffect = OpInfo.hasMemory(TLI); 8054 8055 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8056 // FIXME: Could we compute this on OpInfo rather than T? 8057 8058 // Compute the constraint code and ConstraintType to use. 8059 TLI.ComputeConstraintToUse(T, SDValue()); 8060 8061 if (T.ConstraintType == TargetLowering::C_Immediate && 8062 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8063 // We've delayed emitting a diagnostic like the "n" constraint because 8064 // inlining could cause an integer showing up. 8065 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8066 "' expects an integer constant " 8067 "expression"); 8068 8069 ExtraInfo.update(T); 8070 } 8071 8072 8073 // We won't need to flush pending loads if this asm doesn't touch 8074 // memory and is nonvolatile. 8075 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8076 8077 bool IsCallBr = isa<CallBrInst>(Call); 8078 if (IsCallBr) { 8079 // If this is a callbr we need to flush pending exports since inlineasm_br 8080 // is a terminator. We need to do this before nodes are glued to 8081 // the inlineasm_br node. 8082 Chain = getControlRoot(); 8083 } 8084 8085 // Second pass over the constraints: compute which constraint option to use. 8086 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8087 // If this is an output operand with a matching input operand, look up the 8088 // matching input. If their types mismatch, e.g. one is an integer, the 8089 // other is floating point, or their sizes are different, flag it as an 8090 // error. 8091 if (OpInfo.hasMatchingInput()) { 8092 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8093 patchMatchingInput(OpInfo, Input, DAG); 8094 } 8095 8096 // Compute the constraint code and ConstraintType to use. 8097 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8098 8099 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8100 OpInfo.Type == InlineAsm::isClobber) 8101 continue; 8102 8103 // If this is a memory input, and if the operand is not indirect, do what we 8104 // need to provide an address for the memory input. 8105 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8106 !OpInfo.isIndirect) { 8107 assert((OpInfo.isMultipleAlternative || 8108 (OpInfo.Type == InlineAsm::isInput)) && 8109 "Can only indirectify direct input operands!"); 8110 8111 // Memory operands really want the address of the value. 8112 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8113 8114 // There is no longer a Value* corresponding to this operand. 8115 OpInfo.CallOperandVal = nullptr; 8116 8117 // It is now an indirect operand. 8118 OpInfo.isIndirect = true; 8119 } 8120 8121 } 8122 8123 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8124 std::vector<SDValue> AsmNodeOperands; 8125 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8126 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8127 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8128 8129 // If we have a !srcloc metadata node associated with it, we want to attach 8130 // this to the ultimately generated inline asm machineinstr. To do this, we 8131 // pass in the third operand as this (potentially null) inline asm MDNode. 8132 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8133 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8134 8135 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8136 // bits as operand 3. 8137 AsmNodeOperands.push_back(DAG.getTargetConstant( 8138 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8139 8140 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8141 // this, assign virtual and physical registers for inputs and otput. 8142 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8143 // Assign Registers. 8144 SDISelAsmOperandInfo &RefOpInfo = 8145 OpInfo.isMatchingInputConstraint() 8146 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8147 : OpInfo; 8148 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8149 8150 auto DetectWriteToReservedRegister = [&]() { 8151 const MachineFunction &MF = DAG.getMachineFunction(); 8152 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8153 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8154 if (Register::isPhysicalRegister(Reg) && 8155 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8156 const char *RegName = TRI.getName(Reg); 8157 emitInlineAsmError(Call, "write to reserved register '" + 8158 Twine(RegName) + "'"); 8159 return true; 8160 } 8161 } 8162 return false; 8163 }; 8164 8165 switch (OpInfo.Type) { 8166 case InlineAsm::isOutput: 8167 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8168 unsigned ConstraintID = 8169 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8170 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8171 "Failed to convert memory constraint code to constraint id."); 8172 8173 // Add information to the INLINEASM node to know about this output. 8174 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8175 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8176 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8177 MVT::i32)); 8178 AsmNodeOperands.push_back(OpInfo.CallOperand); 8179 } else { 8180 // Otherwise, this outputs to a register (directly for C_Register / 8181 // C_RegisterClass, and a target-defined fashion for 8182 // C_Immediate/C_Other). Find a register that we can use. 8183 if (OpInfo.AssignedRegs.Regs.empty()) { 8184 emitInlineAsmError( 8185 Call, "couldn't allocate output register for constraint '" + 8186 Twine(OpInfo.ConstraintCode) + "'"); 8187 return; 8188 } 8189 8190 if (DetectWriteToReservedRegister()) 8191 return; 8192 8193 // Add information to the INLINEASM node to know that this register is 8194 // set. 8195 OpInfo.AssignedRegs.AddInlineAsmOperands( 8196 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8197 : InlineAsm::Kind_RegDef, 8198 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8199 } 8200 break; 8201 8202 case InlineAsm::isInput: { 8203 SDValue InOperandVal = OpInfo.CallOperand; 8204 8205 if (OpInfo.isMatchingInputConstraint()) { 8206 // If this is required to match an output register we have already set, 8207 // just use its register. 8208 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8209 AsmNodeOperands); 8210 unsigned OpFlag = 8211 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8212 if (InlineAsm::isRegDefKind(OpFlag) || 8213 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8214 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8215 if (OpInfo.isIndirect) { 8216 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8217 emitInlineAsmError(Call, "inline asm not supported yet: " 8218 "don't know how to handle tied " 8219 "indirect register inputs"); 8220 return; 8221 } 8222 8223 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8224 SmallVector<unsigned, 4> Regs; 8225 8226 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8227 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8228 MachineRegisterInfo &RegInfo = 8229 DAG.getMachineFunction().getRegInfo(); 8230 for (unsigned i = 0; i != NumRegs; ++i) 8231 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8232 } else { 8233 emitInlineAsmError(Call, 8234 "inline asm error: This value type register " 8235 "class is not natively supported!"); 8236 return; 8237 } 8238 8239 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8240 8241 SDLoc dl = getCurSDLoc(); 8242 // Use the produced MatchedRegs object to 8243 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8244 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8245 true, OpInfo.getMatchedOperand(), dl, 8246 DAG, AsmNodeOperands); 8247 break; 8248 } 8249 8250 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8251 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8252 "Unexpected number of operands"); 8253 // Add information to the INLINEASM node to know about this input. 8254 // See InlineAsm.h isUseOperandTiedToDef. 8255 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8256 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8257 OpInfo.getMatchedOperand()); 8258 AsmNodeOperands.push_back(DAG.getTargetConstant( 8259 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8260 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8261 break; 8262 } 8263 8264 // Treat indirect 'X' constraint as memory. 8265 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8266 OpInfo.isIndirect) 8267 OpInfo.ConstraintType = TargetLowering::C_Memory; 8268 8269 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8270 OpInfo.ConstraintType == TargetLowering::C_Other) { 8271 std::vector<SDValue> Ops; 8272 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8273 Ops, DAG); 8274 if (Ops.empty()) { 8275 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8276 if (isa<ConstantSDNode>(InOperandVal)) { 8277 emitInlineAsmError(Call, "value out of range for constraint '" + 8278 Twine(OpInfo.ConstraintCode) + "'"); 8279 return; 8280 } 8281 8282 emitInlineAsmError(Call, 8283 "invalid operand for inline asm constraint '" + 8284 Twine(OpInfo.ConstraintCode) + "'"); 8285 return; 8286 } 8287 8288 // Add information to the INLINEASM node to know about this input. 8289 unsigned ResOpType = 8290 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8291 AsmNodeOperands.push_back(DAG.getTargetConstant( 8292 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8293 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8294 break; 8295 } 8296 8297 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8298 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8299 assert(InOperandVal.getValueType() == 8300 TLI.getPointerTy(DAG.getDataLayout()) && 8301 "Memory operands expect pointer values"); 8302 8303 unsigned ConstraintID = 8304 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8305 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8306 "Failed to convert memory constraint code to constraint id."); 8307 8308 // Add information to the INLINEASM node to know about this input. 8309 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8310 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8311 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8312 getCurSDLoc(), 8313 MVT::i32)); 8314 AsmNodeOperands.push_back(InOperandVal); 8315 break; 8316 } 8317 8318 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8319 OpInfo.ConstraintType == TargetLowering::C_Register) && 8320 "Unknown constraint type!"); 8321 8322 // TODO: Support this. 8323 if (OpInfo.isIndirect) { 8324 emitInlineAsmError( 8325 Call, "Don't know how to handle indirect register inputs yet " 8326 "for constraint '" + 8327 Twine(OpInfo.ConstraintCode) + "'"); 8328 return; 8329 } 8330 8331 // Copy the input into the appropriate registers. 8332 if (OpInfo.AssignedRegs.Regs.empty()) { 8333 emitInlineAsmError(Call, 8334 "couldn't allocate input reg for constraint '" + 8335 Twine(OpInfo.ConstraintCode) + "'"); 8336 return; 8337 } 8338 8339 if (DetectWriteToReservedRegister()) 8340 return; 8341 8342 SDLoc dl = getCurSDLoc(); 8343 8344 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8345 &Call); 8346 8347 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8348 dl, DAG, AsmNodeOperands); 8349 break; 8350 } 8351 case InlineAsm::isClobber: 8352 // Add the clobbered value to the operand list, so that the register 8353 // allocator is aware that the physreg got clobbered. 8354 if (!OpInfo.AssignedRegs.Regs.empty()) 8355 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8356 false, 0, getCurSDLoc(), DAG, 8357 AsmNodeOperands); 8358 break; 8359 } 8360 } 8361 8362 // Finish up input operands. Set the input chain and add the flag last. 8363 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8364 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8365 8366 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8367 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8368 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8369 Flag = Chain.getValue(1); 8370 8371 // Do additional work to generate outputs. 8372 8373 SmallVector<EVT, 1> ResultVTs; 8374 SmallVector<SDValue, 1> ResultValues; 8375 SmallVector<SDValue, 8> OutChains; 8376 8377 llvm::Type *CallResultType = Call.getType(); 8378 ArrayRef<Type *> ResultTypes; 8379 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8380 ResultTypes = StructResult->elements(); 8381 else if (!CallResultType->isVoidTy()) 8382 ResultTypes = makeArrayRef(CallResultType); 8383 8384 auto CurResultType = ResultTypes.begin(); 8385 auto handleRegAssign = [&](SDValue V) { 8386 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8387 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8388 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8389 ++CurResultType; 8390 // If the type of the inline asm call site return value is different but has 8391 // same size as the type of the asm output bitcast it. One example of this 8392 // is for vectors with different width / number of elements. This can 8393 // happen for register classes that can contain multiple different value 8394 // types. The preg or vreg allocated may not have the same VT as was 8395 // expected. 8396 // 8397 // This can also happen for a return value that disagrees with the register 8398 // class it is put in, eg. a double in a general-purpose register on a 8399 // 32-bit machine. 8400 if (ResultVT != V.getValueType() && 8401 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8402 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8403 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8404 V.getValueType().isInteger()) { 8405 // If a result value was tied to an input value, the computed result 8406 // may have a wider width than the expected result. Extract the 8407 // relevant portion. 8408 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8409 } 8410 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8411 ResultVTs.push_back(ResultVT); 8412 ResultValues.push_back(V); 8413 }; 8414 8415 // Deal with output operands. 8416 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8417 if (OpInfo.Type == InlineAsm::isOutput) { 8418 SDValue Val; 8419 // Skip trivial output operands. 8420 if (OpInfo.AssignedRegs.Regs.empty()) 8421 continue; 8422 8423 switch (OpInfo.ConstraintType) { 8424 case TargetLowering::C_Register: 8425 case TargetLowering::C_RegisterClass: 8426 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8427 Chain, &Flag, &Call); 8428 break; 8429 case TargetLowering::C_Immediate: 8430 case TargetLowering::C_Other: 8431 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8432 OpInfo, DAG); 8433 break; 8434 case TargetLowering::C_Memory: 8435 break; // Already handled. 8436 case TargetLowering::C_Unknown: 8437 assert(false && "Unexpected unknown constraint"); 8438 } 8439 8440 // Indirect output manifest as stores. Record output chains. 8441 if (OpInfo.isIndirect) { 8442 const Value *Ptr = OpInfo.CallOperandVal; 8443 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8444 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8445 MachinePointerInfo(Ptr)); 8446 OutChains.push_back(Store); 8447 } else { 8448 // generate CopyFromRegs to associated registers. 8449 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8450 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8451 for (const SDValue &V : Val->op_values()) 8452 handleRegAssign(V); 8453 } else 8454 handleRegAssign(Val); 8455 } 8456 } 8457 } 8458 8459 // Set results. 8460 if (!ResultValues.empty()) { 8461 assert(CurResultType == ResultTypes.end() && 8462 "Mismatch in number of ResultTypes"); 8463 assert(ResultValues.size() == ResultTypes.size() && 8464 "Mismatch in number of output operands in asm result"); 8465 8466 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8467 DAG.getVTList(ResultVTs), ResultValues); 8468 setValue(&Call, V); 8469 } 8470 8471 // Collect store chains. 8472 if (!OutChains.empty()) 8473 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8474 8475 // Only Update Root if inline assembly has a memory effect. 8476 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8477 DAG.setRoot(Chain); 8478 } 8479 8480 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8481 const Twine &Message) { 8482 LLVMContext &Ctx = *DAG.getContext(); 8483 Ctx.emitError(&Call, Message); 8484 8485 // Make sure we leave the DAG in a valid state 8486 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8487 SmallVector<EVT, 1> ValueVTs; 8488 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8489 8490 if (ValueVTs.empty()) 8491 return; 8492 8493 SmallVector<SDValue, 1> Ops; 8494 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8495 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8496 8497 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8498 } 8499 8500 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8501 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8502 MVT::Other, getRoot(), 8503 getValue(I.getArgOperand(0)), 8504 DAG.getSrcValue(I.getArgOperand(0)))); 8505 } 8506 8507 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8509 const DataLayout &DL = DAG.getDataLayout(); 8510 SDValue V = DAG.getVAArg( 8511 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8512 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8513 DL.getABITypeAlignment(I.getType())); 8514 DAG.setRoot(V.getValue(1)); 8515 8516 if (I.getType()->isPointerTy()) 8517 V = DAG.getPtrExtOrTrunc( 8518 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8519 setValue(&I, V); 8520 } 8521 8522 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8523 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8524 MVT::Other, getRoot(), 8525 getValue(I.getArgOperand(0)), 8526 DAG.getSrcValue(I.getArgOperand(0)))); 8527 } 8528 8529 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8530 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8531 MVT::Other, getRoot(), 8532 getValue(I.getArgOperand(0)), 8533 getValue(I.getArgOperand(1)), 8534 DAG.getSrcValue(I.getArgOperand(0)), 8535 DAG.getSrcValue(I.getArgOperand(1)))); 8536 } 8537 8538 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8539 const Instruction &I, 8540 SDValue Op) { 8541 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8542 if (!Range) 8543 return Op; 8544 8545 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8546 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8547 return Op; 8548 8549 APInt Lo = CR.getUnsignedMin(); 8550 if (!Lo.isMinValue()) 8551 return Op; 8552 8553 APInt Hi = CR.getUnsignedMax(); 8554 unsigned Bits = std::max(Hi.getActiveBits(), 8555 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8556 8557 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8558 8559 SDLoc SL = getCurSDLoc(); 8560 8561 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8562 DAG.getValueType(SmallVT)); 8563 unsigned NumVals = Op.getNode()->getNumValues(); 8564 if (NumVals == 1) 8565 return ZExt; 8566 8567 SmallVector<SDValue, 4> Ops; 8568 8569 Ops.push_back(ZExt); 8570 for (unsigned I = 1; I != NumVals; ++I) 8571 Ops.push_back(Op.getValue(I)); 8572 8573 return DAG.getMergeValues(Ops, SL); 8574 } 8575 8576 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8577 /// the call being lowered. 8578 /// 8579 /// This is a helper for lowering intrinsics that follow a target calling 8580 /// convention or require stack pointer adjustment. Only a subset of the 8581 /// intrinsic's operands need to participate in the calling convention. 8582 void SelectionDAGBuilder::populateCallLoweringInfo( 8583 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8584 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8585 bool IsPatchPoint) { 8586 TargetLowering::ArgListTy Args; 8587 Args.reserve(NumArgs); 8588 8589 // Populate the argument list. 8590 // Attributes for args start at offset 1, after the return attribute. 8591 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8592 ArgI != ArgE; ++ArgI) { 8593 const Value *V = Call->getOperand(ArgI); 8594 8595 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8596 8597 TargetLowering::ArgListEntry Entry; 8598 Entry.Node = getValue(V); 8599 Entry.Ty = V->getType(); 8600 Entry.setAttributes(Call, ArgI); 8601 Args.push_back(Entry); 8602 } 8603 8604 CLI.setDebugLoc(getCurSDLoc()) 8605 .setChain(getRoot()) 8606 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8607 .setDiscardResult(Call->use_empty()) 8608 .setIsPatchPoint(IsPatchPoint); 8609 } 8610 8611 /// Add a stack map intrinsic call's live variable operands to a stackmap 8612 /// or patchpoint target node's operand list. 8613 /// 8614 /// Constants are converted to TargetConstants purely as an optimization to 8615 /// avoid constant materialization and register allocation. 8616 /// 8617 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8618 /// generate addess computation nodes, and so FinalizeISel can convert the 8619 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8620 /// address materialization and register allocation, but may also be required 8621 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8622 /// alloca in the entry block, then the runtime may assume that the alloca's 8623 /// StackMap location can be read immediately after compilation and that the 8624 /// location is valid at any point during execution (this is similar to the 8625 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8626 /// only available in a register, then the runtime would need to trap when 8627 /// execution reaches the StackMap in order to read the alloca's location. 8628 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8629 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8630 SelectionDAGBuilder &Builder) { 8631 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8632 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8633 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8634 Ops.push_back( 8635 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8636 Ops.push_back( 8637 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8638 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8639 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8640 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8641 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8642 } else 8643 Ops.push_back(OpVal); 8644 } 8645 } 8646 8647 /// Lower llvm.experimental.stackmap directly to its target opcode. 8648 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8649 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8650 // [live variables...]) 8651 8652 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8653 8654 SDValue Chain, InFlag, Callee, NullPtr; 8655 SmallVector<SDValue, 32> Ops; 8656 8657 SDLoc DL = getCurSDLoc(); 8658 Callee = getValue(CI.getCalledOperand()); 8659 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8660 8661 // The stackmap intrinsic only records the live variables (the arguments 8662 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8663 // intrinsic, this won't be lowered to a function call. This means we don't 8664 // have to worry about calling conventions and target specific lowering code. 8665 // Instead we perform the call lowering right here. 8666 // 8667 // chain, flag = CALLSEQ_START(chain, 0, 0) 8668 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8669 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8670 // 8671 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8672 InFlag = Chain.getValue(1); 8673 8674 // Add the <id> and <numBytes> constants. 8675 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8676 Ops.push_back(DAG.getTargetConstant( 8677 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8678 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8679 Ops.push_back(DAG.getTargetConstant( 8680 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8681 MVT::i32)); 8682 8683 // Push live variables for the stack map. 8684 addStackMapLiveVars(CI, 2, DL, Ops, *this); 8685 8686 // We are not pushing any register mask info here on the operands list, 8687 // because the stackmap doesn't clobber anything. 8688 8689 // Push the chain and the glue flag. 8690 Ops.push_back(Chain); 8691 Ops.push_back(InFlag); 8692 8693 // Create the STACKMAP node. 8694 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8695 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8696 Chain = SDValue(SM, 0); 8697 InFlag = Chain.getValue(1); 8698 8699 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8700 8701 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8702 8703 // Set the root to the target-lowered call chain. 8704 DAG.setRoot(Chain); 8705 8706 // Inform the Frame Information that we have a stackmap in this function. 8707 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8708 } 8709 8710 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8711 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 8712 const BasicBlock *EHPadBB) { 8713 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8714 // i32 <numBytes>, 8715 // i8* <target>, 8716 // i32 <numArgs>, 8717 // [Args...], 8718 // [live variables...]) 8719 8720 CallingConv::ID CC = CB.getCallingConv(); 8721 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8722 bool HasDef = !CB.getType()->isVoidTy(); 8723 SDLoc dl = getCurSDLoc(); 8724 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 8725 8726 // Handle immediate and symbolic callees. 8727 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8728 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8729 /*isTarget=*/true); 8730 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8731 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8732 SDLoc(SymbolicCallee), 8733 SymbolicCallee->getValueType(0)); 8734 8735 // Get the real number of arguments participating in the call <numArgs> 8736 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 8737 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8738 8739 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8740 // Intrinsics include all meta-operands up to but not including CC. 8741 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8742 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 8743 "Not enough arguments provided to the patchpoint intrinsic"); 8744 8745 // For AnyRegCC the arguments are lowered later on manually. 8746 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8747 Type *ReturnTy = 8748 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 8749 8750 TargetLowering::CallLoweringInfo CLI(DAG); 8751 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 8752 ReturnTy, true); 8753 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8754 8755 SDNode *CallEnd = Result.second.getNode(); 8756 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8757 CallEnd = CallEnd->getOperand(0).getNode(); 8758 8759 /// Get a call instruction from the call sequence chain. 8760 /// Tail calls are not allowed. 8761 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8762 "Expected a callseq node."); 8763 SDNode *Call = CallEnd->getOperand(0).getNode(); 8764 bool HasGlue = Call->getGluedNode(); 8765 8766 // Replace the target specific call node with the patchable intrinsic. 8767 SmallVector<SDValue, 8> Ops; 8768 8769 // Add the <id> and <numBytes> constants. 8770 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 8771 Ops.push_back(DAG.getTargetConstant( 8772 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8773 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 8774 Ops.push_back(DAG.getTargetConstant( 8775 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8776 MVT::i32)); 8777 8778 // Add the callee. 8779 Ops.push_back(Callee); 8780 8781 // Adjust <numArgs> to account for any arguments that have been passed on the 8782 // stack instead. 8783 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8784 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8785 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8786 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8787 8788 // Add the calling convention 8789 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8790 8791 // Add the arguments we omitted previously. The register allocator should 8792 // place these in any free register. 8793 if (IsAnyRegCC) 8794 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8795 Ops.push_back(getValue(CB.getArgOperand(i))); 8796 8797 // Push the arguments from the call instruction up to the register mask. 8798 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8799 Ops.append(Call->op_begin() + 2, e); 8800 8801 // Push live variables for the stack map. 8802 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 8803 8804 // Push the register mask info. 8805 if (HasGlue) 8806 Ops.push_back(*(Call->op_end()-2)); 8807 else 8808 Ops.push_back(*(Call->op_end()-1)); 8809 8810 // Push the chain (this is originally the first operand of the call, but 8811 // becomes now the last or second to last operand). 8812 Ops.push_back(*(Call->op_begin())); 8813 8814 // Push the glue flag (last operand). 8815 if (HasGlue) 8816 Ops.push_back(*(Call->op_end()-1)); 8817 8818 SDVTList NodeTys; 8819 if (IsAnyRegCC && HasDef) { 8820 // Create the return types based on the intrinsic definition 8821 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8822 SmallVector<EVT, 3> ValueVTs; 8823 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 8824 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8825 8826 // There is always a chain and a glue type at the end 8827 ValueVTs.push_back(MVT::Other); 8828 ValueVTs.push_back(MVT::Glue); 8829 NodeTys = DAG.getVTList(ValueVTs); 8830 } else 8831 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8832 8833 // Replace the target specific call node with a PATCHPOINT node. 8834 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8835 dl, NodeTys, Ops); 8836 8837 // Update the NodeMap. 8838 if (HasDef) { 8839 if (IsAnyRegCC) 8840 setValue(&CB, SDValue(MN, 0)); 8841 else 8842 setValue(&CB, Result.first); 8843 } 8844 8845 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8846 // call sequence. Furthermore the location of the chain and glue can change 8847 // when the AnyReg calling convention is used and the intrinsic returns a 8848 // value. 8849 if (IsAnyRegCC && HasDef) { 8850 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8851 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8852 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8853 } else 8854 DAG.ReplaceAllUsesWith(Call, MN); 8855 DAG.DeleteNode(Call); 8856 8857 // Inform the Frame Information that we have a patchpoint in this function. 8858 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8859 } 8860 8861 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8862 unsigned Intrinsic) { 8863 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8864 SDValue Op1 = getValue(I.getArgOperand(0)); 8865 SDValue Op2; 8866 if (I.getNumArgOperands() > 1) 8867 Op2 = getValue(I.getArgOperand(1)); 8868 SDLoc dl = getCurSDLoc(); 8869 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8870 SDValue Res; 8871 FastMathFlags FMF; 8872 if (isa<FPMathOperator>(I)) 8873 FMF = I.getFastMathFlags(); 8874 8875 switch (Intrinsic) { 8876 case Intrinsic::experimental_vector_reduce_v2_fadd: 8877 if (FMF.allowReassoc()) 8878 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8879 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8880 else 8881 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8882 break; 8883 case Intrinsic::experimental_vector_reduce_v2_fmul: 8884 if (FMF.allowReassoc()) 8885 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8886 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8887 else 8888 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8889 break; 8890 case Intrinsic::experimental_vector_reduce_add: 8891 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8892 break; 8893 case Intrinsic::experimental_vector_reduce_mul: 8894 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8895 break; 8896 case Intrinsic::experimental_vector_reduce_and: 8897 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8898 break; 8899 case Intrinsic::experimental_vector_reduce_or: 8900 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8901 break; 8902 case Intrinsic::experimental_vector_reduce_xor: 8903 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8904 break; 8905 case Intrinsic::experimental_vector_reduce_smax: 8906 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8907 break; 8908 case Intrinsic::experimental_vector_reduce_smin: 8909 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8910 break; 8911 case Intrinsic::experimental_vector_reduce_umax: 8912 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8913 break; 8914 case Intrinsic::experimental_vector_reduce_umin: 8915 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8916 break; 8917 case Intrinsic::experimental_vector_reduce_fmax: 8918 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8919 break; 8920 case Intrinsic::experimental_vector_reduce_fmin: 8921 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8922 break; 8923 default: 8924 llvm_unreachable("Unhandled vector reduce intrinsic"); 8925 } 8926 setValue(&I, Res); 8927 } 8928 8929 /// Returns an AttributeList representing the attributes applied to the return 8930 /// value of the given call. 8931 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8932 SmallVector<Attribute::AttrKind, 2> Attrs; 8933 if (CLI.RetSExt) 8934 Attrs.push_back(Attribute::SExt); 8935 if (CLI.RetZExt) 8936 Attrs.push_back(Attribute::ZExt); 8937 if (CLI.IsInReg) 8938 Attrs.push_back(Attribute::InReg); 8939 8940 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8941 Attrs); 8942 } 8943 8944 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8945 /// implementation, which just calls LowerCall. 8946 /// FIXME: When all targets are 8947 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8948 std::pair<SDValue, SDValue> 8949 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8950 // Handle the incoming return values from the call. 8951 CLI.Ins.clear(); 8952 Type *OrigRetTy = CLI.RetTy; 8953 SmallVector<EVT, 4> RetTys; 8954 SmallVector<uint64_t, 4> Offsets; 8955 auto &DL = CLI.DAG.getDataLayout(); 8956 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8957 8958 if (CLI.IsPostTypeLegalization) { 8959 // If we are lowering a libcall after legalization, split the return type. 8960 SmallVector<EVT, 4> OldRetTys; 8961 SmallVector<uint64_t, 4> OldOffsets; 8962 RetTys.swap(OldRetTys); 8963 Offsets.swap(OldOffsets); 8964 8965 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8966 EVT RetVT = OldRetTys[i]; 8967 uint64_t Offset = OldOffsets[i]; 8968 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8969 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8970 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8971 RetTys.append(NumRegs, RegisterVT); 8972 for (unsigned j = 0; j != NumRegs; ++j) 8973 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8974 } 8975 } 8976 8977 SmallVector<ISD::OutputArg, 4> Outs; 8978 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8979 8980 bool CanLowerReturn = 8981 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8982 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8983 8984 SDValue DemoteStackSlot; 8985 int DemoteStackIdx = -100; 8986 if (!CanLowerReturn) { 8987 // FIXME: equivalent assert? 8988 // assert(!CS.hasInAllocaArgument() && 8989 // "sret demotion is incompatible with inalloca"); 8990 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8991 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 8992 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8993 DemoteStackIdx = 8994 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 8995 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8996 DL.getAllocaAddrSpace()); 8997 8998 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8999 ArgListEntry Entry; 9000 Entry.Node = DemoteStackSlot; 9001 Entry.Ty = StackSlotPtrType; 9002 Entry.IsSExt = false; 9003 Entry.IsZExt = false; 9004 Entry.IsInReg = false; 9005 Entry.IsSRet = true; 9006 Entry.IsNest = false; 9007 Entry.IsByVal = false; 9008 Entry.IsReturned = false; 9009 Entry.IsSwiftSelf = false; 9010 Entry.IsSwiftError = false; 9011 Entry.IsCFGuardTarget = false; 9012 Entry.Alignment = Alignment; 9013 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9014 CLI.NumFixedArgs += 1; 9015 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9016 9017 // sret demotion isn't compatible with tail-calls, since the sret argument 9018 // points into the callers stack frame. 9019 CLI.IsTailCall = false; 9020 } else { 9021 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9022 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9023 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9024 ISD::ArgFlagsTy Flags; 9025 if (NeedsRegBlock) { 9026 Flags.setInConsecutiveRegs(); 9027 if (I == RetTys.size() - 1) 9028 Flags.setInConsecutiveRegsLast(); 9029 } 9030 EVT VT = RetTys[I]; 9031 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9032 CLI.CallConv, VT); 9033 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9034 CLI.CallConv, VT); 9035 for (unsigned i = 0; i != NumRegs; ++i) { 9036 ISD::InputArg MyFlags; 9037 MyFlags.Flags = Flags; 9038 MyFlags.VT = RegisterVT; 9039 MyFlags.ArgVT = VT; 9040 MyFlags.Used = CLI.IsReturnValueUsed; 9041 if (CLI.RetTy->isPointerTy()) { 9042 MyFlags.Flags.setPointer(); 9043 MyFlags.Flags.setPointerAddrSpace( 9044 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9045 } 9046 if (CLI.RetSExt) 9047 MyFlags.Flags.setSExt(); 9048 if (CLI.RetZExt) 9049 MyFlags.Flags.setZExt(); 9050 if (CLI.IsInReg) 9051 MyFlags.Flags.setInReg(); 9052 CLI.Ins.push_back(MyFlags); 9053 } 9054 } 9055 } 9056 9057 // We push in swifterror return as the last element of CLI.Ins. 9058 ArgListTy &Args = CLI.getArgs(); 9059 if (supportSwiftError()) { 9060 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9061 if (Args[i].IsSwiftError) { 9062 ISD::InputArg MyFlags; 9063 MyFlags.VT = getPointerTy(DL); 9064 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9065 MyFlags.Flags.setSwiftError(); 9066 CLI.Ins.push_back(MyFlags); 9067 } 9068 } 9069 } 9070 9071 // Handle all of the outgoing arguments. 9072 CLI.Outs.clear(); 9073 CLI.OutVals.clear(); 9074 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9075 SmallVector<EVT, 4> ValueVTs; 9076 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9077 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9078 Type *FinalType = Args[i].Ty; 9079 if (Args[i].IsByVal) 9080 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9081 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9082 FinalType, CLI.CallConv, CLI.IsVarArg); 9083 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9084 ++Value) { 9085 EVT VT = ValueVTs[Value]; 9086 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9087 SDValue Op = SDValue(Args[i].Node.getNode(), 9088 Args[i].Node.getResNo() + Value); 9089 ISD::ArgFlagsTy Flags; 9090 9091 // Certain targets (such as MIPS), may have a different ABI alignment 9092 // for a type depending on the context. Give the target a chance to 9093 // specify the alignment it wants. 9094 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9095 9096 if (Args[i].Ty->isPointerTy()) { 9097 Flags.setPointer(); 9098 Flags.setPointerAddrSpace( 9099 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9100 } 9101 if (Args[i].IsZExt) 9102 Flags.setZExt(); 9103 if (Args[i].IsSExt) 9104 Flags.setSExt(); 9105 if (Args[i].IsInReg) { 9106 // If we are using vectorcall calling convention, a structure that is 9107 // passed InReg - is surely an HVA 9108 if (CLI.CallConv == CallingConv::X86_VectorCall && 9109 isa<StructType>(FinalType)) { 9110 // The first value of a structure is marked 9111 if (0 == Value) 9112 Flags.setHvaStart(); 9113 Flags.setHva(); 9114 } 9115 // Set InReg Flag 9116 Flags.setInReg(); 9117 } 9118 if (Args[i].IsSRet) 9119 Flags.setSRet(); 9120 if (Args[i].IsSwiftSelf) 9121 Flags.setSwiftSelf(); 9122 if (Args[i].IsSwiftError) 9123 Flags.setSwiftError(); 9124 if (Args[i].IsCFGuardTarget) 9125 Flags.setCFGuardTarget(); 9126 if (Args[i].IsByVal) 9127 Flags.setByVal(); 9128 if (Args[i].IsInAlloca) { 9129 Flags.setInAlloca(); 9130 // Set the byval flag for CCAssignFn callbacks that don't know about 9131 // inalloca. This way we can know how many bytes we should've allocated 9132 // and how many bytes a callee cleanup function will pop. If we port 9133 // inalloca to more targets, we'll have to add custom inalloca handling 9134 // in the various CC lowering callbacks. 9135 Flags.setByVal(); 9136 } 9137 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9138 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9139 Type *ElementTy = Ty->getElementType(); 9140 9141 unsigned FrameSize = DL.getTypeAllocSize( 9142 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9143 Flags.setByValSize(FrameSize); 9144 9145 // info is not there but there are cases it cannot get right. 9146 Align FrameAlign; 9147 if (auto MA = Args[i].Alignment) 9148 FrameAlign = *MA; 9149 else 9150 FrameAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9151 Flags.setByValAlign(FrameAlign); 9152 } 9153 if (Args[i].IsNest) 9154 Flags.setNest(); 9155 if (NeedsRegBlock) 9156 Flags.setInConsecutiveRegs(); 9157 Flags.setOrigAlign(OriginalAlignment); 9158 9159 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9160 CLI.CallConv, VT); 9161 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9162 CLI.CallConv, VT); 9163 SmallVector<SDValue, 4> Parts(NumParts); 9164 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9165 9166 if (Args[i].IsSExt) 9167 ExtendKind = ISD::SIGN_EXTEND; 9168 else if (Args[i].IsZExt) 9169 ExtendKind = ISD::ZERO_EXTEND; 9170 9171 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9172 // for now. 9173 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9174 CanLowerReturn) { 9175 assert((CLI.RetTy == Args[i].Ty || 9176 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9177 CLI.RetTy->getPointerAddressSpace() == 9178 Args[i].Ty->getPointerAddressSpace())) && 9179 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9180 // Before passing 'returned' to the target lowering code, ensure that 9181 // either the register MVT and the actual EVT are the same size or that 9182 // the return value and argument are extended in the same way; in these 9183 // cases it's safe to pass the argument register value unchanged as the 9184 // return register value (although it's at the target's option whether 9185 // to do so) 9186 // TODO: allow code generation to take advantage of partially preserved 9187 // registers rather than clobbering the entire register when the 9188 // parameter extension method is not compatible with the return 9189 // extension method 9190 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9191 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9192 CLI.RetZExt == Args[i].IsZExt)) 9193 Flags.setReturned(); 9194 } 9195 9196 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9197 CLI.CallConv, ExtendKind); 9198 9199 for (unsigned j = 0; j != NumParts; ++j) { 9200 // if it isn't first piece, alignment must be 1 9201 // For scalable vectors the scalable part is currently handled 9202 // by individual targets, so we just use the known minimum size here. 9203 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9204 i < CLI.NumFixedArgs, i, 9205 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9206 if (NumParts > 1 && j == 0) 9207 MyFlags.Flags.setSplit(); 9208 else if (j != 0) { 9209 MyFlags.Flags.setOrigAlign(Align(1)); 9210 if (j == NumParts - 1) 9211 MyFlags.Flags.setSplitEnd(); 9212 } 9213 9214 CLI.Outs.push_back(MyFlags); 9215 CLI.OutVals.push_back(Parts[j]); 9216 } 9217 9218 if (NeedsRegBlock && Value == NumValues - 1) 9219 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9220 } 9221 } 9222 9223 SmallVector<SDValue, 4> InVals; 9224 CLI.Chain = LowerCall(CLI, InVals); 9225 9226 // Update CLI.InVals to use outside of this function. 9227 CLI.InVals = InVals; 9228 9229 // Verify that the target's LowerCall behaved as expected. 9230 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9231 "LowerCall didn't return a valid chain!"); 9232 assert((!CLI.IsTailCall || InVals.empty()) && 9233 "LowerCall emitted a return value for a tail call!"); 9234 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9235 "LowerCall didn't emit the correct number of values!"); 9236 9237 // For a tail call, the return value is merely live-out and there aren't 9238 // any nodes in the DAG representing it. Return a special value to 9239 // indicate that a tail call has been emitted and no more Instructions 9240 // should be processed in the current block. 9241 if (CLI.IsTailCall) { 9242 CLI.DAG.setRoot(CLI.Chain); 9243 return std::make_pair(SDValue(), SDValue()); 9244 } 9245 9246 #ifndef NDEBUG 9247 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9248 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9249 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9250 "LowerCall emitted a value with the wrong type!"); 9251 } 9252 #endif 9253 9254 SmallVector<SDValue, 4> ReturnValues; 9255 if (!CanLowerReturn) { 9256 // The instruction result is the result of loading from the 9257 // hidden sret parameter. 9258 SmallVector<EVT, 1> PVTs; 9259 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9260 9261 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9262 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9263 EVT PtrVT = PVTs[0]; 9264 9265 unsigned NumValues = RetTys.size(); 9266 ReturnValues.resize(NumValues); 9267 SmallVector<SDValue, 4> Chains(NumValues); 9268 9269 // An aggregate return value cannot wrap around the address space, so 9270 // offsets to its parts don't wrap either. 9271 SDNodeFlags Flags; 9272 Flags.setNoUnsignedWrap(true); 9273 9274 for (unsigned i = 0; i < NumValues; ++i) { 9275 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9276 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9277 PtrVT), Flags); 9278 SDValue L = CLI.DAG.getLoad( 9279 RetTys[i], CLI.DL, CLI.Chain, Add, 9280 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9281 DemoteStackIdx, Offsets[i]), 9282 /* Alignment = */ 1); 9283 ReturnValues[i] = L; 9284 Chains[i] = L.getValue(1); 9285 } 9286 9287 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9288 } else { 9289 // Collect the legal value parts into potentially illegal values 9290 // that correspond to the original function's return values. 9291 Optional<ISD::NodeType> AssertOp; 9292 if (CLI.RetSExt) 9293 AssertOp = ISD::AssertSext; 9294 else if (CLI.RetZExt) 9295 AssertOp = ISD::AssertZext; 9296 unsigned CurReg = 0; 9297 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9298 EVT VT = RetTys[I]; 9299 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9300 CLI.CallConv, VT); 9301 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9302 CLI.CallConv, VT); 9303 9304 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9305 NumRegs, RegisterVT, VT, nullptr, 9306 CLI.CallConv, AssertOp)); 9307 CurReg += NumRegs; 9308 } 9309 9310 // For a function returning void, there is no return value. We can't create 9311 // such a node, so we just return a null return value in that case. In 9312 // that case, nothing will actually look at the value. 9313 if (ReturnValues.empty()) 9314 return std::make_pair(SDValue(), CLI.Chain); 9315 } 9316 9317 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9318 CLI.DAG.getVTList(RetTys), ReturnValues); 9319 return std::make_pair(Res, CLI.Chain); 9320 } 9321 9322 void TargetLowering::LowerOperationWrapper(SDNode *N, 9323 SmallVectorImpl<SDValue> &Results, 9324 SelectionDAG &DAG) const { 9325 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9326 Results.push_back(Res); 9327 } 9328 9329 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9330 llvm_unreachable("LowerOperation not implemented for this target!"); 9331 } 9332 9333 void 9334 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9335 SDValue Op = getNonRegisterValue(V); 9336 assert((Op.getOpcode() != ISD::CopyFromReg || 9337 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9338 "Copy from a reg to the same reg!"); 9339 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9340 9341 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9342 // If this is an InlineAsm we have to match the registers required, not the 9343 // notional registers required by the type. 9344 9345 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9346 None); // This is not an ABI copy. 9347 SDValue Chain = DAG.getEntryNode(); 9348 9349 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9350 FuncInfo.PreferredExtendType.end()) 9351 ? ISD::ANY_EXTEND 9352 : FuncInfo.PreferredExtendType[V]; 9353 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9354 PendingExports.push_back(Chain); 9355 } 9356 9357 #include "llvm/CodeGen/SelectionDAGISel.h" 9358 9359 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9360 /// entry block, return true. This includes arguments used by switches, since 9361 /// the switch may expand into multiple basic blocks. 9362 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9363 // With FastISel active, we may be splitting blocks, so force creation 9364 // of virtual registers for all non-dead arguments. 9365 if (FastISel) 9366 return A->use_empty(); 9367 9368 const BasicBlock &Entry = A->getParent()->front(); 9369 for (const User *U : A->users()) 9370 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9371 return false; // Use not in entry block. 9372 9373 return true; 9374 } 9375 9376 using ArgCopyElisionMapTy = 9377 DenseMap<const Argument *, 9378 std::pair<const AllocaInst *, const StoreInst *>>; 9379 9380 /// Scan the entry block of the function in FuncInfo for arguments that look 9381 /// like copies into a local alloca. Record any copied arguments in 9382 /// ArgCopyElisionCandidates. 9383 static void 9384 findArgumentCopyElisionCandidates(const DataLayout &DL, 9385 FunctionLoweringInfo *FuncInfo, 9386 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9387 // Record the state of every static alloca used in the entry block. Argument 9388 // allocas are all used in the entry block, so we need approximately as many 9389 // entries as we have arguments. 9390 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9391 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9392 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9393 StaticAllocas.reserve(NumArgs * 2); 9394 9395 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9396 if (!V) 9397 return nullptr; 9398 V = V->stripPointerCasts(); 9399 const auto *AI = dyn_cast<AllocaInst>(V); 9400 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9401 return nullptr; 9402 auto Iter = StaticAllocas.insert({AI, Unknown}); 9403 return &Iter.first->second; 9404 }; 9405 9406 // Look for stores of arguments to static allocas. Look through bitcasts and 9407 // GEPs to handle type coercions, as long as the alloca is fully initialized 9408 // by the store. Any non-store use of an alloca escapes it and any subsequent 9409 // unanalyzed store might write it. 9410 // FIXME: Handle structs initialized with multiple stores. 9411 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9412 // Look for stores, and handle non-store uses conservatively. 9413 const auto *SI = dyn_cast<StoreInst>(&I); 9414 if (!SI) { 9415 // We will look through cast uses, so ignore them completely. 9416 if (I.isCast()) 9417 continue; 9418 // Ignore debug info intrinsics, they don't escape or store to allocas. 9419 if (isa<DbgInfoIntrinsic>(I)) 9420 continue; 9421 // This is an unknown instruction. Assume it escapes or writes to all 9422 // static alloca operands. 9423 for (const Use &U : I.operands()) { 9424 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9425 *Info = StaticAllocaInfo::Clobbered; 9426 } 9427 continue; 9428 } 9429 9430 // If the stored value is a static alloca, mark it as escaped. 9431 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9432 *Info = StaticAllocaInfo::Clobbered; 9433 9434 // Check if the destination is a static alloca. 9435 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9436 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9437 if (!Info) 9438 continue; 9439 const AllocaInst *AI = cast<AllocaInst>(Dst); 9440 9441 // Skip allocas that have been initialized or clobbered. 9442 if (*Info != StaticAllocaInfo::Unknown) 9443 continue; 9444 9445 // Check if the stored value is an argument, and that this store fully 9446 // initializes the alloca. Don't elide copies from the same argument twice. 9447 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9448 const auto *Arg = dyn_cast<Argument>(Val); 9449 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9450 Arg->getType()->isEmptyTy() || 9451 DL.getTypeStoreSize(Arg->getType()) != 9452 DL.getTypeAllocSize(AI->getAllocatedType()) || 9453 ArgCopyElisionCandidates.count(Arg)) { 9454 *Info = StaticAllocaInfo::Clobbered; 9455 continue; 9456 } 9457 9458 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9459 << '\n'); 9460 9461 // Mark this alloca and store for argument copy elision. 9462 *Info = StaticAllocaInfo::Elidable; 9463 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9464 9465 // Stop scanning if we've seen all arguments. This will happen early in -O0 9466 // builds, which is useful, because -O0 builds have large entry blocks and 9467 // many allocas. 9468 if (ArgCopyElisionCandidates.size() == NumArgs) 9469 break; 9470 } 9471 } 9472 9473 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9474 /// ArgVal is a load from a suitable fixed stack object. 9475 static void tryToElideArgumentCopy( 9476 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9477 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9478 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9479 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9480 SDValue ArgVal, bool &ArgHasUses) { 9481 // Check if this is a load from a fixed stack object. 9482 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9483 if (!LNode) 9484 return; 9485 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9486 if (!FINode) 9487 return; 9488 9489 // Check that the fixed stack object is the right size and alignment. 9490 // Look at the alignment that the user wrote on the alloca instead of looking 9491 // at the stack object. 9492 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9493 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9494 const AllocaInst *AI = ArgCopyIter->second.first; 9495 int FixedIndex = FINode->getIndex(); 9496 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9497 int OldIndex = AllocaIndex; 9498 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9499 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9500 LLVM_DEBUG( 9501 dbgs() << " argument copy elision failed due to bad fixed stack " 9502 "object size\n"); 9503 return; 9504 } 9505 Align RequiredAlignment = AI->getAlign().getValueOr( 9506 FuncInfo.MF->getDataLayout().getABITypeAlign(AI->getAllocatedType())); 9507 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9508 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9509 "greater than stack argument alignment (" 9510 << DebugStr(RequiredAlignment) << " vs " 9511 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9512 return; 9513 } 9514 9515 // Perform the elision. Delete the old stack object and replace its only use 9516 // in the variable info map. Mark the stack object as mutable. 9517 LLVM_DEBUG({ 9518 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9519 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9520 << '\n'; 9521 }); 9522 MFI.RemoveStackObject(OldIndex); 9523 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9524 AllocaIndex = FixedIndex; 9525 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9526 Chains.push_back(ArgVal.getValue(1)); 9527 9528 // Avoid emitting code for the store implementing the copy. 9529 const StoreInst *SI = ArgCopyIter->second.second; 9530 ElidedArgCopyInstrs.insert(SI); 9531 9532 // Check for uses of the argument again so that we can avoid exporting ArgVal 9533 // if it is't used by anything other than the store. 9534 for (const Value *U : Arg.users()) { 9535 if (U != SI) { 9536 ArgHasUses = true; 9537 break; 9538 } 9539 } 9540 } 9541 9542 void SelectionDAGISel::LowerArguments(const Function &F) { 9543 SelectionDAG &DAG = SDB->DAG; 9544 SDLoc dl = SDB->getCurSDLoc(); 9545 const DataLayout &DL = DAG.getDataLayout(); 9546 SmallVector<ISD::InputArg, 16> Ins; 9547 9548 if (!FuncInfo->CanLowerReturn) { 9549 // Put in an sret pointer parameter before all the other parameters. 9550 SmallVector<EVT, 1> ValueVTs; 9551 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9552 F.getReturnType()->getPointerTo( 9553 DAG.getDataLayout().getAllocaAddrSpace()), 9554 ValueVTs); 9555 9556 // NOTE: Assuming that a pointer will never break down to more than one VT 9557 // or one register. 9558 ISD::ArgFlagsTy Flags; 9559 Flags.setSRet(); 9560 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9561 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9562 ISD::InputArg::NoArgIndex, 0); 9563 Ins.push_back(RetArg); 9564 } 9565 9566 // Look for stores of arguments to static allocas. Mark such arguments with a 9567 // flag to ask the target to give us the memory location of that argument if 9568 // available. 9569 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9570 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9571 ArgCopyElisionCandidates); 9572 9573 // Set up the incoming argument description vector. 9574 for (const Argument &Arg : F.args()) { 9575 unsigned ArgNo = Arg.getArgNo(); 9576 SmallVector<EVT, 4> ValueVTs; 9577 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9578 bool isArgValueUsed = !Arg.use_empty(); 9579 unsigned PartBase = 0; 9580 Type *FinalType = Arg.getType(); 9581 if (Arg.hasAttribute(Attribute::ByVal)) 9582 FinalType = Arg.getParamByValType(); 9583 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9584 FinalType, F.getCallingConv(), F.isVarArg()); 9585 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9586 Value != NumValues; ++Value) { 9587 EVT VT = ValueVTs[Value]; 9588 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9589 ISD::ArgFlagsTy Flags; 9590 9591 // Certain targets (such as MIPS), may have a different ABI alignment 9592 // for a type depending on the context. Give the target a chance to 9593 // specify the alignment it wants. 9594 const Align OriginalAlignment( 9595 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9596 9597 if (Arg.getType()->isPointerTy()) { 9598 Flags.setPointer(); 9599 Flags.setPointerAddrSpace( 9600 cast<PointerType>(Arg.getType())->getAddressSpace()); 9601 } 9602 if (Arg.hasAttribute(Attribute::ZExt)) 9603 Flags.setZExt(); 9604 if (Arg.hasAttribute(Attribute::SExt)) 9605 Flags.setSExt(); 9606 if (Arg.hasAttribute(Attribute::InReg)) { 9607 // If we are using vectorcall calling convention, a structure that is 9608 // passed InReg - is surely an HVA 9609 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9610 isa<StructType>(Arg.getType())) { 9611 // The first value of a structure is marked 9612 if (0 == Value) 9613 Flags.setHvaStart(); 9614 Flags.setHva(); 9615 } 9616 // Set InReg Flag 9617 Flags.setInReg(); 9618 } 9619 if (Arg.hasAttribute(Attribute::StructRet)) 9620 Flags.setSRet(); 9621 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9622 Flags.setSwiftSelf(); 9623 if (Arg.hasAttribute(Attribute::SwiftError)) 9624 Flags.setSwiftError(); 9625 if (Arg.hasAttribute(Attribute::ByVal)) 9626 Flags.setByVal(); 9627 if (Arg.hasAttribute(Attribute::InAlloca)) { 9628 Flags.setInAlloca(); 9629 // Set the byval flag for CCAssignFn callbacks that don't know about 9630 // inalloca. This way we can know how many bytes we should've allocated 9631 // and how many bytes a callee cleanup function will pop. If we port 9632 // inalloca to more targets, we'll have to add custom inalloca handling 9633 // in the various CC lowering callbacks. 9634 Flags.setByVal(); 9635 } 9636 if (F.getCallingConv() == CallingConv::X86_INTR) { 9637 // IA Interrupt passes frame (1st parameter) by value in the stack. 9638 if (ArgNo == 0) 9639 Flags.setByVal(); 9640 } 9641 if (Flags.isByVal() || Flags.isInAlloca()) { 9642 Type *ElementTy = Arg.getParamByValType(); 9643 9644 // For ByVal, size and alignment should be passed from FE. BE will 9645 // guess if this info is not there but there are cases it cannot get 9646 // right. 9647 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9648 Flags.setByValSize(FrameSize); 9649 9650 unsigned FrameAlign; 9651 if (Arg.getParamAlignment()) 9652 FrameAlign = Arg.getParamAlignment(); 9653 else 9654 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9655 Flags.setByValAlign(Align(FrameAlign)); 9656 } 9657 if (Arg.hasAttribute(Attribute::Nest)) 9658 Flags.setNest(); 9659 if (NeedsRegBlock) 9660 Flags.setInConsecutiveRegs(); 9661 Flags.setOrigAlign(OriginalAlignment); 9662 if (ArgCopyElisionCandidates.count(&Arg)) 9663 Flags.setCopyElisionCandidate(); 9664 if (Arg.hasAttribute(Attribute::Returned)) 9665 Flags.setReturned(); 9666 9667 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9668 *CurDAG->getContext(), F.getCallingConv(), VT); 9669 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9670 *CurDAG->getContext(), F.getCallingConv(), VT); 9671 for (unsigned i = 0; i != NumRegs; ++i) { 9672 // For scalable vectors, use the minimum size; individual targets 9673 // are responsible for handling scalable vector arguments and 9674 // return values. 9675 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9676 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9677 if (NumRegs > 1 && i == 0) 9678 MyFlags.Flags.setSplit(); 9679 // if it isn't first piece, alignment must be 1 9680 else if (i > 0) { 9681 MyFlags.Flags.setOrigAlign(Align(1)); 9682 if (i == NumRegs - 1) 9683 MyFlags.Flags.setSplitEnd(); 9684 } 9685 Ins.push_back(MyFlags); 9686 } 9687 if (NeedsRegBlock && Value == NumValues - 1) 9688 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9689 PartBase += VT.getStoreSize().getKnownMinSize(); 9690 } 9691 } 9692 9693 // Call the target to set up the argument values. 9694 SmallVector<SDValue, 8> InVals; 9695 SDValue NewRoot = TLI->LowerFormalArguments( 9696 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9697 9698 // Verify that the target's LowerFormalArguments behaved as expected. 9699 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9700 "LowerFormalArguments didn't return a valid chain!"); 9701 assert(InVals.size() == Ins.size() && 9702 "LowerFormalArguments didn't emit the correct number of values!"); 9703 LLVM_DEBUG({ 9704 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9705 assert(InVals[i].getNode() && 9706 "LowerFormalArguments emitted a null value!"); 9707 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9708 "LowerFormalArguments emitted a value with the wrong type!"); 9709 } 9710 }); 9711 9712 // Update the DAG with the new chain value resulting from argument lowering. 9713 DAG.setRoot(NewRoot); 9714 9715 // Set up the argument values. 9716 unsigned i = 0; 9717 if (!FuncInfo->CanLowerReturn) { 9718 // Create a virtual register for the sret pointer, and put in a copy 9719 // from the sret argument into it. 9720 SmallVector<EVT, 1> ValueVTs; 9721 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9722 F.getReturnType()->getPointerTo( 9723 DAG.getDataLayout().getAllocaAddrSpace()), 9724 ValueVTs); 9725 MVT VT = ValueVTs[0].getSimpleVT(); 9726 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9727 Optional<ISD::NodeType> AssertOp = None; 9728 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9729 nullptr, F.getCallingConv(), AssertOp); 9730 9731 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9732 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9733 Register SRetReg = 9734 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9735 FuncInfo->DemoteRegister = SRetReg; 9736 NewRoot = 9737 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9738 DAG.setRoot(NewRoot); 9739 9740 // i indexes lowered arguments. Bump it past the hidden sret argument. 9741 ++i; 9742 } 9743 9744 SmallVector<SDValue, 4> Chains; 9745 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9746 for (const Argument &Arg : F.args()) { 9747 SmallVector<SDValue, 4> ArgValues; 9748 SmallVector<EVT, 4> ValueVTs; 9749 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9750 unsigned NumValues = ValueVTs.size(); 9751 if (NumValues == 0) 9752 continue; 9753 9754 bool ArgHasUses = !Arg.use_empty(); 9755 9756 // Elide the copying store if the target loaded this argument from a 9757 // suitable fixed stack object. 9758 if (Ins[i].Flags.isCopyElisionCandidate()) { 9759 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9760 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9761 InVals[i], ArgHasUses); 9762 } 9763 9764 // If this argument is unused then remember its value. It is used to generate 9765 // debugging information. 9766 bool isSwiftErrorArg = 9767 TLI->supportSwiftError() && 9768 Arg.hasAttribute(Attribute::SwiftError); 9769 if (!ArgHasUses && !isSwiftErrorArg) { 9770 SDB->setUnusedArgValue(&Arg, InVals[i]); 9771 9772 // Also remember any frame index for use in FastISel. 9773 if (FrameIndexSDNode *FI = 9774 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9775 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9776 } 9777 9778 for (unsigned Val = 0; Val != NumValues; ++Val) { 9779 EVT VT = ValueVTs[Val]; 9780 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9781 F.getCallingConv(), VT); 9782 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9783 *CurDAG->getContext(), F.getCallingConv(), VT); 9784 9785 // Even an apparent 'unused' swifterror argument needs to be returned. So 9786 // we do generate a copy for it that can be used on return from the 9787 // function. 9788 if (ArgHasUses || isSwiftErrorArg) { 9789 Optional<ISD::NodeType> AssertOp; 9790 if (Arg.hasAttribute(Attribute::SExt)) 9791 AssertOp = ISD::AssertSext; 9792 else if (Arg.hasAttribute(Attribute::ZExt)) 9793 AssertOp = ISD::AssertZext; 9794 9795 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9796 PartVT, VT, nullptr, 9797 F.getCallingConv(), AssertOp)); 9798 } 9799 9800 i += NumParts; 9801 } 9802 9803 // We don't need to do anything else for unused arguments. 9804 if (ArgValues.empty()) 9805 continue; 9806 9807 // Note down frame index. 9808 if (FrameIndexSDNode *FI = 9809 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9810 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9811 9812 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9813 SDB->getCurSDLoc()); 9814 9815 SDB->setValue(&Arg, Res); 9816 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9817 // We want to associate the argument with the frame index, among 9818 // involved operands, that correspond to the lowest address. The 9819 // getCopyFromParts function, called earlier, is swapping the order of 9820 // the operands to BUILD_PAIR depending on endianness. The result of 9821 // that swapping is that the least significant bits of the argument will 9822 // be in the first operand of the BUILD_PAIR node, and the most 9823 // significant bits will be in the second operand. 9824 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9825 if (LoadSDNode *LNode = 9826 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9827 if (FrameIndexSDNode *FI = 9828 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9829 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9830 } 9831 9832 // Analyses past this point are naive and don't expect an assertion. 9833 if (Res.getOpcode() == ISD::AssertZext) 9834 Res = Res.getOperand(0); 9835 9836 // Update the SwiftErrorVRegDefMap. 9837 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9838 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9839 if (Register::isVirtualRegister(Reg)) 9840 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9841 Reg); 9842 } 9843 9844 // If this argument is live outside of the entry block, insert a copy from 9845 // wherever we got it to the vreg that other BB's will reference it as. 9846 if (Res.getOpcode() == ISD::CopyFromReg) { 9847 // If we can, though, try to skip creating an unnecessary vreg. 9848 // FIXME: This isn't very clean... it would be nice to make this more 9849 // general. 9850 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9851 if (Register::isVirtualRegister(Reg)) { 9852 FuncInfo->ValueMap[&Arg] = Reg; 9853 continue; 9854 } 9855 } 9856 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9857 FuncInfo->InitializeRegForValue(&Arg); 9858 SDB->CopyToExportRegsIfNeeded(&Arg); 9859 } 9860 } 9861 9862 if (!Chains.empty()) { 9863 Chains.push_back(NewRoot); 9864 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9865 } 9866 9867 DAG.setRoot(NewRoot); 9868 9869 assert(i == InVals.size() && "Argument register count mismatch!"); 9870 9871 // If any argument copy elisions occurred and we have debug info, update the 9872 // stale frame indices used in the dbg.declare variable info table. 9873 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9874 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9875 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9876 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9877 if (I != ArgCopyElisionFrameIndexMap.end()) 9878 VI.Slot = I->second; 9879 } 9880 } 9881 9882 // Finally, if the target has anything special to do, allow it to do so. 9883 emitFunctionEntryCode(); 9884 } 9885 9886 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9887 /// ensure constants are generated when needed. Remember the virtual registers 9888 /// that need to be added to the Machine PHI nodes as input. We cannot just 9889 /// directly add them, because expansion might result in multiple MBB's for one 9890 /// BB. As such, the start of the BB might correspond to a different MBB than 9891 /// the end. 9892 void 9893 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9894 const Instruction *TI = LLVMBB->getTerminator(); 9895 9896 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9897 9898 // Check PHI nodes in successors that expect a value to be available from this 9899 // block. 9900 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9901 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9902 if (!isa<PHINode>(SuccBB->begin())) continue; 9903 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9904 9905 // If this terminator has multiple identical successors (common for 9906 // switches), only handle each succ once. 9907 if (!SuccsHandled.insert(SuccMBB).second) 9908 continue; 9909 9910 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9911 9912 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9913 // nodes and Machine PHI nodes, but the incoming operands have not been 9914 // emitted yet. 9915 for (const PHINode &PN : SuccBB->phis()) { 9916 // Ignore dead phi's. 9917 if (PN.use_empty()) 9918 continue; 9919 9920 // Skip empty types 9921 if (PN.getType()->isEmptyTy()) 9922 continue; 9923 9924 unsigned Reg; 9925 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9926 9927 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9928 unsigned &RegOut = ConstantsOut[C]; 9929 if (RegOut == 0) { 9930 RegOut = FuncInfo.CreateRegs(C); 9931 CopyValueToVirtualRegister(C, RegOut); 9932 } 9933 Reg = RegOut; 9934 } else { 9935 DenseMap<const Value *, Register>::iterator I = 9936 FuncInfo.ValueMap.find(PHIOp); 9937 if (I != FuncInfo.ValueMap.end()) 9938 Reg = I->second; 9939 else { 9940 assert(isa<AllocaInst>(PHIOp) && 9941 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9942 "Didn't codegen value into a register!??"); 9943 Reg = FuncInfo.CreateRegs(PHIOp); 9944 CopyValueToVirtualRegister(PHIOp, Reg); 9945 } 9946 } 9947 9948 // Remember that this register needs to added to the machine PHI node as 9949 // the input for this MBB. 9950 SmallVector<EVT, 4> ValueVTs; 9951 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9952 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9953 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9954 EVT VT = ValueVTs[vti]; 9955 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9956 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9957 FuncInfo.PHINodesToUpdate.push_back( 9958 std::make_pair(&*MBBI++, Reg + i)); 9959 Reg += NumRegisters; 9960 } 9961 } 9962 } 9963 9964 ConstantsOut.clear(); 9965 } 9966 9967 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9968 /// is 0. 9969 MachineBasicBlock * 9970 SelectionDAGBuilder::StackProtectorDescriptor:: 9971 AddSuccessorMBB(const BasicBlock *BB, 9972 MachineBasicBlock *ParentMBB, 9973 bool IsLikely, 9974 MachineBasicBlock *SuccMBB) { 9975 // If SuccBB has not been created yet, create it. 9976 if (!SuccMBB) { 9977 MachineFunction *MF = ParentMBB->getParent(); 9978 MachineFunction::iterator BBI(ParentMBB); 9979 SuccMBB = MF->CreateMachineBasicBlock(BB); 9980 MF->insert(++BBI, SuccMBB); 9981 } 9982 // Add it as a successor of ParentMBB. 9983 ParentMBB->addSuccessor( 9984 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9985 return SuccMBB; 9986 } 9987 9988 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9989 MachineFunction::iterator I(MBB); 9990 if (++I == FuncInfo.MF->end()) 9991 return nullptr; 9992 return &*I; 9993 } 9994 9995 /// During lowering new call nodes can be created (such as memset, etc.). 9996 /// Those will become new roots of the current DAG, but complications arise 9997 /// when they are tail calls. In such cases, the call lowering will update 9998 /// the root, but the builder still needs to know that a tail call has been 9999 /// lowered in order to avoid generating an additional return. 10000 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10001 // If the node is null, we do have a tail call. 10002 if (MaybeTC.getNode() != nullptr) 10003 DAG.setRoot(MaybeTC); 10004 else 10005 HasTailCall = true; 10006 } 10007 10008 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10009 MachineBasicBlock *SwitchMBB, 10010 MachineBasicBlock *DefaultMBB) { 10011 MachineFunction *CurMF = FuncInfo.MF; 10012 MachineBasicBlock *NextMBB = nullptr; 10013 MachineFunction::iterator BBI(W.MBB); 10014 if (++BBI != FuncInfo.MF->end()) 10015 NextMBB = &*BBI; 10016 10017 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10018 10019 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10020 10021 if (Size == 2 && W.MBB == SwitchMBB) { 10022 // If any two of the cases has the same destination, and if one value 10023 // is the same as the other, but has one bit unset that the other has set, 10024 // use bit manipulation to do two compares at once. For example: 10025 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10026 // TODO: This could be extended to merge any 2 cases in switches with 3 10027 // cases. 10028 // TODO: Handle cases where W.CaseBB != SwitchBB. 10029 CaseCluster &Small = *W.FirstCluster; 10030 CaseCluster &Big = *W.LastCluster; 10031 10032 if (Small.Low == Small.High && Big.Low == Big.High && 10033 Small.MBB == Big.MBB) { 10034 const APInt &SmallValue = Small.Low->getValue(); 10035 const APInt &BigValue = Big.Low->getValue(); 10036 10037 // Check that there is only one bit different. 10038 APInt CommonBit = BigValue ^ SmallValue; 10039 if (CommonBit.isPowerOf2()) { 10040 SDValue CondLHS = getValue(Cond); 10041 EVT VT = CondLHS.getValueType(); 10042 SDLoc DL = getCurSDLoc(); 10043 10044 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10045 DAG.getConstant(CommonBit, DL, VT)); 10046 SDValue Cond = DAG.getSetCC( 10047 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10048 ISD::SETEQ); 10049 10050 // Update successor info. 10051 // Both Small and Big will jump to Small.BB, so we sum up the 10052 // probabilities. 10053 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10054 if (BPI) 10055 addSuccessorWithProb( 10056 SwitchMBB, DefaultMBB, 10057 // The default destination is the first successor in IR. 10058 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10059 else 10060 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10061 10062 // Insert the true branch. 10063 SDValue BrCond = 10064 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10065 DAG.getBasicBlock(Small.MBB)); 10066 // Insert the false branch. 10067 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10068 DAG.getBasicBlock(DefaultMBB)); 10069 10070 DAG.setRoot(BrCond); 10071 return; 10072 } 10073 } 10074 } 10075 10076 if (TM.getOptLevel() != CodeGenOpt::None) { 10077 // Here, we order cases by probability so the most likely case will be 10078 // checked first. However, two clusters can have the same probability in 10079 // which case their relative ordering is non-deterministic. So we use Low 10080 // as a tie-breaker as clusters are guaranteed to never overlap. 10081 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10082 [](const CaseCluster &a, const CaseCluster &b) { 10083 return a.Prob != b.Prob ? 10084 a.Prob > b.Prob : 10085 a.Low->getValue().slt(b.Low->getValue()); 10086 }); 10087 10088 // Rearrange the case blocks so that the last one falls through if possible 10089 // without changing the order of probabilities. 10090 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10091 --I; 10092 if (I->Prob > W.LastCluster->Prob) 10093 break; 10094 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10095 std::swap(*I, *W.LastCluster); 10096 break; 10097 } 10098 } 10099 } 10100 10101 // Compute total probability. 10102 BranchProbability DefaultProb = W.DefaultProb; 10103 BranchProbability UnhandledProbs = DefaultProb; 10104 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10105 UnhandledProbs += I->Prob; 10106 10107 MachineBasicBlock *CurMBB = W.MBB; 10108 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10109 bool FallthroughUnreachable = false; 10110 MachineBasicBlock *Fallthrough; 10111 if (I == W.LastCluster) { 10112 // For the last cluster, fall through to the default destination. 10113 Fallthrough = DefaultMBB; 10114 FallthroughUnreachable = isa<UnreachableInst>( 10115 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10116 } else { 10117 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10118 CurMF->insert(BBI, Fallthrough); 10119 // Put Cond in a virtual register to make it available from the new blocks. 10120 ExportFromCurrentBlock(Cond); 10121 } 10122 UnhandledProbs -= I->Prob; 10123 10124 switch (I->Kind) { 10125 case CC_JumpTable: { 10126 // FIXME: Optimize away range check based on pivot comparisons. 10127 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10128 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10129 10130 // The jump block hasn't been inserted yet; insert it here. 10131 MachineBasicBlock *JumpMBB = JT->MBB; 10132 CurMF->insert(BBI, JumpMBB); 10133 10134 auto JumpProb = I->Prob; 10135 auto FallthroughProb = UnhandledProbs; 10136 10137 // If the default statement is a target of the jump table, we evenly 10138 // distribute the default probability to successors of CurMBB. Also 10139 // update the probability on the edge from JumpMBB to Fallthrough. 10140 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10141 SE = JumpMBB->succ_end(); 10142 SI != SE; ++SI) { 10143 if (*SI == DefaultMBB) { 10144 JumpProb += DefaultProb / 2; 10145 FallthroughProb -= DefaultProb / 2; 10146 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10147 JumpMBB->normalizeSuccProbs(); 10148 break; 10149 } 10150 } 10151 10152 if (FallthroughUnreachable) { 10153 // Skip the range check if the fallthrough block is unreachable. 10154 JTH->OmitRangeCheck = true; 10155 } 10156 10157 if (!JTH->OmitRangeCheck) 10158 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10159 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10160 CurMBB->normalizeSuccProbs(); 10161 10162 // The jump table header will be inserted in our current block, do the 10163 // range check, and fall through to our fallthrough block. 10164 JTH->HeaderBB = CurMBB; 10165 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10166 10167 // If we're in the right place, emit the jump table header right now. 10168 if (CurMBB == SwitchMBB) { 10169 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10170 JTH->Emitted = true; 10171 } 10172 break; 10173 } 10174 case CC_BitTests: { 10175 // FIXME: Optimize away range check based on pivot comparisons. 10176 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10177 10178 // The bit test blocks haven't been inserted yet; insert them here. 10179 for (BitTestCase &BTC : BTB->Cases) 10180 CurMF->insert(BBI, BTC.ThisBB); 10181 10182 // Fill in fields of the BitTestBlock. 10183 BTB->Parent = CurMBB; 10184 BTB->Default = Fallthrough; 10185 10186 BTB->DefaultProb = UnhandledProbs; 10187 // If the cases in bit test don't form a contiguous range, we evenly 10188 // distribute the probability on the edge to Fallthrough to two 10189 // successors of CurMBB. 10190 if (!BTB->ContiguousRange) { 10191 BTB->Prob += DefaultProb / 2; 10192 BTB->DefaultProb -= DefaultProb / 2; 10193 } 10194 10195 if (FallthroughUnreachable) { 10196 // Skip the range check if the fallthrough block is unreachable. 10197 BTB->OmitRangeCheck = true; 10198 } 10199 10200 // If we're in the right place, emit the bit test header right now. 10201 if (CurMBB == SwitchMBB) { 10202 visitBitTestHeader(*BTB, SwitchMBB); 10203 BTB->Emitted = true; 10204 } 10205 break; 10206 } 10207 case CC_Range: { 10208 const Value *RHS, *LHS, *MHS; 10209 ISD::CondCode CC; 10210 if (I->Low == I->High) { 10211 // Check Cond == I->Low. 10212 CC = ISD::SETEQ; 10213 LHS = Cond; 10214 RHS=I->Low; 10215 MHS = nullptr; 10216 } else { 10217 // Check I->Low <= Cond <= I->High. 10218 CC = ISD::SETLE; 10219 LHS = I->Low; 10220 MHS = Cond; 10221 RHS = I->High; 10222 } 10223 10224 // If Fallthrough is unreachable, fold away the comparison. 10225 if (FallthroughUnreachable) 10226 CC = ISD::SETTRUE; 10227 10228 // The false probability is the sum of all unhandled cases. 10229 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10230 getCurSDLoc(), I->Prob, UnhandledProbs); 10231 10232 if (CurMBB == SwitchMBB) 10233 visitSwitchCase(CB, SwitchMBB); 10234 else 10235 SL->SwitchCases.push_back(CB); 10236 10237 break; 10238 } 10239 } 10240 CurMBB = Fallthrough; 10241 } 10242 } 10243 10244 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10245 CaseClusterIt First, 10246 CaseClusterIt Last) { 10247 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10248 if (X.Prob != CC.Prob) 10249 return X.Prob > CC.Prob; 10250 10251 // Ties are broken by comparing the case value. 10252 return X.Low->getValue().slt(CC.Low->getValue()); 10253 }); 10254 } 10255 10256 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10257 const SwitchWorkListItem &W, 10258 Value *Cond, 10259 MachineBasicBlock *SwitchMBB) { 10260 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10261 "Clusters not sorted?"); 10262 10263 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10264 10265 // Balance the tree based on branch probabilities to create a near-optimal (in 10266 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10267 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10268 CaseClusterIt LastLeft = W.FirstCluster; 10269 CaseClusterIt FirstRight = W.LastCluster; 10270 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10271 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10272 10273 // Move LastLeft and FirstRight towards each other from opposite directions to 10274 // find a partitioning of the clusters which balances the probability on both 10275 // sides. If LeftProb and RightProb are equal, alternate which side is 10276 // taken to ensure 0-probability nodes are distributed evenly. 10277 unsigned I = 0; 10278 while (LastLeft + 1 < FirstRight) { 10279 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10280 LeftProb += (++LastLeft)->Prob; 10281 else 10282 RightProb += (--FirstRight)->Prob; 10283 I++; 10284 } 10285 10286 while (true) { 10287 // Our binary search tree differs from a typical BST in that ours can have up 10288 // to three values in each leaf. The pivot selection above doesn't take that 10289 // into account, which means the tree might require more nodes and be less 10290 // efficient. We compensate for this here. 10291 10292 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10293 unsigned NumRight = W.LastCluster - FirstRight + 1; 10294 10295 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10296 // If one side has less than 3 clusters, and the other has more than 3, 10297 // consider taking a cluster from the other side. 10298 10299 if (NumLeft < NumRight) { 10300 // Consider moving the first cluster on the right to the left side. 10301 CaseCluster &CC = *FirstRight; 10302 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10303 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10304 if (LeftSideRank <= RightSideRank) { 10305 // Moving the cluster to the left does not demote it. 10306 ++LastLeft; 10307 ++FirstRight; 10308 continue; 10309 } 10310 } else { 10311 assert(NumRight < NumLeft); 10312 // Consider moving the last element on the left to the right side. 10313 CaseCluster &CC = *LastLeft; 10314 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10315 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10316 if (RightSideRank <= LeftSideRank) { 10317 // Moving the cluster to the right does not demot it. 10318 --LastLeft; 10319 --FirstRight; 10320 continue; 10321 } 10322 } 10323 } 10324 break; 10325 } 10326 10327 assert(LastLeft + 1 == FirstRight); 10328 assert(LastLeft >= W.FirstCluster); 10329 assert(FirstRight <= W.LastCluster); 10330 10331 // Use the first element on the right as pivot since we will make less-than 10332 // comparisons against it. 10333 CaseClusterIt PivotCluster = FirstRight; 10334 assert(PivotCluster > W.FirstCluster); 10335 assert(PivotCluster <= W.LastCluster); 10336 10337 CaseClusterIt FirstLeft = W.FirstCluster; 10338 CaseClusterIt LastRight = W.LastCluster; 10339 10340 const ConstantInt *Pivot = PivotCluster->Low; 10341 10342 // New blocks will be inserted immediately after the current one. 10343 MachineFunction::iterator BBI(W.MBB); 10344 ++BBI; 10345 10346 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10347 // we can branch to its destination directly if it's squeezed exactly in 10348 // between the known lower bound and Pivot - 1. 10349 MachineBasicBlock *LeftMBB; 10350 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10351 FirstLeft->Low == W.GE && 10352 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10353 LeftMBB = FirstLeft->MBB; 10354 } else { 10355 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10356 FuncInfo.MF->insert(BBI, LeftMBB); 10357 WorkList.push_back( 10358 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10359 // Put Cond in a virtual register to make it available from the new blocks. 10360 ExportFromCurrentBlock(Cond); 10361 } 10362 10363 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10364 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10365 // directly if RHS.High equals the current upper bound. 10366 MachineBasicBlock *RightMBB; 10367 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10368 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10369 RightMBB = FirstRight->MBB; 10370 } else { 10371 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10372 FuncInfo.MF->insert(BBI, RightMBB); 10373 WorkList.push_back( 10374 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10375 // Put Cond in a virtual register to make it available from the new blocks. 10376 ExportFromCurrentBlock(Cond); 10377 } 10378 10379 // Create the CaseBlock record that will be used to lower the branch. 10380 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10381 getCurSDLoc(), LeftProb, RightProb); 10382 10383 if (W.MBB == SwitchMBB) 10384 visitSwitchCase(CB, SwitchMBB); 10385 else 10386 SL->SwitchCases.push_back(CB); 10387 } 10388 10389 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10390 // from the swith statement. 10391 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10392 BranchProbability PeeledCaseProb) { 10393 if (PeeledCaseProb == BranchProbability::getOne()) 10394 return BranchProbability::getZero(); 10395 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10396 10397 uint32_t Numerator = CaseProb.getNumerator(); 10398 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10399 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10400 } 10401 10402 // Try to peel the top probability case if it exceeds the threshold. 10403 // Return current MachineBasicBlock for the switch statement if the peeling 10404 // does not occur. 10405 // If the peeling is performed, return the newly created MachineBasicBlock 10406 // for the peeled switch statement. Also update Clusters to remove the peeled 10407 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10408 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10409 const SwitchInst &SI, CaseClusterVector &Clusters, 10410 BranchProbability &PeeledCaseProb) { 10411 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10412 // Don't perform if there is only one cluster or optimizing for size. 10413 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10414 TM.getOptLevel() == CodeGenOpt::None || 10415 SwitchMBB->getParent()->getFunction().hasMinSize()) 10416 return SwitchMBB; 10417 10418 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10419 unsigned PeeledCaseIndex = 0; 10420 bool SwitchPeeled = false; 10421 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10422 CaseCluster &CC = Clusters[Index]; 10423 if (CC.Prob < TopCaseProb) 10424 continue; 10425 TopCaseProb = CC.Prob; 10426 PeeledCaseIndex = Index; 10427 SwitchPeeled = true; 10428 } 10429 if (!SwitchPeeled) 10430 return SwitchMBB; 10431 10432 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10433 << TopCaseProb << "\n"); 10434 10435 // Record the MBB for the peeled switch statement. 10436 MachineFunction::iterator BBI(SwitchMBB); 10437 ++BBI; 10438 MachineBasicBlock *PeeledSwitchMBB = 10439 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10440 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10441 10442 ExportFromCurrentBlock(SI.getCondition()); 10443 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10444 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10445 nullptr, nullptr, TopCaseProb.getCompl()}; 10446 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10447 10448 Clusters.erase(PeeledCaseIt); 10449 for (CaseCluster &CC : Clusters) { 10450 LLVM_DEBUG( 10451 dbgs() << "Scale the probablity for one cluster, before scaling: " 10452 << CC.Prob << "\n"); 10453 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10454 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10455 } 10456 PeeledCaseProb = TopCaseProb; 10457 return PeeledSwitchMBB; 10458 } 10459 10460 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10461 // Extract cases from the switch. 10462 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10463 CaseClusterVector Clusters; 10464 Clusters.reserve(SI.getNumCases()); 10465 for (auto I : SI.cases()) { 10466 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10467 const ConstantInt *CaseVal = I.getCaseValue(); 10468 BranchProbability Prob = 10469 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10470 : BranchProbability(1, SI.getNumCases() + 1); 10471 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10472 } 10473 10474 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10475 10476 // Cluster adjacent cases with the same destination. We do this at all 10477 // optimization levels because it's cheap to do and will make codegen faster 10478 // if there are many clusters. 10479 sortAndRangeify(Clusters); 10480 10481 // The branch probablity of the peeled case. 10482 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10483 MachineBasicBlock *PeeledSwitchMBB = 10484 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10485 10486 // If there is only the default destination, jump there directly. 10487 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10488 if (Clusters.empty()) { 10489 assert(PeeledSwitchMBB == SwitchMBB); 10490 SwitchMBB->addSuccessor(DefaultMBB); 10491 if (DefaultMBB != NextBlock(SwitchMBB)) { 10492 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10493 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10494 } 10495 return; 10496 } 10497 10498 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10499 SL->findBitTestClusters(Clusters, &SI); 10500 10501 LLVM_DEBUG({ 10502 dbgs() << "Case clusters: "; 10503 for (const CaseCluster &C : Clusters) { 10504 if (C.Kind == CC_JumpTable) 10505 dbgs() << "JT:"; 10506 if (C.Kind == CC_BitTests) 10507 dbgs() << "BT:"; 10508 10509 C.Low->getValue().print(dbgs(), true); 10510 if (C.Low != C.High) { 10511 dbgs() << '-'; 10512 C.High->getValue().print(dbgs(), true); 10513 } 10514 dbgs() << ' '; 10515 } 10516 dbgs() << '\n'; 10517 }); 10518 10519 assert(!Clusters.empty()); 10520 SwitchWorkList WorkList; 10521 CaseClusterIt First = Clusters.begin(); 10522 CaseClusterIt Last = Clusters.end() - 1; 10523 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10524 // Scale the branchprobability for DefaultMBB if the peel occurs and 10525 // DefaultMBB is not replaced. 10526 if (PeeledCaseProb != BranchProbability::getZero() && 10527 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10528 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10529 WorkList.push_back( 10530 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10531 10532 while (!WorkList.empty()) { 10533 SwitchWorkListItem W = WorkList.back(); 10534 WorkList.pop_back(); 10535 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10536 10537 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10538 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10539 // For optimized builds, lower large range as a balanced binary tree. 10540 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10541 continue; 10542 } 10543 10544 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10545 } 10546 } 10547 10548 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10549 SmallVector<EVT, 4> ValueVTs; 10550 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10551 ValueVTs); 10552 unsigned NumValues = ValueVTs.size(); 10553 if (NumValues == 0) return; 10554 10555 SmallVector<SDValue, 4> Values(NumValues); 10556 SDValue Op = getValue(I.getOperand(0)); 10557 10558 for (unsigned i = 0; i != NumValues; ++i) 10559 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10560 SDValue(Op.getNode(), Op.getResNo() + i)); 10561 10562 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10563 DAG.getVTList(ValueVTs), Values)); 10564 } 10565