1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Triple.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Analysis/AliasAnalysis.h" 30 #include "llvm/Analysis/BlockFrequencyInfo.h" 31 #include "llvm/Analysis/BranchProbabilityInfo.h" 32 #include "llvm/Analysis/ConstantFolding.h" 33 #include "llvm/Analysis/EHPersonalities.h" 34 #include "llvm/Analysis/Loads.h" 35 #include "llvm/Analysis/MemoryLocation.h" 36 #include "llvm/Analysis/ProfileSummaryInfo.h" 37 #include "llvm/Analysis/TargetLibraryInfo.h" 38 #include "llvm/Analysis/ValueTracking.h" 39 #include "llvm/Analysis/VectorUtils.h" 40 #include "llvm/CodeGen/Analysis.h" 41 #include "llvm/CodeGen/FunctionLoweringInfo.h" 42 #include "llvm/CodeGen/GCMetadata.h" 43 #include "llvm/CodeGen/ISDOpcodes.h" 44 #include "llvm/CodeGen/MachineBasicBlock.h" 45 #include "llvm/CodeGen/MachineFrameInfo.h" 46 #include "llvm/CodeGen/MachineFunction.h" 47 #include "llvm/CodeGen/MachineInstr.h" 48 #include "llvm/CodeGen/MachineInstrBuilder.h" 49 #include "llvm/CodeGen/MachineJumpTableInfo.h" 50 #include "llvm/CodeGen/MachineMemOperand.h" 51 #include "llvm/CodeGen/MachineModuleInfo.h" 52 #include "llvm/CodeGen/MachineOperand.h" 53 #include "llvm/CodeGen/MachineRegisterInfo.h" 54 #include "llvm/CodeGen/RuntimeLibcalls.h" 55 #include "llvm/CodeGen/SelectionDAG.h" 56 #include "llvm/CodeGen/SelectionDAGNodes.h" 57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 58 #include "llvm/CodeGen/StackMaps.h" 59 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 60 #include "llvm/CodeGen/TargetFrameLowering.h" 61 #include "llvm/CodeGen/TargetInstrInfo.h" 62 #include "llvm/CodeGen/TargetLowering.h" 63 #include "llvm/CodeGen/TargetOpcodes.h" 64 #include "llvm/CodeGen/TargetRegisterInfo.h" 65 #include "llvm/CodeGen/TargetSubtargetInfo.h" 66 #include "llvm/CodeGen/ValueTypes.h" 67 #include "llvm/CodeGen/WinEHFuncInfo.h" 68 #include "llvm/IR/Argument.h" 69 #include "llvm/IR/Attributes.h" 70 #include "llvm/IR/BasicBlock.h" 71 #include "llvm/IR/CFG.h" 72 #include "llvm/IR/CallSite.h" 73 #include "llvm/IR/CallingConv.h" 74 #include "llvm/IR/Constant.h" 75 #include "llvm/IR/ConstantRange.h" 76 #include "llvm/IR/Constants.h" 77 #include "llvm/IR/DataLayout.h" 78 #include "llvm/IR/DebugInfoMetadata.h" 79 #include "llvm/IR/DebugLoc.h" 80 #include "llvm/IR/DerivedTypes.h" 81 #include "llvm/IR/Function.h" 82 #include "llvm/IR/GetElementPtrTypeIterator.h" 83 #include "llvm/IR/InlineAsm.h" 84 #include "llvm/IR/InstrTypes.h" 85 #include "llvm/IR/Instruction.h" 86 #include "llvm/IR/Instructions.h" 87 #include "llvm/IR/IntrinsicInst.h" 88 #include "llvm/IR/Intrinsics.h" 89 #include "llvm/IR/IntrinsicsAArch64.h" 90 #include "llvm/IR/IntrinsicsWebAssembly.h" 91 #include "llvm/IR/LLVMContext.h" 92 #include "llvm/IR/Metadata.h" 93 #include "llvm/IR/Module.h" 94 #include "llvm/IR/Operator.h" 95 #include "llvm/IR/PatternMatch.h" 96 #include "llvm/IR/Statepoint.h" 97 #include "llvm/IR/Type.h" 98 #include "llvm/IR/User.h" 99 #include "llvm/IR/Value.h" 100 #include "llvm/MC/MCContext.h" 101 #include "llvm/MC/MCSymbol.h" 102 #include "llvm/Support/AtomicOrdering.h" 103 #include "llvm/Support/BranchProbability.h" 104 #include "llvm/Support/Casting.h" 105 #include "llvm/Support/CodeGen.h" 106 #include "llvm/Support/CommandLine.h" 107 #include "llvm/Support/Compiler.h" 108 #include "llvm/Support/Debug.h" 109 #include "llvm/Support/ErrorHandling.h" 110 #include "llvm/Support/MachineValueType.h" 111 #include "llvm/Support/MathExtras.h" 112 #include "llvm/Support/raw_ostream.h" 113 #include "llvm/Target/TargetIntrinsicInfo.h" 114 #include "llvm/Target/TargetMachine.h" 115 #include "llvm/Target/TargetOptions.h" 116 #include "llvm/Transforms/Utils/Local.h" 117 #include <algorithm> 118 #include <cassert> 119 #include <cstddef> 120 #include <cstdint> 121 #include <cstring> 122 #include <iterator> 123 #include <limits> 124 #include <numeric> 125 #include <tuple> 126 #include <utility> 127 #include <vector> 128 129 using namespace llvm; 130 using namespace PatternMatch; 131 using namespace SwitchCG; 132 133 #define DEBUG_TYPE "isel" 134 135 /// LimitFloatPrecision - Generate low-precision inline sequences for 136 /// some float libcalls (6, 8 or 12 bits). 137 static unsigned LimitFloatPrecision; 138 139 static cl::opt<unsigned, true> 140 LimitFPPrecision("limit-float-precision", 141 cl::desc("Generate low-precision inline sequences " 142 "for some float libcalls"), 143 cl::location(LimitFloatPrecision), cl::Hidden, 144 cl::init(0)); 145 146 static cl::opt<unsigned> SwitchPeelThreshold( 147 "switch-peel-threshold", cl::Hidden, cl::init(66), 148 cl::desc("Set the case probability threshold for peeling the case from a " 149 "switch statement. A value greater than 100 will void this " 150 "optimization")); 151 152 // Limit the width of DAG chains. This is important in general to prevent 153 // DAG-based analysis from blowing up. For example, alias analysis and 154 // load clustering may not complete in reasonable time. It is difficult to 155 // recognize and avoid this situation within each individual analysis, and 156 // future analyses are likely to have the same behavior. Limiting DAG width is 157 // the safe approach and will be especially important with global DAGs. 158 // 159 // MaxParallelChains default is arbitrarily high to avoid affecting 160 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 161 // sequence over this should have been converted to llvm.memcpy by the 162 // frontend. It is easy to induce this behavior with .ll code such as: 163 // %buffer = alloca [4096 x i8] 164 // %data = load [4096 x i8]* %argPtr 165 // store [4096 x i8] %data, [4096 x i8]* %buffer 166 static const unsigned MaxParallelChains = 64; 167 168 // Return the calling convention if the Value passed requires ABI mangling as it 169 // is a parameter to a function or a return value from a function which is not 170 // an intrinsic. 171 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 172 if (auto *R = dyn_cast<ReturnInst>(V)) 173 return R->getParent()->getParent()->getCallingConv(); 174 175 if (auto *CI = dyn_cast<CallInst>(V)) { 176 const bool IsInlineAsm = CI->isInlineAsm(); 177 const bool IsIndirectFunctionCall = 178 !IsInlineAsm && !CI->getCalledFunction(); 179 180 // It is possible that the call instruction is an inline asm statement or an 181 // indirect function call in which case the return value of 182 // getCalledFunction() would be nullptr. 183 const bool IsInstrinsicCall = 184 !IsInlineAsm && !IsIndirectFunctionCall && 185 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 186 187 if (!IsInlineAsm && !IsInstrinsicCall) 188 return CI->getCallingConv(); 189 } 190 191 return None; 192 } 193 194 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 195 const SDValue *Parts, unsigned NumParts, 196 MVT PartVT, EVT ValueVT, const Value *V, 197 Optional<CallingConv::ID> CC); 198 199 /// getCopyFromParts - Create a value that contains the specified legal parts 200 /// combined into the value they represent. If the parts combine to a type 201 /// larger than ValueVT then AssertOp can be used to specify whether the extra 202 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 203 /// (ISD::AssertSext). 204 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 205 const SDValue *Parts, unsigned NumParts, 206 MVT PartVT, EVT ValueVT, const Value *V, 207 Optional<CallingConv::ID> CC = None, 208 Optional<ISD::NodeType> AssertOp = None) { 209 if (ValueVT.isVector()) 210 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 211 CC); 212 213 assert(NumParts > 0 && "No parts to assemble!"); 214 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 215 SDValue Val = Parts[0]; 216 217 if (NumParts > 1) { 218 // Assemble the value from multiple parts. 219 if (ValueVT.isInteger()) { 220 unsigned PartBits = PartVT.getSizeInBits(); 221 unsigned ValueBits = ValueVT.getSizeInBits(); 222 223 // Assemble the power of 2 part. 224 unsigned RoundParts = 225 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 226 unsigned RoundBits = PartBits * RoundParts; 227 EVT RoundVT = RoundBits == ValueBits ? 228 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 229 SDValue Lo, Hi; 230 231 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 232 233 if (RoundParts > 2) { 234 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 235 PartVT, HalfVT, V); 236 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 237 RoundParts / 2, PartVT, HalfVT, V); 238 } else { 239 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 240 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 241 } 242 243 if (DAG.getDataLayout().isBigEndian()) 244 std::swap(Lo, Hi); 245 246 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 247 248 if (RoundParts < NumParts) { 249 // Assemble the trailing non-power-of-2 part. 250 unsigned OddParts = NumParts - RoundParts; 251 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 252 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 253 OddVT, V, CC); 254 255 // Combine the round and odd parts. 256 Lo = Val; 257 if (DAG.getDataLayout().isBigEndian()) 258 std::swap(Lo, Hi); 259 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 260 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 261 Hi = 262 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 263 DAG.getConstant(Lo.getValueSizeInBits(), DL, 264 TLI.getPointerTy(DAG.getDataLayout()))); 265 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 266 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 267 } 268 } else if (PartVT.isFloatingPoint()) { 269 // FP split into multiple FP parts (for ppcf128) 270 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 271 "Unexpected split"); 272 SDValue Lo, Hi; 273 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 274 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 275 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 276 std::swap(Lo, Hi); 277 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 278 } else { 279 // FP split into integer parts (soft fp) 280 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 281 !PartVT.isVector() && "Unexpected split"); 282 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 283 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 284 } 285 } 286 287 // There is now one part, held in Val. Correct it to match ValueVT. 288 // PartEVT is the type of the register class that holds the value. 289 // ValueVT is the type of the inline asm operation. 290 EVT PartEVT = Val.getValueType(); 291 292 if (PartEVT == ValueVT) 293 return Val; 294 295 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 296 ValueVT.bitsLT(PartEVT)) { 297 // For an FP value in an integer part, we need to truncate to the right 298 // width first. 299 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 300 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 301 } 302 303 // Handle types that have the same size. 304 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 305 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 306 307 // Handle types with different sizes. 308 if (PartEVT.isInteger() && ValueVT.isInteger()) { 309 if (ValueVT.bitsLT(PartEVT)) { 310 // For a truncate, see if we have any information to 311 // indicate whether the truncated bits will always be 312 // zero or sign-extension. 313 if (AssertOp.hasValue()) 314 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 315 DAG.getValueType(ValueVT)); 316 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 317 } 318 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 319 } 320 321 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 322 // FP_ROUND's are always exact here. 323 if (ValueVT.bitsLT(Val.getValueType())) 324 return DAG.getNode( 325 ISD::FP_ROUND, DL, ValueVT, Val, 326 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 327 328 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 329 } 330 331 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 332 // then truncating. 333 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 334 ValueVT.bitsLT(PartEVT)) { 335 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 336 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 337 } 338 339 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 340 } 341 342 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 343 const Twine &ErrMsg) { 344 const Instruction *I = dyn_cast_or_null<Instruction>(V); 345 if (!V) 346 return Ctx.emitError(ErrMsg); 347 348 const char *AsmError = ", possible invalid constraint for vector type"; 349 if (const CallInst *CI = dyn_cast<CallInst>(I)) 350 if (isa<InlineAsm>(CI->getCalledValue())) 351 return Ctx.emitError(I, ErrMsg + AsmError); 352 353 return Ctx.emitError(I, ErrMsg); 354 } 355 356 /// getCopyFromPartsVector - Create a value that contains the specified legal 357 /// parts combined into the value they represent. If the parts combine to a 358 /// type larger than ValueVT then AssertOp can be used to specify whether the 359 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 360 /// ValueVT (ISD::AssertSext). 361 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 362 const SDValue *Parts, unsigned NumParts, 363 MVT PartVT, EVT ValueVT, const Value *V, 364 Optional<CallingConv::ID> CallConv) { 365 assert(ValueVT.isVector() && "Not a vector value"); 366 assert(NumParts > 0 && "No parts to assemble!"); 367 const bool IsABIRegCopy = CallConv.hasValue(); 368 369 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 370 SDValue Val = Parts[0]; 371 372 // Handle a multi-element vector. 373 if (NumParts > 1) { 374 EVT IntermediateVT; 375 MVT RegisterVT; 376 unsigned NumIntermediates; 377 unsigned NumRegs; 378 379 if (IsABIRegCopy) { 380 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 381 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 382 NumIntermediates, RegisterVT); 383 } else { 384 NumRegs = 385 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 386 NumIntermediates, RegisterVT); 387 } 388 389 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 390 NumParts = NumRegs; // Silence a compiler warning. 391 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 392 assert(RegisterVT.getSizeInBits() == 393 Parts[0].getSimpleValueType().getSizeInBits() && 394 "Part type sizes don't match!"); 395 396 // Assemble the parts into intermediate operands. 397 SmallVector<SDValue, 8> Ops(NumIntermediates); 398 if (NumIntermediates == NumParts) { 399 // If the register was not expanded, truncate or copy the value, 400 // as appropriate. 401 for (unsigned i = 0; i != NumParts; ++i) 402 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 403 PartVT, IntermediateVT, V); 404 } else if (NumParts > 0) { 405 // If the intermediate type was expanded, build the intermediate 406 // operands from the parts. 407 assert(NumParts % NumIntermediates == 0 && 408 "Must expand into a divisible number of parts!"); 409 unsigned Factor = NumParts / NumIntermediates; 410 for (unsigned i = 0; i != NumIntermediates; ++i) 411 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 412 PartVT, IntermediateVT, V); 413 } 414 415 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 416 // intermediate operands. 417 EVT BuiltVectorTy = 418 IntermediateVT.isVector() 419 ? EVT::getVectorVT( 420 *DAG.getContext(), IntermediateVT.getScalarType(), 421 IntermediateVT.getVectorElementCount() * NumParts) 422 : EVT::getVectorVT(*DAG.getContext(), 423 IntermediateVT.getScalarType(), 424 NumIntermediates); 425 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 426 : ISD::BUILD_VECTOR, 427 DL, BuiltVectorTy, Ops); 428 } 429 430 // There is now one part, held in Val. Correct it to match ValueVT. 431 EVT PartEVT = Val.getValueType(); 432 433 if (PartEVT == ValueVT) 434 return Val; 435 436 if (PartEVT.isVector()) { 437 // If the element type of the source/dest vectors are the same, but the 438 // parts vector has more elements than the value vector, then we have a 439 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 440 // elements we want. 441 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 442 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 443 "Cannot narrow, it would be a lossy transformation"); 444 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 445 DAG.getVectorIdxConstant(0, DL)); 446 } 447 448 // Vector/Vector bitcast. 449 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 450 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 451 452 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 453 "Cannot handle this kind of promotion"); 454 // Promoted vector extract 455 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 456 457 } 458 459 // Trivial bitcast if the types are the same size and the destination 460 // vector type is legal. 461 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 462 TLI.isTypeLegal(ValueVT)) 463 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 464 465 if (ValueVT.getVectorNumElements() != 1) { 466 // Certain ABIs require that vectors are passed as integers. For vectors 467 // are the same size, this is an obvious bitcast. 468 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 469 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 470 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 471 // Bitcast Val back the original type and extract the corresponding 472 // vector we want. 473 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 474 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 475 ValueVT.getVectorElementType(), Elts); 476 Val = DAG.getBitcast(WiderVecType, Val); 477 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 478 DAG.getVectorIdxConstant(0, DL)); 479 } 480 481 diagnosePossiblyInvalidConstraint( 482 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 483 return DAG.getUNDEF(ValueVT); 484 } 485 486 // Handle cases such as i8 -> <1 x i1> 487 EVT ValueSVT = ValueVT.getVectorElementType(); 488 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 489 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 490 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 491 else 492 Val = ValueVT.isFloatingPoint() 493 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 494 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 495 } 496 497 return DAG.getBuildVector(ValueVT, DL, Val); 498 } 499 500 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 501 SDValue Val, SDValue *Parts, unsigned NumParts, 502 MVT PartVT, const Value *V, 503 Optional<CallingConv::ID> CallConv); 504 505 /// getCopyToParts - Create a series of nodes that contain the specified value 506 /// split into legal parts. If the parts contain more bits than Val, then, for 507 /// integers, ExtendKind can be used to specify how to generate the extra bits. 508 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 509 SDValue *Parts, unsigned NumParts, MVT PartVT, 510 const Value *V, 511 Optional<CallingConv::ID> CallConv = None, 512 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 513 EVT ValueVT = Val.getValueType(); 514 515 // Handle the vector case separately. 516 if (ValueVT.isVector()) 517 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 518 CallConv); 519 520 unsigned PartBits = PartVT.getSizeInBits(); 521 unsigned OrigNumParts = NumParts; 522 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 523 "Copying to an illegal type!"); 524 525 if (NumParts == 0) 526 return; 527 528 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 529 EVT PartEVT = PartVT; 530 if (PartEVT == ValueVT) { 531 assert(NumParts == 1 && "No-op copy with multiple parts!"); 532 Parts[0] = Val; 533 return; 534 } 535 536 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 537 // If the parts cover more bits than the value has, promote the value. 538 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 539 assert(NumParts == 1 && "Do not know what to promote to!"); 540 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 541 } else { 542 if (ValueVT.isFloatingPoint()) { 543 // FP values need to be bitcast, then extended if they are being put 544 // into a larger container. 545 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 546 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 547 } 548 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 549 ValueVT.isInteger() && 550 "Unknown mismatch!"); 551 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 552 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 553 if (PartVT == MVT::x86mmx) 554 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 555 } 556 } else if (PartBits == ValueVT.getSizeInBits()) { 557 // Different types of the same size. 558 assert(NumParts == 1 && PartEVT != ValueVT); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 561 // If the parts cover less bits than value has, truncate the value. 562 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 563 ValueVT.isInteger() && 564 "Unknown mismatch!"); 565 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 566 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 567 if (PartVT == MVT::x86mmx) 568 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 569 } 570 571 // The value may have changed - recompute ValueVT. 572 ValueVT = Val.getValueType(); 573 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 574 "Failed to tile the value with PartVT!"); 575 576 if (NumParts == 1) { 577 if (PartEVT != ValueVT) { 578 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 579 "scalar-to-vector conversion failed"); 580 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 581 } 582 583 Parts[0] = Val; 584 return; 585 } 586 587 // Expand the value into multiple parts. 588 if (NumParts & (NumParts - 1)) { 589 // The number of parts is not a power of 2. Split off and copy the tail. 590 assert(PartVT.isInteger() && ValueVT.isInteger() && 591 "Do not know what to expand to!"); 592 unsigned RoundParts = 1 << Log2_32(NumParts); 593 unsigned RoundBits = RoundParts * PartBits; 594 unsigned OddParts = NumParts - RoundParts; 595 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 596 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 597 598 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 599 CallConv); 600 601 if (DAG.getDataLayout().isBigEndian()) 602 // The odd parts were reversed by getCopyToParts - unreverse them. 603 std::reverse(Parts + RoundParts, Parts + NumParts); 604 605 NumParts = RoundParts; 606 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 607 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 608 } 609 610 // The number of parts is a power of 2. Repeatedly bisect the value using 611 // EXTRACT_ELEMENT. 612 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 613 EVT::getIntegerVT(*DAG.getContext(), 614 ValueVT.getSizeInBits()), 615 Val); 616 617 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 618 for (unsigned i = 0; i < NumParts; i += StepSize) { 619 unsigned ThisBits = StepSize * PartBits / 2; 620 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 621 SDValue &Part0 = Parts[i]; 622 SDValue &Part1 = Parts[i+StepSize/2]; 623 624 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 625 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 626 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 627 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 628 629 if (ThisBits == PartBits && ThisVT != PartVT) { 630 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 631 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 632 } 633 } 634 } 635 636 if (DAG.getDataLayout().isBigEndian()) 637 std::reverse(Parts, Parts + OrigNumParts); 638 } 639 640 static SDValue widenVectorToPartType(SelectionDAG &DAG, 641 SDValue Val, const SDLoc &DL, EVT PartVT) { 642 if (!PartVT.isVector()) 643 return SDValue(); 644 645 EVT ValueVT = Val.getValueType(); 646 unsigned PartNumElts = PartVT.getVectorNumElements(); 647 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 648 if (PartNumElts > ValueNumElts && 649 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 650 EVT ElementVT = PartVT.getVectorElementType(); 651 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 652 // undef elements. 653 SmallVector<SDValue, 16> Ops; 654 DAG.ExtractVectorElements(Val, Ops); 655 SDValue EltUndef = DAG.getUNDEF(ElementVT); 656 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 657 Ops.push_back(EltUndef); 658 659 // FIXME: Use CONCAT for 2x -> 4x. 660 return DAG.getBuildVector(PartVT, DL, Ops); 661 } 662 663 return SDValue(); 664 } 665 666 /// getCopyToPartsVector - Create a series of nodes that contain the specified 667 /// value split into legal parts. 668 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 669 SDValue Val, SDValue *Parts, unsigned NumParts, 670 MVT PartVT, const Value *V, 671 Optional<CallingConv::ID> CallConv) { 672 EVT ValueVT = Val.getValueType(); 673 assert(ValueVT.isVector() && "Not a vector"); 674 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 675 const bool IsABIRegCopy = CallConv.hasValue(); 676 677 if (NumParts == 1) { 678 EVT PartEVT = PartVT; 679 if (PartEVT == ValueVT) { 680 // Nothing to do. 681 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 682 // Bitconvert vector->vector case. 683 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 684 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 685 Val = Widened; 686 } else if (PartVT.isVector() && 687 PartEVT.getVectorElementType().bitsGE( 688 ValueVT.getVectorElementType()) && 689 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 690 691 // Promoted vector extract 692 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 693 } else { 694 if (ValueVT.getVectorNumElements() == 1) { 695 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 696 DAG.getVectorIdxConstant(0, DL)); 697 } else { 698 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 699 "lossy conversion of vector to scalar type"); 700 EVT IntermediateType = 701 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 702 Val = DAG.getBitcast(IntermediateType, Val); 703 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 704 } 705 } 706 707 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 708 Parts[0] = Val; 709 return; 710 } 711 712 // Handle a multi-element vector. 713 EVT IntermediateVT; 714 MVT RegisterVT; 715 unsigned NumIntermediates; 716 unsigned NumRegs; 717 if (IsABIRegCopy) { 718 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 719 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 720 NumIntermediates, RegisterVT); 721 } else { 722 NumRegs = 723 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 724 NumIntermediates, RegisterVT); 725 } 726 727 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 728 NumParts = NumRegs; // Silence a compiler warning. 729 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 730 731 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 732 IntermediateVT.getVectorNumElements() : 1; 733 734 // Convert the vector to the appropriate type if necessary. 735 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 736 737 EVT BuiltVectorTy = EVT::getVectorVT( 738 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 739 if (ValueVT != BuiltVectorTy) { 740 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 741 Val = Widened; 742 743 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 744 } 745 746 // Split the vector into intermediate operands. 747 SmallVector<SDValue, 8> Ops(NumIntermediates); 748 for (unsigned i = 0; i != NumIntermediates; ++i) { 749 if (IntermediateVT.isVector()) { 750 Ops[i] = 751 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 752 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 753 } else { 754 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 755 DAG.getVectorIdxConstant(i, DL)); 756 } 757 } 758 759 // Split the intermediate operands into legal parts. 760 if (NumParts == NumIntermediates) { 761 // If the register was not expanded, promote or copy the value, 762 // as appropriate. 763 for (unsigned i = 0; i != NumParts; ++i) 764 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 765 } else if (NumParts > 0) { 766 // If the intermediate type was expanded, split each the value into 767 // legal parts. 768 assert(NumIntermediates != 0 && "division by zero"); 769 assert(NumParts % NumIntermediates == 0 && 770 "Must expand into a divisible number of parts!"); 771 unsigned Factor = NumParts / NumIntermediates; 772 for (unsigned i = 0; i != NumIntermediates; ++i) 773 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 774 CallConv); 775 } 776 } 777 778 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 779 EVT valuevt, Optional<CallingConv::ID> CC) 780 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 781 RegCount(1, regs.size()), CallConv(CC) {} 782 783 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 784 const DataLayout &DL, unsigned Reg, Type *Ty, 785 Optional<CallingConv::ID> CC) { 786 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 787 788 CallConv = CC; 789 790 for (EVT ValueVT : ValueVTs) { 791 unsigned NumRegs = 792 isABIMangled() 793 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 794 : TLI.getNumRegisters(Context, ValueVT); 795 MVT RegisterVT = 796 isABIMangled() 797 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 798 : TLI.getRegisterType(Context, ValueVT); 799 for (unsigned i = 0; i != NumRegs; ++i) 800 Regs.push_back(Reg + i); 801 RegVTs.push_back(RegisterVT); 802 RegCount.push_back(NumRegs); 803 Reg += NumRegs; 804 } 805 } 806 807 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 808 FunctionLoweringInfo &FuncInfo, 809 const SDLoc &dl, SDValue &Chain, 810 SDValue *Flag, const Value *V) const { 811 // A Value with type {} or [0 x %t] needs no registers. 812 if (ValueVTs.empty()) 813 return SDValue(); 814 815 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 816 817 // Assemble the legal parts into the final values. 818 SmallVector<SDValue, 4> Values(ValueVTs.size()); 819 SmallVector<SDValue, 8> Parts; 820 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 821 // Copy the legal parts from the registers. 822 EVT ValueVT = ValueVTs[Value]; 823 unsigned NumRegs = RegCount[Value]; 824 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 825 *DAG.getContext(), 826 CallConv.getValue(), RegVTs[Value]) 827 : RegVTs[Value]; 828 829 Parts.resize(NumRegs); 830 for (unsigned i = 0; i != NumRegs; ++i) { 831 SDValue P; 832 if (!Flag) { 833 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 834 } else { 835 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 836 *Flag = P.getValue(2); 837 } 838 839 Chain = P.getValue(1); 840 Parts[i] = P; 841 842 // If the source register was virtual and if we know something about it, 843 // add an assert node. 844 if (!Register::isVirtualRegister(Regs[Part + i]) || 845 !RegisterVT.isInteger()) 846 continue; 847 848 const FunctionLoweringInfo::LiveOutInfo *LOI = 849 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 850 if (!LOI) 851 continue; 852 853 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 854 unsigned NumSignBits = LOI->NumSignBits; 855 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 856 857 if (NumZeroBits == RegSize) { 858 // The current value is a zero. 859 // Explicitly express that as it would be easier for 860 // optimizations to kick in. 861 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 862 continue; 863 } 864 865 // FIXME: We capture more information than the dag can represent. For 866 // now, just use the tightest assertzext/assertsext possible. 867 bool isSExt; 868 EVT FromVT(MVT::Other); 869 if (NumZeroBits) { 870 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 871 isSExt = false; 872 } else if (NumSignBits > 1) { 873 FromVT = 874 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 875 isSExt = true; 876 } else { 877 continue; 878 } 879 // Add an assertion node. 880 assert(FromVT != MVT::Other); 881 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 882 RegisterVT, P, DAG.getValueType(FromVT)); 883 } 884 885 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 886 RegisterVT, ValueVT, V, CallConv); 887 Part += NumRegs; 888 Parts.clear(); 889 } 890 891 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 892 } 893 894 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 895 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 896 const Value *V, 897 ISD::NodeType PreferredExtendType) const { 898 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 899 ISD::NodeType ExtendKind = PreferredExtendType; 900 901 // Get the list of the values's legal parts. 902 unsigned NumRegs = Regs.size(); 903 SmallVector<SDValue, 8> Parts(NumRegs); 904 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 905 unsigned NumParts = RegCount[Value]; 906 907 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 908 *DAG.getContext(), 909 CallConv.getValue(), RegVTs[Value]) 910 : RegVTs[Value]; 911 912 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 913 ExtendKind = ISD::ZERO_EXTEND; 914 915 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 916 NumParts, RegisterVT, V, CallConv, ExtendKind); 917 Part += NumParts; 918 } 919 920 // Copy the parts into the registers. 921 SmallVector<SDValue, 8> Chains(NumRegs); 922 for (unsigned i = 0; i != NumRegs; ++i) { 923 SDValue Part; 924 if (!Flag) { 925 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 926 } else { 927 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 928 *Flag = Part.getValue(1); 929 } 930 931 Chains[i] = Part.getValue(0); 932 } 933 934 if (NumRegs == 1 || Flag) 935 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 936 // flagged to it. That is the CopyToReg nodes and the user are considered 937 // a single scheduling unit. If we create a TokenFactor and return it as 938 // chain, then the TokenFactor is both a predecessor (operand) of the 939 // user as well as a successor (the TF operands are flagged to the user). 940 // c1, f1 = CopyToReg 941 // c2, f2 = CopyToReg 942 // c3 = TokenFactor c1, c2 943 // ... 944 // = op c3, ..., f2 945 Chain = Chains[NumRegs-1]; 946 else 947 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 948 } 949 950 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 951 unsigned MatchingIdx, const SDLoc &dl, 952 SelectionDAG &DAG, 953 std::vector<SDValue> &Ops) const { 954 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 955 956 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 957 if (HasMatching) 958 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 959 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 960 // Put the register class of the virtual registers in the flag word. That 961 // way, later passes can recompute register class constraints for inline 962 // assembly as well as normal instructions. 963 // Don't do this for tied operands that can use the regclass information 964 // from the def. 965 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 966 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 967 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 968 } 969 970 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 971 Ops.push_back(Res); 972 973 if (Code == InlineAsm::Kind_Clobber) { 974 // Clobbers should always have a 1:1 mapping with registers, and may 975 // reference registers that have illegal (e.g. vector) types. Hence, we 976 // shouldn't try to apply any sort of splitting logic to them. 977 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 978 "No 1:1 mapping from clobbers to regs?"); 979 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 980 (void)SP; 981 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 982 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 983 assert( 984 (Regs[I] != SP || 985 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 986 "If we clobbered the stack pointer, MFI should know about it."); 987 } 988 return; 989 } 990 991 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 992 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 993 MVT RegisterVT = RegVTs[Value]; 994 for (unsigned i = 0; i != NumRegs; ++i) { 995 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 996 unsigned TheReg = Regs[Reg++]; 997 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 998 } 999 } 1000 } 1001 1002 SmallVector<std::pair<unsigned, unsigned>, 4> 1003 RegsForValue::getRegsAndSizes() const { 1004 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 1005 unsigned I = 0; 1006 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1007 unsigned RegCount = std::get<0>(CountAndVT); 1008 MVT RegisterVT = std::get<1>(CountAndVT); 1009 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1010 for (unsigned E = I + RegCount; I != E; ++I) 1011 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1012 } 1013 return OutVec; 1014 } 1015 1016 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1017 const TargetLibraryInfo *li) { 1018 AA = aa; 1019 GFI = gfi; 1020 LibInfo = li; 1021 DL = &DAG.getDataLayout(); 1022 Context = DAG.getContext(); 1023 LPadToCallSiteMap.clear(); 1024 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1025 } 1026 1027 void SelectionDAGBuilder::clear() { 1028 NodeMap.clear(); 1029 UnusedArgNodeMap.clear(); 1030 PendingLoads.clear(); 1031 PendingExports.clear(); 1032 PendingConstrainedFP.clear(); 1033 PendingConstrainedFPStrict.clear(); 1034 CurInst = nullptr; 1035 HasTailCall = false; 1036 SDNodeOrder = LowestSDNodeOrder; 1037 StatepointLowering.clear(); 1038 } 1039 1040 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1041 DanglingDebugInfoMap.clear(); 1042 } 1043 1044 // Update DAG root to include dependencies on Pending chains. 1045 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1046 SDValue Root = DAG.getRoot(); 1047 1048 if (Pending.empty()) 1049 return Root; 1050 1051 // Add current root to PendingChains, unless we already indirectly 1052 // depend on it. 1053 if (Root.getOpcode() != ISD::EntryToken) { 1054 unsigned i = 0, e = Pending.size(); 1055 for (; i != e; ++i) { 1056 assert(Pending[i].getNode()->getNumOperands() > 1); 1057 if (Pending[i].getNode()->getOperand(0) == Root) 1058 break; // Don't add the root if we already indirectly depend on it. 1059 } 1060 1061 if (i == e) 1062 Pending.push_back(Root); 1063 } 1064 1065 if (Pending.size() == 1) 1066 Root = Pending[0]; 1067 else 1068 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1069 1070 DAG.setRoot(Root); 1071 Pending.clear(); 1072 return Root; 1073 } 1074 1075 SDValue SelectionDAGBuilder::getMemoryRoot() { 1076 return updateRoot(PendingLoads); 1077 } 1078 1079 SDValue SelectionDAGBuilder::getRoot() { 1080 // Chain up all pending constrained intrinsics together with all 1081 // pending loads, by simply appending them to PendingLoads and 1082 // then calling getMemoryRoot(). 1083 PendingLoads.reserve(PendingLoads.size() + 1084 PendingConstrainedFP.size() + 1085 PendingConstrainedFPStrict.size()); 1086 PendingLoads.append(PendingConstrainedFP.begin(), 1087 PendingConstrainedFP.end()); 1088 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1089 PendingConstrainedFPStrict.end()); 1090 PendingConstrainedFP.clear(); 1091 PendingConstrainedFPStrict.clear(); 1092 return getMemoryRoot(); 1093 } 1094 1095 SDValue SelectionDAGBuilder::getControlRoot() { 1096 // We need to emit pending fpexcept.strict constrained intrinsics, 1097 // so append them to the PendingExports list. 1098 PendingExports.append(PendingConstrainedFPStrict.begin(), 1099 PendingConstrainedFPStrict.end()); 1100 PendingConstrainedFPStrict.clear(); 1101 return updateRoot(PendingExports); 1102 } 1103 1104 void SelectionDAGBuilder::visit(const Instruction &I) { 1105 // Set up outgoing PHI node register values before emitting the terminator. 1106 if (I.isTerminator()) { 1107 HandlePHINodesInSuccessorBlocks(I.getParent()); 1108 } 1109 1110 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1111 if (!isa<DbgInfoIntrinsic>(I)) 1112 ++SDNodeOrder; 1113 1114 CurInst = &I; 1115 1116 visit(I.getOpcode(), I); 1117 1118 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1119 // ConstrainedFPIntrinsics handle their own FMF. 1120 if (!isa<ConstrainedFPIntrinsic>(&I)) { 1121 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1122 // maps to this instruction. 1123 // TODO: We could handle all flags (nsw, etc) here. 1124 // TODO: If an IR instruction maps to >1 node, only the final node will have 1125 // flags set. 1126 if (SDNode *Node = getNodeForIRValue(&I)) { 1127 SDNodeFlags IncomingFlags; 1128 IncomingFlags.copyFMF(*FPMO); 1129 if (!Node->getFlags().isDefined()) 1130 Node->setFlags(IncomingFlags); 1131 else 1132 Node->intersectFlagsWith(IncomingFlags); 1133 } 1134 } 1135 } 1136 1137 if (!I.isTerminator() && !HasTailCall && 1138 !isStatepoint(&I)) // statepoints handle their exports internally 1139 CopyToExportRegsIfNeeded(&I); 1140 1141 CurInst = nullptr; 1142 } 1143 1144 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1145 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1146 } 1147 1148 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1149 // Note: this doesn't use InstVisitor, because it has to work with 1150 // ConstantExpr's in addition to instructions. 1151 switch (Opcode) { 1152 default: llvm_unreachable("Unknown instruction type encountered!"); 1153 // Build the switch statement using the Instruction.def file. 1154 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1155 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1156 #include "llvm/IR/Instruction.def" 1157 } 1158 } 1159 1160 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1161 const DIExpression *Expr) { 1162 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1163 const DbgValueInst *DI = DDI.getDI(); 1164 DIVariable *DanglingVariable = DI->getVariable(); 1165 DIExpression *DanglingExpr = DI->getExpression(); 1166 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1167 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1168 return true; 1169 } 1170 return false; 1171 }; 1172 1173 for (auto &DDIMI : DanglingDebugInfoMap) { 1174 DanglingDebugInfoVector &DDIV = DDIMI.second; 1175 1176 // If debug info is to be dropped, run it through final checks to see 1177 // whether it can be salvaged. 1178 for (auto &DDI : DDIV) 1179 if (isMatchingDbgValue(DDI)) 1180 salvageUnresolvedDbgValue(DDI); 1181 1182 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1183 } 1184 } 1185 1186 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1187 // generate the debug data structures now that we've seen its definition. 1188 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1189 SDValue Val) { 1190 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1191 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1192 return; 1193 1194 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1195 for (auto &DDI : DDIV) { 1196 const DbgValueInst *DI = DDI.getDI(); 1197 assert(DI && "Ill-formed DanglingDebugInfo"); 1198 DebugLoc dl = DDI.getdl(); 1199 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1200 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1201 DILocalVariable *Variable = DI->getVariable(); 1202 DIExpression *Expr = DI->getExpression(); 1203 assert(Variable->isValidLocationForIntrinsic(dl) && 1204 "Expected inlined-at fields to agree"); 1205 SDDbgValue *SDV; 1206 if (Val.getNode()) { 1207 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1208 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1209 // we couldn't resolve it directly when examining the DbgValue intrinsic 1210 // in the first place we should not be more successful here). Unless we 1211 // have some test case that prove this to be correct we should avoid 1212 // calling EmitFuncArgumentDbgValue here. 1213 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1214 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1215 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1216 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1217 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1218 // inserted after the definition of Val when emitting the instructions 1219 // after ISel. An alternative could be to teach 1220 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1221 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1222 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1223 << ValSDNodeOrder << "\n"); 1224 SDV = getDbgValue(Val, Variable, Expr, dl, 1225 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1226 DAG.AddDbgValue(SDV, Val.getNode(), false); 1227 } else 1228 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1229 << "in EmitFuncArgumentDbgValue\n"); 1230 } else { 1231 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1232 auto Undef = 1233 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1234 auto SDV = 1235 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1236 DAG.AddDbgValue(SDV, nullptr, false); 1237 } 1238 } 1239 DDIV.clear(); 1240 } 1241 1242 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1243 Value *V = DDI.getDI()->getValue(); 1244 DILocalVariable *Var = DDI.getDI()->getVariable(); 1245 DIExpression *Expr = DDI.getDI()->getExpression(); 1246 DebugLoc DL = DDI.getdl(); 1247 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1248 unsigned SDOrder = DDI.getSDNodeOrder(); 1249 1250 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1251 // that DW_OP_stack_value is desired. 1252 assert(isa<DbgValueInst>(DDI.getDI())); 1253 bool StackValue = true; 1254 1255 // Can this Value can be encoded without any further work? 1256 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1257 return; 1258 1259 // Attempt to salvage back through as many instructions as possible. Bail if 1260 // a non-instruction is seen, such as a constant expression or global 1261 // variable. FIXME: Further work could recover those too. 1262 while (isa<Instruction>(V)) { 1263 Instruction &VAsInst = *cast<Instruction>(V); 1264 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1265 1266 // If we cannot salvage any further, and haven't yet found a suitable debug 1267 // expression, bail out. 1268 if (!NewExpr) 1269 break; 1270 1271 // New value and expr now represent this debuginfo. 1272 V = VAsInst.getOperand(0); 1273 Expr = NewExpr; 1274 1275 // Some kind of simplification occurred: check whether the operand of the 1276 // salvaged debug expression can be encoded in this DAG. 1277 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1278 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1279 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1280 return; 1281 } 1282 } 1283 1284 // This was the final opportunity to salvage this debug information, and it 1285 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1286 // any earlier variable location. 1287 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1288 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1289 DAG.AddDbgValue(SDV, nullptr, false); 1290 1291 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1292 << "\n"); 1293 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1294 << "\n"); 1295 } 1296 1297 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1298 DIExpression *Expr, DebugLoc dl, 1299 DebugLoc InstDL, unsigned Order) { 1300 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1301 SDDbgValue *SDV; 1302 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1303 isa<ConstantPointerNull>(V)) { 1304 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1305 DAG.AddDbgValue(SDV, nullptr, false); 1306 return true; 1307 } 1308 1309 // If the Value is a frame index, we can create a FrameIndex debug value 1310 // without relying on the DAG at all. 1311 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1312 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1313 if (SI != FuncInfo.StaticAllocaMap.end()) { 1314 auto SDV = 1315 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1316 /*IsIndirect*/ false, dl, SDNodeOrder); 1317 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1318 // is still available even if the SDNode gets optimized out. 1319 DAG.AddDbgValue(SDV, nullptr, false); 1320 return true; 1321 } 1322 } 1323 1324 // Do not use getValue() in here; we don't want to generate code at 1325 // this point if it hasn't been done yet. 1326 SDValue N = NodeMap[V]; 1327 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1328 N = UnusedArgNodeMap[V]; 1329 if (N.getNode()) { 1330 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1331 return true; 1332 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1333 DAG.AddDbgValue(SDV, N.getNode(), false); 1334 return true; 1335 } 1336 1337 // Special rules apply for the first dbg.values of parameter variables in a 1338 // function. Identify them by the fact they reference Argument Values, that 1339 // they're parameters, and they are parameters of the current function. We 1340 // need to let them dangle until they get an SDNode. 1341 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1342 !InstDL.getInlinedAt(); 1343 if (!IsParamOfFunc) { 1344 // The value is not used in this block yet (or it would have an SDNode). 1345 // We still want the value to appear for the user if possible -- if it has 1346 // an associated VReg, we can refer to that instead. 1347 auto VMI = FuncInfo.ValueMap.find(V); 1348 if (VMI != FuncInfo.ValueMap.end()) { 1349 unsigned Reg = VMI->second; 1350 // If this is a PHI node, it may be split up into several MI PHI nodes 1351 // (in FunctionLoweringInfo::set). 1352 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1353 V->getType(), None); 1354 if (RFV.occupiesMultipleRegs()) { 1355 unsigned Offset = 0; 1356 unsigned BitsToDescribe = 0; 1357 if (auto VarSize = Var->getSizeInBits()) 1358 BitsToDescribe = *VarSize; 1359 if (auto Fragment = Expr->getFragmentInfo()) 1360 BitsToDescribe = Fragment->SizeInBits; 1361 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1362 unsigned RegisterSize = RegAndSize.second; 1363 // Bail out if all bits are described already. 1364 if (Offset >= BitsToDescribe) 1365 break; 1366 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1367 ? BitsToDescribe - Offset 1368 : RegisterSize; 1369 auto FragmentExpr = DIExpression::createFragmentExpression( 1370 Expr, Offset, FragmentSize); 1371 if (!FragmentExpr) 1372 continue; 1373 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1374 false, dl, SDNodeOrder); 1375 DAG.AddDbgValue(SDV, nullptr, false); 1376 Offset += RegisterSize; 1377 } 1378 } else { 1379 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1380 DAG.AddDbgValue(SDV, nullptr, false); 1381 } 1382 return true; 1383 } 1384 } 1385 1386 return false; 1387 } 1388 1389 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1390 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1391 for (auto &Pair : DanglingDebugInfoMap) 1392 for (auto &DDI : Pair.second) 1393 salvageUnresolvedDbgValue(DDI); 1394 clearDanglingDebugInfo(); 1395 } 1396 1397 /// getCopyFromRegs - If there was virtual register allocated for the value V 1398 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1399 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1400 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1401 SDValue Result; 1402 1403 if (It != FuncInfo.ValueMap.end()) { 1404 unsigned InReg = It->second; 1405 1406 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1407 DAG.getDataLayout(), InReg, Ty, 1408 None); // This is not an ABI copy. 1409 SDValue Chain = DAG.getEntryNode(); 1410 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1411 V); 1412 resolveDanglingDebugInfo(V, Result); 1413 } 1414 1415 return Result; 1416 } 1417 1418 /// getValue - Return an SDValue for the given Value. 1419 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1420 // If we already have an SDValue for this value, use it. It's important 1421 // to do this first, so that we don't create a CopyFromReg if we already 1422 // have a regular SDValue. 1423 SDValue &N = NodeMap[V]; 1424 if (N.getNode()) return N; 1425 1426 // If there's a virtual register allocated and initialized for this 1427 // value, use it. 1428 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1429 return copyFromReg; 1430 1431 // Otherwise create a new SDValue and remember it. 1432 SDValue Val = getValueImpl(V); 1433 NodeMap[V] = Val; 1434 resolveDanglingDebugInfo(V, Val); 1435 return Val; 1436 } 1437 1438 // Return true if SDValue exists for the given Value 1439 bool SelectionDAGBuilder::findValue(const Value *V) const { 1440 return (NodeMap.find(V) != NodeMap.end()) || 1441 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1442 } 1443 1444 /// getNonRegisterValue - Return an SDValue for the given Value, but 1445 /// don't look in FuncInfo.ValueMap for a virtual register. 1446 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1447 // If we already have an SDValue for this value, use it. 1448 SDValue &N = NodeMap[V]; 1449 if (N.getNode()) { 1450 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1451 // Remove the debug location from the node as the node is about to be used 1452 // in a location which may differ from the original debug location. This 1453 // is relevant to Constant and ConstantFP nodes because they can appear 1454 // as constant expressions inside PHI nodes. 1455 N->setDebugLoc(DebugLoc()); 1456 } 1457 return N; 1458 } 1459 1460 // Otherwise create a new SDValue and remember it. 1461 SDValue Val = getValueImpl(V); 1462 NodeMap[V] = Val; 1463 resolveDanglingDebugInfo(V, Val); 1464 return Val; 1465 } 1466 1467 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1468 /// Create an SDValue for the given value. 1469 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1470 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1471 1472 if (const Constant *C = dyn_cast<Constant>(V)) { 1473 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1474 1475 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1476 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1477 1478 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1479 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1480 1481 if (isa<ConstantPointerNull>(C)) { 1482 unsigned AS = V->getType()->getPointerAddressSpace(); 1483 return DAG.getConstant(0, getCurSDLoc(), 1484 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1485 } 1486 1487 if (match(C, m_VScale(DAG.getDataLayout()))) 1488 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1489 1490 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1491 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1492 1493 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1494 return DAG.getUNDEF(VT); 1495 1496 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1497 visit(CE->getOpcode(), *CE); 1498 SDValue N1 = NodeMap[V]; 1499 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1500 return N1; 1501 } 1502 1503 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1504 SmallVector<SDValue, 4> Constants; 1505 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1506 OI != OE; ++OI) { 1507 SDNode *Val = getValue(*OI).getNode(); 1508 // If the operand is an empty aggregate, there are no values. 1509 if (!Val) continue; 1510 // Add each leaf value from the operand to the Constants list 1511 // to form a flattened list of all the values. 1512 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1513 Constants.push_back(SDValue(Val, i)); 1514 } 1515 1516 return DAG.getMergeValues(Constants, getCurSDLoc()); 1517 } 1518 1519 if (const ConstantDataSequential *CDS = 1520 dyn_cast<ConstantDataSequential>(C)) { 1521 SmallVector<SDValue, 4> Ops; 1522 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1523 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1524 // Add each leaf value from the operand to the Constants list 1525 // to form a flattened list of all the values. 1526 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1527 Ops.push_back(SDValue(Val, i)); 1528 } 1529 1530 if (isa<ArrayType>(CDS->getType())) 1531 return DAG.getMergeValues(Ops, getCurSDLoc()); 1532 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1533 } 1534 1535 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1536 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1537 "Unknown struct or array constant!"); 1538 1539 SmallVector<EVT, 4> ValueVTs; 1540 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1541 unsigned NumElts = ValueVTs.size(); 1542 if (NumElts == 0) 1543 return SDValue(); // empty struct 1544 SmallVector<SDValue, 4> Constants(NumElts); 1545 for (unsigned i = 0; i != NumElts; ++i) { 1546 EVT EltVT = ValueVTs[i]; 1547 if (isa<UndefValue>(C)) 1548 Constants[i] = DAG.getUNDEF(EltVT); 1549 else if (EltVT.isFloatingPoint()) 1550 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1551 else 1552 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1553 } 1554 1555 return DAG.getMergeValues(Constants, getCurSDLoc()); 1556 } 1557 1558 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1559 return DAG.getBlockAddress(BA, VT); 1560 1561 VectorType *VecTy = cast<VectorType>(V->getType()); 1562 unsigned NumElements = VecTy->getNumElements(); 1563 1564 // Now that we know the number and type of the elements, get that number of 1565 // elements into the Ops array based on what kind of constant it is. 1566 SmallVector<SDValue, 16> Ops; 1567 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1568 for (unsigned i = 0; i != NumElements; ++i) 1569 Ops.push_back(getValue(CV->getOperand(i))); 1570 } else { 1571 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1572 EVT EltVT = 1573 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1574 1575 SDValue Op; 1576 if (EltVT.isFloatingPoint()) 1577 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1578 else 1579 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1580 Ops.assign(NumElements, Op); 1581 } 1582 1583 // Create a BUILD_VECTOR node. 1584 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1585 } 1586 1587 // If this is a static alloca, generate it as the frameindex instead of 1588 // computation. 1589 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1590 DenseMap<const AllocaInst*, int>::iterator SI = 1591 FuncInfo.StaticAllocaMap.find(AI); 1592 if (SI != FuncInfo.StaticAllocaMap.end()) 1593 return DAG.getFrameIndex(SI->second, 1594 TLI.getFrameIndexTy(DAG.getDataLayout())); 1595 } 1596 1597 // If this is an instruction which fast-isel has deferred, select it now. 1598 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1599 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1600 1601 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1602 Inst->getType(), getABIRegCopyCC(V)); 1603 SDValue Chain = DAG.getEntryNode(); 1604 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1605 } 1606 1607 llvm_unreachable("Can't get register for value!"); 1608 } 1609 1610 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1611 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1612 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1613 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1614 bool IsSEH = isAsynchronousEHPersonality(Pers); 1615 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1616 if (!IsSEH) 1617 CatchPadMBB->setIsEHScopeEntry(); 1618 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1619 if (IsMSVCCXX || IsCoreCLR) 1620 CatchPadMBB->setIsEHFuncletEntry(); 1621 } 1622 1623 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1624 // Update machine-CFG edge. 1625 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1626 FuncInfo.MBB->addSuccessor(TargetMBB); 1627 1628 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1629 bool IsSEH = isAsynchronousEHPersonality(Pers); 1630 if (IsSEH) { 1631 // If this is not a fall-through branch or optimizations are switched off, 1632 // emit the branch. 1633 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1634 TM.getOptLevel() == CodeGenOpt::None) 1635 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1636 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1637 return; 1638 } 1639 1640 // Figure out the funclet membership for the catchret's successor. 1641 // This will be used by the FuncletLayout pass to determine how to order the 1642 // BB's. 1643 // A 'catchret' returns to the outer scope's color. 1644 Value *ParentPad = I.getCatchSwitchParentPad(); 1645 const BasicBlock *SuccessorColor; 1646 if (isa<ConstantTokenNone>(ParentPad)) 1647 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1648 else 1649 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1650 assert(SuccessorColor && "No parent funclet for catchret!"); 1651 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1652 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1653 1654 // Create the terminator node. 1655 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1656 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1657 DAG.getBasicBlock(SuccessorColorMBB)); 1658 DAG.setRoot(Ret); 1659 } 1660 1661 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1662 // Don't emit any special code for the cleanuppad instruction. It just marks 1663 // the start of an EH scope/funclet. 1664 FuncInfo.MBB->setIsEHScopeEntry(); 1665 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1666 if (Pers != EHPersonality::Wasm_CXX) { 1667 FuncInfo.MBB->setIsEHFuncletEntry(); 1668 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1669 } 1670 } 1671 1672 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1673 // the control flow always stops at the single catch pad, as it does for a 1674 // cleanup pad. In case the exception caught is not of the types the catch pad 1675 // catches, it will be rethrown by a rethrow. 1676 static void findWasmUnwindDestinations( 1677 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1678 BranchProbability Prob, 1679 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1680 &UnwindDests) { 1681 while (EHPadBB) { 1682 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1683 if (isa<CleanupPadInst>(Pad)) { 1684 // Stop on cleanup pads. 1685 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1686 UnwindDests.back().first->setIsEHScopeEntry(); 1687 break; 1688 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1689 // Add the catchpad handlers to the possible destinations. We don't 1690 // continue to the unwind destination of the catchswitch for wasm. 1691 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1692 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1693 UnwindDests.back().first->setIsEHScopeEntry(); 1694 } 1695 break; 1696 } else { 1697 continue; 1698 } 1699 } 1700 } 1701 1702 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1703 /// many places it could ultimately go. In the IR, we have a single unwind 1704 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1705 /// This function skips over imaginary basic blocks that hold catchswitch 1706 /// instructions, and finds all the "real" machine 1707 /// basic block destinations. As those destinations may not be successors of 1708 /// EHPadBB, here we also calculate the edge probability to those destinations. 1709 /// The passed-in Prob is the edge probability to EHPadBB. 1710 static void findUnwindDestinations( 1711 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1712 BranchProbability Prob, 1713 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1714 &UnwindDests) { 1715 EHPersonality Personality = 1716 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1717 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1718 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1719 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1720 bool IsSEH = isAsynchronousEHPersonality(Personality); 1721 1722 if (IsWasmCXX) { 1723 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1724 assert(UnwindDests.size() <= 1 && 1725 "There should be at most one unwind destination for wasm"); 1726 return; 1727 } 1728 1729 while (EHPadBB) { 1730 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1731 BasicBlock *NewEHPadBB = nullptr; 1732 if (isa<LandingPadInst>(Pad)) { 1733 // Stop on landingpads. They are not funclets. 1734 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1735 break; 1736 } else if (isa<CleanupPadInst>(Pad)) { 1737 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1738 // personalities. 1739 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1740 UnwindDests.back().first->setIsEHScopeEntry(); 1741 UnwindDests.back().first->setIsEHFuncletEntry(); 1742 break; 1743 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1744 // Add the catchpad handlers to the possible destinations. 1745 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1746 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1747 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1748 if (IsMSVCCXX || IsCoreCLR) 1749 UnwindDests.back().first->setIsEHFuncletEntry(); 1750 if (!IsSEH) 1751 UnwindDests.back().first->setIsEHScopeEntry(); 1752 } 1753 NewEHPadBB = CatchSwitch->getUnwindDest(); 1754 } else { 1755 continue; 1756 } 1757 1758 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1759 if (BPI && NewEHPadBB) 1760 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1761 EHPadBB = NewEHPadBB; 1762 } 1763 } 1764 1765 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1766 // Update successor info. 1767 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1768 auto UnwindDest = I.getUnwindDest(); 1769 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1770 BranchProbability UnwindDestProb = 1771 (BPI && UnwindDest) 1772 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1773 : BranchProbability::getZero(); 1774 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1775 for (auto &UnwindDest : UnwindDests) { 1776 UnwindDest.first->setIsEHPad(); 1777 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1778 } 1779 FuncInfo.MBB->normalizeSuccProbs(); 1780 1781 // Create the terminator node. 1782 SDValue Ret = 1783 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1784 DAG.setRoot(Ret); 1785 } 1786 1787 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1788 report_fatal_error("visitCatchSwitch not yet implemented!"); 1789 } 1790 1791 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1792 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1793 auto &DL = DAG.getDataLayout(); 1794 SDValue Chain = getControlRoot(); 1795 SmallVector<ISD::OutputArg, 8> Outs; 1796 SmallVector<SDValue, 8> OutVals; 1797 1798 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1799 // lower 1800 // 1801 // %val = call <ty> @llvm.experimental.deoptimize() 1802 // ret <ty> %val 1803 // 1804 // differently. 1805 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1806 LowerDeoptimizingReturn(); 1807 return; 1808 } 1809 1810 if (!FuncInfo.CanLowerReturn) { 1811 unsigned DemoteReg = FuncInfo.DemoteRegister; 1812 const Function *F = I.getParent()->getParent(); 1813 1814 // Emit a store of the return value through the virtual register. 1815 // Leave Outs empty so that LowerReturn won't try to load return 1816 // registers the usual way. 1817 SmallVector<EVT, 1> PtrValueVTs; 1818 ComputeValueVTs(TLI, DL, 1819 F->getReturnType()->getPointerTo( 1820 DAG.getDataLayout().getAllocaAddrSpace()), 1821 PtrValueVTs); 1822 1823 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1824 DemoteReg, PtrValueVTs[0]); 1825 SDValue RetOp = getValue(I.getOperand(0)); 1826 1827 SmallVector<EVT, 4> ValueVTs, MemVTs; 1828 SmallVector<uint64_t, 4> Offsets; 1829 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1830 &Offsets); 1831 unsigned NumValues = ValueVTs.size(); 1832 1833 SmallVector<SDValue, 4> Chains(NumValues); 1834 for (unsigned i = 0; i != NumValues; ++i) { 1835 // An aggregate return value cannot wrap around the address space, so 1836 // offsets to its parts don't wrap either. 1837 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1838 1839 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1840 if (MemVTs[i] != ValueVTs[i]) 1841 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1842 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val, 1843 // FIXME: better loc info would be nice. 1844 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1845 } 1846 1847 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1848 MVT::Other, Chains); 1849 } else if (I.getNumOperands() != 0) { 1850 SmallVector<EVT, 4> ValueVTs; 1851 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1852 unsigned NumValues = ValueVTs.size(); 1853 if (NumValues) { 1854 SDValue RetOp = getValue(I.getOperand(0)); 1855 1856 const Function *F = I.getParent()->getParent(); 1857 1858 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1859 I.getOperand(0)->getType(), F->getCallingConv(), 1860 /*IsVarArg*/ false); 1861 1862 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1863 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1864 Attribute::SExt)) 1865 ExtendKind = ISD::SIGN_EXTEND; 1866 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1867 Attribute::ZExt)) 1868 ExtendKind = ISD::ZERO_EXTEND; 1869 1870 LLVMContext &Context = F->getContext(); 1871 bool RetInReg = F->getAttributes().hasAttribute( 1872 AttributeList::ReturnIndex, Attribute::InReg); 1873 1874 for (unsigned j = 0; j != NumValues; ++j) { 1875 EVT VT = ValueVTs[j]; 1876 1877 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1878 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1879 1880 CallingConv::ID CC = F->getCallingConv(); 1881 1882 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1883 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1884 SmallVector<SDValue, 4> Parts(NumParts); 1885 getCopyToParts(DAG, getCurSDLoc(), 1886 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1887 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1888 1889 // 'inreg' on function refers to return value 1890 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1891 if (RetInReg) 1892 Flags.setInReg(); 1893 1894 if (I.getOperand(0)->getType()->isPointerTy()) { 1895 Flags.setPointer(); 1896 Flags.setPointerAddrSpace( 1897 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1898 } 1899 1900 if (NeedsRegBlock) { 1901 Flags.setInConsecutiveRegs(); 1902 if (j == NumValues - 1) 1903 Flags.setInConsecutiveRegsLast(); 1904 } 1905 1906 // Propagate extension type if any 1907 if (ExtendKind == ISD::SIGN_EXTEND) 1908 Flags.setSExt(); 1909 else if (ExtendKind == ISD::ZERO_EXTEND) 1910 Flags.setZExt(); 1911 1912 for (unsigned i = 0; i < NumParts; ++i) { 1913 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1914 VT, /*isfixed=*/true, 0, 0)); 1915 OutVals.push_back(Parts[i]); 1916 } 1917 } 1918 } 1919 } 1920 1921 // Push in swifterror virtual register as the last element of Outs. This makes 1922 // sure swifterror virtual register will be returned in the swifterror 1923 // physical register. 1924 const Function *F = I.getParent()->getParent(); 1925 if (TLI.supportSwiftError() && 1926 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1927 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1928 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1929 Flags.setSwiftError(); 1930 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1931 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1932 true /*isfixed*/, 1 /*origidx*/, 1933 0 /*partOffs*/)); 1934 // Create SDNode for the swifterror virtual register. 1935 OutVals.push_back( 1936 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1937 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1938 EVT(TLI.getPointerTy(DL)))); 1939 } 1940 1941 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1942 CallingConv::ID CallConv = 1943 DAG.getMachineFunction().getFunction().getCallingConv(); 1944 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1945 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1946 1947 // Verify that the target's LowerReturn behaved as expected. 1948 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1949 "LowerReturn didn't return a valid chain!"); 1950 1951 // Update the DAG with the new chain value resulting from return lowering. 1952 DAG.setRoot(Chain); 1953 } 1954 1955 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1956 /// created for it, emit nodes to copy the value into the virtual 1957 /// registers. 1958 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1959 // Skip empty types 1960 if (V->getType()->isEmptyTy()) 1961 return; 1962 1963 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1964 if (VMI != FuncInfo.ValueMap.end()) { 1965 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1966 CopyValueToVirtualRegister(V, VMI->second); 1967 } 1968 } 1969 1970 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1971 /// the current basic block, add it to ValueMap now so that we'll get a 1972 /// CopyTo/FromReg. 1973 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1974 // No need to export constants. 1975 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1976 1977 // Already exported? 1978 if (FuncInfo.isExportedInst(V)) return; 1979 1980 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1981 CopyValueToVirtualRegister(V, Reg); 1982 } 1983 1984 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1985 const BasicBlock *FromBB) { 1986 // The operands of the setcc have to be in this block. We don't know 1987 // how to export them from some other block. 1988 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1989 // Can export from current BB. 1990 if (VI->getParent() == FromBB) 1991 return true; 1992 1993 // Is already exported, noop. 1994 return FuncInfo.isExportedInst(V); 1995 } 1996 1997 // If this is an argument, we can export it if the BB is the entry block or 1998 // if it is already exported. 1999 if (isa<Argument>(V)) { 2000 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2001 return true; 2002 2003 // Otherwise, can only export this if it is already exported. 2004 return FuncInfo.isExportedInst(V); 2005 } 2006 2007 // Otherwise, constants can always be exported. 2008 return true; 2009 } 2010 2011 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2012 BranchProbability 2013 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2014 const MachineBasicBlock *Dst) const { 2015 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2016 const BasicBlock *SrcBB = Src->getBasicBlock(); 2017 const BasicBlock *DstBB = Dst->getBasicBlock(); 2018 if (!BPI) { 2019 // If BPI is not available, set the default probability as 1 / N, where N is 2020 // the number of successors. 2021 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2022 return BranchProbability(1, SuccSize); 2023 } 2024 return BPI->getEdgeProbability(SrcBB, DstBB); 2025 } 2026 2027 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2028 MachineBasicBlock *Dst, 2029 BranchProbability Prob) { 2030 if (!FuncInfo.BPI) 2031 Src->addSuccessorWithoutProb(Dst); 2032 else { 2033 if (Prob.isUnknown()) 2034 Prob = getEdgeProbability(Src, Dst); 2035 Src->addSuccessor(Dst, Prob); 2036 } 2037 } 2038 2039 static bool InBlock(const Value *V, const BasicBlock *BB) { 2040 if (const Instruction *I = dyn_cast<Instruction>(V)) 2041 return I->getParent() == BB; 2042 return true; 2043 } 2044 2045 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2046 /// This function emits a branch and is used at the leaves of an OR or an 2047 /// AND operator tree. 2048 void 2049 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2050 MachineBasicBlock *TBB, 2051 MachineBasicBlock *FBB, 2052 MachineBasicBlock *CurBB, 2053 MachineBasicBlock *SwitchBB, 2054 BranchProbability TProb, 2055 BranchProbability FProb, 2056 bool InvertCond) { 2057 const BasicBlock *BB = CurBB->getBasicBlock(); 2058 2059 // If the leaf of the tree is a comparison, merge the condition into 2060 // the caseblock. 2061 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2062 // The operands of the cmp have to be in this block. We don't know 2063 // how to export them from some other block. If this is the first block 2064 // of the sequence, no exporting is needed. 2065 if (CurBB == SwitchBB || 2066 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2067 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2068 ISD::CondCode Condition; 2069 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2070 ICmpInst::Predicate Pred = 2071 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2072 Condition = getICmpCondCode(Pred); 2073 } else { 2074 const FCmpInst *FC = cast<FCmpInst>(Cond); 2075 FCmpInst::Predicate Pred = 2076 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2077 Condition = getFCmpCondCode(Pred); 2078 if (TM.Options.NoNaNsFPMath) 2079 Condition = getFCmpCodeWithoutNaN(Condition); 2080 } 2081 2082 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2083 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2084 SL->SwitchCases.push_back(CB); 2085 return; 2086 } 2087 } 2088 2089 // Create a CaseBlock record representing this branch. 2090 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2091 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2092 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2093 SL->SwitchCases.push_back(CB); 2094 } 2095 2096 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2097 MachineBasicBlock *TBB, 2098 MachineBasicBlock *FBB, 2099 MachineBasicBlock *CurBB, 2100 MachineBasicBlock *SwitchBB, 2101 Instruction::BinaryOps Opc, 2102 BranchProbability TProb, 2103 BranchProbability FProb, 2104 bool InvertCond) { 2105 // Skip over not part of the tree and remember to invert op and operands at 2106 // next level. 2107 Value *NotCond; 2108 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2109 InBlock(NotCond, CurBB->getBasicBlock())) { 2110 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2111 !InvertCond); 2112 return; 2113 } 2114 2115 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2116 // Compute the effective opcode for Cond, taking into account whether it needs 2117 // to be inverted, e.g. 2118 // and (not (or A, B)), C 2119 // gets lowered as 2120 // and (and (not A, not B), C) 2121 unsigned BOpc = 0; 2122 if (BOp) { 2123 BOpc = BOp->getOpcode(); 2124 if (InvertCond) { 2125 if (BOpc == Instruction::And) 2126 BOpc = Instruction::Or; 2127 else if (BOpc == Instruction::Or) 2128 BOpc = Instruction::And; 2129 } 2130 } 2131 2132 // If this node is not part of the or/and tree, emit it as a branch. 2133 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2134 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2135 BOp->getParent() != CurBB->getBasicBlock() || 2136 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2137 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2138 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2139 TProb, FProb, InvertCond); 2140 return; 2141 } 2142 2143 // Create TmpBB after CurBB. 2144 MachineFunction::iterator BBI(CurBB); 2145 MachineFunction &MF = DAG.getMachineFunction(); 2146 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2147 CurBB->getParent()->insert(++BBI, TmpBB); 2148 2149 if (Opc == Instruction::Or) { 2150 // Codegen X | Y as: 2151 // BB1: 2152 // jmp_if_X TBB 2153 // jmp TmpBB 2154 // TmpBB: 2155 // jmp_if_Y TBB 2156 // jmp FBB 2157 // 2158 2159 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2160 // The requirement is that 2161 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2162 // = TrueProb for original BB. 2163 // Assuming the original probabilities are A and B, one choice is to set 2164 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2165 // A/(1+B) and 2B/(1+B). This choice assumes that 2166 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2167 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2168 // TmpBB, but the math is more complicated. 2169 2170 auto NewTrueProb = TProb / 2; 2171 auto NewFalseProb = TProb / 2 + FProb; 2172 // Emit the LHS condition. 2173 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2174 NewTrueProb, NewFalseProb, InvertCond); 2175 2176 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2177 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2178 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2179 // Emit the RHS condition into TmpBB. 2180 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2181 Probs[0], Probs[1], InvertCond); 2182 } else { 2183 assert(Opc == Instruction::And && "Unknown merge op!"); 2184 // Codegen X & Y as: 2185 // BB1: 2186 // jmp_if_X TmpBB 2187 // jmp FBB 2188 // TmpBB: 2189 // jmp_if_Y TBB 2190 // jmp FBB 2191 // 2192 // This requires creation of TmpBB after CurBB. 2193 2194 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2195 // The requirement is that 2196 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2197 // = FalseProb for original BB. 2198 // Assuming the original probabilities are A and B, one choice is to set 2199 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2200 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2201 // TrueProb for BB1 * FalseProb for TmpBB. 2202 2203 auto NewTrueProb = TProb + FProb / 2; 2204 auto NewFalseProb = FProb / 2; 2205 // Emit the LHS condition. 2206 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2207 NewTrueProb, NewFalseProb, InvertCond); 2208 2209 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2210 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2211 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2212 // Emit the RHS condition into TmpBB. 2213 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2214 Probs[0], Probs[1], InvertCond); 2215 } 2216 } 2217 2218 /// If the set of cases should be emitted as a series of branches, return true. 2219 /// If we should emit this as a bunch of and/or'd together conditions, return 2220 /// false. 2221 bool 2222 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2223 if (Cases.size() != 2) return true; 2224 2225 // If this is two comparisons of the same values or'd or and'd together, they 2226 // will get folded into a single comparison, so don't emit two blocks. 2227 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2228 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2229 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2230 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2231 return false; 2232 } 2233 2234 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2235 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2236 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2237 Cases[0].CC == Cases[1].CC && 2238 isa<Constant>(Cases[0].CmpRHS) && 2239 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2240 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2241 return false; 2242 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2243 return false; 2244 } 2245 2246 return true; 2247 } 2248 2249 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2250 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2251 2252 // Update machine-CFG edges. 2253 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2254 2255 if (I.isUnconditional()) { 2256 // Update machine-CFG edges. 2257 BrMBB->addSuccessor(Succ0MBB); 2258 2259 // If this is not a fall-through branch or optimizations are switched off, 2260 // emit the branch. 2261 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2262 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2263 MVT::Other, getControlRoot(), 2264 DAG.getBasicBlock(Succ0MBB))); 2265 2266 return; 2267 } 2268 2269 // If this condition is one of the special cases we handle, do special stuff 2270 // now. 2271 const Value *CondVal = I.getCondition(); 2272 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2273 2274 // If this is a series of conditions that are or'd or and'd together, emit 2275 // this as a sequence of branches instead of setcc's with and/or operations. 2276 // As long as jumps are not expensive, this should improve performance. 2277 // For example, instead of something like: 2278 // cmp A, B 2279 // C = seteq 2280 // cmp D, E 2281 // F = setle 2282 // or C, F 2283 // jnz foo 2284 // Emit: 2285 // cmp A, B 2286 // je foo 2287 // cmp D, E 2288 // jle foo 2289 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2290 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2291 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2292 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2293 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2294 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2295 Opcode, 2296 getEdgeProbability(BrMBB, Succ0MBB), 2297 getEdgeProbability(BrMBB, Succ1MBB), 2298 /*InvertCond=*/false); 2299 // If the compares in later blocks need to use values not currently 2300 // exported from this block, export them now. This block should always 2301 // be the first entry. 2302 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2303 2304 // Allow some cases to be rejected. 2305 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2306 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2307 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2308 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2309 } 2310 2311 // Emit the branch for this block. 2312 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2313 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2314 return; 2315 } 2316 2317 // Okay, we decided not to do this, remove any inserted MBB's and clear 2318 // SwitchCases. 2319 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2320 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2321 2322 SL->SwitchCases.clear(); 2323 } 2324 } 2325 2326 // Create a CaseBlock record representing this branch. 2327 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2328 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2329 2330 // Use visitSwitchCase to actually insert the fast branch sequence for this 2331 // cond branch. 2332 visitSwitchCase(CB, BrMBB); 2333 } 2334 2335 /// visitSwitchCase - Emits the necessary code to represent a single node in 2336 /// the binary search tree resulting from lowering a switch instruction. 2337 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2338 MachineBasicBlock *SwitchBB) { 2339 SDValue Cond; 2340 SDValue CondLHS = getValue(CB.CmpLHS); 2341 SDLoc dl = CB.DL; 2342 2343 if (CB.CC == ISD::SETTRUE) { 2344 // Branch or fall through to TrueBB. 2345 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2346 SwitchBB->normalizeSuccProbs(); 2347 if (CB.TrueBB != NextBlock(SwitchBB)) { 2348 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2349 DAG.getBasicBlock(CB.TrueBB))); 2350 } 2351 return; 2352 } 2353 2354 auto &TLI = DAG.getTargetLoweringInfo(); 2355 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2356 2357 // Build the setcc now. 2358 if (!CB.CmpMHS) { 2359 // Fold "(X == true)" to X and "(X == false)" to !X to 2360 // handle common cases produced by branch lowering. 2361 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2362 CB.CC == ISD::SETEQ) 2363 Cond = CondLHS; 2364 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2365 CB.CC == ISD::SETEQ) { 2366 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2367 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2368 } else { 2369 SDValue CondRHS = getValue(CB.CmpRHS); 2370 2371 // If a pointer's DAG type is larger than its memory type then the DAG 2372 // values are zero-extended. This breaks signed comparisons so truncate 2373 // back to the underlying type before doing the compare. 2374 if (CondLHS.getValueType() != MemVT) { 2375 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2376 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2377 } 2378 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2379 } 2380 } else { 2381 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2382 2383 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2384 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2385 2386 SDValue CmpOp = getValue(CB.CmpMHS); 2387 EVT VT = CmpOp.getValueType(); 2388 2389 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2390 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2391 ISD::SETLE); 2392 } else { 2393 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2394 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2395 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2396 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2397 } 2398 } 2399 2400 // Update successor info 2401 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2402 // TrueBB and FalseBB are always different unless the incoming IR is 2403 // degenerate. This only happens when running llc on weird IR. 2404 if (CB.TrueBB != CB.FalseBB) 2405 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2406 SwitchBB->normalizeSuccProbs(); 2407 2408 // If the lhs block is the next block, invert the condition so that we can 2409 // fall through to the lhs instead of the rhs block. 2410 if (CB.TrueBB == NextBlock(SwitchBB)) { 2411 std::swap(CB.TrueBB, CB.FalseBB); 2412 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2413 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2414 } 2415 2416 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2417 MVT::Other, getControlRoot(), Cond, 2418 DAG.getBasicBlock(CB.TrueBB)); 2419 2420 // Insert the false branch. Do this even if it's a fall through branch, 2421 // this makes it easier to do DAG optimizations which require inverting 2422 // the branch condition. 2423 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2424 DAG.getBasicBlock(CB.FalseBB)); 2425 2426 DAG.setRoot(BrCond); 2427 } 2428 2429 /// visitJumpTable - Emit JumpTable node in the current MBB 2430 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2431 // Emit the code for the jump table 2432 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2433 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2434 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2435 JT.Reg, PTy); 2436 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2437 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2438 MVT::Other, Index.getValue(1), 2439 Table, Index); 2440 DAG.setRoot(BrJumpTable); 2441 } 2442 2443 /// visitJumpTableHeader - This function emits necessary code to produce index 2444 /// in the JumpTable from switch case. 2445 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2446 JumpTableHeader &JTH, 2447 MachineBasicBlock *SwitchBB) { 2448 SDLoc dl = getCurSDLoc(); 2449 2450 // Subtract the lowest switch case value from the value being switched on. 2451 SDValue SwitchOp = getValue(JTH.SValue); 2452 EVT VT = SwitchOp.getValueType(); 2453 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2454 DAG.getConstant(JTH.First, dl, VT)); 2455 2456 // The SDNode we just created, which holds the value being switched on minus 2457 // the smallest case value, needs to be copied to a virtual register so it 2458 // can be used as an index into the jump table in a subsequent basic block. 2459 // This value may be smaller or larger than the target's pointer type, and 2460 // therefore require extension or truncating. 2461 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2462 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2463 2464 unsigned JumpTableReg = 2465 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2466 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2467 JumpTableReg, SwitchOp); 2468 JT.Reg = JumpTableReg; 2469 2470 if (!JTH.OmitRangeCheck) { 2471 // Emit the range check for the jump table, and branch to the default block 2472 // for the switch statement if the value being switched on exceeds the 2473 // largest case in the switch. 2474 SDValue CMP = DAG.getSetCC( 2475 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2476 Sub.getValueType()), 2477 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2478 2479 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2480 MVT::Other, CopyTo, CMP, 2481 DAG.getBasicBlock(JT.Default)); 2482 2483 // Avoid emitting unnecessary branches to the next block. 2484 if (JT.MBB != NextBlock(SwitchBB)) 2485 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2486 DAG.getBasicBlock(JT.MBB)); 2487 2488 DAG.setRoot(BrCond); 2489 } else { 2490 // Avoid emitting unnecessary branches to the next block. 2491 if (JT.MBB != NextBlock(SwitchBB)) 2492 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2493 DAG.getBasicBlock(JT.MBB))); 2494 else 2495 DAG.setRoot(CopyTo); 2496 } 2497 } 2498 2499 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2500 /// variable if there exists one. 2501 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2502 SDValue &Chain) { 2503 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2504 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2505 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2506 MachineFunction &MF = DAG.getMachineFunction(); 2507 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2508 MachineSDNode *Node = 2509 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2510 if (Global) { 2511 MachinePointerInfo MPInfo(Global); 2512 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2513 MachineMemOperand::MODereferenceable; 2514 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2515 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2516 DAG.setNodeMemRefs(Node, {MemRef}); 2517 } 2518 if (PtrTy != PtrMemTy) 2519 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2520 return SDValue(Node, 0); 2521 } 2522 2523 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2524 /// tail spliced into a stack protector check success bb. 2525 /// 2526 /// For a high level explanation of how this fits into the stack protector 2527 /// generation see the comment on the declaration of class 2528 /// StackProtectorDescriptor. 2529 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2530 MachineBasicBlock *ParentBB) { 2531 2532 // First create the loads to the guard/stack slot for the comparison. 2533 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2534 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2535 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2536 2537 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2538 int FI = MFI.getStackProtectorIndex(); 2539 2540 SDValue Guard; 2541 SDLoc dl = getCurSDLoc(); 2542 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2543 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2544 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2545 2546 // Generate code to load the content of the guard slot. 2547 SDValue GuardVal = DAG.getLoad( 2548 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2549 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2550 MachineMemOperand::MOVolatile); 2551 2552 if (TLI.useStackGuardXorFP()) 2553 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2554 2555 // Retrieve guard check function, nullptr if instrumentation is inlined. 2556 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2557 // The target provides a guard check function to validate the guard value. 2558 // Generate a call to that function with the content of the guard slot as 2559 // argument. 2560 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2561 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2562 2563 TargetLowering::ArgListTy Args; 2564 TargetLowering::ArgListEntry Entry; 2565 Entry.Node = GuardVal; 2566 Entry.Ty = FnTy->getParamType(0); 2567 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2568 Entry.IsInReg = true; 2569 Args.push_back(Entry); 2570 2571 TargetLowering::CallLoweringInfo CLI(DAG); 2572 CLI.setDebugLoc(getCurSDLoc()) 2573 .setChain(DAG.getEntryNode()) 2574 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2575 getValue(GuardCheckFn), std::move(Args)); 2576 2577 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2578 DAG.setRoot(Result.second); 2579 return; 2580 } 2581 2582 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2583 // Otherwise, emit a volatile load to retrieve the stack guard value. 2584 SDValue Chain = DAG.getEntryNode(); 2585 if (TLI.useLoadStackGuardNode()) { 2586 Guard = getLoadStackGuard(DAG, dl, Chain); 2587 } else { 2588 const Value *IRGuard = TLI.getSDagStackGuard(M); 2589 SDValue GuardPtr = getValue(IRGuard); 2590 2591 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2592 MachinePointerInfo(IRGuard, 0), Align, 2593 MachineMemOperand::MOVolatile); 2594 } 2595 2596 // Perform the comparison via a getsetcc. 2597 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2598 *DAG.getContext(), 2599 Guard.getValueType()), 2600 Guard, GuardVal, ISD::SETNE); 2601 2602 // If the guard/stackslot do not equal, branch to failure MBB. 2603 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2604 MVT::Other, GuardVal.getOperand(0), 2605 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2606 // Otherwise branch to success MBB. 2607 SDValue Br = DAG.getNode(ISD::BR, dl, 2608 MVT::Other, BrCond, 2609 DAG.getBasicBlock(SPD.getSuccessMBB())); 2610 2611 DAG.setRoot(Br); 2612 } 2613 2614 /// Codegen the failure basic block for a stack protector check. 2615 /// 2616 /// A failure stack protector machine basic block consists simply of a call to 2617 /// __stack_chk_fail(). 2618 /// 2619 /// For a high level explanation of how this fits into the stack protector 2620 /// generation see the comment on the declaration of class 2621 /// StackProtectorDescriptor. 2622 void 2623 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2624 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2625 TargetLowering::MakeLibCallOptions CallOptions; 2626 CallOptions.setDiscardResult(true); 2627 SDValue Chain = 2628 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2629 None, CallOptions, getCurSDLoc()).second; 2630 // On PS4, the "return address" must still be within the calling function, 2631 // even if it's at the very end, so emit an explicit TRAP here. 2632 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2633 if (TM.getTargetTriple().isPS4CPU()) 2634 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2635 2636 DAG.setRoot(Chain); 2637 } 2638 2639 /// visitBitTestHeader - This function emits necessary code to produce value 2640 /// suitable for "bit tests" 2641 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2642 MachineBasicBlock *SwitchBB) { 2643 SDLoc dl = getCurSDLoc(); 2644 2645 // Subtract the minimum value. 2646 SDValue SwitchOp = getValue(B.SValue); 2647 EVT VT = SwitchOp.getValueType(); 2648 SDValue RangeSub = 2649 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2650 2651 // Determine the type of the test operands. 2652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2653 bool UsePtrType = false; 2654 if (!TLI.isTypeLegal(VT)) { 2655 UsePtrType = true; 2656 } else { 2657 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2658 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2659 // Switch table case range are encoded into series of masks. 2660 // Just use pointer type, it's guaranteed to fit. 2661 UsePtrType = true; 2662 break; 2663 } 2664 } 2665 SDValue Sub = RangeSub; 2666 if (UsePtrType) { 2667 VT = TLI.getPointerTy(DAG.getDataLayout()); 2668 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2669 } 2670 2671 B.RegVT = VT.getSimpleVT(); 2672 B.Reg = FuncInfo.CreateReg(B.RegVT); 2673 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2674 2675 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2676 2677 if (!B.OmitRangeCheck) 2678 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2679 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2680 SwitchBB->normalizeSuccProbs(); 2681 2682 SDValue Root = CopyTo; 2683 if (!B.OmitRangeCheck) { 2684 // Conditional branch to the default block. 2685 SDValue RangeCmp = DAG.getSetCC(dl, 2686 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2687 RangeSub.getValueType()), 2688 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2689 ISD::SETUGT); 2690 2691 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2692 DAG.getBasicBlock(B.Default)); 2693 } 2694 2695 // Avoid emitting unnecessary branches to the next block. 2696 if (MBB != NextBlock(SwitchBB)) 2697 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2698 2699 DAG.setRoot(Root); 2700 } 2701 2702 /// visitBitTestCase - this function produces one "bit test" 2703 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2704 MachineBasicBlock* NextMBB, 2705 BranchProbability BranchProbToNext, 2706 unsigned Reg, 2707 BitTestCase &B, 2708 MachineBasicBlock *SwitchBB) { 2709 SDLoc dl = getCurSDLoc(); 2710 MVT VT = BB.RegVT; 2711 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2712 SDValue Cmp; 2713 unsigned PopCount = countPopulation(B.Mask); 2714 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2715 if (PopCount == 1) { 2716 // Testing for a single bit; just compare the shift count with what it 2717 // would need to be to shift a 1 bit in that position. 2718 Cmp = DAG.getSetCC( 2719 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2720 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2721 ISD::SETEQ); 2722 } else if (PopCount == BB.Range) { 2723 // There is only one zero bit in the range, test for it directly. 2724 Cmp = DAG.getSetCC( 2725 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2726 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2727 ISD::SETNE); 2728 } else { 2729 // Make desired shift 2730 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2731 DAG.getConstant(1, dl, VT), ShiftOp); 2732 2733 // Emit bit tests and jumps 2734 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2735 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2736 Cmp = DAG.getSetCC( 2737 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2738 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2739 } 2740 2741 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2742 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2743 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2744 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2745 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2746 // one as they are relative probabilities (and thus work more like weights), 2747 // and hence we need to normalize them to let the sum of them become one. 2748 SwitchBB->normalizeSuccProbs(); 2749 2750 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2751 MVT::Other, getControlRoot(), 2752 Cmp, DAG.getBasicBlock(B.TargetBB)); 2753 2754 // Avoid emitting unnecessary branches to the next block. 2755 if (NextMBB != NextBlock(SwitchBB)) 2756 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2757 DAG.getBasicBlock(NextMBB)); 2758 2759 DAG.setRoot(BrAnd); 2760 } 2761 2762 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2763 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2764 2765 // Retrieve successors. Look through artificial IR level blocks like 2766 // catchswitch for successors. 2767 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2768 const BasicBlock *EHPadBB = I.getSuccessor(1); 2769 2770 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2771 // have to do anything here to lower funclet bundles. 2772 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2773 LLVMContext::OB_funclet, 2774 LLVMContext::OB_cfguardtarget}) && 2775 "Cannot lower invokes with arbitrary operand bundles yet!"); 2776 2777 const Value *Callee(I.getCalledValue()); 2778 const Function *Fn = dyn_cast<Function>(Callee); 2779 if (isa<InlineAsm>(Callee)) 2780 visitInlineAsm(&I); 2781 else if (Fn && Fn->isIntrinsic()) { 2782 switch (Fn->getIntrinsicID()) { 2783 default: 2784 llvm_unreachable("Cannot invoke this intrinsic"); 2785 case Intrinsic::donothing: 2786 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2787 break; 2788 case Intrinsic::experimental_patchpoint_void: 2789 case Intrinsic::experimental_patchpoint_i64: 2790 visitPatchpoint(&I, EHPadBB); 2791 break; 2792 case Intrinsic::experimental_gc_statepoint: 2793 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2794 break; 2795 case Intrinsic::wasm_rethrow_in_catch: { 2796 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2797 // special because it can be invoked, so we manually lower it to a DAG 2798 // node here. 2799 SmallVector<SDValue, 8> Ops; 2800 Ops.push_back(getRoot()); // inchain 2801 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2802 Ops.push_back( 2803 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2804 TLI.getPointerTy(DAG.getDataLayout()))); 2805 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2806 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2807 break; 2808 } 2809 } 2810 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2811 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2812 // Eventually we will support lowering the @llvm.experimental.deoptimize 2813 // intrinsic, and right now there are no plans to support other intrinsics 2814 // with deopt state. 2815 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2816 } else { 2817 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2818 } 2819 2820 // If the value of the invoke is used outside of its defining block, make it 2821 // available as a virtual register. 2822 // We already took care of the exported value for the statepoint instruction 2823 // during call to the LowerStatepoint. 2824 if (!isStatepoint(I)) { 2825 CopyToExportRegsIfNeeded(&I); 2826 } 2827 2828 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2829 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2830 BranchProbability EHPadBBProb = 2831 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2832 : BranchProbability::getZero(); 2833 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2834 2835 // Update successor info. 2836 addSuccessorWithProb(InvokeMBB, Return); 2837 for (auto &UnwindDest : UnwindDests) { 2838 UnwindDest.first->setIsEHPad(); 2839 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2840 } 2841 InvokeMBB->normalizeSuccProbs(); 2842 2843 // Drop into normal successor. 2844 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2845 DAG.getBasicBlock(Return))); 2846 } 2847 2848 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2849 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2850 2851 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2852 // have to do anything here to lower funclet bundles. 2853 assert(!I.hasOperandBundlesOtherThan( 2854 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2855 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2856 2857 assert(isa<InlineAsm>(I.getCalledValue()) && 2858 "Only know how to handle inlineasm callbr"); 2859 visitInlineAsm(&I); 2860 CopyToExportRegsIfNeeded(&I); 2861 2862 // Retrieve successors. 2863 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2864 Return->setInlineAsmBrDefaultTarget(); 2865 2866 // Update successor info. 2867 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2868 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2869 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2870 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2871 CallBrMBB->addInlineAsmBrIndirectTarget(Target); 2872 } 2873 CallBrMBB->normalizeSuccProbs(); 2874 2875 // Drop into default successor. 2876 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2877 MVT::Other, getControlRoot(), 2878 DAG.getBasicBlock(Return))); 2879 } 2880 2881 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2882 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2883 } 2884 2885 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2886 assert(FuncInfo.MBB->isEHPad() && 2887 "Call to landingpad not in landing pad!"); 2888 2889 // If there aren't registers to copy the values into (e.g., during SjLj 2890 // exceptions), then don't bother to create these DAG nodes. 2891 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2892 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2893 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2894 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2895 return; 2896 2897 // If landingpad's return type is token type, we don't create DAG nodes 2898 // for its exception pointer and selector value. The extraction of exception 2899 // pointer or selector value from token type landingpads is not currently 2900 // supported. 2901 if (LP.getType()->isTokenTy()) 2902 return; 2903 2904 SmallVector<EVT, 2> ValueVTs; 2905 SDLoc dl = getCurSDLoc(); 2906 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2907 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2908 2909 // Get the two live-in registers as SDValues. The physregs have already been 2910 // copied into virtual registers. 2911 SDValue Ops[2]; 2912 if (FuncInfo.ExceptionPointerVirtReg) { 2913 Ops[0] = DAG.getZExtOrTrunc( 2914 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2915 FuncInfo.ExceptionPointerVirtReg, 2916 TLI.getPointerTy(DAG.getDataLayout())), 2917 dl, ValueVTs[0]); 2918 } else { 2919 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2920 } 2921 Ops[1] = DAG.getZExtOrTrunc( 2922 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2923 FuncInfo.ExceptionSelectorVirtReg, 2924 TLI.getPointerTy(DAG.getDataLayout())), 2925 dl, ValueVTs[1]); 2926 2927 // Merge into one. 2928 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2929 DAG.getVTList(ValueVTs), Ops); 2930 setValue(&LP, Res); 2931 } 2932 2933 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2934 MachineBasicBlock *Last) { 2935 // Update JTCases. 2936 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2937 if (SL->JTCases[i].first.HeaderBB == First) 2938 SL->JTCases[i].first.HeaderBB = Last; 2939 2940 // Update BitTestCases. 2941 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2942 if (SL->BitTestCases[i].Parent == First) 2943 SL->BitTestCases[i].Parent = Last; 2944 } 2945 2946 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2947 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2948 2949 // Update machine-CFG edges with unique successors. 2950 SmallSet<BasicBlock*, 32> Done; 2951 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2952 BasicBlock *BB = I.getSuccessor(i); 2953 bool Inserted = Done.insert(BB).second; 2954 if (!Inserted) 2955 continue; 2956 2957 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2958 addSuccessorWithProb(IndirectBrMBB, Succ); 2959 } 2960 IndirectBrMBB->normalizeSuccProbs(); 2961 2962 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2963 MVT::Other, getControlRoot(), 2964 getValue(I.getAddress()))); 2965 } 2966 2967 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2968 if (!DAG.getTarget().Options.TrapUnreachable) 2969 return; 2970 2971 // We may be able to ignore unreachable behind a noreturn call. 2972 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2973 const BasicBlock &BB = *I.getParent(); 2974 if (&I != &BB.front()) { 2975 BasicBlock::const_iterator PredI = 2976 std::prev(BasicBlock::const_iterator(&I)); 2977 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2978 if (Call->doesNotReturn()) 2979 return; 2980 } 2981 } 2982 } 2983 2984 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2985 } 2986 2987 void SelectionDAGBuilder::visitFSub(const User &I) { 2988 // -0.0 - X --> fneg 2989 Type *Ty = I.getType(); 2990 if (isa<Constant>(I.getOperand(0)) && 2991 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2992 SDValue Op2 = getValue(I.getOperand(1)); 2993 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2994 Op2.getValueType(), Op2)); 2995 return; 2996 } 2997 2998 visitBinary(I, ISD::FSUB); 2999 } 3000 3001 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3002 SDNodeFlags Flags; 3003 3004 SDValue Op = getValue(I.getOperand(0)); 3005 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3006 Op, Flags); 3007 setValue(&I, UnNodeValue); 3008 } 3009 3010 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3011 SDNodeFlags Flags; 3012 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3013 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3014 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3015 } 3016 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3017 Flags.setExact(ExactOp->isExact()); 3018 } 3019 3020 SDValue Op1 = getValue(I.getOperand(0)); 3021 SDValue Op2 = getValue(I.getOperand(1)); 3022 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3023 Op1, Op2, Flags); 3024 setValue(&I, BinNodeValue); 3025 } 3026 3027 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3028 SDValue Op1 = getValue(I.getOperand(0)); 3029 SDValue Op2 = getValue(I.getOperand(1)); 3030 3031 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3032 Op1.getValueType(), DAG.getDataLayout()); 3033 3034 // Coerce the shift amount to the right type if we can. 3035 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3036 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3037 unsigned Op2Size = Op2.getValueSizeInBits(); 3038 SDLoc DL = getCurSDLoc(); 3039 3040 // If the operand is smaller than the shift count type, promote it. 3041 if (ShiftSize > Op2Size) 3042 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3043 3044 // If the operand is larger than the shift count type but the shift 3045 // count type has enough bits to represent any shift value, truncate 3046 // it now. This is a common case and it exposes the truncate to 3047 // optimization early. 3048 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3049 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3050 // Otherwise we'll need to temporarily settle for some other convenient 3051 // type. Type legalization will make adjustments once the shiftee is split. 3052 else 3053 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3054 } 3055 3056 bool nuw = false; 3057 bool nsw = false; 3058 bool exact = false; 3059 3060 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3061 3062 if (const OverflowingBinaryOperator *OFBinOp = 3063 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3064 nuw = OFBinOp->hasNoUnsignedWrap(); 3065 nsw = OFBinOp->hasNoSignedWrap(); 3066 } 3067 if (const PossiblyExactOperator *ExactOp = 3068 dyn_cast<const PossiblyExactOperator>(&I)) 3069 exact = ExactOp->isExact(); 3070 } 3071 SDNodeFlags Flags; 3072 Flags.setExact(exact); 3073 Flags.setNoSignedWrap(nsw); 3074 Flags.setNoUnsignedWrap(nuw); 3075 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3076 Flags); 3077 setValue(&I, Res); 3078 } 3079 3080 void SelectionDAGBuilder::visitSDiv(const User &I) { 3081 SDValue Op1 = getValue(I.getOperand(0)); 3082 SDValue Op2 = getValue(I.getOperand(1)); 3083 3084 SDNodeFlags Flags; 3085 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3086 cast<PossiblyExactOperator>(&I)->isExact()); 3087 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3088 Op2, Flags)); 3089 } 3090 3091 void SelectionDAGBuilder::visitICmp(const User &I) { 3092 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3093 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3094 predicate = IC->getPredicate(); 3095 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3096 predicate = ICmpInst::Predicate(IC->getPredicate()); 3097 SDValue Op1 = getValue(I.getOperand(0)); 3098 SDValue Op2 = getValue(I.getOperand(1)); 3099 ISD::CondCode Opcode = getICmpCondCode(predicate); 3100 3101 auto &TLI = DAG.getTargetLoweringInfo(); 3102 EVT MemVT = 3103 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3104 3105 // If a pointer's DAG type is larger than its memory type then the DAG values 3106 // are zero-extended. This breaks signed comparisons so truncate back to the 3107 // underlying type before doing the compare. 3108 if (Op1.getValueType() != MemVT) { 3109 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3110 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3111 } 3112 3113 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3114 I.getType()); 3115 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3116 } 3117 3118 void SelectionDAGBuilder::visitFCmp(const User &I) { 3119 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3120 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3121 predicate = FC->getPredicate(); 3122 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3123 predicate = FCmpInst::Predicate(FC->getPredicate()); 3124 SDValue Op1 = getValue(I.getOperand(0)); 3125 SDValue Op2 = getValue(I.getOperand(1)); 3126 3127 ISD::CondCode Condition = getFCmpCondCode(predicate); 3128 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3129 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3130 Condition = getFCmpCodeWithoutNaN(Condition); 3131 3132 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3133 I.getType()); 3134 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3135 } 3136 3137 // Check if the condition of the select has one use or two users that are both 3138 // selects with the same condition. 3139 static bool hasOnlySelectUsers(const Value *Cond) { 3140 return llvm::all_of(Cond->users(), [](const Value *V) { 3141 return isa<SelectInst>(V); 3142 }); 3143 } 3144 3145 void SelectionDAGBuilder::visitSelect(const User &I) { 3146 SmallVector<EVT, 4> ValueVTs; 3147 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3148 ValueVTs); 3149 unsigned NumValues = ValueVTs.size(); 3150 if (NumValues == 0) return; 3151 3152 SmallVector<SDValue, 4> Values(NumValues); 3153 SDValue Cond = getValue(I.getOperand(0)); 3154 SDValue LHSVal = getValue(I.getOperand(1)); 3155 SDValue RHSVal = getValue(I.getOperand(2)); 3156 SmallVector<SDValue, 1> BaseOps(1, Cond); 3157 ISD::NodeType OpCode = 3158 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3159 3160 bool IsUnaryAbs = false; 3161 3162 // Min/max matching is only viable if all output VTs are the same. 3163 if (is_splat(ValueVTs)) { 3164 EVT VT = ValueVTs[0]; 3165 LLVMContext &Ctx = *DAG.getContext(); 3166 auto &TLI = DAG.getTargetLoweringInfo(); 3167 3168 // We care about the legality of the operation after it has been type 3169 // legalized. 3170 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3171 VT = TLI.getTypeToTransformTo(Ctx, VT); 3172 3173 // If the vselect is legal, assume we want to leave this as a vector setcc + 3174 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3175 // min/max is legal on the scalar type. 3176 bool UseScalarMinMax = VT.isVector() && 3177 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3178 3179 Value *LHS, *RHS; 3180 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3181 ISD::NodeType Opc = ISD::DELETED_NODE; 3182 switch (SPR.Flavor) { 3183 case SPF_UMAX: Opc = ISD::UMAX; break; 3184 case SPF_UMIN: Opc = ISD::UMIN; break; 3185 case SPF_SMAX: Opc = ISD::SMAX; break; 3186 case SPF_SMIN: Opc = ISD::SMIN; break; 3187 case SPF_FMINNUM: 3188 switch (SPR.NaNBehavior) { 3189 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3190 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3191 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3192 case SPNB_RETURNS_ANY: { 3193 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3194 Opc = ISD::FMINNUM; 3195 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3196 Opc = ISD::FMINIMUM; 3197 else if (UseScalarMinMax) 3198 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3199 ISD::FMINNUM : ISD::FMINIMUM; 3200 break; 3201 } 3202 } 3203 break; 3204 case SPF_FMAXNUM: 3205 switch (SPR.NaNBehavior) { 3206 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3207 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3208 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3209 case SPNB_RETURNS_ANY: 3210 3211 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3212 Opc = ISD::FMAXNUM; 3213 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3214 Opc = ISD::FMAXIMUM; 3215 else if (UseScalarMinMax) 3216 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3217 ISD::FMAXNUM : ISD::FMAXIMUM; 3218 break; 3219 } 3220 break; 3221 case SPF_ABS: 3222 IsUnaryAbs = true; 3223 Opc = ISD::ABS; 3224 break; 3225 case SPF_NABS: 3226 // TODO: we need to produce sub(0, abs(X)). 3227 default: break; 3228 } 3229 3230 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3231 (TLI.isOperationLegalOrCustom(Opc, VT) || 3232 (UseScalarMinMax && 3233 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3234 // If the underlying comparison instruction is used by any other 3235 // instruction, the consumed instructions won't be destroyed, so it is 3236 // not profitable to convert to a min/max. 3237 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3238 OpCode = Opc; 3239 LHSVal = getValue(LHS); 3240 RHSVal = getValue(RHS); 3241 BaseOps.clear(); 3242 } 3243 3244 if (IsUnaryAbs) { 3245 OpCode = Opc; 3246 LHSVal = getValue(LHS); 3247 BaseOps.clear(); 3248 } 3249 } 3250 3251 if (IsUnaryAbs) { 3252 for (unsigned i = 0; i != NumValues; ++i) { 3253 Values[i] = 3254 DAG.getNode(OpCode, getCurSDLoc(), 3255 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3256 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3257 } 3258 } else { 3259 for (unsigned i = 0; i != NumValues; ++i) { 3260 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3261 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3262 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3263 Values[i] = DAG.getNode( 3264 OpCode, getCurSDLoc(), 3265 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3266 } 3267 } 3268 3269 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3270 DAG.getVTList(ValueVTs), Values)); 3271 } 3272 3273 void SelectionDAGBuilder::visitTrunc(const User &I) { 3274 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3275 SDValue N = getValue(I.getOperand(0)); 3276 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3277 I.getType()); 3278 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3279 } 3280 3281 void SelectionDAGBuilder::visitZExt(const User &I) { 3282 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3283 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3284 SDValue N = getValue(I.getOperand(0)); 3285 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3286 I.getType()); 3287 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3288 } 3289 3290 void SelectionDAGBuilder::visitSExt(const User &I) { 3291 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3292 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3293 SDValue N = getValue(I.getOperand(0)); 3294 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3295 I.getType()); 3296 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3297 } 3298 3299 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3300 // FPTrunc is never a no-op cast, no need to check 3301 SDValue N = getValue(I.getOperand(0)); 3302 SDLoc dl = getCurSDLoc(); 3303 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3304 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3305 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3306 DAG.getTargetConstant( 3307 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3308 } 3309 3310 void SelectionDAGBuilder::visitFPExt(const User &I) { 3311 // FPExt is never a no-op cast, no need to check 3312 SDValue N = getValue(I.getOperand(0)); 3313 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3314 I.getType()); 3315 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3316 } 3317 3318 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3319 // FPToUI is never a no-op cast, no need to check 3320 SDValue N = getValue(I.getOperand(0)); 3321 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3322 I.getType()); 3323 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3324 } 3325 3326 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3327 // FPToSI is never a no-op cast, no need to check 3328 SDValue N = getValue(I.getOperand(0)); 3329 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3330 I.getType()); 3331 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3332 } 3333 3334 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3335 // UIToFP is never a no-op cast, no need to check 3336 SDValue N = getValue(I.getOperand(0)); 3337 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3338 I.getType()); 3339 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3340 } 3341 3342 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3343 // SIToFP is never a no-op cast, no need to check 3344 SDValue N = getValue(I.getOperand(0)); 3345 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3346 I.getType()); 3347 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3348 } 3349 3350 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3351 // What to do depends on the size of the integer and the size of the pointer. 3352 // We can either truncate, zero extend, or no-op, accordingly. 3353 SDValue N = getValue(I.getOperand(0)); 3354 auto &TLI = DAG.getTargetLoweringInfo(); 3355 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3356 I.getType()); 3357 EVT PtrMemVT = 3358 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3359 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3360 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3361 setValue(&I, N); 3362 } 3363 3364 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3365 // What to do depends on the size of the integer and the size of the pointer. 3366 // We can either truncate, zero extend, or no-op, accordingly. 3367 SDValue N = getValue(I.getOperand(0)); 3368 auto &TLI = DAG.getTargetLoweringInfo(); 3369 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3370 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3371 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3372 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3373 setValue(&I, N); 3374 } 3375 3376 void SelectionDAGBuilder::visitBitCast(const User &I) { 3377 SDValue N = getValue(I.getOperand(0)); 3378 SDLoc dl = getCurSDLoc(); 3379 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3380 I.getType()); 3381 3382 // BitCast assures us that source and destination are the same size so this is 3383 // either a BITCAST or a no-op. 3384 if (DestVT != N.getValueType()) 3385 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3386 DestVT, N)); // convert types. 3387 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3388 // might fold any kind of constant expression to an integer constant and that 3389 // is not what we are looking for. Only recognize a bitcast of a genuine 3390 // constant integer as an opaque constant. 3391 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3392 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3393 /*isOpaque*/true)); 3394 else 3395 setValue(&I, N); // noop cast. 3396 } 3397 3398 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3399 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3400 const Value *SV = I.getOperand(0); 3401 SDValue N = getValue(SV); 3402 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3403 3404 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3405 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3406 3407 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3408 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3409 3410 setValue(&I, N); 3411 } 3412 3413 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3414 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3415 SDValue InVec = getValue(I.getOperand(0)); 3416 SDValue InVal = getValue(I.getOperand(1)); 3417 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3418 TLI.getVectorIdxTy(DAG.getDataLayout())); 3419 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3420 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3421 InVec, InVal, InIdx)); 3422 } 3423 3424 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3425 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3426 SDValue InVec = getValue(I.getOperand(0)); 3427 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3428 TLI.getVectorIdxTy(DAG.getDataLayout())); 3429 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3430 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3431 InVec, InIdx)); 3432 } 3433 3434 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3435 SDValue Src1 = getValue(I.getOperand(0)); 3436 SDValue Src2 = getValue(I.getOperand(1)); 3437 Constant *MaskV = cast<Constant>(I.getOperand(2)); 3438 SDLoc DL = getCurSDLoc(); 3439 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3440 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3441 EVT SrcVT = Src1.getValueType(); 3442 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3443 3444 if (MaskV->isNullValue() && VT.isScalableVector()) { 3445 // Canonical splat form of first element of first input vector. 3446 SDValue FirstElt = 3447 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3448 DAG.getVectorIdxConstant(0, DL)); 3449 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3450 return; 3451 } 3452 3453 // For now, we only handle splats for scalable vectors. 3454 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3455 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3456 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3457 3458 SmallVector<int, 8> Mask; 3459 ShuffleVectorInst::getShuffleMask(MaskV, Mask); 3460 unsigned MaskNumElts = Mask.size(); 3461 3462 if (SrcNumElts == MaskNumElts) { 3463 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3464 return; 3465 } 3466 3467 // Normalize the shuffle vector since mask and vector length don't match. 3468 if (SrcNumElts < MaskNumElts) { 3469 // Mask is longer than the source vectors. We can use concatenate vector to 3470 // make the mask and vectors lengths match. 3471 3472 if (MaskNumElts % SrcNumElts == 0) { 3473 // Mask length is a multiple of the source vector length. 3474 // Check if the shuffle is some kind of concatenation of the input 3475 // vectors. 3476 unsigned NumConcat = MaskNumElts / SrcNumElts; 3477 bool IsConcat = true; 3478 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3479 for (unsigned i = 0; i != MaskNumElts; ++i) { 3480 int Idx = Mask[i]; 3481 if (Idx < 0) 3482 continue; 3483 // Ensure the indices in each SrcVT sized piece are sequential and that 3484 // the same source is used for the whole piece. 3485 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3486 (ConcatSrcs[i / SrcNumElts] >= 0 && 3487 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3488 IsConcat = false; 3489 break; 3490 } 3491 // Remember which source this index came from. 3492 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3493 } 3494 3495 // The shuffle is concatenating multiple vectors together. Just emit 3496 // a CONCAT_VECTORS operation. 3497 if (IsConcat) { 3498 SmallVector<SDValue, 8> ConcatOps; 3499 for (auto Src : ConcatSrcs) { 3500 if (Src < 0) 3501 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3502 else if (Src == 0) 3503 ConcatOps.push_back(Src1); 3504 else 3505 ConcatOps.push_back(Src2); 3506 } 3507 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3508 return; 3509 } 3510 } 3511 3512 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3513 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3514 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3515 PaddedMaskNumElts); 3516 3517 // Pad both vectors with undefs to make them the same length as the mask. 3518 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3519 3520 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3521 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3522 MOps1[0] = Src1; 3523 MOps2[0] = Src2; 3524 3525 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3526 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3527 3528 // Readjust mask for new input vector length. 3529 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3530 for (unsigned i = 0; i != MaskNumElts; ++i) { 3531 int Idx = Mask[i]; 3532 if (Idx >= (int)SrcNumElts) 3533 Idx -= SrcNumElts - PaddedMaskNumElts; 3534 MappedOps[i] = Idx; 3535 } 3536 3537 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3538 3539 // If the concatenated vector was padded, extract a subvector with the 3540 // correct number of elements. 3541 if (MaskNumElts != PaddedMaskNumElts) 3542 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3543 DAG.getVectorIdxConstant(0, DL)); 3544 3545 setValue(&I, Result); 3546 return; 3547 } 3548 3549 if (SrcNumElts > MaskNumElts) { 3550 // Analyze the access pattern of the vector to see if we can extract 3551 // two subvectors and do the shuffle. 3552 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3553 bool CanExtract = true; 3554 for (int Idx : Mask) { 3555 unsigned Input = 0; 3556 if (Idx < 0) 3557 continue; 3558 3559 if (Idx >= (int)SrcNumElts) { 3560 Input = 1; 3561 Idx -= SrcNumElts; 3562 } 3563 3564 // If all the indices come from the same MaskNumElts sized portion of 3565 // the sources we can use extract. Also make sure the extract wouldn't 3566 // extract past the end of the source. 3567 int NewStartIdx = alignDown(Idx, MaskNumElts); 3568 if (NewStartIdx + MaskNumElts > SrcNumElts || 3569 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3570 CanExtract = false; 3571 // Make sure we always update StartIdx as we use it to track if all 3572 // elements are undef. 3573 StartIdx[Input] = NewStartIdx; 3574 } 3575 3576 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3577 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3578 return; 3579 } 3580 if (CanExtract) { 3581 // Extract appropriate subvector and generate a vector shuffle 3582 for (unsigned Input = 0; Input < 2; ++Input) { 3583 SDValue &Src = Input == 0 ? Src1 : Src2; 3584 if (StartIdx[Input] < 0) 3585 Src = DAG.getUNDEF(VT); 3586 else { 3587 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3588 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3589 } 3590 } 3591 3592 // Calculate new mask. 3593 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3594 for (int &Idx : MappedOps) { 3595 if (Idx >= (int)SrcNumElts) 3596 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3597 else if (Idx >= 0) 3598 Idx -= StartIdx[0]; 3599 } 3600 3601 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3602 return; 3603 } 3604 } 3605 3606 // We can't use either concat vectors or extract subvectors so fall back to 3607 // replacing the shuffle with extract and build vector. 3608 // to insert and build vector. 3609 EVT EltVT = VT.getVectorElementType(); 3610 SmallVector<SDValue,8> Ops; 3611 for (int Idx : Mask) { 3612 SDValue Res; 3613 3614 if (Idx < 0) { 3615 Res = DAG.getUNDEF(EltVT); 3616 } else { 3617 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3618 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3619 3620 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3621 DAG.getVectorIdxConstant(Idx, DL)); 3622 } 3623 3624 Ops.push_back(Res); 3625 } 3626 3627 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3628 } 3629 3630 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3631 ArrayRef<unsigned> Indices; 3632 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3633 Indices = IV->getIndices(); 3634 else 3635 Indices = cast<ConstantExpr>(&I)->getIndices(); 3636 3637 const Value *Op0 = I.getOperand(0); 3638 const Value *Op1 = I.getOperand(1); 3639 Type *AggTy = I.getType(); 3640 Type *ValTy = Op1->getType(); 3641 bool IntoUndef = isa<UndefValue>(Op0); 3642 bool FromUndef = isa<UndefValue>(Op1); 3643 3644 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3645 3646 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3647 SmallVector<EVT, 4> AggValueVTs; 3648 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3649 SmallVector<EVT, 4> ValValueVTs; 3650 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3651 3652 unsigned NumAggValues = AggValueVTs.size(); 3653 unsigned NumValValues = ValValueVTs.size(); 3654 SmallVector<SDValue, 4> Values(NumAggValues); 3655 3656 // Ignore an insertvalue that produces an empty object 3657 if (!NumAggValues) { 3658 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3659 return; 3660 } 3661 3662 SDValue Agg = getValue(Op0); 3663 unsigned i = 0; 3664 // Copy the beginning value(s) from the original aggregate. 3665 for (; i != LinearIndex; ++i) 3666 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3667 SDValue(Agg.getNode(), Agg.getResNo() + i); 3668 // Copy values from the inserted value(s). 3669 if (NumValValues) { 3670 SDValue Val = getValue(Op1); 3671 for (; i != LinearIndex + NumValValues; ++i) 3672 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3673 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3674 } 3675 // Copy remaining value(s) from the original aggregate. 3676 for (; i != NumAggValues; ++i) 3677 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3678 SDValue(Agg.getNode(), Agg.getResNo() + i); 3679 3680 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3681 DAG.getVTList(AggValueVTs), Values)); 3682 } 3683 3684 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3685 ArrayRef<unsigned> Indices; 3686 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3687 Indices = EV->getIndices(); 3688 else 3689 Indices = cast<ConstantExpr>(&I)->getIndices(); 3690 3691 const Value *Op0 = I.getOperand(0); 3692 Type *AggTy = Op0->getType(); 3693 Type *ValTy = I.getType(); 3694 bool OutOfUndef = isa<UndefValue>(Op0); 3695 3696 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3697 3698 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3699 SmallVector<EVT, 4> ValValueVTs; 3700 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3701 3702 unsigned NumValValues = ValValueVTs.size(); 3703 3704 // Ignore a extractvalue that produces an empty object 3705 if (!NumValValues) { 3706 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3707 return; 3708 } 3709 3710 SmallVector<SDValue, 4> Values(NumValValues); 3711 3712 SDValue Agg = getValue(Op0); 3713 // Copy out the selected value(s). 3714 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3715 Values[i - LinearIndex] = 3716 OutOfUndef ? 3717 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3718 SDValue(Agg.getNode(), Agg.getResNo() + i); 3719 3720 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3721 DAG.getVTList(ValValueVTs), Values)); 3722 } 3723 3724 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3725 Value *Op0 = I.getOperand(0); 3726 // Note that the pointer operand may be a vector of pointers. Take the scalar 3727 // element which holds a pointer. 3728 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3729 SDValue N = getValue(Op0); 3730 SDLoc dl = getCurSDLoc(); 3731 auto &TLI = DAG.getTargetLoweringInfo(); 3732 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3733 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3734 3735 // Normalize Vector GEP - all scalar operands should be converted to the 3736 // splat vector. 3737 bool IsVectorGEP = I.getType()->isVectorTy(); 3738 ElementCount VectorElementCount = IsVectorGEP ? 3739 I.getType()->getVectorElementCount() : ElementCount(0, false); 3740 3741 if (IsVectorGEP && !N.getValueType().isVector()) { 3742 LLVMContext &Context = *DAG.getContext(); 3743 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3744 if (VectorElementCount.Scalable) 3745 N = DAG.getSplatVector(VT, dl, N); 3746 else 3747 N = DAG.getSplatBuildVector(VT, dl, N); 3748 } 3749 3750 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3751 GTI != E; ++GTI) { 3752 const Value *Idx = GTI.getOperand(); 3753 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3754 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3755 if (Field) { 3756 // N = N + Offset 3757 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3758 3759 // In an inbounds GEP with an offset that is nonnegative even when 3760 // interpreted as signed, assume there is no unsigned overflow. 3761 SDNodeFlags Flags; 3762 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3763 Flags.setNoUnsignedWrap(true); 3764 3765 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3766 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3767 } 3768 } else { 3769 // IdxSize is the width of the arithmetic according to IR semantics. 3770 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3771 // (and fix up the result later). 3772 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3773 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3774 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3775 // We intentionally mask away the high bits here; ElementSize may not 3776 // fit in IdxTy. 3777 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3778 bool ElementScalable = ElementSize.isScalable(); 3779 3780 // If this is a scalar constant or a splat vector of constants, 3781 // handle it quickly. 3782 const auto *C = dyn_cast<Constant>(Idx); 3783 if (C && isa<VectorType>(C->getType())) 3784 C = C->getSplatValue(); 3785 3786 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3787 if (CI && CI->isZero()) 3788 continue; 3789 if (CI && !ElementScalable) { 3790 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3791 LLVMContext &Context = *DAG.getContext(); 3792 SDValue OffsVal; 3793 if (IsVectorGEP) 3794 OffsVal = DAG.getConstant( 3795 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3796 else 3797 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3798 3799 // In an inbounds GEP with an offset that is nonnegative even when 3800 // interpreted as signed, assume there is no unsigned overflow. 3801 SDNodeFlags Flags; 3802 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3803 Flags.setNoUnsignedWrap(true); 3804 3805 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3806 3807 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3808 continue; 3809 } 3810 3811 // N = N + Idx * ElementMul; 3812 SDValue IdxN = getValue(Idx); 3813 3814 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3815 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3816 VectorElementCount); 3817 if (VectorElementCount.Scalable) 3818 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3819 else 3820 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3821 } 3822 3823 // If the index is smaller or larger than intptr_t, truncate or extend 3824 // it. 3825 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3826 3827 if (ElementScalable) { 3828 EVT VScaleTy = N.getValueType().getScalarType(); 3829 SDValue VScale = DAG.getNode( 3830 ISD::VSCALE, dl, VScaleTy, 3831 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3832 if (IsVectorGEP) 3833 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3834 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3835 } else { 3836 // If this is a multiply by a power of two, turn it into a shl 3837 // immediately. This is a very common case. 3838 if (ElementMul != 1) { 3839 if (ElementMul.isPowerOf2()) { 3840 unsigned Amt = ElementMul.logBase2(); 3841 IdxN = DAG.getNode(ISD::SHL, dl, 3842 N.getValueType(), IdxN, 3843 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3844 } else { 3845 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3846 IdxN.getValueType()); 3847 IdxN = DAG.getNode(ISD::MUL, dl, 3848 N.getValueType(), IdxN, Scale); 3849 } 3850 } 3851 } 3852 3853 N = DAG.getNode(ISD::ADD, dl, 3854 N.getValueType(), N, IdxN); 3855 } 3856 } 3857 3858 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3859 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3860 3861 setValue(&I, N); 3862 } 3863 3864 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3865 // If this is a fixed sized alloca in the entry block of the function, 3866 // allocate it statically on the stack. 3867 if (FuncInfo.StaticAllocaMap.count(&I)) 3868 return; // getValue will auto-populate this. 3869 3870 SDLoc dl = getCurSDLoc(); 3871 Type *Ty = I.getAllocatedType(); 3872 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3873 auto &DL = DAG.getDataLayout(); 3874 uint64_t TySize = DL.getTypeAllocSize(Ty); 3875 MaybeAlign Alignment = max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3876 3877 SDValue AllocSize = getValue(I.getArraySize()); 3878 3879 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3880 if (AllocSize.getValueType() != IntPtr) 3881 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3882 3883 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3884 AllocSize, 3885 DAG.getConstant(TySize, dl, IntPtr)); 3886 3887 // Handle alignment. If the requested alignment is less than or equal to 3888 // the stack alignment, ignore it. If the size is greater than or equal to 3889 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3890 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3891 if (Alignment <= StackAlign) 3892 Alignment = None; 3893 3894 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3895 // Round the size of the allocation up to the stack alignment size 3896 // by add SA-1 to the size. This doesn't overflow because we're computing 3897 // an address inside an alloca. 3898 SDNodeFlags Flags; 3899 Flags.setNoUnsignedWrap(true); 3900 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3901 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3902 3903 // Mask out the low bits for alignment purposes. 3904 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3905 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3906 3907 SDValue Ops[] = { 3908 getRoot(), AllocSize, 3909 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 3910 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3911 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3912 setValue(&I, DSA); 3913 DAG.setRoot(DSA.getValue(1)); 3914 3915 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3916 } 3917 3918 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3919 if (I.isAtomic()) 3920 return visitAtomicLoad(I); 3921 3922 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3923 const Value *SV = I.getOperand(0); 3924 if (TLI.supportSwiftError()) { 3925 // Swifterror values can come from either a function parameter with 3926 // swifterror attribute or an alloca with swifterror attribute. 3927 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3928 if (Arg->hasSwiftErrorAttr()) 3929 return visitLoadFromSwiftError(I); 3930 } 3931 3932 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3933 if (Alloca->isSwiftError()) 3934 return visitLoadFromSwiftError(I); 3935 } 3936 } 3937 3938 SDValue Ptr = getValue(SV); 3939 3940 Type *Ty = I.getType(); 3941 unsigned Alignment = I.getAlignment(); 3942 3943 AAMDNodes AAInfo; 3944 I.getAAMetadata(AAInfo); 3945 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3946 3947 SmallVector<EVT, 4> ValueVTs, MemVTs; 3948 SmallVector<uint64_t, 4> Offsets; 3949 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 3950 unsigned NumValues = ValueVTs.size(); 3951 if (NumValues == 0) 3952 return; 3953 3954 bool isVolatile = I.isVolatile(); 3955 3956 SDValue Root; 3957 bool ConstantMemory = false; 3958 if (isVolatile) 3959 // Serialize volatile loads with other side effects. 3960 Root = getRoot(); 3961 else if (NumValues > MaxParallelChains) 3962 Root = getMemoryRoot(); 3963 else if (AA && 3964 AA->pointsToConstantMemory(MemoryLocation( 3965 SV, 3966 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3967 AAInfo))) { 3968 // Do not serialize (non-volatile) loads of constant memory with anything. 3969 Root = DAG.getEntryNode(); 3970 ConstantMemory = true; 3971 } else { 3972 // Do not serialize non-volatile loads against each other. 3973 Root = DAG.getRoot(); 3974 } 3975 3976 SDLoc dl = getCurSDLoc(); 3977 3978 if (isVolatile) 3979 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3980 3981 // An aggregate load cannot wrap around the address space, so offsets to its 3982 // parts don't wrap either. 3983 SDNodeFlags Flags; 3984 Flags.setNoUnsignedWrap(true); 3985 3986 SmallVector<SDValue, 4> Values(NumValues); 3987 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3988 EVT PtrVT = Ptr.getValueType(); 3989 3990 MachineMemOperand::Flags MMOFlags 3991 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 3992 3993 unsigned ChainI = 0; 3994 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3995 // Serializing loads here may result in excessive register pressure, and 3996 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3997 // could recover a bit by hoisting nodes upward in the chain by recognizing 3998 // they are side-effect free or do not alias. The optimizer should really 3999 // avoid this case by converting large object/array copies to llvm.memcpy 4000 // (MaxParallelChains should always remain as failsafe). 4001 if (ChainI == MaxParallelChains) { 4002 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4003 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4004 makeArrayRef(Chains.data(), ChainI)); 4005 Root = Chain; 4006 ChainI = 0; 4007 } 4008 SDValue A = DAG.getNode(ISD::ADD, dl, 4009 PtrVT, Ptr, 4010 DAG.getConstant(Offsets[i], dl, PtrVT), 4011 Flags); 4012 4013 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4014 MachinePointerInfo(SV, Offsets[i]), Alignment, 4015 MMOFlags, AAInfo, Ranges); 4016 Chains[ChainI] = L.getValue(1); 4017 4018 if (MemVTs[i] != ValueVTs[i]) 4019 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4020 4021 Values[i] = L; 4022 } 4023 4024 if (!ConstantMemory) { 4025 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4026 makeArrayRef(Chains.data(), ChainI)); 4027 if (isVolatile) 4028 DAG.setRoot(Chain); 4029 else 4030 PendingLoads.push_back(Chain); 4031 } 4032 4033 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4034 DAG.getVTList(ValueVTs), Values)); 4035 } 4036 4037 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4038 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4039 "call visitStoreToSwiftError when backend supports swifterror"); 4040 4041 SmallVector<EVT, 4> ValueVTs; 4042 SmallVector<uint64_t, 4> Offsets; 4043 const Value *SrcV = I.getOperand(0); 4044 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4045 SrcV->getType(), ValueVTs, &Offsets); 4046 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4047 "expect a single EVT for swifterror"); 4048 4049 SDValue Src = getValue(SrcV); 4050 // Create a virtual register, then update the virtual register. 4051 Register VReg = 4052 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4053 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4054 // Chain can be getRoot or getControlRoot. 4055 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4056 SDValue(Src.getNode(), Src.getResNo())); 4057 DAG.setRoot(CopyNode); 4058 } 4059 4060 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4061 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4062 "call visitLoadFromSwiftError when backend supports swifterror"); 4063 4064 assert(!I.isVolatile() && 4065 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4066 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4067 "Support volatile, non temporal, invariant for load_from_swift_error"); 4068 4069 const Value *SV = I.getOperand(0); 4070 Type *Ty = I.getType(); 4071 AAMDNodes AAInfo; 4072 I.getAAMetadata(AAInfo); 4073 assert( 4074 (!AA || 4075 !AA->pointsToConstantMemory(MemoryLocation( 4076 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4077 AAInfo))) && 4078 "load_from_swift_error should not be constant memory"); 4079 4080 SmallVector<EVT, 4> ValueVTs; 4081 SmallVector<uint64_t, 4> Offsets; 4082 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4083 ValueVTs, &Offsets); 4084 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4085 "expect a single EVT for swifterror"); 4086 4087 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4088 SDValue L = DAG.getCopyFromReg( 4089 getRoot(), getCurSDLoc(), 4090 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4091 4092 setValue(&I, L); 4093 } 4094 4095 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4096 if (I.isAtomic()) 4097 return visitAtomicStore(I); 4098 4099 const Value *SrcV = I.getOperand(0); 4100 const Value *PtrV = I.getOperand(1); 4101 4102 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4103 if (TLI.supportSwiftError()) { 4104 // Swifterror values can come from either a function parameter with 4105 // swifterror attribute or an alloca with swifterror attribute. 4106 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4107 if (Arg->hasSwiftErrorAttr()) 4108 return visitStoreToSwiftError(I); 4109 } 4110 4111 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4112 if (Alloca->isSwiftError()) 4113 return visitStoreToSwiftError(I); 4114 } 4115 } 4116 4117 SmallVector<EVT, 4> ValueVTs, MemVTs; 4118 SmallVector<uint64_t, 4> Offsets; 4119 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4120 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4121 unsigned NumValues = ValueVTs.size(); 4122 if (NumValues == 0) 4123 return; 4124 4125 // Get the lowered operands. Note that we do this after 4126 // checking if NumResults is zero, because with zero results 4127 // the operands won't have values in the map. 4128 SDValue Src = getValue(SrcV); 4129 SDValue Ptr = getValue(PtrV); 4130 4131 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4132 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4133 SDLoc dl = getCurSDLoc(); 4134 unsigned Alignment = I.getAlignment(); 4135 AAMDNodes AAInfo; 4136 I.getAAMetadata(AAInfo); 4137 4138 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4139 4140 // An aggregate load cannot wrap around the address space, so offsets to its 4141 // parts don't wrap either. 4142 SDNodeFlags Flags; 4143 Flags.setNoUnsignedWrap(true); 4144 4145 unsigned ChainI = 0; 4146 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4147 // See visitLoad comments. 4148 if (ChainI == MaxParallelChains) { 4149 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4150 makeArrayRef(Chains.data(), ChainI)); 4151 Root = Chain; 4152 ChainI = 0; 4153 } 4154 SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags); 4155 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4156 if (MemVTs[i] != ValueVTs[i]) 4157 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4158 SDValue St = 4159 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4160 Alignment, MMOFlags, AAInfo); 4161 Chains[ChainI] = St; 4162 } 4163 4164 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4165 makeArrayRef(Chains.data(), ChainI)); 4166 DAG.setRoot(StoreNode); 4167 } 4168 4169 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4170 bool IsCompressing) { 4171 SDLoc sdl = getCurSDLoc(); 4172 4173 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4174 unsigned& Alignment) { 4175 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4176 Src0 = I.getArgOperand(0); 4177 Ptr = I.getArgOperand(1); 4178 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 4179 Mask = I.getArgOperand(3); 4180 }; 4181 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4182 unsigned& Alignment) { 4183 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4184 Src0 = I.getArgOperand(0); 4185 Ptr = I.getArgOperand(1); 4186 Mask = I.getArgOperand(2); 4187 Alignment = 0; 4188 }; 4189 4190 Value *PtrOperand, *MaskOperand, *Src0Operand; 4191 unsigned Alignment; 4192 if (IsCompressing) 4193 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4194 else 4195 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4196 4197 SDValue Ptr = getValue(PtrOperand); 4198 SDValue Src0 = getValue(Src0Operand); 4199 SDValue Mask = getValue(MaskOperand); 4200 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4201 4202 EVT VT = Src0.getValueType(); 4203 if (!Alignment) 4204 Alignment = DAG.getEVTAlignment(VT); 4205 4206 AAMDNodes AAInfo; 4207 I.getAAMetadata(AAInfo); 4208 4209 MachineMemOperand *MMO = 4210 DAG.getMachineFunction(). 4211 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4212 MachineMemOperand::MOStore, 4213 // TODO: Make MachineMemOperands aware of scalable 4214 // vectors. 4215 VT.getStoreSize().getKnownMinSize(), 4216 Alignment, AAInfo); 4217 SDValue StoreNode = 4218 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4219 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4220 DAG.setRoot(StoreNode); 4221 setValue(&I, StoreNode); 4222 } 4223 4224 // Get a uniform base for the Gather/Scatter intrinsic. 4225 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4226 // We try to represent it as a base pointer + vector of indices. 4227 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4228 // The first operand of the GEP may be a single pointer or a vector of pointers 4229 // Example: 4230 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4231 // or 4232 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4233 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4234 // 4235 // When the first GEP operand is a single pointer - it is the uniform base we 4236 // are looking for. If first operand of the GEP is a splat vector - we 4237 // extract the splat value and use it as a uniform base. 4238 // In all other cases the function returns 'false'. 4239 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4240 ISD::MemIndexType &IndexType, SDValue &Scale, 4241 SelectionDAGBuilder *SDB) { 4242 SelectionDAG& DAG = SDB->DAG; 4243 LLVMContext &Context = *DAG.getContext(); 4244 4245 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4246 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4247 if (!GEP) 4248 return false; 4249 4250 const Value *BasePtr = GEP->getPointerOperand(); 4251 if (BasePtr->getType()->isVectorTy()) { 4252 BasePtr = getSplatValue(BasePtr); 4253 if (!BasePtr) 4254 return false; 4255 } 4256 4257 unsigned FinalIndex = GEP->getNumOperands() - 1; 4258 Value *IndexVal = GEP->getOperand(FinalIndex); 4259 gep_type_iterator GTI = gep_type_begin(*GEP); 4260 4261 // Ensure all the other indices are 0. 4262 for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) { 4263 auto *C = dyn_cast<Constant>(GEP->getOperand(i)); 4264 if (!C) 4265 return false; 4266 if (isa<VectorType>(C->getType())) 4267 C = C->getSplatValue(); 4268 auto *CI = dyn_cast_or_null<ConstantInt>(C); 4269 if (!CI || !CI->isZero()) 4270 return false; 4271 } 4272 4273 // The operands of the GEP may be defined in another basic block. 4274 // In this case we'll not find nodes for the operands. 4275 if (!SDB->findValue(BasePtr)) 4276 return false; 4277 Constant *C = dyn_cast<Constant>(IndexVal); 4278 if (!C && !SDB->findValue(IndexVal)) 4279 return false; 4280 4281 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4282 const DataLayout &DL = DAG.getDataLayout(); 4283 StructType *STy = GTI.getStructTypeOrNull(); 4284 4285 if (STy) { 4286 const StructLayout *SL = DL.getStructLayout(STy); 4287 unsigned Field = cast<Constant>(IndexVal)->getUniqueInteger().getZExtValue(); 4288 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4289 Index = DAG.getConstant(SL->getElementOffset(Field), 4290 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4291 } else { 4292 Scale = DAG.getTargetConstant( 4293 DL.getTypeAllocSize(GEP->getResultElementType()), 4294 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4295 Index = SDB->getValue(IndexVal); 4296 } 4297 Base = SDB->getValue(BasePtr); 4298 IndexType = ISD::SIGNED_SCALED; 4299 4300 if (STy || !Index.getValueType().isVector()) { 4301 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4302 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4303 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4304 } 4305 return true; 4306 } 4307 4308 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4309 SDLoc sdl = getCurSDLoc(); 4310 4311 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4312 const Value *Ptr = I.getArgOperand(1); 4313 SDValue Src0 = getValue(I.getArgOperand(0)); 4314 SDValue Mask = getValue(I.getArgOperand(3)); 4315 EVT VT = Src0.getValueType(); 4316 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4317 if (!Alignment) 4318 Alignment = DAG.getEVTAlignment(VT); 4319 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4320 4321 AAMDNodes AAInfo; 4322 I.getAAMetadata(AAInfo); 4323 4324 SDValue Base; 4325 SDValue Index; 4326 ISD::MemIndexType IndexType; 4327 SDValue Scale; 4328 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this); 4329 4330 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4331 MachineMemOperand *MMO = DAG.getMachineFunction(). 4332 getMachineMemOperand(MachinePointerInfo(AS), 4333 MachineMemOperand::MOStore, 4334 // TODO: Make MachineMemOperands aware of scalable 4335 // vectors. 4336 MemoryLocation::UnknownSize, 4337 Alignment, AAInfo); 4338 if (!UniformBase) { 4339 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4340 Index = getValue(Ptr); 4341 IndexType = ISD::SIGNED_SCALED; 4342 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4343 } 4344 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4345 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4346 Ops, MMO, IndexType); 4347 DAG.setRoot(Scatter); 4348 setValue(&I, Scatter); 4349 } 4350 4351 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4352 SDLoc sdl = getCurSDLoc(); 4353 4354 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4355 unsigned& Alignment) { 4356 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4357 Ptr = I.getArgOperand(0); 4358 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4359 Mask = I.getArgOperand(2); 4360 Src0 = I.getArgOperand(3); 4361 }; 4362 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4363 unsigned& Alignment) { 4364 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4365 Ptr = I.getArgOperand(0); 4366 Alignment = 0; 4367 Mask = I.getArgOperand(1); 4368 Src0 = I.getArgOperand(2); 4369 }; 4370 4371 Value *PtrOperand, *MaskOperand, *Src0Operand; 4372 unsigned Alignment; 4373 if (IsExpanding) 4374 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4375 else 4376 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4377 4378 SDValue Ptr = getValue(PtrOperand); 4379 SDValue Src0 = getValue(Src0Operand); 4380 SDValue Mask = getValue(MaskOperand); 4381 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4382 4383 EVT VT = Src0.getValueType(); 4384 if (!Alignment) 4385 Alignment = DAG.getEVTAlignment(VT); 4386 4387 AAMDNodes AAInfo; 4388 I.getAAMetadata(AAInfo); 4389 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4390 4391 // Do not serialize masked loads of constant memory with anything. 4392 MemoryLocation ML; 4393 if (VT.isScalableVector()) 4394 ML = MemoryLocation(PtrOperand); 4395 else 4396 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4397 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4398 AAInfo); 4399 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4400 4401 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4402 4403 MachineMemOperand *MMO = 4404 DAG.getMachineFunction(). 4405 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4406 MachineMemOperand::MOLoad, 4407 // TODO: Make MachineMemOperands aware of scalable 4408 // vectors. 4409 VT.getStoreSize().getKnownMinSize(), 4410 Alignment, AAInfo, Ranges); 4411 4412 SDValue Load = 4413 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4414 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4415 if (AddToChain) 4416 PendingLoads.push_back(Load.getValue(1)); 4417 setValue(&I, Load); 4418 } 4419 4420 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4421 SDLoc sdl = getCurSDLoc(); 4422 4423 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4424 const Value *Ptr = I.getArgOperand(0); 4425 SDValue Src0 = getValue(I.getArgOperand(3)); 4426 SDValue Mask = getValue(I.getArgOperand(2)); 4427 4428 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4429 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4430 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4431 if (!Alignment) 4432 Alignment = DAG.getEVTAlignment(VT); 4433 4434 AAMDNodes AAInfo; 4435 I.getAAMetadata(AAInfo); 4436 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4437 4438 SDValue Root = DAG.getRoot(); 4439 SDValue Base; 4440 SDValue Index; 4441 ISD::MemIndexType IndexType; 4442 SDValue Scale; 4443 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this); 4444 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4445 MachineMemOperand *MMO = 4446 DAG.getMachineFunction(). 4447 getMachineMemOperand(MachinePointerInfo(AS), 4448 MachineMemOperand::MOLoad, 4449 // TODO: Make MachineMemOperands aware of scalable 4450 // vectors. 4451 MemoryLocation::UnknownSize, 4452 Alignment, AAInfo, Ranges); 4453 4454 if (!UniformBase) { 4455 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4456 Index = getValue(Ptr); 4457 IndexType = ISD::SIGNED_SCALED; 4458 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4459 } 4460 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4461 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4462 Ops, MMO, IndexType); 4463 4464 PendingLoads.push_back(Gather.getValue(1)); 4465 setValue(&I, Gather); 4466 } 4467 4468 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4469 SDLoc dl = getCurSDLoc(); 4470 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4471 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4472 SyncScope::ID SSID = I.getSyncScopeID(); 4473 4474 SDValue InChain = getRoot(); 4475 4476 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4477 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4478 4479 auto Alignment = DAG.getEVTAlignment(MemVT); 4480 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4481 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4482 4483 MachineFunction &MF = DAG.getMachineFunction(); 4484 MachineMemOperand *MMO = 4485 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4486 Flags, MemVT.getStoreSize(), Alignment, 4487 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4488 FailureOrdering); 4489 4490 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4491 dl, MemVT, VTs, InChain, 4492 getValue(I.getPointerOperand()), 4493 getValue(I.getCompareOperand()), 4494 getValue(I.getNewValOperand()), MMO); 4495 4496 SDValue OutChain = L.getValue(2); 4497 4498 setValue(&I, L); 4499 DAG.setRoot(OutChain); 4500 } 4501 4502 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4503 SDLoc dl = getCurSDLoc(); 4504 ISD::NodeType NT; 4505 switch (I.getOperation()) { 4506 default: llvm_unreachable("Unknown atomicrmw operation"); 4507 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4508 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4509 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4510 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4511 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4512 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4513 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4514 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4515 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4516 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4517 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4518 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4519 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4520 } 4521 AtomicOrdering Ordering = I.getOrdering(); 4522 SyncScope::ID SSID = I.getSyncScopeID(); 4523 4524 SDValue InChain = getRoot(); 4525 4526 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4527 auto Alignment = DAG.getEVTAlignment(MemVT); 4528 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4529 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4530 4531 MachineFunction &MF = DAG.getMachineFunction(); 4532 MachineMemOperand *MMO = 4533 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4534 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4535 nullptr, SSID, Ordering); 4536 4537 SDValue L = 4538 DAG.getAtomic(NT, dl, MemVT, InChain, 4539 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4540 MMO); 4541 4542 SDValue OutChain = L.getValue(1); 4543 4544 setValue(&I, L); 4545 DAG.setRoot(OutChain); 4546 } 4547 4548 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4549 SDLoc dl = getCurSDLoc(); 4550 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4551 SDValue Ops[3]; 4552 Ops[0] = getRoot(); 4553 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4554 TLI.getFenceOperandTy(DAG.getDataLayout())); 4555 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4556 TLI.getFenceOperandTy(DAG.getDataLayout())); 4557 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4558 } 4559 4560 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4561 SDLoc dl = getCurSDLoc(); 4562 AtomicOrdering Order = I.getOrdering(); 4563 SyncScope::ID SSID = I.getSyncScopeID(); 4564 4565 SDValue InChain = getRoot(); 4566 4567 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4568 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4569 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4570 4571 if (!TLI.supportsUnalignedAtomics() && 4572 I.getAlignment() < MemVT.getSizeInBits() / 8) 4573 report_fatal_error("Cannot generate unaligned atomic load"); 4574 4575 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4576 4577 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4578 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4579 I.getAlign().getValueOr(DAG.getEVTAlign(MemVT)), AAMDNodes(), nullptr, 4580 SSID, Order); 4581 4582 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4583 4584 SDValue Ptr = getValue(I.getPointerOperand()); 4585 4586 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4587 // TODO: Once this is better exercised by tests, it should be merged with 4588 // the normal path for loads to prevent future divergence. 4589 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4590 if (MemVT != VT) 4591 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4592 4593 setValue(&I, L); 4594 SDValue OutChain = L.getValue(1); 4595 if (!I.isUnordered()) 4596 DAG.setRoot(OutChain); 4597 else 4598 PendingLoads.push_back(OutChain); 4599 return; 4600 } 4601 4602 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4603 Ptr, MMO); 4604 4605 SDValue OutChain = L.getValue(1); 4606 if (MemVT != VT) 4607 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4608 4609 setValue(&I, L); 4610 DAG.setRoot(OutChain); 4611 } 4612 4613 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4614 SDLoc dl = getCurSDLoc(); 4615 4616 AtomicOrdering Ordering = I.getOrdering(); 4617 SyncScope::ID SSID = I.getSyncScopeID(); 4618 4619 SDValue InChain = getRoot(); 4620 4621 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4622 EVT MemVT = 4623 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4624 4625 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4626 report_fatal_error("Cannot generate unaligned atomic store"); 4627 4628 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4629 4630 MachineFunction &MF = DAG.getMachineFunction(); 4631 MachineMemOperand *MMO = MF.getMachineMemOperand( 4632 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4633 *I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4634 4635 SDValue Val = getValue(I.getValueOperand()); 4636 if (Val.getValueType() != MemVT) 4637 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4638 SDValue Ptr = getValue(I.getPointerOperand()); 4639 4640 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4641 // TODO: Once this is better exercised by tests, it should be merged with 4642 // the normal path for stores to prevent future divergence. 4643 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4644 DAG.setRoot(S); 4645 return; 4646 } 4647 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4648 Ptr, Val, MMO); 4649 4650 4651 DAG.setRoot(OutChain); 4652 } 4653 4654 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4655 /// node. 4656 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4657 unsigned Intrinsic) { 4658 // Ignore the callsite's attributes. A specific call site may be marked with 4659 // readnone, but the lowering code will expect the chain based on the 4660 // definition. 4661 const Function *F = I.getCalledFunction(); 4662 bool HasChain = !F->doesNotAccessMemory(); 4663 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4664 4665 // Build the operand list. 4666 SmallVector<SDValue, 8> Ops; 4667 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4668 if (OnlyLoad) { 4669 // We don't need to serialize loads against other loads. 4670 Ops.push_back(DAG.getRoot()); 4671 } else { 4672 Ops.push_back(getRoot()); 4673 } 4674 } 4675 4676 // Info is set by getTgtMemInstrinsic 4677 TargetLowering::IntrinsicInfo Info; 4678 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4679 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4680 DAG.getMachineFunction(), 4681 Intrinsic); 4682 4683 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4684 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4685 Info.opc == ISD::INTRINSIC_W_CHAIN) 4686 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4687 TLI.getPointerTy(DAG.getDataLayout()))); 4688 4689 // Add all operands of the call to the operand list. 4690 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4691 const Value *Arg = I.getArgOperand(i); 4692 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4693 Ops.push_back(getValue(Arg)); 4694 continue; 4695 } 4696 4697 // Use TargetConstant instead of a regular constant for immarg. 4698 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4699 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4700 assert(CI->getBitWidth() <= 64 && 4701 "large intrinsic immediates not handled"); 4702 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4703 } else { 4704 Ops.push_back( 4705 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4706 } 4707 } 4708 4709 SmallVector<EVT, 4> ValueVTs; 4710 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4711 4712 if (HasChain) 4713 ValueVTs.push_back(MVT::Other); 4714 4715 SDVTList VTs = DAG.getVTList(ValueVTs); 4716 4717 // Create the node. 4718 SDValue Result; 4719 if (IsTgtIntrinsic) { 4720 // This is target intrinsic that touches memory 4721 AAMDNodes AAInfo; 4722 I.getAAMetadata(AAInfo); 4723 Result = DAG.getMemIntrinsicNode( 4724 Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4725 MachinePointerInfo(Info.ptrVal, Info.offset), 4726 Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo); 4727 } else if (!HasChain) { 4728 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4729 } else if (!I.getType()->isVoidTy()) { 4730 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4731 } else { 4732 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4733 } 4734 4735 if (HasChain) { 4736 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4737 if (OnlyLoad) 4738 PendingLoads.push_back(Chain); 4739 else 4740 DAG.setRoot(Chain); 4741 } 4742 4743 if (!I.getType()->isVoidTy()) { 4744 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4745 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4746 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4747 } else 4748 Result = lowerRangeToAssertZExt(DAG, I, Result); 4749 4750 setValue(&I, Result); 4751 } 4752 } 4753 4754 /// GetSignificand - Get the significand and build it into a floating-point 4755 /// number with exponent of 1: 4756 /// 4757 /// Op = (Op & 0x007fffff) | 0x3f800000; 4758 /// 4759 /// where Op is the hexadecimal representation of floating point value. 4760 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4761 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4762 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4763 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4764 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4765 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4766 } 4767 4768 /// GetExponent - Get the exponent: 4769 /// 4770 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4771 /// 4772 /// where Op is the hexadecimal representation of floating point value. 4773 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4774 const TargetLowering &TLI, const SDLoc &dl) { 4775 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4776 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4777 SDValue t1 = DAG.getNode( 4778 ISD::SRL, dl, MVT::i32, t0, 4779 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4780 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4781 DAG.getConstant(127, dl, MVT::i32)); 4782 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4783 } 4784 4785 /// getF32Constant - Get 32-bit floating point constant. 4786 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4787 const SDLoc &dl) { 4788 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4789 MVT::f32); 4790 } 4791 4792 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4793 SelectionDAG &DAG) { 4794 // TODO: What fast-math-flags should be set on the floating-point nodes? 4795 4796 // IntegerPartOfX = ((int32_t)(t0); 4797 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4798 4799 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4800 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4801 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4802 4803 // IntegerPartOfX <<= 23; 4804 IntegerPartOfX = DAG.getNode( 4805 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4806 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4807 DAG.getDataLayout()))); 4808 4809 SDValue TwoToFractionalPartOfX; 4810 if (LimitFloatPrecision <= 6) { 4811 // For floating-point precision of 6: 4812 // 4813 // TwoToFractionalPartOfX = 4814 // 0.997535578f + 4815 // (0.735607626f + 0.252464424f * x) * x; 4816 // 4817 // error 0.0144103317, which is 6 bits 4818 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4819 getF32Constant(DAG, 0x3e814304, dl)); 4820 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4821 getF32Constant(DAG, 0x3f3c50c8, dl)); 4822 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4823 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4824 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4825 } else if (LimitFloatPrecision <= 12) { 4826 // For floating-point precision of 12: 4827 // 4828 // TwoToFractionalPartOfX = 4829 // 0.999892986f + 4830 // (0.696457318f + 4831 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4832 // 4833 // error 0.000107046256, which is 13 to 14 bits 4834 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4835 getF32Constant(DAG, 0x3da235e3, dl)); 4836 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4837 getF32Constant(DAG, 0x3e65b8f3, dl)); 4838 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4839 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4840 getF32Constant(DAG, 0x3f324b07, dl)); 4841 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4842 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4843 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4844 } else { // LimitFloatPrecision <= 18 4845 // For floating-point precision of 18: 4846 // 4847 // TwoToFractionalPartOfX = 4848 // 0.999999982f + 4849 // (0.693148872f + 4850 // (0.240227044f + 4851 // (0.554906021e-1f + 4852 // (0.961591928e-2f + 4853 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4854 // error 2.47208000*10^(-7), which is better than 18 bits 4855 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4856 getF32Constant(DAG, 0x3924b03e, dl)); 4857 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4858 getF32Constant(DAG, 0x3ab24b87, dl)); 4859 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4860 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4861 getF32Constant(DAG, 0x3c1d8c17, dl)); 4862 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4863 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4864 getF32Constant(DAG, 0x3d634a1d, dl)); 4865 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4866 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4867 getF32Constant(DAG, 0x3e75fe14, dl)); 4868 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4869 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4870 getF32Constant(DAG, 0x3f317234, dl)); 4871 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4872 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4873 getF32Constant(DAG, 0x3f800000, dl)); 4874 } 4875 4876 // Add the exponent into the result in integer domain. 4877 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4878 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4879 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4880 } 4881 4882 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4883 /// limited-precision mode. 4884 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4885 const TargetLowering &TLI) { 4886 if (Op.getValueType() == MVT::f32 && 4887 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4888 4889 // Put the exponent in the right bit position for later addition to the 4890 // final result: 4891 // 4892 // t0 = Op * log2(e) 4893 4894 // TODO: What fast-math-flags should be set here? 4895 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4896 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4897 return getLimitedPrecisionExp2(t0, dl, DAG); 4898 } 4899 4900 // No special expansion. 4901 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4902 } 4903 4904 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4905 /// limited-precision mode. 4906 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4907 const TargetLowering &TLI) { 4908 // TODO: What fast-math-flags should be set on the floating-point nodes? 4909 4910 if (Op.getValueType() == MVT::f32 && 4911 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4912 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4913 4914 // Scale the exponent by log(2). 4915 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4916 SDValue LogOfExponent = 4917 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4918 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 4919 4920 // Get the significand and build it into a floating-point number with 4921 // exponent of 1. 4922 SDValue X = GetSignificand(DAG, Op1, dl); 4923 4924 SDValue LogOfMantissa; 4925 if (LimitFloatPrecision <= 6) { 4926 // For floating-point precision of 6: 4927 // 4928 // LogofMantissa = 4929 // -1.1609546f + 4930 // (1.4034025f - 0.23903021f * x) * x; 4931 // 4932 // error 0.0034276066, which is better than 8 bits 4933 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4934 getF32Constant(DAG, 0xbe74c456, dl)); 4935 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4936 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4937 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4938 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4939 getF32Constant(DAG, 0x3f949a29, dl)); 4940 } else if (LimitFloatPrecision <= 12) { 4941 // For floating-point precision of 12: 4942 // 4943 // LogOfMantissa = 4944 // -1.7417939f + 4945 // (2.8212026f + 4946 // (-1.4699568f + 4947 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4948 // 4949 // error 0.000061011436, which is 14 bits 4950 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4951 getF32Constant(DAG, 0xbd67b6d6, dl)); 4952 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4953 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4954 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4955 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4956 getF32Constant(DAG, 0x3fbc278b, dl)); 4957 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4958 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4959 getF32Constant(DAG, 0x40348e95, dl)); 4960 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4961 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4962 getF32Constant(DAG, 0x3fdef31a, dl)); 4963 } else { // LimitFloatPrecision <= 18 4964 // For floating-point precision of 18: 4965 // 4966 // LogOfMantissa = 4967 // -2.1072184f + 4968 // (4.2372794f + 4969 // (-3.7029485f + 4970 // (2.2781945f + 4971 // (-0.87823314f + 4972 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4973 // 4974 // error 0.0000023660568, which is better than 18 bits 4975 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4976 getF32Constant(DAG, 0xbc91e5ac, dl)); 4977 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4978 getF32Constant(DAG, 0x3e4350aa, dl)); 4979 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4980 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4981 getF32Constant(DAG, 0x3f60d3e3, dl)); 4982 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4983 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4984 getF32Constant(DAG, 0x4011cdf0, dl)); 4985 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4986 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4987 getF32Constant(DAG, 0x406cfd1c, dl)); 4988 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4989 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4990 getF32Constant(DAG, 0x408797cb, dl)); 4991 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4992 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4993 getF32Constant(DAG, 0x4006dcab, dl)); 4994 } 4995 4996 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4997 } 4998 4999 // No special expansion. 5000 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5001 } 5002 5003 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5004 /// limited-precision mode. 5005 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5006 const TargetLowering &TLI) { 5007 // TODO: What fast-math-flags should be set on the floating-point nodes? 5008 5009 if (Op.getValueType() == MVT::f32 && 5010 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5011 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5012 5013 // Get the exponent. 5014 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5015 5016 // Get the significand and build it into a floating-point number with 5017 // exponent of 1. 5018 SDValue X = GetSignificand(DAG, Op1, dl); 5019 5020 // Different possible minimax approximations of significand in 5021 // floating-point for various degrees of accuracy over [1,2]. 5022 SDValue Log2ofMantissa; 5023 if (LimitFloatPrecision <= 6) { 5024 // For floating-point precision of 6: 5025 // 5026 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5027 // 5028 // error 0.0049451742, which is more than 7 bits 5029 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5030 getF32Constant(DAG, 0xbeb08fe0, dl)); 5031 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5032 getF32Constant(DAG, 0x40019463, dl)); 5033 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5034 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5035 getF32Constant(DAG, 0x3fd6633d, dl)); 5036 } else if (LimitFloatPrecision <= 12) { 5037 // For floating-point precision of 12: 5038 // 5039 // Log2ofMantissa = 5040 // -2.51285454f + 5041 // (4.07009056f + 5042 // (-2.12067489f + 5043 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5044 // 5045 // error 0.0000876136000, which is better than 13 bits 5046 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5047 getF32Constant(DAG, 0xbda7262e, dl)); 5048 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5049 getF32Constant(DAG, 0x3f25280b, dl)); 5050 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5051 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5052 getF32Constant(DAG, 0x4007b923, dl)); 5053 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5054 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5055 getF32Constant(DAG, 0x40823e2f, dl)); 5056 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5057 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5058 getF32Constant(DAG, 0x4020d29c, dl)); 5059 } else { // LimitFloatPrecision <= 18 5060 // For floating-point precision of 18: 5061 // 5062 // Log2ofMantissa = 5063 // -3.0400495f + 5064 // (6.1129976f + 5065 // (-5.3420409f + 5066 // (3.2865683f + 5067 // (-1.2669343f + 5068 // (0.27515199f - 5069 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5070 // 5071 // error 0.0000018516, which is better than 18 bits 5072 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5073 getF32Constant(DAG, 0xbcd2769e, dl)); 5074 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5075 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5076 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5077 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5078 getF32Constant(DAG, 0x3fa22ae7, dl)); 5079 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5080 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5081 getF32Constant(DAG, 0x40525723, dl)); 5082 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5083 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5084 getF32Constant(DAG, 0x40aaf200, dl)); 5085 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5086 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5087 getF32Constant(DAG, 0x40c39dad, dl)); 5088 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5089 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5090 getF32Constant(DAG, 0x4042902c, dl)); 5091 } 5092 5093 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5094 } 5095 5096 // No special expansion. 5097 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5098 } 5099 5100 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5101 /// limited-precision mode. 5102 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5103 const TargetLowering &TLI) { 5104 // TODO: What fast-math-flags should be set on the floating-point nodes? 5105 5106 if (Op.getValueType() == MVT::f32 && 5107 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5108 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5109 5110 // Scale the exponent by log10(2) [0.30102999f]. 5111 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5112 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5113 getF32Constant(DAG, 0x3e9a209a, dl)); 5114 5115 // Get the significand and build it into a floating-point number with 5116 // exponent of 1. 5117 SDValue X = GetSignificand(DAG, Op1, dl); 5118 5119 SDValue Log10ofMantissa; 5120 if (LimitFloatPrecision <= 6) { 5121 // For floating-point precision of 6: 5122 // 5123 // Log10ofMantissa = 5124 // -0.50419619f + 5125 // (0.60948995f - 0.10380950f * x) * x; 5126 // 5127 // error 0.0014886165, which is 6 bits 5128 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5129 getF32Constant(DAG, 0xbdd49a13, dl)); 5130 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5131 getF32Constant(DAG, 0x3f1c0789, dl)); 5132 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5133 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5134 getF32Constant(DAG, 0x3f011300, dl)); 5135 } else if (LimitFloatPrecision <= 12) { 5136 // For floating-point precision of 12: 5137 // 5138 // Log10ofMantissa = 5139 // -0.64831180f + 5140 // (0.91751397f + 5141 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5142 // 5143 // error 0.00019228036, which is better than 12 bits 5144 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5145 getF32Constant(DAG, 0x3d431f31, dl)); 5146 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5147 getF32Constant(DAG, 0x3ea21fb2, dl)); 5148 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5149 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5150 getF32Constant(DAG, 0x3f6ae232, dl)); 5151 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5152 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5153 getF32Constant(DAG, 0x3f25f7c3, dl)); 5154 } else { // LimitFloatPrecision <= 18 5155 // For floating-point precision of 18: 5156 // 5157 // Log10ofMantissa = 5158 // -0.84299375f + 5159 // (1.5327582f + 5160 // (-1.0688956f + 5161 // (0.49102474f + 5162 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5163 // 5164 // error 0.0000037995730, which is better than 18 bits 5165 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5166 getF32Constant(DAG, 0x3c5d51ce, dl)); 5167 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5168 getF32Constant(DAG, 0x3e00685a, dl)); 5169 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5170 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5171 getF32Constant(DAG, 0x3efb6798, dl)); 5172 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5173 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5174 getF32Constant(DAG, 0x3f88d192, dl)); 5175 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5176 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5177 getF32Constant(DAG, 0x3fc4316c, dl)); 5178 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5179 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5180 getF32Constant(DAG, 0x3f57ce70, dl)); 5181 } 5182 5183 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5184 } 5185 5186 // No special expansion. 5187 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5188 } 5189 5190 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5191 /// limited-precision mode. 5192 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5193 const TargetLowering &TLI) { 5194 if (Op.getValueType() == MVT::f32 && 5195 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5196 return getLimitedPrecisionExp2(Op, dl, DAG); 5197 5198 // No special expansion. 5199 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5200 } 5201 5202 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5203 /// limited-precision mode with x == 10.0f. 5204 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5205 SelectionDAG &DAG, const TargetLowering &TLI) { 5206 bool IsExp10 = false; 5207 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5208 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5209 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5210 APFloat Ten(10.0f); 5211 IsExp10 = LHSC->isExactlyValue(Ten); 5212 } 5213 } 5214 5215 // TODO: What fast-math-flags should be set on the FMUL node? 5216 if (IsExp10) { 5217 // Put the exponent in the right bit position for later addition to the 5218 // final result: 5219 // 5220 // #define LOG2OF10 3.3219281f 5221 // t0 = Op * LOG2OF10; 5222 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5223 getF32Constant(DAG, 0x40549a78, dl)); 5224 return getLimitedPrecisionExp2(t0, dl, DAG); 5225 } 5226 5227 // No special expansion. 5228 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5229 } 5230 5231 /// ExpandPowI - Expand a llvm.powi intrinsic. 5232 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5233 SelectionDAG &DAG) { 5234 // If RHS is a constant, we can expand this out to a multiplication tree, 5235 // otherwise we end up lowering to a call to __powidf2 (for example). When 5236 // optimizing for size, we only want to do this if the expansion would produce 5237 // a small number of multiplies, otherwise we do the full expansion. 5238 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5239 // Get the exponent as a positive value. 5240 unsigned Val = RHSC->getSExtValue(); 5241 if ((int)Val < 0) Val = -Val; 5242 5243 // powi(x, 0) -> 1.0 5244 if (Val == 0) 5245 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5246 5247 bool OptForSize = DAG.shouldOptForSize(); 5248 if (!OptForSize || 5249 // If optimizing for size, don't insert too many multiplies. 5250 // This inserts up to 5 multiplies. 5251 countPopulation(Val) + Log2_32(Val) < 7) { 5252 // We use the simple binary decomposition method to generate the multiply 5253 // sequence. There are more optimal ways to do this (for example, 5254 // powi(x,15) generates one more multiply than it should), but this has 5255 // the benefit of being both really simple and much better than a libcall. 5256 SDValue Res; // Logically starts equal to 1.0 5257 SDValue CurSquare = LHS; 5258 // TODO: Intrinsics should have fast-math-flags that propagate to these 5259 // nodes. 5260 while (Val) { 5261 if (Val & 1) { 5262 if (Res.getNode()) 5263 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5264 else 5265 Res = CurSquare; // 1.0*CurSquare. 5266 } 5267 5268 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5269 CurSquare, CurSquare); 5270 Val >>= 1; 5271 } 5272 5273 // If the original was negative, invert the result, producing 1/(x*x*x). 5274 if (RHSC->getSExtValue() < 0) 5275 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5276 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5277 return Res; 5278 } 5279 } 5280 5281 // Otherwise, expand to a libcall. 5282 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5283 } 5284 5285 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5286 SDValue LHS, SDValue RHS, SDValue Scale, 5287 SelectionDAG &DAG, const TargetLowering &TLI) { 5288 EVT VT = LHS.getValueType(); 5289 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5290 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5291 LLVMContext &Ctx = *DAG.getContext(); 5292 5293 // If the type is legal but the operation isn't, this node might survive all 5294 // the way to operation legalization. If we end up there and we do not have 5295 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5296 // node. 5297 5298 // Coax the legalizer into expanding the node during type legalization instead 5299 // by bumping the size by one bit. This will force it to Promote, enabling the 5300 // early expansion and avoiding the need to expand later. 5301 5302 // We don't have to do this if Scale is 0; that can always be expanded, unless 5303 // it's a saturating signed operation. Those can experience true integer 5304 // division overflow, a case which we must avoid. 5305 5306 // FIXME: We wouldn't have to do this (or any of the early 5307 // expansion/promotion) if it was possible to expand a libcall of an 5308 // illegal type during operation legalization. But it's not, so things 5309 // get a bit hacky. 5310 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5311 if ((ScaleInt > 0 || (Saturating && Signed)) && 5312 (TLI.isTypeLegal(VT) || 5313 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5314 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5315 Opcode, VT, ScaleInt); 5316 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5317 EVT PromVT; 5318 if (VT.isScalarInteger()) 5319 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5320 else if (VT.isVector()) { 5321 PromVT = VT.getVectorElementType(); 5322 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5323 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5324 } else 5325 llvm_unreachable("Wrong VT for DIVFIX?"); 5326 if (Signed) { 5327 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5328 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5329 } else { 5330 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5331 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5332 } 5333 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5334 // For saturating operations, we need to shift up the LHS to get the 5335 // proper saturation width, and then shift down again afterwards. 5336 if (Saturating) 5337 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5338 DAG.getConstant(1, DL, ShiftTy)); 5339 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5340 if (Saturating) 5341 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5342 DAG.getConstant(1, DL, ShiftTy)); 5343 return DAG.getZExtOrTrunc(Res, DL, VT); 5344 } 5345 } 5346 5347 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5348 } 5349 5350 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5351 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5352 static void 5353 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5354 const SDValue &N) { 5355 switch (N.getOpcode()) { 5356 case ISD::CopyFromReg: { 5357 SDValue Op = N.getOperand(1); 5358 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5359 Op.getValueType().getSizeInBits()); 5360 return; 5361 } 5362 case ISD::BITCAST: 5363 case ISD::AssertZext: 5364 case ISD::AssertSext: 5365 case ISD::TRUNCATE: 5366 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5367 return; 5368 case ISD::BUILD_PAIR: 5369 case ISD::BUILD_VECTOR: 5370 case ISD::CONCAT_VECTORS: 5371 for (SDValue Op : N->op_values()) 5372 getUnderlyingArgRegs(Regs, Op); 5373 return; 5374 default: 5375 return; 5376 } 5377 } 5378 5379 /// If the DbgValueInst is a dbg_value of a function argument, create the 5380 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5381 /// instruction selection, they will be inserted to the entry BB. 5382 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5383 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5384 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5385 const Argument *Arg = dyn_cast<Argument>(V); 5386 if (!Arg) 5387 return false; 5388 5389 if (!IsDbgDeclare) { 5390 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5391 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5392 // the entry block. 5393 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5394 if (!IsInEntryBlock) 5395 return false; 5396 5397 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5398 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5399 // variable that also is a param. 5400 // 5401 // Although, if we are at the top of the entry block already, we can still 5402 // emit using ArgDbgValue. This might catch some situations when the 5403 // dbg.value refers to an argument that isn't used in the entry block, so 5404 // any CopyToReg node would be optimized out and the only way to express 5405 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5406 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5407 // we should only emit as ArgDbgValue if the Variable is an argument to the 5408 // current function, and the dbg.value intrinsic is found in the entry 5409 // block. 5410 bool VariableIsFunctionInputArg = Variable->isParameter() && 5411 !DL->getInlinedAt(); 5412 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5413 if (!IsInPrologue && !VariableIsFunctionInputArg) 5414 return false; 5415 5416 // Here we assume that a function argument on IR level only can be used to 5417 // describe one input parameter on source level. If we for example have 5418 // source code like this 5419 // 5420 // struct A { long x, y; }; 5421 // void foo(struct A a, long b) { 5422 // ... 5423 // b = a.x; 5424 // ... 5425 // } 5426 // 5427 // and IR like this 5428 // 5429 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5430 // entry: 5431 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5432 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5433 // call void @llvm.dbg.value(metadata i32 %b, "b", 5434 // ... 5435 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5436 // ... 5437 // 5438 // then the last dbg.value is describing a parameter "b" using a value that 5439 // is an argument. But since we already has used %a1 to describe a parameter 5440 // we should not handle that last dbg.value here (that would result in an 5441 // incorrect hoisting of the DBG_VALUE to the function entry). 5442 // Notice that we allow one dbg.value per IR level argument, to accommodate 5443 // for the situation with fragments above. 5444 if (VariableIsFunctionInputArg) { 5445 unsigned ArgNo = Arg->getArgNo(); 5446 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5447 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5448 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5449 return false; 5450 FuncInfo.DescribedArgs.set(ArgNo); 5451 } 5452 } 5453 5454 MachineFunction &MF = DAG.getMachineFunction(); 5455 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5456 5457 bool IsIndirect = false; 5458 Optional<MachineOperand> Op; 5459 // Some arguments' frame index is recorded during argument lowering. 5460 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5461 if (FI != std::numeric_limits<int>::max()) 5462 Op = MachineOperand::CreateFI(FI); 5463 5464 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5465 if (!Op && N.getNode()) { 5466 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5467 Register Reg; 5468 if (ArgRegsAndSizes.size() == 1) 5469 Reg = ArgRegsAndSizes.front().first; 5470 5471 if (Reg && Reg.isVirtual()) { 5472 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5473 Register PR = RegInfo.getLiveInPhysReg(Reg); 5474 if (PR) 5475 Reg = PR; 5476 } 5477 if (Reg) { 5478 Op = MachineOperand::CreateReg(Reg, false); 5479 IsIndirect = IsDbgDeclare; 5480 } 5481 } 5482 5483 if (!Op && N.getNode()) { 5484 // Check if frame index is available. 5485 SDValue LCandidate = peekThroughBitcasts(N); 5486 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5487 if (FrameIndexSDNode *FINode = 5488 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5489 Op = MachineOperand::CreateFI(FINode->getIndex()); 5490 } 5491 5492 if (!Op) { 5493 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5494 auto splitMultiRegDbgValue 5495 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5496 unsigned Offset = 0; 5497 for (auto RegAndSize : SplitRegs) { 5498 // If the expression is already a fragment, the current register 5499 // offset+size might extend beyond the fragment. In this case, only 5500 // the register bits that are inside the fragment are relevant. 5501 int RegFragmentSizeInBits = RegAndSize.second; 5502 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5503 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5504 // The register is entirely outside the expression fragment, 5505 // so is irrelevant for debug info. 5506 if (Offset >= ExprFragmentSizeInBits) 5507 break; 5508 // The register is partially outside the expression fragment, only 5509 // the low bits within the fragment are relevant for debug info. 5510 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5511 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5512 } 5513 } 5514 5515 auto FragmentExpr = DIExpression::createFragmentExpression( 5516 Expr, Offset, RegFragmentSizeInBits); 5517 Offset += RegAndSize.second; 5518 // If a valid fragment expression cannot be created, the variable's 5519 // correct value cannot be determined and so it is set as Undef. 5520 if (!FragmentExpr) { 5521 SDDbgValue *SDV = DAG.getConstantDbgValue( 5522 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5523 DAG.AddDbgValue(SDV, nullptr, false); 5524 continue; 5525 } 5526 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5527 FuncInfo.ArgDbgValues.push_back( 5528 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5529 RegAndSize.first, Variable, *FragmentExpr)); 5530 } 5531 }; 5532 5533 // Check if ValueMap has reg number. 5534 DenseMap<const Value *, unsigned>::const_iterator 5535 VMI = FuncInfo.ValueMap.find(V); 5536 if (VMI != FuncInfo.ValueMap.end()) { 5537 const auto &TLI = DAG.getTargetLoweringInfo(); 5538 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5539 V->getType(), getABIRegCopyCC(V)); 5540 if (RFV.occupiesMultipleRegs()) { 5541 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5542 return true; 5543 } 5544 5545 Op = MachineOperand::CreateReg(VMI->second, false); 5546 IsIndirect = IsDbgDeclare; 5547 } else if (ArgRegsAndSizes.size() > 1) { 5548 // This was split due to the calling convention, and no virtual register 5549 // mapping exists for the value. 5550 splitMultiRegDbgValue(ArgRegsAndSizes); 5551 return true; 5552 } 5553 } 5554 5555 if (!Op) 5556 return false; 5557 5558 assert(Variable->isValidLocationForIntrinsic(DL) && 5559 "Expected inlined-at fields to agree"); 5560 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5561 FuncInfo.ArgDbgValues.push_back( 5562 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5563 *Op, Variable, Expr)); 5564 5565 return true; 5566 } 5567 5568 /// Return the appropriate SDDbgValue based on N. 5569 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5570 DILocalVariable *Variable, 5571 DIExpression *Expr, 5572 const DebugLoc &dl, 5573 unsigned DbgSDNodeOrder) { 5574 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5575 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5576 // stack slot locations. 5577 // 5578 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5579 // debug values here after optimization: 5580 // 5581 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5582 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5583 // 5584 // Both describe the direct values of their associated variables. 5585 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5586 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5587 } 5588 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5589 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5590 } 5591 5592 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5593 switch (Intrinsic) { 5594 case Intrinsic::smul_fix: 5595 return ISD::SMULFIX; 5596 case Intrinsic::umul_fix: 5597 return ISD::UMULFIX; 5598 case Intrinsic::smul_fix_sat: 5599 return ISD::SMULFIXSAT; 5600 case Intrinsic::umul_fix_sat: 5601 return ISD::UMULFIXSAT; 5602 case Intrinsic::sdiv_fix: 5603 return ISD::SDIVFIX; 5604 case Intrinsic::udiv_fix: 5605 return ISD::UDIVFIX; 5606 case Intrinsic::sdiv_fix_sat: 5607 return ISD::SDIVFIXSAT; 5608 case Intrinsic::udiv_fix_sat: 5609 return ISD::UDIVFIXSAT; 5610 default: 5611 llvm_unreachable("Unhandled fixed point intrinsic"); 5612 } 5613 } 5614 5615 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5616 const char *FunctionName) { 5617 assert(FunctionName && "FunctionName must not be nullptr"); 5618 SDValue Callee = DAG.getExternalSymbol( 5619 FunctionName, 5620 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5621 LowerCallTo(&I, Callee, I.isTailCall()); 5622 } 5623 5624 /// Lower the call to the specified intrinsic function. 5625 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5626 unsigned Intrinsic) { 5627 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5628 SDLoc sdl = getCurSDLoc(); 5629 DebugLoc dl = getCurDebugLoc(); 5630 SDValue Res; 5631 5632 switch (Intrinsic) { 5633 default: 5634 // By default, turn this into a target intrinsic node. 5635 visitTargetIntrinsic(I, Intrinsic); 5636 return; 5637 case Intrinsic::vscale: { 5638 match(&I, m_VScale(DAG.getDataLayout())); 5639 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5640 setValue(&I, 5641 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5642 return; 5643 } 5644 case Intrinsic::vastart: visitVAStart(I); return; 5645 case Intrinsic::vaend: visitVAEnd(I); return; 5646 case Intrinsic::vacopy: visitVACopy(I); return; 5647 case Intrinsic::returnaddress: 5648 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5649 TLI.getPointerTy(DAG.getDataLayout()), 5650 getValue(I.getArgOperand(0)))); 5651 return; 5652 case Intrinsic::addressofreturnaddress: 5653 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5654 TLI.getPointerTy(DAG.getDataLayout()))); 5655 return; 5656 case Intrinsic::sponentry: 5657 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5658 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5659 return; 5660 case Intrinsic::frameaddress: 5661 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5662 TLI.getFrameIndexTy(DAG.getDataLayout()), 5663 getValue(I.getArgOperand(0)))); 5664 return; 5665 case Intrinsic::read_register: { 5666 Value *Reg = I.getArgOperand(0); 5667 SDValue Chain = getRoot(); 5668 SDValue RegName = 5669 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5670 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5671 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5672 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5673 setValue(&I, Res); 5674 DAG.setRoot(Res.getValue(1)); 5675 return; 5676 } 5677 case Intrinsic::write_register: { 5678 Value *Reg = I.getArgOperand(0); 5679 Value *RegValue = I.getArgOperand(1); 5680 SDValue Chain = getRoot(); 5681 SDValue RegName = 5682 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5683 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5684 RegName, getValue(RegValue))); 5685 return; 5686 } 5687 case Intrinsic::memcpy: { 5688 const auto &MCI = cast<MemCpyInst>(I); 5689 SDValue Op1 = getValue(I.getArgOperand(0)); 5690 SDValue Op2 = getValue(I.getArgOperand(1)); 5691 SDValue Op3 = getValue(I.getArgOperand(2)); 5692 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5693 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5694 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5695 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5696 bool isVol = MCI.isVolatile(); 5697 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5698 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5699 // node. 5700 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5701 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5702 /* AlwaysInline */ false, isTC, 5703 MachinePointerInfo(I.getArgOperand(0)), 5704 MachinePointerInfo(I.getArgOperand(1))); 5705 updateDAGForMaybeTailCall(MC); 5706 return; 5707 } 5708 case Intrinsic::memcpy_inline: { 5709 const auto &MCI = cast<MemCpyInlineInst>(I); 5710 SDValue Dst = getValue(I.getArgOperand(0)); 5711 SDValue Src = getValue(I.getArgOperand(1)); 5712 SDValue Size = getValue(I.getArgOperand(2)); 5713 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5714 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5715 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5716 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5717 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5718 bool isVol = MCI.isVolatile(); 5719 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5720 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5721 // node. 5722 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5723 /* AlwaysInline */ true, isTC, 5724 MachinePointerInfo(I.getArgOperand(0)), 5725 MachinePointerInfo(I.getArgOperand(1))); 5726 updateDAGForMaybeTailCall(MC); 5727 return; 5728 } 5729 case Intrinsic::memset: { 5730 const auto &MSI = cast<MemSetInst>(I); 5731 SDValue Op1 = getValue(I.getArgOperand(0)); 5732 SDValue Op2 = getValue(I.getArgOperand(1)); 5733 SDValue Op3 = getValue(I.getArgOperand(2)); 5734 // @llvm.memset defines 0 and 1 to both mean no alignment. 5735 Align Alignment = MSI.getDestAlign().valueOrOne(); 5736 bool isVol = MSI.isVolatile(); 5737 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5738 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5739 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5740 MachinePointerInfo(I.getArgOperand(0))); 5741 updateDAGForMaybeTailCall(MS); 5742 return; 5743 } 5744 case Intrinsic::memmove: { 5745 const auto &MMI = cast<MemMoveInst>(I); 5746 SDValue Op1 = getValue(I.getArgOperand(0)); 5747 SDValue Op2 = getValue(I.getArgOperand(1)); 5748 SDValue Op3 = getValue(I.getArgOperand(2)); 5749 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5750 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5751 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5752 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5753 bool isVol = MMI.isVolatile(); 5754 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5755 // FIXME: Support passing different dest/src alignments to the memmove DAG 5756 // node. 5757 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5758 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5759 isTC, MachinePointerInfo(I.getArgOperand(0)), 5760 MachinePointerInfo(I.getArgOperand(1))); 5761 updateDAGForMaybeTailCall(MM); 5762 return; 5763 } 5764 case Intrinsic::memcpy_element_unordered_atomic: { 5765 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5766 SDValue Dst = getValue(MI.getRawDest()); 5767 SDValue Src = getValue(MI.getRawSource()); 5768 SDValue Length = getValue(MI.getLength()); 5769 5770 unsigned DstAlign = MI.getDestAlignment(); 5771 unsigned SrcAlign = MI.getSourceAlignment(); 5772 Type *LengthTy = MI.getLength()->getType(); 5773 unsigned ElemSz = MI.getElementSizeInBytes(); 5774 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5775 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5776 SrcAlign, Length, LengthTy, ElemSz, isTC, 5777 MachinePointerInfo(MI.getRawDest()), 5778 MachinePointerInfo(MI.getRawSource())); 5779 updateDAGForMaybeTailCall(MC); 5780 return; 5781 } 5782 case Intrinsic::memmove_element_unordered_atomic: { 5783 auto &MI = cast<AtomicMemMoveInst>(I); 5784 SDValue Dst = getValue(MI.getRawDest()); 5785 SDValue Src = getValue(MI.getRawSource()); 5786 SDValue Length = getValue(MI.getLength()); 5787 5788 unsigned DstAlign = MI.getDestAlignment(); 5789 unsigned SrcAlign = MI.getSourceAlignment(); 5790 Type *LengthTy = MI.getLength()->getType(); 5791 unsigned ElemSz = MI.getElementSizeInBytes(); 5792 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5793 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5794 SrcAlign, Length, LengthTy, ElemSz, isTC, 5795 MachinePointerInfo(MI.getRawDest()), 5796 MachinePointerInfo(MI.getRawSource())); 5797 updateDAGForMaybeTailCall(MC); 5798 return; 5799 } 5800 case Intrinsic::memset_element_unordered_atomic: { 5801 auto &MI = cast<AtomicMemSetInst>(I); 5802 SDValue Dst = getValue(MI.getRawDest()); 5803 SDValue Val = getValue(MI.getValue()); 5804 SDValue Length = getValue(MI.getLength()); 5805 5806 unsigned DstAlign = MI.getDestAlignment(); 5807 Type *LengthTy = MI.getLength()->getType(); 5808 unsigned ElemSz = MI.getElementSizeInBytes(); 5809 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5810 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5811 LengthTy, ElemSz, isTC, 5812 MachinePointerInfo(MI.getRawDest())); 5813 updateDAGForMaybeTailCall(MC); 5814 return; 5815 } 5816 case Intrinsic::dbg_addr: 5817 case Intrinsic::dbg_declare: { 5818 const auto &DI = cast<DbgVariableIntrinsic>(I); 5819 DILocalVariable *Variable = DI.getVariable(); 5820 DIExpression *Expression = DI.getExpression(); 5821 dropDanglingDebugInfo(Variable, Expression); 5822 assert(Variable && "Missing variable"); 5823 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5824 << "\n"); 5825 // Check if address has undef value. 5826 const Value *Address = DI.getVariableLocation(); 5827 if (!Address || isa<UndefValue>(Address) || 5828 (Address->use_empty() && !isa<Argument>(Address))) { 5829 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5830 << " (bad/undef/unused-arg address)\n"); 5831 return; 5832 } 5833 5834 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5835 5836 // Check if this variable can be described by a frame index, typically 5837 // either as a static alloca or a byval parameter. 5838 int FI = std::numeric_limits<int>::max(); 5839 if (const auto *AI = 5840 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5841 if (AI->isStaticAlloca()) { 5842 auto I = FuncInfo.StaticAllocaMap.find(AI); 5843 if (I != FuncInfo.StaticAllocaMap.end()) 5844 FI = I->second; 5845 } 5846 } else if (const auto *Arg = dyn_cast<Argument>( 5847 Address->stripInBoundsConstantOffsets())) { 5848 FI = FuncInfo.getArgumentFrameIndex(Arg); 5849 } 5850 5851 // llvm.dbg.addr is control dependent and always generates indirect 5852 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5853 // the MachineFunction variable table. 5854 if (FI != std::numeric_limits<int>::max()) { 5855 if (Intrinsic == Intrinsic::dbg_addr) { 5856 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5857 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5858 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5859 } else { 5860 LLVM_DEBUG(dbgs() << "Skipping " << DI 5861 << " (variable info stashed in MF side table)\n"); 5862 } 5863 return; 5864 } 5865 5866 SDValue &N = NodeMap[Address]; 5867 if (!N.getNode() && isa<Argument>(Address)) 5868 // Check unused arguments map. 5869 N = UnusedArgNodeMap[Address]; 5870 SDDbgValue *SDV; 5871 if (N.getNode()) { 5872 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5873 Address = BCI->getOperand(0); 5874 // Parameters are handled specially. 5875 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5876 if (isParameter && FINode) { 5877 // Byval parameter. We have a frame index at this point. 5878 SDV = 5879 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5880 /*IsIndirect*/ true, dl, SDNodeOrder); 5881 } else if (isa<Argument>(Address)) { 5882 // Address is an argument, so try to emit its dbg value using 5883 // virtual register info from the FuncInfo.ValueMap. 5884 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5885 return; 5886 } else { 5887 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5888 true, dl, SDNodeOrder); 5889 } 5890 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5891 } else { 5892 // If Address is an argument then try to emit its dbg value using 5893 // virtual register info from the FuncInfo.ValueMap. 5894 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5895 N)) { 5896 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5897 << " (could not emit func-arg dbg_value)\n"); 5898 } 5899 } 5900 return; 5901 } 5902 case Intrinsic::dbg_label: { 5903 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5904 DILabel *Label = DI.getLabel(); 5905 assert(Label && "Missing label"); 5906 5907 SDDbgLabel *SDV; 5908 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5909 DAG.AddDbgLabel(SDV); 5910 return; 5911 } 5912 case Intrinsic::dbg_value: { 5913 const DbgValueInst &DI = cast<DbgValueInst>(I); 5914 assert(DI.getVariable() && "Missing variable"); 5915 5916 DILocalVariable *Variable = DI.getVariable(); 5917 DIExpression *Expression = DI.getExpression(); 5918 dropDanglingDebugInfo(Variable, Expression); 5919 const Value *V = DI.getValue(); 5920 if (!V) 5921 return; 5922 5923 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5924 SDNodeOrder)) 5925 return; 5926 5927 // TODO: Dangling debug info will eventually either be resolved or produce 5928 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5929 // between the original dbg.value location and its resolved DBG_VALUE, which 5930 // we should ideally fill with an extra Undef DBG_VALUE. 5931 5932 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5933 return; 5934 } 5935 5936 case Intrinsic::eh_typeid_for: { 5937 // Find the type id for the given typeinfo. 5938 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5939 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5940 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5941 setValue(&I, Res); 5942 return; 5943 } 5944 5945 case Intrinsic::eh_return_i32: 5946 case Intrinsic::eh_return_i64: 5947 DAG.getMachineFunction().setCallsEHReturn(true); 5948 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5949 MVT::Other, 5950 getControlRoot(), 5951 getValue(I.getArgOperand(0)), 5952 getValue(I.getArgOperand(1)))); 5953 return; 5954 case Intrinsic::eh_unwind_init: 5955 DAG.getMachineFunction().setCallsUnwindInit(true); 5956 return; 5957 case Intrinsic::eh_dwarf_cfa: 5958 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5959 TLI.getPointerTy(DAG.getDataLayout()), 5960 getValue(I.getArgOperand(0)))); 5961 return; 5962 case Intrinsic::eh_sjlj_callsite: { 5963 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5964 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5965 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5966 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5967 5968 MMI.setCurrentCallSite(CI->getZExtValue()); 5969 return; 5970 } 5971 case Intrinsic::eh_sjlj_functioncontext: { 5972 // Get and store the index of the function context. 5973 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5974 AllocaInst *FnCtx = 5975 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5976 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5977 MFI.setFunctionContextIndex(FI); 5978 return; 5979 } 5980 case Intrinsic::eh_sjlj_setjmp: { 5981 SDValue Ops[2]; 5982 Ops[0] = getRoot(); 5983 Ops[1] = getValue(I.getArgOperand(0)); 5984 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5985 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5986 setValue(&I, Op.getValue(0)); 5987 DAG.setRoot(Op.getValue(1)); 5988 return; 5989 } 5990 case Intrinsic::eh_sjlj_longjmp: 5991 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5992 getRoot(), getValue(I.getArgOperand(0)))); 5993 return; 5994 case Intrinsic::eh_sjlj_setup_dispatch: 5995 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5996 getRoot())); 5997 return; 5998 case Intrinsic::masked_gather: 5999 visitMaskedGather(I); 6000 return; 6001 case Intrinsic::masked_load: 6002 visitMaskedLoad(I); 6003 return; 6004 case Intrinsic::masked_scatter: 6005 visitMaskedScatter(I); 6006 return; 6007 case Intrinsic::masked_store: 6008 visitMaskedStore(I); 6009 return; 6010 case Intrinsic::masked_expandload: 6011 visitMaskedLoad(I, true /* IsExpanding */); 6012 return; 6013 case Intrinsic::masked_compressstore: 6014 visitMaskedStore(I, true /* IsCompressing */); 6015 return; 6016 case Intrinsic::powi: 6017 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6018 getValue(I.getArgOperand(1)), DAG)); 6019 return; 6020 case Intrinsic::log: 6021 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6022 return; 6023 case Intrinsic::log2: 6024 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6025 return; 6026 case Intrinsic::log10: 6027 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6028 return; 6029 case Intrinsic::exp: 6030 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6031 return; 6032 case Intrinsic::exp2: 6033 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6034 return; 6035 case Intrinsic::pow: 6036 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6037 getValue(I.getArgOperand(1)), DAG, TLI)); 6038 return; 6039 case Intrinsic::sqrt: 6040 case Intrinsic::fabs: 6041 case Intrinsic::sin: 6042 case Intrinsic::cos: 6043 case Intrinsic::floor: 6044 case Intrinsic::ceil: 6045 case Intrinsic::trunc: 6046 case Intrinsic::rint: 6047 case Intrinsic::nearbyint: 6048 case Intrinsic::round: 6049 case Intrinsic::canonicalize: { 6050 unsigned Opcode; 6051 switch (Intrinsic) { 6052 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6053 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6054 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6055 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6056 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6057 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6058 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6059 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6060 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6061 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6062 case Intrinsic::round: Opcode = ISD::FROUND; break; 6063 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6064 } 6065 6066 setValue(&I, DAG.getNode(Opcode, sdl, 6067 getValue(I.getArgOperand(0)).getValueType(), 6068 getValue(I.getArgOperand(0)))); 6069 return; 6070 } 6071 case Intrinsic::lround: 6072 case Intrinsic::llround: 6073 case Intrinsic::lrint: 6074 case Intrinsic::llrint: { 6075 unsigned Opcode; 6076 switch (Intrinsic) { 6077 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6078 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6079 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6080 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6081 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6082 } 6083 6084 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6085 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6086 getValue(I.getArgOperand(0)))); 6087 return; 6088 } 6089 case Intrinsic::minnum: 6090 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6091 getValue(I.getArgOperand(0)).getValueType(), 6092 getValue(I.getArgOperand(0)), 6093 getValue(I.getArgOperand(1)))); 6094 return; 6095 case Intrinsic::maxnum: 6096 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6097 getValue(I.getArgOperand(0)).getValueType(), 6098 getValue(I.getArgOperand(0)), 6099 getValue(I.getArgOperand(1)))); 6100 return; 6101 case Intrinsic::minimum: 6102 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6103 getValue(I.getArgOperand(0)).getValueType(), 6104 getValue(I.getArgOperand(0)), 6105 getValue(I.getArgOperand(1)))); 6106 return; 6107 case Intrinsic::maximum: 6108 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6109 getValue(I.getArgOperand(0)).getValueType(), 6110 getValue(I.getArgOperand(0)), 6111 getValue(I.getArgOperand(1)))); 6112 return; 6113 case Intrinsic::copysign: 6114 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6115 getValue(I.getArgOperand(0)).getValueType(), 6116 getValue(I.getArgOperand(0)), 6117 getValue(I.getArgOperand(1)))); 6118 return; 6119 case Intrinsic::fma: 6120 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6121 getValue(I.getArgOperand(0)).getValueType(), 6122 getValue(I.getArgOperand(0)), 6123 getValue(I.getArgOperand(1)), 6124 getValue(I.getArgOperand(2)))); 6125 return; 6126 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6127 case Intrinsic::INTRINSIC: 6128 #include "llvm/IR/ConstrainedOps.def" 6129 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6130 return; 6131 case Intrinsic::fmuladd: { 6132 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6133 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6134 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6135 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6136 getValue(I.getArgOperand(0)).getValueType(), 6137 getValue(I.getArgOperand(0)), 6138 getValue(I.getArgOperand(1)), 6139 getValue(I.getArgOperand(2)))); 6140 } else { 6141 // TODO: Intrinsic calls should have fast-math-flags. 6142 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6143 getValue(I.getArgOperand(0)).getValueType(), 6144 getValue(I.getArgOperand(0)), 6145 getValue(I.getArgOperand(1))); 6146 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6147 getValue(I.getArgOperand(0)).getValueType(), 6148 Mul, 6149 getValue(I.getArgOperand(2))); 6150 setValue(&I, Add); 6151 } 6152 return; 6153 } 6154 case Intrinsic::convert_to_fp16: 6155 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6156 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6157 getValue(I.getArgOperand(0)), 6158 DAG.getTargetConstant(0, sdl, 6159 MVT::i32)))); 6160 return; 6161 case Intrinsic::convert_from_fp16: 6162 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6163 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6164 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6165 getValue(I.getArgOperand(0))))); 6166 return; 6167 case Intrinsic::pcmarker: { 6168 SDValue Tmp = getValue(I.getArgOperand(0)); 6169 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6170 return; 6171 } 6172 case Intrinsic::readcyclecounter: { 6173 SDValue Op = getRoot(); 6174 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6175 DAG.getVTList(MVT::i64, MVT::Other), Op); 6176 setValue(&I, Res); 6177 DAG.setRoot(Res.getValue(1)); 6178 return; 6179 } 6180 case Intrinsic::bitreverse: 6181 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6182 getValue(I.getArgOperand(0)).getValueType(), 6183 getValue(I.getArgOperand(0)))); 6184 return; 6185 case Intrinsic::bswap: 6186 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6187 getValue(I.getArgOperand(0)).getValueType(), 6188 getValue(I.getArgOperand(0)))); 6189 return; 6190 case Intrinsic::cttz: { 6191 SDValue Arg = getValue(I.getArgOperand(0)); 6192 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6193 EVT Ty = Arg.getValueType(); 6194 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6195 sdl, Ty, Arg)); 6196 return; 6197 } 6198 case Intrinsic::ctlz: { 6199 SDValue Arg = getValue(I.getArgOperand(0)); 6200 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6201 EVT Ty = Arg.getValueType(); 6202 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6203 sdl, Ty, Arg)); 6204 return; 6205 } 6206 case Intrinsic::ctpop: { 6207 SDValue Arg = getValue(I.getArgOperand(0)); 6208 EVT Ty = Arg.getValueType(); 6209 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6210 return; 6211 } 6212 case Intrinsic::fshl: 6213 case Intrinsic::fshr: { 6214 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6215 SDValue X = getValue(I.getArgOperand(0)); 6216 SDValue Y = getValue(I.getArgOperand(1)); 6217 SDValue Z = getValue(I.getArgOperand(2)); 6218 EVT VT = X.getValueType(); 6219 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6220 SDValue Zero = DAG.getConstant(0, sdl, VT); 6221 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6222 6223 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6224 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6225 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6226 return; 6227 } 6228 6229 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6230 // avoid the select that is necessary in the general case to filter out 6231 // the 0-shift possibility that leads to UB. 6232 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6233 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6234 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6235 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6236 return; 6237 } 6238 6239 // Some targets only rotate one way. Try the opposite direction. 6240 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6241 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6242 // Negate the shift amount because it is safe to ignore the high bits. 6243 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6244 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6245 return; 6246 } 6247 6248 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6249 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6250 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6251 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6252 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6253 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6254 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6255 return; 6256 } 6257 6258 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6259 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6260 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6261 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6262 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6263 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6264 6265 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6266 // and that is undefined. We must compare and select to avoid UB. 6267 EVT CCVT = MVT::i1; 6268 if (VT.isVector()) 6269 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6270 6271 // For fshl, 0-shift returns the 1st arg (X). 6272 // For fshr, 0-shift returns the 2nd arg (Y). 6273 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6274 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6275 return; 6276 } 6277 case Intrinsic::sadd_sat: { 6278 SDValue Op1 = getValue(I.getArgOperand(0)); 6279 SDValue Op2 = getValue(I.getArgOperand(1)); 6280 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6281 return; 6282 } 6283 case Intrinsic::uadd_sat: { 6284 SDValue Op1 = getValue(I.getArgOperand(0)); 6285 SDValue Op2 = getValue(I.getArgOperand(1)); 6286 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6287 return; 6288 } 6289 case Intrinsic::ssub_sat: { 6290 SDValue Op1 = getValue(I.getArgOperand(0)); 6291 SDValue Op2 = getValue(I.getArgOperand(1)); 6292 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6293 return; 6294 } 6295 case Intrinsic::usub_sat: { 6296 SDValue Op1 = getValue(I.getArgOperand(0)); 6297 SDValue Op2 = getValue(I.getArgOperand(1)); 6298 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6299 return; 6300 } 6301 case Intrinsic::smul_fix: 6302 case Intrinsic::umul_fix: 6303 case Intrinsic::smul_fix_sat: 6304 case Intrinsic::umul_fix_sat: { 6305 SDValue Op1 = getValue(I.getArgOperand(0)); 6306 SDValue Op2 = getValue(I.getArgOperand(1)); 6307 SDValue Op3 = getValue(I.getArgOperand(2)); 6308 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6309 Op1.getValueType(), Op1, Op2, Op3)); 6310 return; 6311 } 6312 case Intrinsic::sdiv_fix: 6313 case Intrinsic::udiv_fix: 6314 case Intrinsic::sdiv_fix_sat: 6315 case Intrinsic::udiv_fix_sat: { 6316 SDValue Op1 = getValue(I.getArgOperand(0)); 6317 SDValue Op2 = getValue(I.getArgOperand(1)); 6318 SDValue Op3 = getValue(I.getArgOperand(2)); 6319 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6320 Op1, Op2, Op3, DAG, TLI)); 6321 return; 6322 } 6323 case Intrinsic::stacksave: { 6324 SDValue Op = getRoot(); 6325 Res = DAG.getNode( 6326 ISD::STACKSAVE, sdl, 6327 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6328 setValue(&I, Res); 6329 DAG.setRoot(Res.getValue(1)); 6330 return; 6331 } 6332 case Intrinsic::stackrestore: 6333 Res = getValue(I.getArgOperand(0)); 6334 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6335 return; 6336 case Intrinsic::get_dynamic_area_offset: { 6337 SDValue Op = getRoot(); 6338 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6339 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6340 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6341 // target. 6342 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6343 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6344 " intrinsic!"); 6345 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6346 Op); 6347 DAG.setRoot(Op); 6348 setValue(&I, Res); 6349 return; 6350 } 6351 case Intrinsic::stackguard: { 6352 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6353 MachineFunction &MF = DAG.getMachineFunction(); 6354 const Module &M = *MF.getFunction().getParent(); 6355 SDValue Chain = getRoot(); 6356 if (TLI.useLoadStackGuardNode()) { 6357 Res = getLoadStackGuard(DAG, sdl, Chain); 6358 } else { 6359 const Value *Global = TLI.getSDagStackGuard(M); 6360 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6361 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6362 MachinePointerInfo(Global, 0), Align, 6363 MachineMemOperand::MOVolatile); 6364 } 6365 if (TLI.useStackGuardXorFP()) 6366 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6367 DAG.setRoot(Chain); 6368 setValue(&I, Res); 6369 return; 6370 } 6371 case Intrinsic::stackprotector: { 6372 // Emit code into the DAG to store the stack guard onto the stack. 6373 MachineFunction &MF = DAG.getMachineFunction(); 6374 MachineFrameInfo &MFI = MF.getFrameInfo(); 6375 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6376 SDValue Src, Chain = getRoot(); 6377 6378 if (TLI.useLoadStackGuardNode()) 6379 Src = getLoadStackGuard(DAG, sdl, Chain); 6380 else 6381 Src = getValue(I.getArgOperand(0)); // The guard's value. 6382 6383 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6384 6385 int FI = FuncInfo.StaticAllocaMap[Slot]; 6386 MFI.setStackProtectorIndex(FI); 6387 6388 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6389 6390 // Store the stack protector onto the stack. 6391 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6392 DAG.getMachineFunction(), FI), 6393 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6394 setValue(&I, Res); 6395 DAG.setRoot(Res); 6396 return; 6397 } 6398 case Intrinsic::objectsize: 6399 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6400 6401 case Intrinsic::is_constant: 6402 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6403 6404 case Intrinsic::annotation: 6405 case Intrinsic::ptr_annotation: 6406 case Intrinsic::launder_invariant_group: 6407 case Intrinsic::strip_invariant_group: 6408 // Drop the intrinsic, but forward the value 6409 setValue(&I, getValue(I.getOperand(0))); 6410 return; 6411 case Intrinsic::assume: 6412 case Intrinsic::var_annotation: 6413 case Intrinsic::sideeffect: 6414 // Discard annotate attributes, assumptions, and artificial side-effects. 6415 return; 6416 6417 case Intrinsic::codeview_annotation: { 6418 // Emit a label associated with this metadata. 6419 MachineFunction &MF = DAG.getMachineFunction(); 6420 MCSymbol *Label = 6421 MF.getMMI().getContext().createTempSymbol("annotation", true); 6422 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6423 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6424 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6425 DAG.setRoot(Res); 6426 return; 6427 } 6428 6429 case Intrinsic::init_trampoline: { 6430 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6431 6432 SDValue Ops[6]; 6433 Ops[0] = getRoot(); 6434 Ops[1] = getValue(I.getArgOperand(0)); 6435 Ops[2] = getValue(I.getArgOperand(1)); 6436 Ops[3] = getValue(I.getArgOperand(2)); 6437 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6438 Ops[5] = DAG.getSrcValue(F); 6439 6440 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6441 6442 DAG.setRoot(Res); 6443 return; 6444 } 6445 case Intrinsic::adjust_trampoline: 6446 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6447 TLI.getPointerTy(DAG.getDataLayout()), 6448 getValue(I.getArgOperand(0)))); 6449 return; 6450 case Intrinsic::gcroot: { 6451 assert(DAG.getMachineFunction().getFunction().hasGC() && 6452 "only valid in functions with gc specified, enforced by Verifier"); 6453 assert(GFI && "implied by previous"); 6454 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6455 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6456 6457 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6458 GFI->addStackRoot(FI->getIndex(), TypeMap); 6459 return; 6460 } 6461 case Intrinsic::gcread: 6462 case Intrinsic::gcwrite: 6463 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6464 case Intrinsic::flt_rounds: 6465 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6466 setValue(&I, Res); 6467 DAG.setRoot(Res.getValue(1)); 6468 return; 6469 6470 case Intrinsic::expect: 6471 // Just replace __builtin_expect(exp, c) with EXP. 6472 setValue(&I, getValue(I.getArgOperand(0))); 6473 return; 6474 6475 case Intrinsic::debugtrap: 6476 case Intrinsic::trap: { 6477 StringRef TrapFuncName = 6478 I.getAttributes() 6479 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6480 .getValueAsString(); 6481 if (TrapFuncName.empty()) { 6482 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6483 ISD::TRAP : ISD::DEBUGTRAP; 6484 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6485 return; 6486 } 6487 TargetLowering::ArgListTy Args; 6488 6489 TargetLowering::CallLoweringInfo CLI(DAG); 6490 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6491 CallingConv::C, I.getType(), 6492 DAG.getExternalSymbol(TrapFuncName.data(), 6493 TLI.getPointerTy(DAG.getDataLayout())), 6494 std::move(Args)); 6495 6496 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6497 DAG.setRoot(Result.second); 6498 return; 6499 } 6500 6501 case Intrinsic::uadd_with_overflow: 6502 case Intrinsic::sadd_with_overflow: 6503 case Intrinsic::usub_with_overflow: 6504 case Intrinsic::ssub_with_overflow: 6505 case Intrinsic::umul_with_overflow: 6506 case Intrinsic::smul_with_overflow: { 6507 ISD::NodeType Op; 6508 switch (Intrinsic) { 6509 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6510 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6511 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6512 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6513 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6514 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6515 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6516 } 6517 SDValue Op1 = getValue(I.getArgOperand(0)); 6518 SDValue Op2 = getValue(I.getArgOperand(1)); 6519 6520 EVT ResultVT = Op1.getValueType(); 6521 EVT OverflowVT = MVT::i1; 6522 if (ResultVT.isVector()) 6523 OverflowVT = EVT::getVectorVT( 6524 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6525 6526 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6527 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6528 return; 6529 } 6530 case Intrinsic::prefetch: { 6531 SDValue Ops[5]; 6532 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6533 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6534 Ops[0] = DAG.getRoot(); 6535 Ops[1] = getValue(I.getArgOperand(0)); 6536 Ops[2] = getValue(I.getArgOperand(1)); 6537 Ops[3] = getValue(I.getArgOperand(2)); 6538 Ops[4] = getValue(I.getArgOperand(3)); 6539 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6540 DAG.getVTList(MVT::Other), Ops, 6541 EVT::getIntegerVT(*Context, 8), 6542 MachinePointerInfo(I.getArgOperand(0)), 6543 0, /* align */ 6544 Flags); 6545 6546 // Chain the prefetch in parallell with any pending loads, to stay out of 6547 // the way of later optimizations. 6548 PendingLoads.push_back(Result); 6549 Result = getRoot(); 6550 DAG.setRoot(Result); 6551 return; 6552 } 6553 case Intrinsic::lifetime_start: 6554 case Intrinsic::lifetime_end: { 6555 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6556 // Stack coloring is not enabled in O0, discard region information. 6557 if (TM.getOptLevel() == CodeGenOpt::None) 6558 return; 6559 6560 const int64_t ObjectSize = 6561 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6562 Value *const ObjectPtr = I.getArgOperand(1); 6563 SmallVector<const Value *, 4> Allocas; 6564 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6565 6566 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6567 E = Allocas.end(); Object != E; ++Object) { 6568 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6569 6570 // Could not find an Alloca. 6571 if (!LifetimeObject) 6572 continue; 6573 6574 // First check that the Alloca is static, otherwise it won't have a 6575 // valid frame index. 6576 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6577 if (SI == FuncInfo.StaticAllocaMap.end()) 6578 return; 6579 6580 const int FrameIndex = SI->second; 6581 int64_t Offset; 6582 if (GetPointerBaseWithConstantOffset( 6583 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6584 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6585 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6586 Offset); 6587 DAG.setRoot(Res); 6588 } 6589 return; 6590 } 6591 case Intrinsic::invariant_start: 6592 // Discard region information. 6593 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6594 return; 6595 case Intrinsic::invariant_end: 6596 // Discard region information. 6597 return; 6598 case Intrinsic::clear_cache: 6599 /// FunctionName may be null. 6600 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6601 lowerCallToExternalSymbol(I, FunctionName); 6602 return; 6603 case Intrinsic::donothing: 6604 // ignore 6605 return; 6606 case Intrinsic::experimental_stackmap: 6607 visitStackmap(I); 6608 return; 6609 case Intrinsic::experimental_patchpoint_void: 6610 case Intrinsic::experimental_patchpoint_i64: 6611 visitPatchpoint(&I); 6612 return; 6613 case Intrinsic::experimental_gc_statepoint: 6614 LowerStatepoint(ImmutableStatepoint(&I)); 6615 return; 6616 case Intrinsic::experimental_gc_result: 6617 visitGCResult(cast<GCResultInst>(I)); 6618 return; 6619 case Intrinsic::experimental_gc_relocate: 6620 visitGCRelocate(cast<GCRelocateInst>(I)); 6621 return; 6622 case Intrinsic::instrprof_increment: 6623 llvm_unreachable("instrprof failed to lower an increment"); 6624 case Intrinsic::instrprof_value_profile: 6625 llvm_unreachable("instrprof failed to lower a value profiling call"); 6626 case Intrinsic::localescape: { 6627 MachineFunction &MF = DAG.getMachineFunction(); 6628 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6629 6630 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6631 // is the same on all targets. 6632 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6633 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6634 if (isa<ConstantPointerNull>(Arg)) 6635 continue; // Skip null pointers. They represent a hole in index space. 6636 AllocaInst *Slot = cast<AllocaInst>(Arg); 6637 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6638 "can only escape static allocas"); 6639 int FI = FuncInfo.StaticAllocaMap[Slot]; 6640 MCSymbol *FrameAllocSym = 6641 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6642 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6643 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6644 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6645 .addSym(FrameAllocSym) 6646 .addFrameIndex(FI); 6647 } 6648 6649 return; 6650 } 6651 6652 case Intrinsic::localrecover: { 6653 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6654 MachineFunction &MF = DAG.getMachineFunction(); 6655 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6656 6657 // Get the symbol that defines the frame offset. 6658 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6659 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6660 unsigned IdxVal = 6661 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6662 MCSymbol *FrameAllocSym = 6663 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6664 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6665 6666 // Create a MCSymbol for the label to avoid any target lowering 6667 // that would make this PC relative. 6668 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6669 SDValue OffsetVal = 6670 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6671 6672 // Add the offset to the FP. 6673 Value *FP = I.getArgOperand(1); 6674 SDValue FPVal = getValue(FP); 6675 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6676 setValue(&I, Add); 6677 6678 return; 6679 } 6680 6681 case Intrinsic::eh_exceptionpointer: 6682 case Intrinsic::eh_exceptioncode: { 6683 // Get the exception pointer vreg, copy from it, and resize it to fit. 6684 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6685 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6686 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6687 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6688 SDValue N = 6689 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6690 if (Intrinsic == Intrinsic::eh_exceptioncode) 6691 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6692 setValue(&I, N); 6693 return; 6694 } 6695 case Intrinsic::xray_customevent: { 6696 // Here we want to make sure that the intrinsic behaves as if it has a 6697 // specific calling convention, and only for x86_64. 6698 // FIXME: Support other platforms later. 6699 const auto &Triple = DAG.getTarget().getTargetTriple(); 6700 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6701 return; 6702 6703 SDLoc DL = getCurSDLoc(); 6704 SmallVector<SDValue, 8> Ops; 6705 6706 // We want to say that we always want the arguments in registers. 6707 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6708 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6709 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6710 SDValue Chain = getRoot(); 6711 Ops.push_back(LogEntryVal); 6712 Ops.push_back(StrSizeVal); 6713 Ops.push_back(Chain); 6714 6715 // We need to enforce the calling convention for the callsite, so that 6716 // argument ordering is enforced correctly, and that register allocation can 6717 // see that some registers may be assumed clobbered and have to preserve 6718 // them across calls to the intrinsic. 6719 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6720 DL, NodeTys, Ops); 6721 SDValue patchableNode = SDValue(MN, 0); 6722 DAG.setRoot(patchableNode); 6723 setValue(&I, patchableNode); 6724 return; 6725 } 6726 case Intrinsic::xray_typedevent: { 6727 // Here we want to make sure that the intrinsic behaves as if it has a 6728 // specific calling convention, and only for x86_64. 6729 // FIXME: Support other platforms later. 6730 const auto &Triple = DAG.getTarget().getTargetTriple(); 6731 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6732 return; 6733 6734 SDLoc DL = getCurSDLoc(); 6735 SmallVector<SDValue, 8> Ops; 6736 6737 // We want to say that we always want the arguments in registers. 6738 // It's unclear to me how manipulating the selection DAG here forces callers 6739 // to provide arguments in registers instead of on the stack. 6740 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6741 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6742 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6743 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6744 SDValue Chain = getRoot(); 6745 Ops.push_back(LogTypeId); 6746 Ops.push_back(LogEntryVal); 6747 Ops.push_back(StrSizeVal); 6748 Ops.push_back(Chain); 6749 6750 // We need to enforce the calling convention for the callsite, so that 6751 // argument ordering is enforced correctly, and that register allocation can 6752 // see that some registers may be assumed clobbered and have to preserve 6753 // them across calls to the intrinsic. 6754 MachineSDNode *MN = DAG.getMachineNode( 6755 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6756 SDValue patchableNode = SDValue(MN, 0); 6757 DAG.setRoot(patchableNode); 6758 setValue(&I, patchableNode); 6759 return; 6760 } 6761 case Intrinsic::experimental_deoptimize: 6762 LowerDeoptimizeCall(&I); 6763 return; 6764 6765 case Intrinsic::experimental_vector_reduce_v2_fadd: 6766 case Intrinsic::experimental_vector_reduce_v2_fmul: 6767 case Intrinsic::experimental_vector_reduce_add: 6768 case Intrinsic::experimental_vector_reduce_mul: 6769 case Intrinsic::experimental_vector_reduce_and: 6770 case Intrinsic::experimental_vector_reduce_or: 6771 case Intrinsic::experimental_vector_reduce_xor: 6772 case Intrinsic::experimental_vector_reduce_smax: 6773 case Intrinsic::experimental_vector_reduce_smin: 6774 case Intrinsic::experimental_vector_reduce_umax: 6775 case Intrinsic::experimental_vector_reduce_umin: 6776 case Intrinsic::experimental_vector_reduce_fmax: 6777 case Intrinsic::experimental_vector_reduce_fmin: 6778 visitVectorReduce(I, Intrinsic); 6779 return; 6780 6781 case Intrinsic::icall_branch_funnel: { 6782 SmallVector<SDValue, 16> Ops; 6783 Ops.push_back(getValue(I.getArgOperand(0))); 6784 6785 int64_t Offset; 6786 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6787 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6788 if (!Base) 6789 report_fatal_error( 6790 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6791 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6792 6793 struct BranchFunnelTarget { 6794 int64_t Offset; 6795 SDValue Target; 6796 }; 6797 SmallVector<BranchFunnelTarget, 8> Targets; 6798 6799 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6800 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6801 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6802 if (ElemBase != Base) 6803 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6804 "to the same GlobalValue"); 6805 6806 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6807 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6808 if (!GA) 6809 report_fatal_error( 6810 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6811 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6812 GA->getGlobal(), getCurSDLoc(), 6813 Val.getValueType(), GA->getOffset())}); 6814 } 6815 llvm::sort(Targets, 6816 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6817 return T1.Offset < T2.Offset; 6818 }); 6819 6820 for (auto &T : Targets) { 6821 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6822 Ops.push_back(T.Target); 6823 } 6824 6825 Ops.push_back(DAG.getRoot()); // Chain 6826 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6827 getCurSDLoc(), MVT::Other, Ops), 6828 0); 6829 DAG.setRoot(N); 6830 setValue(&I, N); 6831 HasTailCall = true; 6832 return; 6833 } 6834 6835 case Intrinsic::wasm_landingpad_index: 6836 // Information this intrinsic contained has been transferred to 6837 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6838 // delete it now. 6839 return; 6840 6841 case Intrinsic::aarch64_settag: 6842 case Intrinsic::aarch64_settag_zero: { 6843 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6844 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6845 SDValue Val = TSI.EmitTargetCodeForSetTag( 6846 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6847 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6848 ZeroMemory); 6849 DAG.setRoot(Val); 6850 setValue(&I, Val); 6851 return; 6852 } 6853 case Intrinsic::ptrmask: { 6854 SDValue Ptr = getValue(I.getOperand(0)); 6855 SDValue Const = getValue(I.getOperand(1)); 6856 6857 EVT DestVT = 6858 EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6859 6860 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr, 6861 DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT))); 6862 return; 6863 } 6864 } 6865 } 6866 6867 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6868 const ConstrainedFPIntrinsic &FPI) { 6869 SDLoc sdl = getCurSDLoc(); 6870 6871 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6872 SmallVector<EVT, 4> ValueVTs; 6873 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6874 ValueVTs.push_back(MVT::Other); // Out chain 6875 6876 // We do not need to serialize constrained FP intrinsics against 6877 // each other or against (nonvolatile) loads, so they can be 6878 // chained like loads. 6879 SDValue Chain = DAG.getRoot(); 6880 SmallVector<SDValue, 4> Opers; 6881 Opers.push_back(Chain); 6882 if (FPI.isUnaryOp()) { 6883 Opers.push_back(getValue(FPI.getArgOperand(0))); 6884 } else if (FPI.isTernaryOp()) { 6885 Opers.push_back(getValue(FPI.getArgOperand(0))); 6886 Opers.push_back(getValue(FPI.getArgOperand(1))); 6887 Opers.push_back(getValue(FPI.getArgOperand(2))); 6888 } else { 6889 Opers.push_back(getValue(FPI.getArgOperand(0))); 6890 Opers.push_back(getValue(FPI.getArgOperand(1))); 6891 } 6892 6893 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 6894 assert(Result.getNode()->getNumValues() == 2); 6895 6896 // Push node to the appropriate list so that future instructions can be 6897 // chained up correctly. 6898 SDValue OutChain = Result.getValue(1); 6899 switch (EB) { 6900 case fp::ExceptionBehavior::ebIgnore: 6901 // The only reason why ebIgnore nodes still need to be chained is that 6902 // they might depend on the current rounding mode, and therefore must 6903 // not be moved across instruction that may change that mode. 6904 LLVM_FALLTHROUGH; 6905 case fp::ExceptionBehavior::ebMayTrap: 6906 // These must not be moved across calls or instructions that may change 6907 // floating-point exception masks. 6908 PendingConstrainedFP.push_back(OutChain); 6909 break; 6910 case fp::ExceptionBehavior::ebStrict: 6911 // These must not be moved across calls or instructions that may change 6912 // floating-point exception masks or read floating-point exception flags. 6913 // In addition, they cannot be optimized out even if unused. 6914 PendingConstrainedFPStrict.push_back(OutChain); 6915 break; 6916 } 6917 }; 6918 6919 SDVTList VTs = DAG.getVTList(ValueVTs); 6920 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 6921 6922 SDNodeFlags Flags; 6923 if (EB == fp::ExceptionBehavior::ebIgnore) 6924 Flags.setNoFPExcept(true); 6925 6926 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 6927 Flags.copyFMF(*FPOp); 6928 6929 unsigned Opcode; 6930 switch (FPI.getIntrinsicID()) { 6931 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6932 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6933 case Intrinsic::INTRINSIC: \ 6934 Opcode = ISD::STRICT_##DAGN; \ 6935 break; 6936 #include "llvm/IR/ConstrainedOps.def" 6937 case Intrinsic::experimental_constrained_fmuladd: { 6938 Opcode = ISD::STRICT_FMA; 6939 // Break fmuladd into fmul and fadd. 6940 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 6941 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 6942 ValueVTs[0])) { 6943 Opers.pop_back(); 6944 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 6945 pushOutChain(Mul, EB); 6946 Opcode = ISD::STRICT_FADD; 6947 Opers.clear(); 6948 Opers.push_back(Mul.getValue(1)); 6949 Opers.push_back(Mul.getValue(0)); 6950 Opers.push_back(getValue(FPI.getArgOperand(2))); 6951 } 6952 break; 6953 } 6954 } 6955 6956 // A few strict DAG nodes carry additional operands that are not 6957 // set up by the default code above. 6958 switch (Opcode) { 6959 default: break; 6960 case ISD::STRICT_FP_ROUND: 6961 Opers.push_back( 6962 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 6963 break; 6964 case ISD::STRICT_FSETCC: 6965 case ISD::STRICT_FSETCCS: { 6966 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 6967 Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate()))); 6968 break; 6969 } 6970 } 6971 6972 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 6973 pushOutChain(Result, EB); 6974 6975 SDValue FPResult = Result.getValue(0); 6976 setValue(&FPI, FPResult); 6977 } 6978 6979 std::pair<SDValue, SDValue> 6980 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6981 const BasicBlock *EHPadBB) { 6982 MachineFunction &MF = DAG.getMachineFunction(); 6983 MachineModuleInfo &MMI = MF.getMMI(); 6984 MCSymbol *BeginLabel = nullptr; 6985 6986 if (EHPadBB) { 6987 // Insert a label before the invoke call to mark the try range. This can be 6988 // used to detect deletion of the invoke via the MachineModuleInfo. 6989 BeginLabel = MMI.getContext().createTempSymbol(); 6990 6991 // For SjLj, keep track of which landing pads go with which invokes 6992 // so as to maintain the ordering of pads in the LSDA. 6993 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6994 if (CallSiteIndex) { 6995 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6996 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6997 6998 // Now that the call site is handled, stop tracking it. 6999 MMI.setCurrentCallSite(0); 7000 } 7001 7002 // Both PendingLoads and PendingExports must be flushed here; 7003 // this call might not return. 7004 (void)getRoot(); 7005 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7006 7007 CLI.setChain(getRoot()); 7008 } 7009 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7010 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7011 7012 assert((CLI.IsTailCall || Result.second.getNode()) && 7013 "Non-null chain expected with non-tail call!"); 7014 assert((Result.second.getNode() || !Result.first.getNode()) && 7015 "Null value expected with tail call!"); 7016 7017 if (!Result.second.getNode()) { 7018 // As a special case, a null chain means that a tail call has been emitted 7019 // and the DAG root is already updated. 7020 HasTailCall = true; 7021 7022 // Since there's no actual continuation from this block, nothing can be 7023 // relying on us setting vregs for them. 7024 PendingExports.clear(); 7025 } else { 7026 DAG.setRoot(Result.second); 7027 } 7028 7029 if (EHPadBB) { 7030 // Insert a label at the end of the invoke call to mark the try range. This 7031 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7032 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7033 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7034 7035 // Inform MachineModuleInfo of range. 7036 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7037 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7038 // actually use outlined funclets and their LSDA info style. 7039 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7040 assert(CLI.CS); 7041 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7042 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 7043 BeginLabel, EndLabel); 7044 } else if (!isScopedEHPersonality(Pers)) { 7045 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7046 } 7047 } 7048 7049 return Result; 7050 } 7051 7052 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 7053 bool isTailCall, 7054 const BasicBlock *EHPadBB) { 7055 auto &DL = DAG.getDataLayout(); 7056 FunctionType *FTy = CS.getFunctionType(); 7057 Type *RetTy = CS.getType(); 7058 7059 TargetLowering::ArgListTy Args; 7060 Args.reserve(CS.arg_size()); 7061 7062 const Value *SwiftErrorVal = nullptr; 7063 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7064 7065 if (isTailCall) { 7066 // Avoid emitting tail calls in functions with the disable-tail-calls 7067 // attribute. 7068 auto *Caller = CS.getInstruction()->getParent()->getParent(); 7069 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7070 "true") 7071 isTailCall = false; 7072 7073 // We can't tail call inside a function with a swifterror argument. Lowering 7074 // does not support this yet. It would have to move into the swifterror 7075 // register before the call. 7076 if (TLI.supportSwiftError() && 7077 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7078 isTailCall = false; 7079 } 7080 7081 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 7082 i != e; ++i) { 7083 TargetLowering::ArgListEntry Entry; 7084 const Value *V = *i; 7085 7086 // Skip empty types 7087 if (V->getType()->isEmptyTy()) 7088 continue; 7089 7090 SDValue ArgNode = getValue(V); 7091 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7092 7093 Entry.setAttributes(&CS, i - CS.arg_begin()); 7094 7095 // Use swifterror virtual register as input to the call. 7096 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7097 SwiftErrorVal = V; 7098 // We find the virtual register for the actual swifterror argument. 7099 // Instead of using the Value, we use the virtual register instead. 7100 Entry.Node = DAG.getRegister( 7101 SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V), 7102 EVT(TLI.getPointerTy(DL))); 7103 } 7104 7105 Args.push_back(Entry); 7106 7107 // If we have an explicit sret argument that is an Instruction, (i.e., it 7108 // might point to function-local memory), we can't meaningfully tail-call. 7109 if (Entry.IsSRet && isa<Instruction>(V)) 7110 isTailCall = false; 7111 } 7112 7113 // If call site has a cfguardtarget operand bundle, create and add an 7114 // additional ArgListEntry. 7115 if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7116 TargetLowering::ArgListEntry Entry; 7117 Value *V = Bundle->Inputs[0]; 7118 SDValue ArgNode = getValue(V); 7119 Entry.Node = ArgNode; 7120 Entry.Ty = V->getType(); 7121 Entry.IsCFGuardTarget = true; 7122 Args.push_back(Entry); 7123 } 7124 7125 // Check if target-independent constraints permit a tail call here. 7126 // Target-dependent constraints are checked within TLI->LowerCallTo. 7127 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 7128 isTailCall = false; 7129 7130 // Disable tail calls if there is an swifterror argument. Targets have not 7131 // been updated to support tail calls. 7132 if (TLI.supportSwiftError() && SwiftErrorVal) 7133 isTailCall = false; 7134 7135 TargetLowering::CallLoweringInfo CLI(DAG); 7136 CLI.setDebugLoc(getCurSDLoc()) 7137 .setChain(getRoot()) 7138 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 7139 .setTailCall(isTailCall) 7140 .setConvergent(CS.isConvergent()); 7141 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7142 7143 if (Result.first.getNode()) { 7144 const Instruction *Inst = CS.getInstruction(); 7145 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 7146 setValue(Inst, Result.first); 7147 } 7148 7149 // The last element of CLI.InVals has the SDValue for swifterror return. 7150 // Here we copy it to a virtual register and update SwiftErrorMap for 7151 // book-keeping. 7152 if (SwiftErrorVal && TLI.supportSwiftError()) { 7153 // Get the last element of InVals. 7154 SDValue Src = CLI.InVals.back(); 7155 Register VReg = SwiftError.getOrCreateVRegDefAt( 7156 CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal); 7157 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7158 DAG.setRoot(CopyNode); 7159 } 7160 } 7161 7162 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7163 SelectionDAGBuilder &Builder) { 7164 // Check to see if this load can be trivially constant folded, e.g. if the 7165 // input is from a string literal. 7166 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7167 // Cast pointer to the type we really want to load. 7168 Type *LoadTy = 7169 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7170 if (LoadVT.isVector()) 7171 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7172 7173 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7174 PointerType::getUnqual(LoadTy)); 7175 7176 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7177 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7178 return Builder.getValue(LoadCst); 7179 } 7180 7181 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7182 // still constant memory, the input chain can be the entry node. 7183 SDValue Root; 7184 bool ConstantMemory = false; 7185 7186 // Do not serialize (non-volatile) loads of constant memory with anything. 7187 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7188 Root = Builder.DAG.getEntryNode(); 7189 ConstantMemory = true; 7190 } else { 7191 // Do not serialize non-volatile loads against each other. 7192 Root = Builder.DAG.getRoot(); 7193 } 7194 7195 SDValue Ptr = Builder.getValue(PtrVal); 7196 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7197 Ptr, MachinePointerInfo(PtrVal), 7198 /* Alignment = */ 1); 7199 7200 if (!ConstantMemory) 7201 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7202 return LoadVal; 7203 } 7204 7205 /// Record the value for an instruction that produces an integer result, 7206 /// converting the type where necessary. 7207 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7208 SDValue Value, 7209 bool IsSigned) { 7210 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7211 I.getType(), true); 7212 if (IsSigned) 7213 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7214 else 7215 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7216 setValue(&I, Value); 7217 } 7218 7219 /// See if we can lower a memcmp call into an optimized form. If so, return 7220 /// true and lower it. Otherwise return false, and it will be lowered like a 7221 /// normal call. 7222 /// The caller already checked that \p I calls the appropriate LibFunc with a 7223 /// correct prototype. 7224 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7225 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7226 const Value *Size = I.getArgOperand(2); 7227 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7228 if (CSize && CSize->getZExtValue() == 0) { 7229 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7230 I.getType(), true); 7231 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7232 return true; 7233 } 7234 7235 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7236 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7237 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7238 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7239 if (Res.first.getNode()) { 7240 processIntegerCallValue(I, Res.first, true); 7241 PendingLoads.push_back(Res.second); 7242 return true; 7243 } 7244 7245 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7246 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7247 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7248 return false; 7249 7250 // If the target has a fast compare for the given size, it will return a 7251 // preferred load type for that size. Require that the load VT is legal and 7252 // that the target supports unaligned loads of that type. Otherwise, return 7253 // INVALID. 7254 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7255 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7256 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7257 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7258 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7259 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7260 // TODO: Check alignment of src and dest ptrs. 7261 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7262 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7263 if (!TLI.isTypeLegal(LVT) || 7264 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7265 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7266 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7267 } 7268 7269 return LVT; 7270 }; 7271 7272 // This turns into unaligned loads. We only do this if the target natively 7273 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7274 // we'll only produce a small number of byte loads. 7275 MVT LoadVT; 7276 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7277 switch (NumBitsToCompare) { 7278 default: 7279 return false; 7280 case 16: 7281 LoadVT = MVT::i16; 7282 break; 7283 case 32: 7284 LoadVT = MVT::i32; 7285 break; 7286 case 64: 7287 case 128: 7288 case 256: 7289 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7290 break; 7291 } 7292 7293 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7294 return false; 7295 7296 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7297 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7298 7299 // Bitcast to a wide integer type if the loads are vectors. 7300 if (LoadVT.isVector()) { 7301 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7302 LoadL = DAG.getBitcast(CmpVT, LoadL); 7303 LoadR = DAG.getBitcast(CmpVT, LoadR); 7304 } 7305 7306 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7307 processIntegerCallValue(I, Cmp, false); 7308 return true; 7309 } 7310 7311 /// See if we can lower a memchr call into an optimized form. If so, return 7312 /// true and lower it. Otherwise return false, and it will be lowered like a 7313 /// normal call. 7314 /// The caller already checked that \p I calls the appropriate LibFunc with a 7315 /// correct prototype. 7316 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7317 const Value *Src = I.getArgOperand(0); 7318 const Value *Char = I.getArgOperand(1); 7319 const Value *Length = I.getArgOperand(2); 7320 7321 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7322 std::pair<SDValue, SDValue> Res = 7323 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7324 getValue(Src), getValue(Char), getValue(Length), 7325 MachinePointerInfo(Src)); 7326 if (Res.first.getNode()) { 7327 setValue(&I, Res.first); 7328 PendingLoads.push_back(Res.second); 7329 return true; 7330 } 7331 7332 return false; 7333 } 7334 7335 /// See if we can lower a mempcpy call into an optimized form. If so, return 7336 /// true and lower it. Otherwise return false, and it will be lowered like a 7337 /// normal call. 7338 /// The caller already checked that \p I calls the appropriate LibFunc with a 7339 /// correct prototype. 7340 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7341 SDValue Dst = getValue(I.getArgOperand(0)); 7342 SDValue Src = getValue(I.getArgOperand(1)); 7343 SDValue Size = getValue(I.getArgOperand(2)); 7344 7345 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7346 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7347 // DAG::getMemcpy needs Alignment to be defined. 7348 Align Alignment = assumeAligned(std::min(DstAlign, SrcAlign)); 7349 7350 bool isVol = false; 7351 SDLoc sdl = getCurSDLoc(); 7352 7353 // In the mempcpy context we need to pass in a false value for isTailCall 7354 // because the return pointer needs to be adjusted by the size of 7355 // the copied memory. 7356 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7357 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7358 /*isTailCall=*/false, 7359 MachinePointerInfo(I.getArgOperand(0)), 7360 MachinePointerInfo(I.getArgOperand(1))); 7361 assert(MC.getNode() != nullptr && 7362 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7363 DAG.setRoot(MC); 7364 7365 // Check if Size needs to be truncated or extended. 7366 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7367 7368 // Adjust return pointer to point just past the last dst byte. 7369 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7370 Dst, Size); 7371 setValue(&I, DstPlusSize); 7372 return true; 7373 } 7374 7375 /// See if we can lower a strcpy call into an optimized form. If so, return 7376 /// true and lower it, otherwise return false and it will be lowered like a 7377 /// normal call. 7378 /// The caller already checked that \p I calls the appropriate LibFunc with a 7379 /// correct prototype. 7380 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7381 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7382 7383 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7384 std::pair<SDValue, SDValue> Res = 7385 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7386 getValue(Arg0), getValue(Arg1), 7387 MachinePointerInfo(Arg0), 7388 MachinePointerInfo(Arg1), isStpcpy); 7389 if (Res.first.getNode()) { 7390 setValue(&I, Res.first); 7391 DAG.setRoot(Res.second); 7392 return true; 7393 } 7394 7395 return false; 7396 } 7397 7398 /// See if we can lower a strcmp call into an optimized form. If so, return 7399 /// true and lower it, otherwise return false and it will be lowered like a 7400 /// normal call. 7401 /// The caller already checked that \p I calls the appropriate LibFunc with a 7402 /// correct prototype. 7403 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7404 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7405 7406 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7407 std::pair<SDValue, SDValue> Res = 7408 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7409 getValue(Arg0), getValue(Arg1), 7410 MachinePointerInfo(Arg0), 7411 MachinePointerInfo(Arg1)); 7412 if (Res.first.getNode()) { 7413 processIntegerCallValue(I, Res.first, true); 7414 PendingLoads.push_back(Res.second); 7415 return true; 7416 } 7417 7418 return false; 7419 } 7420 7421 /// See if we can lower a strlen call into an optimized form. If so, return 7422 /// true and lower it, otherwise return false and it will be lowered like a 7423 /// normal call. 7424 /// The caller already checked that \p I calls the appropriate LibFunc with a 7425 /// correct prototype. 7426 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7427 const Value *Arg0 = I.getArgOperand(0); 7428 7429 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7430 std::pair<SDValue, SDValue> Res = 7431 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7432 getValue(Arg0), 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 strnlen call into an optimized form. If so, return 7443 /// true and lower it, otherwise return false and it will be lowered like a 7444 /// normal call. 7445 /// The caller already checked that \p I calls the appropriate LibFunc with a 7446 /// correct prototype. 7447 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7448 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7449 7450 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7451 std::pair<SDValue, SDValue> Res = 7452 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7453 getValue(Arg0), getValue(Arg1), 7454 MachinePointerInfo(Arg0)); 7455 if (Res.first.getNode()) { 7456 processIntegerCallValue(I, Res.first, false); 7457 PendingLoads.push_back(Res.second); 7458 return true; 7459 } 7460 7461 return false; 7462 } 7463 7464 /// See if we can lower a unary floating-point operation into an SDNode with 7465 /// the specified Opcode. If so, return true and lower it, otherwise return 7466 /// false and it will be lowered like a normal call. 7467 /// The caller already checked that \p I calls the appropriate LibFunc with a 7468 /// correct prototype. 7469 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7470 unsigned Opcode) { 7471 // We already checked this call's prototype; verify it doesn't modify errno. 7472 if (!I.onlyReadsMemory()) 7473 return false; 7474 7475 SDValue Tmp = getValue(I.getArgOperand(0)); 7476 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7477 return true; 7478 } 7479 7480 /// See if we can lower a binary floating-point operation into an SDNode with 7481 /// the specified Opcode. If so, return true and lower it. Otherwise return 7482 /// false, and it will be lowered like a normal call. 7483 /// The caller already checked that \p I calls the appropriate LibFunc with a 7484 /// correct prototype. 7485 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7486 unsigned Opcode) { 7487 // We already checked this call's prototype; verify it doesn't modify errno. 7488 if (!I.onlyReadsMemory()) 7489 return false; 7490 7491 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7492 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7493 EVT VT = Tmp0.getValueType(); 7494 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7495 return true; 7496 } 7497 7498 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7499 // Handle inline assembly differently. 7500 if (isa<InlineAsm>(I.getCalledValue())) { 7501 visitInlineAsm(&I); 7502 return; 7503 } 7504 7505 if (Function *F = I.getCalledFunction()) { 7506 if (F->isDeclaration()) { 7507 // Is this an LLVM intrinsic or a target-specific intrinsic? 7508 unsigned IID = F->getIntrinsicID(); 7509 if (!IID) 7510 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7511 IID = II->getIntrinsicID(F); 7512 7513 if (IID) { 7514 visitIntrinsicCall(I, IID); 7515 return; 7516 } 7517 } 7518 7519 // Check for well-known libc/libm calls. If the function is internal, it 7520 // can't be a library call. Don't do the check if marked as nobuiltin for 7521 // some reason or the call site requires strict floating point semantics. 7522 LibFunc Func; 7523 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7524 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7525 LibInfo->hasOptimizedCodeGen(Func)) { 7526 switch (Func) { 7527 default: break; 7528 case LibFunc_copysign: 7529 case LibFunc_copysignf: 7530 case LibFunc_copysignl: 7531 // We already checked this call's prototype; verify it doesn't modify 7532 // errno. 7533 if (I.onlyReadsMemory()) { 7534 SDValue LHS = getValue(I.getArgOperand(0)); 7535 SDValue RHS = getValue(I.getArgOperand(1)); 7536 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7537 LHS.getValueType(), LHS, RHS)); 7538 return; 7539 } 7540 break; 7541 case LibFunc_fabs: 7542 case LibFunc_fabsf: 7543 case LibFunc_fabsl: 7544 if (visitUnaryFloatCall(I, ISD::FABS)) 7545 return; 7546 break; 7547 case LibFunc_fmin: 7548 case LibFunc_fminf: 7549 case LibFunc_fminl: 7550 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7551 return; 7552 break; 7553 case LibFunc_fmax: 7554 case LibFunc_fmaxf: 7555 case LibFunc_fmaxl: 7556 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7557 return; 7558 break; 7559 case LibFunc_sin: 7560 case LibFunc_sinf: 7561 case LibFunc_sinl: 7562 if (visitUnaryFloatCall(I, ISD::FSIN)) 7563 return; 7564 break; 7565 case LibFunc_cos: 7566 case LibFunc_cosf: 7567 case LibFunc_cosl: 7568 if (visitUnaryFloatCall(I, ISD::FCOS)) 7569 return; 7570 break; 7571 case LibFunc_sqrt: 7572 case LibFunc_sqrtf: 7573 case LibFunc_sqrtl: 7574 case LibFunc_sqrt_finite: 7575 case LibFunc_sqrtf_finite: 7576 case LibFunc_sqrtl_finite: 7577 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7578 return; 7579 break; 7580 case LibFunc_floor: 7581 case LibFunc_floorf: 7582 case LibFunc_floorl: 7583 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7584 return; 7585 break; 7586 case LibFunc_nearbyint: 7587 case LibFunc_nearbyintf: 7588 case LibFunc_nearbyintl: 7589 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7590 return; 7591 break; 7592 case LibFunc_ceil: 7593 case LibFunc_ceilf: 7594 case LibFunc_ceill: 7595 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7596 return; 7597 break; 7598 case LibFunc_rint: 7599 case LibFunc_rintf: 7600 case LibFunc_rintl: 7601 if (visitUnaryFloatCall(I, ISD::FRINT)) 7602 return; 7603 break; 7604 case LibFunc_round: 7605 case LibFunc_roundf: 7606 case LibFunc_roundl: 7607 if (visitUnaryFloatCall(I, ISD::FROUND)) 7608 return; 7609 break; 7610 case LibFunc_trunc: 7611 case LibFunc_truncf: 7612 case LibFunc_truncl: 7613 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7614 return; 7615 break; 7616 case LibFunc_log2: 7617 case LibFunc_log2f: 7618 case LibFunc_log2l: 7619 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7620 return; 7621 break; 7622 case LibFunc_exp2: 7623 case LibFunc_exp2f: 7624 case LibFunc_exp2l: 7625 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7626 return; 7627 break; 7628 case LibFunc_memcmp: 7629 if (visitMemCmpCall(I)) 7630 return; 7631 break; 7632 case LibFunc_mempcpy: 7633 if (visitMemPCpyCall(I)) 7634 return; 7635 break; 7636 case LibFunc_memchr: 7637 if (visitMemChrCall(I)) 7638 return; 7639 break; 7640 case LibFunc_strcpy: 7641 if (visitStrCpyCall(I, false)) 7642 return; 7643 break; 7644 case LibFunc_stpcpy: 7645 if (visitStrCpyCall(I, true)) 7646 return; 7647 break; 7648 case LibFunc_strcmp: 7649 if (visitStrCmpCall(I)) 7650 return; 7651 break; 7652 case LibFunc_strlen: 7653 if (visitStrLenCall(I)) 7654 return; 7655 break; 7656 case LibFunc_strnlen: 7657 if (visitStrNLenCall(I)) 7658 return; 7659 break; 7660 } 7661 } 7662 } 7663 7664 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7665 // have to do anything here to lower funclet bundles. 7666 // CFGuardTarget bundles are lowered in LowerCallTo. 7667 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 7668 LLVMContext::OB_funclet, 7669 LLVMContext::OB_cfguardtarget}) && 7670 "Cannot lower calls with arbitrary operand bundles!"); 7671 7672 SDValue Callee = getValue(I.getCalledValue()); 7673 7674 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7675 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7676 else 7677 // Check if we can potentially perform a tail call. More detailed checking 7678 // is be done within LowerCallTo, after more information about the call is 7679 // known. 7680 LowerCallTo(&I, Callee, I.isTailCall()); 7681 } 7682 7683 namespace { 7684 7685 /// AsmOperandInfo - This contains information for each constraint that we are 7686 /// lowering. 7687 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7688 public: 7689 /// CallOperand - If this is the result output operand or a clobber 7690 /// this is null, otherwise it is the incoming operand to the CallInst. 7691 /// This gets modified as the asm is processed. 7692 SDValue CallOperand; 7693 7694 /// AssignedRegs - If this is a register or register class operand, this 7695 /// contains the set of register corresponding to the operand. 7696 RegsForValue AssignedRegs; 7697 7698 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7699 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7700 } 7701 7702 /// Whether or not this operand accesses memory 7703 bool hasMemory(const TargetLowering &TLI) const { 7704 // Indirect operand accesses access memory. 7705 if (isIndirect) 7706 return true; 7707 7708 for (const auto &Code : Codes) 7709 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7710 return true; 7711 7712 return false; 7713 } 7714 7715 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7716 /// corresponds to. If there is no Value* for this operand, it returns 7717 /// MVT::Other. 7718 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7719 const DataLayout &DL) const { 7720 if (!CallOperandVal) return MVT::Other; 7721 7722 if (isa<BasicBlock>(CallOperandVal)) 7723 return TLI.getPointerTy(DL); 7724 7725 llvm::Type *OpTy = CallOperandVal->getType(); 7726 7727 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7728 // If this is an indirect operand, the operand is a pointer to the 7729 // accessed type. 7730 if (isIndirect) { 7731 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7732 if (!PtrTy) 7733 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7734 OpTy = PtrTy->getElementType(); 7735 } 7736 7737 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7738 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7739 if (STy->getNumElements() == 1) 7740 OpTy = STy->getElementType(0); 7741 7742 // If OpTy is not a single value, it may be a struct/union that we 7743 // can tile with integers. 7744 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7745 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7746 switch (BitSize) { 7747 default: break; 7748 case 1: 7749 case 8: 7750 case 16: 7751 case 32: 7752 case 64: 7753 case 128: 7754 OpTy = IntegerType::get(Context, BitSize); 7755 break; 7756 } 7757 } 7758 7759 return TLI.getValueType(DL, OpTy, true); 7760 } 7761 }; 7762 7763 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7764 7765 } // end anonymous namespace 7766 7767 /// Make sure that the output operand \p OpInfo and its corresponding input 7768 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7769 /// out). 7770 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7771 SDISelAsmOperandInfo &MatchingOpInfo, 7772 SelectionDAG &DAG) { 7773 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7774 return; 7775 7776 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7777 const auto &TLI = DAG.getTargetLoweringInfo(); 7778 7779 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7780 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7781 OpInfo.ConstraintVT); 7782 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7783 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7784 MatchingOpInfo.ConstraintVT); 7785 if ((OpInfo.ConstraintVT.isInteger() != 7786 MatchingOpInfo.ConstraintVT.isInteger()) || 7787 (MatchRC.second != InputRC.second)) { 7788 // FIXME: error out in a more elegant fashion 7789 report_fatal_error("Unsupported asm: input constraint" 7790 " with a matching output constraint of" 7791 " incompatible type!"); 7792 } 7793 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7794 } 7795 7796 /// Get a direct memory input to behave well as an indirect operand. 7797 /// This may introduce stores, hence the need for a \p Chain. 7798 /// \return The (possibly updated) chain. 7799 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7800 SDISelAsmOperandInfo &OpInfo, 7801 SelectionDAG &DAG) { 7802 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7803 7804 // If we don't have an indirect input, put it in the constpool if we can, 7805 // otherwise spill it to a stack slot. 7806 // TODO: This isn't quite right. We need to handle these according to 7807 // the addressing mode that the constraint wants. Also, this may take 7808 // an additional register for the computation and we don't want that 7809 // either. 7810 7811 // If the operand is a float, integer, or vector constant, spill to a 7812 // constant pool entry to get its address. 7813 const Value *OpVal = OpInfo.CallOperandVal; 7814 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7815 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7816 OpInfo.CallOperand = DAG.getConstantPool( 7817 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7818 return Chain; 7819 } 7820 7821 // Otherwise, create a stack slot and emit a store to it before the asm. 7822 Type *Ty = OpVal->getType(); 7823 auto &DL = DAG.getDataLayout(); 7824 uint64_t TySize = DL.getTypeAllocSize(Ty); 7825 unsigned Align = DL.getPrefTypeAlignment(Ty); 7826 MachineFunction &MF = DAG.getMachineFunction(); 7827 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7828 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7829 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7830 MachinePointerInfo::getFixedStack(MF, SSFI), 7831 TLI.getMemValueType(DL, Ty)); 7832 OpInfo.CallOperand = StackSlot; 7833 7834 return Chain; 7835 } 7836 7837 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7838 /// specified operand. We prefer to assign virtual registers, to allow the 7839 /// register allocator to handle the assignment process. However, if the asm 7840 /// uses features that we can't model on machineinstrs, we have SDISel do the 7841 /// allocation. This produces generally horrible, but correct, code. 7842 /// 7843 /// OpInfo describes the operand 7844 /// RefOpInfo describes the matching operand if any, the operand otherwise 7845 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7846 SDISelAsmOperandInfo &OpInfo, 7847 SDISelAsmOperandInfo &RefOpInfo) { 7848 LLVMContext &Context = *DAG.getContext(); 7849 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7850 7851 MachineFunction &MF = DAG.getMachineFunction(); 7852 SmallVector<unsigned, 4> Regs; 7853 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7854 7855 // No work to do for memory operations. 7856 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7857 return; 7858 7859 // If this is a constraint for a single physreg, or a constraint for a 7860 // register class, find it. 7861 unsigned AssignedReg; 7862 const TargetRegisterClass *RC; 7863 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7864 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7865 // RC is unset only on failure. Return immediately. 7866 if (!RC) 7867 return; 7868 7869 // Get the actual register value type. This is important, because the user 7870 // may have asked for (e.g.) the AX register in i32 type. We need to 7871 // remember that AX is actually i16 to get the right extension. 7872 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7873 7874 if (OpInfo.ConstraintVT != MVT::Other) { 7875 // If this is an FP operand in an integer register (or visa versa), or more 7876 // generally if the operand value disagrees with the register class we plan 7877 // to stick it in, fix the operand type. 7878 // 7879 // If this is an input value, the bitcast to the new type is done now. 7880 // Bitcast for output value is done at the end of visitInlineAsm(). 7881 if ((OpInfo.Type == InlineAsm::isOutput || 7882 OpInfo.Type == InlineAsm::isInput) && 7883 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7884 // Try to convert to the first EVT that the reg class contains. If the 7885 // types are identical size, use a bitcast to convert (e.g. two differing 7886 // vector types). Note: output bitcast is done at the end of 7887 // visitInlineAsm(). 7888 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7889 // Exclude indirect inputs while they are unsupported because the code 7890 // to perform the load is missing and thus OpInfo.CallOperand still 7891 // refers to the input address rather than the pointed-to value. 7892 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7893 OpInfo.CallOperand = 7894 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7895 OpInfo.ConstraintVT = RegVT; 7896 // If the operand is an FP value and we want it in integer registers, 7897 // use the corresponding integer type. This turns an f64 value into 7898 // i64, which can be passed with two i32 values on a 32-bit machine. 7899 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7900 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7901 if (OpInfo.Type == InlineAsm::isInput) 7902 OpInfo.CallOperand = 7903 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7904 OpInfo.ConstraintVT = VT; 7905 } 7906 } 7907 } 7908 7909 // No need to allocate a matching input constraint since the constraint it's 7910 // matching to has already been allocated. 7911 if (OpInfo.isMatchingInputConstraint()) 7912 return; 7913 7914 EVT ValueVT = OpInfo.ConstraintVT; 7915 if (OpInfo.ConstraintVT == MVT::Other) 7916 ValueVT = RegVT; 7917 7918 // Initialize NumRegs. 7919 unsigned NumRegs = 1; 7920 if (OpInfo.ConstraintVT != MVT::Other) 7921 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7922 7923 // If this is a constraint for a specific physical register, like {r17}, 7924 // assign it now. 7925 7926 // If this associated to a specific register, initialize iterator to correct 7927 // place. If virtual, make sure we have enough registers 7928 7929 // Initialize iterator if necessary 7930 TargetRegisterClass::iterator I = RC->begin(); 7931 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7932 7933 // Do not check for single registers. 7934 if (AssignedReg) { 7935 for (; *I != AssignedReg; ++I) 7936 assert(I != RC->end() && "AssignedReg should be member of RC"); 7937 } 7938 7939 for (; NumRegs; --NumRegs, ++I) { 7940 assert(I != RC->end() && "Ran out of registers to allocate!"); 7941 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 7942 Regs.push_back(R); 7943 } 7944 7945 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7946 } 7947 7948 static unsigned 7949 findMatchingInlineAsmOperand(unsigned OperandNo, 7950 const std::vector<SDValue> &AsmNodeOperands) { 7951 // Scan until we find the definition we already emitted of this operand. 7952 unsigned CurOp = InlineAsm::Op_FirstOperand; 7953 for (; OperandNo; --OperandNo) { 7954 // Advance to the next operand. 7955 unsigned OpFlag = 7956 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7957 assert((InlineAsm::isRegDefKind(OpFlag) || 7958 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7959 InlineAsm::isMemKind(OpFlag)) && 7960 "Skipped past definitions?"); 7961 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7962 } 7963 return CurOp; 7964 } 7965 7966 namespace { 7967 7968 class ExtraFlags { 7969 unsigned Flags = 0; 7970 7971 public: 7972 explicit ExtraFlags(ImmutableCallSite CS) { 7973 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7974 if (IA->hasSideEffects()) 7975 Flags |= InlineAsm::Extra_HasSideEffects; 7976 if (IA->isAlignStack()) 7977 Flags |= InlineAsm::Extra_IsAlignStack; 7978 if (CS.isConvergent()) 7979 Flags |= InlineAsm::Extra_IsConvergent; 7980 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7981 } 7982 7983 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7984 // Ideally, we would only check against memory constraints. However, the 7985 // meaning of an Other constraint can be target-specific and we can't easily 7986 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7987 // for Other constraints as well. 7988 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7989 OpInfo.ConstraintType == TargetLowering::C_Other) { 7990 if (OpInfo.Type == InlineAsm::isInput) 7991 Flags |= InlineAsm::Extra_MayLoad; 7992 else if (OpInfo.Type == InlineAsm::isOutput) 7993 Flags |= InlineAsm::Extra_MayStore; 7994 else if (OpInfo.Type == InlineAsm::isClobber) 7995 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7996 } 7997 } 7998 7999 unsigned get() const { return Flags; } 8000 }; 8001 8002 } // end anonymous namespace 8003 8004 /// visitInlineAsm - Handle a call to an InlineAsm object. 8005 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 8006 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 8007 8008 /// ConstraintOperands - Information about all of the constraints. 8009 SDISelAsmOperandInfoVector ConstraintOperands; 8010 8011 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8012 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8013 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 8014 8015 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8016 // AsmDialect, MayLoad, MayStore). 8017 bool HasSideEffect = IA->hasSideEffects(); 8018 ExtraFlags ExtraInfo(CS); 8019 8020 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8021 unsigned ResNo = 0; // ResNo - The result number of the next output. 8022 unsigned NumMatchingOps = 0; 8023 for (auto &T : TargetConstraints) { 8024 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8025 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8026 8027 // Compute the value type for each operand. 8028 if (OpInfo.Type == InlineAsm::isInput || 8029 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8030 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 8031 8032 // Process the call argument. BasicBlocks are labels, currently appearing 8033 // only in asm's. 8034 const Instruction *I = CS.getInstruction(); 8035 if (isa<CallBrInst>(I) && 8036 ArgNo - 1 >= (cast<CallBrInst>(I)->getNumArgOperands() - 8037 cast<CallBrInst>(I)->getNumIndirectDests() - 8038 NumMatchingOps) && 8039 (NumMatchingOps == 0 || 8040 ArgNo - 1 < (cast<CallBrInst>(I)->getNumArgOperands() - 8041 NumMatchingOps))) { 8042 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8043 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8044 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8045 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8046 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8047 } else { 8048 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8049 } 8050 8051 OpInfo.ConstraintVT = 8052 OpInfo 8053 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8054 .getSimpleVT(); 8055 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8056 // The return value of the call is this value. As such, there is no 8057 // corresponding argument. 8058 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8059 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 8060 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8061 DAG.getDataLayout(), STy->getElementType(ResNo)); 8062 } else { 8063 assert(ResNo == 0 && "Asm only has one result!"); 8064 OpInfo.ConstraintVT = 8065 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 8066 } 8067 ++ResNo; 8068 } else { 8069 OpInfo.ConstraintVT = MVT::Other; 8070 } 8071 8072 if (OpInfo.hasMatchingInput()) 8073 ++NumMatchingOps; 8074 8075 if (!HasSideEffect) 8076 HasSideEffect = OpInfo.hasMemory(TLI); 8077 8078 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8079 // FIXME: Could we compute this on OpInfo rather than T? 8080 8081 // Compute the constraint code and ConstraintType to use. 8082 TLI.ComputeConstraintToUse(T, SDValue()); 8083 8084 if (T.ConstraintType == TargetLowering::C_Immediate && 8085 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8086 // We've delayed emitting a diagnostic like the "n" constraint because 8087 // inlining could cause an integer showing up. 8088 return emitInlineAsmError( 8089 CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an " 8090 "integer constant expression"); 8091 8092 ExtraInfo.update(T); 8093 } 8094 8095 8096 // We won't need to flush pending loads if this asm doesn't touch 8097 // memory and is nonvolatile. 8098 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8099 8100 bool IsCallBr = isa<CallBrInst>(CS.getInstruction()); 8101 if (IsCallBr) { 8102 // If this is a callbr we need to flush pending exports since inlineasm_br 8103 // is a terminator. We need to do this before nodes are glued to 8104 // the inlineasm_br node. 8105 Chain = getControlRoot(); 8106 } 8107 8108 // Second pass over the constraints: compute which constraint option to use. 8109 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8110 // If this is an output operand with a matching input operand, look up the 8111 // matching input. If their types mismatch, e.g. one is an integer, the 8112 // other is floating point, or their sizes are different, flag it as an 8113 // error. 8114 if (OpInfo.hasMatchingInput()) { 8115 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8116 patchMatchingInput(OpInfo, Input, DAG); 8117 } 8118 8119 // Compute the constraint code and ConstraintType to use. 8120 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8121 8122 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8123 OpInfo.Type == InlineAsm::isClobber) 8124 continue; 8125 8126 // If this is a memory input, and if the operand is not indirect, do what we 8127 // need to provide an address for the memory input. 8128 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8129 !OpInfo.isIndirect) { 8130 assert((OpInfo.isMultipleAlternative || 8131 (OpInfo.Type == InlineAsm::isInput)) && 8132 "Can only indirectify direct input operands!"); 8133 8134 // Memory operands really want the address of the value. 8135 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8136 8137 // There is no longer a Value* corresponding to this operand. 8138 OpInfo.CallOperandVal = nullptr; 8139 8140 // It is now an indirect operand. 8141 OpInfo.isIndirect = true; 8142 } 8143 8144 } 8145 8146 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8147 std::vector<SDValue> AsmNodeOperands; 8148 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8149 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8150 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 8151 8152 // If we have a !srcloc metadata node associated with it, we want to attach 8153 // this to the ultimately generated inline asm machineinstr. To do this, we 8154 // pass in the third operand as this (potentially null) inline asm MDNode. 8155 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 8156 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8157 8158 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8159 // bits as operand 3. 8160 AsmNodeOperands.push_back(DAG.getTargetConstant( 8161 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8162 8163 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8164 // this, assign virtual and physical registers for inputs and otput. 8165 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8166 // Assign Registers. 8167 SDISelAsmOperandInfo &RefOpInfo = 8168 OpInfo.isMatchingInputConstraint() 8169 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8170 : OpInfo; 8171 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8172 8173 switch (OpInfo.Type) { 8174 case InlineAsm::isOutput: 8175 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8176 unsigned ConstraintID = 8177 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8178 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8179 "Failed to convert memory constraint code to constraint id."); 8180 8181 // Add information to the INLINEASM node to know about this output. 8182 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8183 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8184 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8185 MVT::i32)); 8186 AsmNodeOperands.push_back(OpInfo.CallOperand); 8187 } else { 8188 // Otherwise, this outputs to a register (directly for C_Register / 8189 // C_RegisterClass, and a target-defined fashion for 8190 // C_Immediate/C_Other). Find a register that we can use. 8191 if (OpInfo.AssignedRegs.Regs.empty()) { 8192 emitInlineAsmError( 8193 CS, "couldn't allocate output register for constraint '" + 8194 Twine(OpInfo.ConstraintCode) + "'"); 8195 return; 8196 } 8197 8198 // Add information to the INLINEASM node to know that this register is 8199 // set. 8200 OpInfo.AssignedRegs.AddInlineAsmOperands( 8201 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8202 : InlineAsm::Kind_RegDef, 8203 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8204 } 8205 break; 8206 8207 case InlineAsm::isInput: { 8208 SDValue InOperandVal = OpInfo.CallOperand; 8209 8210 if (OpInfo.isMatchingInputConstraint()) { 8211 // If this is required to match an output register we have already set, 8212 // just use its register. 8213 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8214 AsmNodeOperands); 8215 unsigned OpFlag = 8216 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8217 if (InlineAsm::isRegDefKind(OpFlag) || 8218 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8219 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8220 if (OpInfo.isIndirect) { 8221 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8222 emitInlineAsmError(CS, "inline asm not supported yet:" 8223 " don't know how to handle tied " 8224 "indirect register inputs"); 8225 return; 8226 } 8227 8228 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8229 SmallVector<unsigned, 4> Regs; 8230 8231 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8232 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8233 MachineRegisterInfo &RegInfo = 8234 DAG.getMachineFunction().getRegInfo(); 8235 for (unsigned i = 0; i != NumRegs; ++i) 8236 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8237 } else { 8238 emitInlineAsmError(CS, "inline asm error: This value type register " 8239 "class is not natively supported!"); 8240 return; 8241 } 8242 8243 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8244 8245 SDLoc dl = getCurSDLoc(); 8246 // Use the produced MatchedRegs object to 8247 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8248 CS.getInstruction()); 8249 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8250 true, OpInfo.getMatchedOperand(), dl, 8251 DAG, AsmNodeOperands); 8252 break; 8253 } 8254 8255 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8256 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8257 "Unexpected number of operands"); 8258 // Add information to the INLINEASM node to know about this input. 8259 // See InlineAsm.h isUseOperandTiedToDef. 8260 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8261 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8262 OpInfo.getMatchedOperand()); 8263 AsmNodeOperands.push_back(DAG.getTargetConstant( 8264 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8265 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8266 break; 8267 } 8268 8269 // Treat indirect 'X' constraint as memory. 8270 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8271 OpInfo.isIndirect) 8272 OpInfo.ConstraintType = TargetLowering::C_Memory; 8273 8274 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8275 OpInfo.ConstraintType == TargetLowering::C_Other) { 8276 std::vector<SDValue> Ops; 8277 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8278 Ops, DAG); 8279 if (Ops.empty()) { 8280 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8281 if (isa<ConstantSDNode>(InOperandVal)) { 8282 emitInlineAsmError(CS, "value out of range for constraint '" + 8283 Twine(OpInfo.ConstraintCode) + "'"); 8284 return; 8285 } 8286 8287 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8288 Twine(OpInfo.ConstraintCode) + "'"); 8289 return; 8290 } 8291 8292 // Add information to the INLINEASM node to know about this input. 8293 unsigned ResOpType = 8294 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8295 AsmNodeOperands.push_back(DAG.getTargetConstant( 8296 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8297 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8298 break; 8299 } 8300 8301 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8302 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8303 assert(InOperandVal.getValueType() == 8304 TLI.getPointerTy(DAG.getDataLayout()) && 8305 "Memory operands expect pointer values"); 8306 8307 unsigned ConstraintID = 8308 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8309 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8310 "Failed to convert memory constraint code to constraint id."); 8311 8312 // Add information to the INLINEASM node to know about this input. 8313 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8314 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8315 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8316 getCurSDLoc(), 8317 MVT::i32)); 8318 AsmNodeOperands.push_back(InOperandVal); 8319 break; 8320 } 8321 8322 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8323 OpInfo.ConstraintType == TargetLowering::C_Register) && 8324 "Unknown constraint type!"); 8325 8326 // TODO: Support this. 8327 if (OpInfo.isIndirect) { 8328 emitInlineAsmError( 8329 CS, "Don't know how to handle indirect register inputs yet " 8330 "for constraint '" + 8331 Twine(OpInfo.ConstraintCode) + "'"); 8332 return; 8333 } 8334 8335 // Copy the input into the appropriate registers. 8336 if (OpInfo.AssignedRegs.Regs.empty()) { 8337 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8338 Twine(OpInfo.ConstraintCode) + "'"); 8339 return; 8340 } 8341 8342 SDLoc dl = getCurSDLoc(); 8343 8344 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8345 Chain, &Flag, CS.getInstruction()); 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 *CSResultType = CS.getType(); 8378 ArrayRef<Type *> ResultTypes; 8379 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8380 ResultTypes = StructResult->elements(); 8381 else if (!CSResultType->isVoidTy()) 8382 ResultTypes = makeArrayRef(CSResultType); 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( 8427 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 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(!CS.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(CS.getInstruction(), 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(ImmutableCallSite CS, 8481 const Twine &Message) { 8482 LLVMContext &Ctx = *DAG.getContext(); 8483 Ctx.emitError(CS.getInstruction(), 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(), CS->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(CS.getInstruction(), 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(ImmutableCallSite CS, unsigned StartIdx, 8629 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8630 SelectionDAGBuilder &Builder) { 8631 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8632 SDValue OpVal = Builder.getValue(CS.getArgument(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.getCalledValue()); 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(ImmutableCallSite CS, 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 = CS.getCallingConv(); 8721 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8722 bool HasDef = !CS->getType()->isVoidTy(); 8723 SDLoc dl = getCurSDLoc(); 8724 SDValue Callee = getValue(CS->getOperand(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(CS.getArgument(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(CS.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()) : CS->getType(); 8749 8750 TargetLowering::CallLoweringInfo CLI(DAG); 8751 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8752 NumMetaOpers, NumCallArgs, Callee, 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(CS->getOperand(PatchPointOpers::IDPos)); 8771 Ops.push_back(DAG.getTargetConstant( 8772 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8773 SDValue NBytesVal = getValue(CS->getOperand(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(CS.getArgument(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(CS, 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(), CS->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(CS.getInstruction(), SDValue(MN, 0)); 8841 else 8842 setValue(CS.getInstruction(), 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 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8992 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8993 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8994 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8995 DL.getAllocaAddrSpace()); 8996 8997 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8998 ArgListEntry Entry; 8999 Entry.Node = DemoteStackSlot; 9000 Entry.Ty = StackSlotPtrType; 9001 Entry.IsSExt = false; 9002 Entry.IsZExt = false; 9003 Entry.IsInReg = false; 9004 Entry.IsSRet = true; 9005 Entry.IsNest = false; 9006 Entry.IsByVal = false; 9007 Entry.IsReturned = false; 9008 Entry.IsSwiftSelf = false; 9009 Entry.IsSwiftError = false; 9010 Entry.IsCFGuardTarget = false; 9011 Entry.Alignment = Align; 9012 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9013 CLI.NumFixedArgs += 1; 9014 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9015 9016 // sret demotion isn't compatible with tail-calls, since the sret argument 9017 // points into the callers stack frame. 9018 CLI.IsTailCall = false; 9019 } else { 9020 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9021 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9022 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9023 ISD::ArgFlagsTy Flags; 9024 if (NeedsRegBlock) { 9025 Flags.setInConsecutiveRegs(); 9026 if (I == RetTys.size() - 1) 9027 Flags.setInConsecutiveRegsLast(); 9028 } 9029 EVT VT = RetTys[I]; 9030 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9031 CLI.CallConv, VT); 9032 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9033 CLI.CallConv, VT); 9034 for (unsigned i = 0; i != NumRegs; ++i) { 9035 ISD::InputArg MyFlags; 9036 MyFlags.Flags = Flags; 9037 MyFlags.VT = RegisterVT; 9038 MyFlags.ArgVT = VT; 9039 MyFlags.Used = CLI.IsReturnValueUsed; 9040 if (CLI.RetTy->isPointerTy()) { 9041 MyFlags.Flags.setPointer(); 9042 MyFlags.Flags.setPointerAddrSpace( 9043 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9044 } 9045 if (CLI.RetSExt) 9046 MyFlags.Flags.setSExt(); 9047 if (CLI.RetZExt) 9048 MyFlags.Flags.setZExt(); 9049 if (CLI.IsInReg) 9050 MyFlags.Flags.setInReg(); 9051 CLI.Ins.push_back(MyFlags); 9052 } 9053 } 9054 } 9055 9056 // We push in swifterror return as the last element of CLI.Ins. 9057 ArgListTy &Args = CLI.getArgs(); 9058 if (supportSwiftError()) { 9059 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9060 if (Args[i].IsSwiftError) { 9061 ISD::InputArg MyFlags; 9062 MyFlags.VT = getPointerTy(DL); 9063 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9064 MyFlags.Flags.setSwiftError(); 9065 CLI.Ins.push_back(MyFlags); 9066 } 9067 } 9068 } 9069 9070 // Handle all of the outgoing arguments. 9071 CLI.Outs.clear(); 9072 CLI.OutVals.clear(); 9073 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9074 SmallVector<EVT, 4> ValueVTs; 9075 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9076 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9077 Type *FinalType = Args[i].Ty; 9078 if (Args[i].IsByVal) 9079 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9080 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9081 FinalType, CLI.CallConv, CLI.IsVarArg); 9082 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9083 ++Value) { 9084 EVT VT = ValueVTs[Value]; 9085 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9086 SDValue Op = SDValue(Args[i].Node.getNode(), 9087 Args[i].Node.getResNo() + Value); 9088 ISD::ArgFlagsTy Flags; 9089 9090 // Certain targets (such as MIPS), may have a different ABI alignment 9091 // for a type depending on the context. Give the target a chance to 9092 // specify the alignment it wants. 9093 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9094 9095 if (Args[i].Ty->isPointerTy()) { 9096 Flags.setPointer(); 9097 Flags.setPointerAddrSpace( 9098 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9099 } 9100 if (Args[i].IsZExt) 9101 Flags.setZExt(); 9102 if (Args[i].IsSExt) 9103 Flags.setSExt(); 9104 if (Args[i].IsInReg) { 9105 // If we are using vectorcall calling convention, a structure that is 9106 // passed InReg - is surely an HVA 9107 if (CLI.CallConv == CallingConv::X86_VectorCall && 9108 isa<StructType>(FinalType)) { 9109 // The first value of a structure is marked 9110 if (0 == Value) 9111 Flags.setHvaStart(); 9112 Flags.setHva(); 9113 } 9114 // Set InReg Flag 9115 Flags.setInReg(); 9116 } 9117 if (Args[i].IsSRet) 9118 Flags.setSRet(); 9119 if (Args[i].IsSwiftSelf) 9120 Flags.setSwiftSelf(); 9121 if (Args[i].IsSwiftError) 9122 Flags.setSwiftError(); 9123 if (Args[i].IsCFGuardTarget) 9124 Flags.setCFGuardTarget(); 9125 if (Args[i].IsByVal) 9126 Flags.setByVal(); 9127 if (Args[i].IsInAlloca) { 9128 Flags.setInAlloca(); 9129 // Set the byval flag for CCAssignFn callbacks that don't know about 9130 // inalloca. This way we can know how many bytes we should've allocated 9131 // and how many bytes a callee cleanup function will pop. If we port 9132 // inalloca to more targets, we'll have to add custom inalloca handling 9133 // in the various CC lowering callbacks. 9134 Flags.setByVal(); 9135 } 9136 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9137 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9138 Type *ElementTy = Ty->getElementType(); 9139 9140 unsigned FrameSize = DL.getTypeAllocSize( 9141 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9142 Flags.setByValSize(FrameSize); 9143 9144 // info is not there but there are cases it cannot get right. 9145 unsigned FrameAlign; 9146 if (Args[i].Alignment) 9147 FrameAlign = Args[i].Alignment; 9148 else 9149 FrameAlign = getByValTypeAlignment(ElementTy, DL); 9150 Flags.setByValAlign(Align(FrameAlign)); 9151 } 9152 if (Args[i].IsNest) 9153 Flags.setNest(); 9154 if (NeedsRegBlock) 9155 Flags.setInConsecutiveRegs(); 9156 Flags.setOrigAlign(OriginalAlignment); 9157 9158 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9159 CLI.CallConv, VT); 9160 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9161 CLI.CallConv, VT); 9162 SmallVector<SDValue, 4> Parts(NumParts); 9163 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9164 9165 if (Args[i].IsSExt) 9166 ExtendKind = ISD::SIGN_EXTEND; 9167 else if (Args[i].IsZExt) 9168 ExtendKind = ISD::ZERO_EXTEND; 9169 9170 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9171 // for now. 9172 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9173 CanLowerReturn) { 9174 assert((CLI.RetTy == Args[i].Ty || 9175 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9176 CLI.RetTy->getPointerAddressSpace() == 9177 Args[i].Ty->getPointerAddressSpace())) && 9178 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9179 // Before passing 'returned' to the target lowering code, ensure that 9180 // either the register MVT and the actual EVT are the same size or that 9181 // the return value and argument are extended in the same way; in these 9182 // cases it's safe to pass the argument register value unchanged as the 9183 // return register value (although it's at the target's option whether 9184 // to do so) 9185 // TODO: allow code generation to take advantage of partially preserved 9186 // registers rather than clobbering the entire register when the 9187 // parameter extension method is not compatible with the return 9188 // extension method 9189 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9190 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9191 CLI.RetZExt == Args[i].IsZExt)) 9192 Flags.setReturned(); 9193 } 9194 9195 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 9196 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 9197 9198 for (unsigned j = 0; j != NumParts; ++j) { 9199 // if it isn't first piece, alignment must be 1 9200 // For scalable vectors the scalable part is currently handled 9201 // by individual targets, so we just use the known minimum size here. 9202 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9203 i < CLI.NumFixedArgs, i, 9204 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9205 if (NumParts > 1 && j == 0) 9206 MyFlags.Flags.setSplit(); 9207 else if (j != 0) { 9208 MyFlags.Flags.setOrigAlign(Align(1)); 9209 if (j == NumParts - 1) 9210 MyFlags.Flags.setSplitEnd(); 9211 } 9212 9213 CLI.Outs.push_back(MyFlags); 9214 CLI.OutVals.push_back(Parts[j]); 9215 } 9216 9217 if (NeedsRegBlock && Value == NumValues - 1) 9218 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9219 } 9220 } 9221 9222 SmallVector<SDValue, 4> InVals; 9223 CLI.Chain = LowerCall(CLI, InVals); 9224 9225 // Update CLI.InVals to use outside of this function. 9226 CLI.InVals = InVals; 9227 9228 // Verify that the target's LowerCall behaved as expected. 9229 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9230 "LowerCall didn't return a valid chain!"); 9231 assert((!CLI.IsTailCall || InVals.empty()) && 9232 "LowerCall emitted a return value for a tail call!"); 9233 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9234 "LowerCall didn't emit the correct number of values!"); 9235 9236 // For a tail call, the return value is merely live-out and there aren't 9237 // any nodes in the DAG representing it. Return a special value to 9238 // indicate that a tail call has been emitted and no more Instructions 9239 // should be processed in the current block. 9240 if (CLI.IsTailCall) { 9241 CLI.DAG.setRoot(CLI.Chain); 9242 return std::make_pair(SDValue(), SDValue()); 9243 } 9244 9245 #ifndef NDEBUG 9246 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9247 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9248 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9249 "LowerCall emitted a value with the wrong type!"); 9250 } 9251 #endif 9252 9253 SmallVector<SDValue, 4> ReturnValues; 9254 if (!CanLowerReturn) { 9255 // The instruction result is the result of loading from the 9256 // hidden sret parameter. 9257 SmallVector<EVT, 1> PVTs; 9258 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9259 9260 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9261 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9262 EVT PtrVT = PVTs[0]; 9263 9264 unsigned NumValues = RetTys.size(); 9265 ReturnValues.resize(NumValues); 9266 SmallVector<SDValue, 4> Chains(NumValues); 9267 9268 // An aggregate return value cannot wrap around the address space, so 9269 // offsets to its parts don't wrap either. 9270 SDNodeFlags Flags; 9271 Flags.setNoUnsignedWrap(true); 9272 9273 for (unsigned i = 0; i < NumValues; ++i) { 9274 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9275 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9276 PtrVT), Flags); 9277 SDValue L = CLI.DAG.getLoad( 9278 RetTys[i], CLI.DL, CLI.Chain, Add, 9279 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9280 DemoteStackIdx, Offsets[i]), 9281 /* Alignment = */ 1); 9282 ReturnValues[i] = L; 9283 Chains[i] = L.getValue(1); 9284 } 9285 9286 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9287 } else { 9288 // Collect the legal value parts into potentially illegal values 9289 // that correspond to the original function's return values. 9290 Optional<ISD::NodeType> AssertOp; 9291 if (CLI.RetSExt) 9292 AssertOp = ISD::AssertSext; 9293 else if (CLI.RetZExt) 9294 AssertOp = ISD::AssertZext; 9295 unsigned CurReg = 0; 9296 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9297 EVT VT = RetTys[I]; 9298 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9299 CLI.CallConv, VT); 9300 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9301 CLI.CallConv, VT); 9302 9303 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9304 NumRegs, RegisterVT, VT, nullptr, 9305 CLI.CallConv, AssertOp)); 9306 CurReg += NumRegs; 9307 } 9308 9309 // For a function returning void, there is no return value. We can't create 9310 // such a node, so we just return a null return value in that case. In 9311 // that case, nothing will actually look at the value. 9312 if (ReturnValues.empty()) 9313 return std::make_pair(SDValue(), CLI.Chain); 9314 } 9315 9316 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9317 CLI.DAG.getVTList(RetTys), ReturnValues); 9318 return std::make_pair(Res, CLI.Chain); 9319 } 9320 9321 void TargetLowering::LowerOperationWrapper(SDNode *N, 9322 SmallVectorImpl<SDValue> &Results, 9323 SelectionDAG &DAG) const { 9324 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9325 Results.push_back(Res); 9326 } 9327 9328 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9329 llvm_unreachable("LowerOperation not implemented for this target!"); 9330 } 9331 9332 void 9333 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9334 SDValue Op = getNonRegisterValue(V); 9335 assert((Op.getOpcode() != ISD::CopyFromReg || 9336 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9337 "Copy from a reg to the same reg!"); 9338 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9339 9340 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9341 // If this is an InlineAsm we have to match the registers required, not the 9342 // notional registers required by the type. 9343 9344 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9345 None); // This is not an ABI copy. 9346 SDValue Chain = DAG.getEntryNode(); 9347 9348 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9349 FuncInfo.PreferredExtendType.end()) 9350 ? ISD::ANY_EXTEND 9351 : FuncInfo.PreferredExtendType[V]; 9352 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9353 PendingExports.push_back(Chain); 9354 } 9355 9356 #include "llvm/CodeGen/SelectionDAGISel.h" 9357 9358 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9359 /// entry block, return true. This includes arguments used by switches, since 9360 /// the switch may expand into multiple basic blocks. 9361 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9362 // With FastISel active, we may be splitting blocks, so force creation 9363 // of virtual registers for all non-dead arguments. 9364 if (FastISel) 9365 return A->use_empty(); 9366 9367 const BasicBlock &Entry = A->getParent()->front(); 9368 for (const User *U : A->users()) 9369 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9370 return false; // Use not in entry block. 9371 9372 return true; 9373 } 9374 9375 using ArgCopyElisionMapTy = 9376 DenseMap<const Argument *, 9377 std::pair<const AllocaInst *, const StoreInst *>>; 9378 9379 /// Scan the entry block of the function in FuncInfo for arguments that look 9380 /// like copies into a local alloca. Record any copied arguments in 9381 /// ArgCopyElisionCandidates. 9382 static void 9383 findArgumentCopyElisionCandidates(const DataLayout &DL, 9384 FunctionLoweringInfo *FuncInfo, 9385 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9386 // Record the state of every static alloca used in the entry block. Argument 9387 // allocas are all used in the entry block, so we need approximately as many 9388 // entries as we have arguments. 9389 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9390 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9391 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9392 StaticAllocas.reserve(NumArgs * 2); 9393 9394 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9395 if (!V) 9396 return nullptr; 9397 V = V->stripPointerCasts(); 9398 const auto *AI = dyn_cast<AllocaInst>(V); 9399 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9400 return nullptr; 9401 auto Iter = StaticAllocas.insert({AI, Unknown}); 9402 return &Iter.first->second; 9403 }; 9404 9405 // Look for stores of arguments to static allocas. Look through bitcasts and 9406 // GEPs to handle type coercions, as long as the alloca is fully initialized 9407 // by the store. Any non-store use of an alloca escapes it and any subsequent 9408 // unanalyzed store might write it. 9409 // FIXME: Handle structs initialized with multiple stores. 9410 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9411 // Look for stores, and handle non-store uses conservatively. 9412 const auto *SI = dyn_cast<StoreInst>(&I); 9413 if (!SI) { 9414 // We will look through cast uses, so ignore them completely. 9415 if (I.isCast()) 9416 continue; 9417 // Ignore debug info intrinsics, they don't escape or store to allocas. 9418 if (isa<DbgInfoIntrinsic>(I)) 9419 continue; 9420 // This is an unknown instruction. Assume it escapes or writes to all 9421 // static alloca operands. 9422 for (const Use &U : I.operands()) { 9423 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9424 *Info = StaticAllocaInfo::Clobbered; 9425 } 9426 continue; 9427 } 9428 9429 // If the stored value is a static alloca, mark it as escaped. 9430 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9431 *Info = StaticAllocaInfo::Clobbered; 9432 9433 // Check if the destination is a static alloca. 9434 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9435 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9436 if (!Info) 9437 continue; 9438 const AllocaInst *AI = cast<AllocaInst>(Dst); 9439 9440 // Skip allocas that have been initialized or clobbered. 9441 if (*Info != StaticAllocaInfo::Unknown) 9442 continue; 9443 9444 // Check if the stored value is an argument, and that this store fully 9445 // initializes the alloca. Don't elide copies from the same argument twice. 9446 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9447 const auto *Arg = dyn_cast<Argument>(Val); 9448 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9449 Arg->getType()->isEmptyTy() || 9450 DL.getTypeStoreSize(Arg->getType()) != 9451 DL.getTypeAllocSize(AI->getAllocatedType()) || 9452 ArgCopyElisionCandidates.count(Arg)) { 9453 *Info = StaticAllocaInfo::Clobbered; 9454 continue; 9455 } 9456 9457 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9458 << '\n'); 9459 9460 // Mark this alloca and store for argument copy elision. 9461 *Info = StaticAllocaInfo::Elidable; 9462 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9463 9464 // Stop scanning if we've seen all arguments. This will happen early in -O0 9465 // builds, which is useful, because -O0 builds have large entry blocks and 9466 // many allocas. 9467 if (ArgCopyElisionCandidates.size() == NumArgs) 9468 break; 9469 } 9470 } 9471 9472 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9473 /// ArgVal is a load from a suitable fixed stack object. 9474 static void tryToElideArgumentCopy( 9475 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9476 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9477 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9478 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9479 SDValue ArgVal, bool &ArgHasUses) { 9480 // Check if this is a load from a fixed stack object. 9481 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9482 if (!LNode) 9483 return; 9484 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9485 if (!FINode) 9486 return; 9487 9488 // Check that the fixed stack object is the right size and alignment. 9489 // Look at the alignment that the user wrote on the alloca instead of looking 9490 // at the stack object. 9491 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9492 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9493 const AllocaInst *AI = ArgCopyIter->second.first; 9494 int FixedIndex = FINode->getIndex(); 9495 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9496 int OldIndex = AllocaIndex; 9497 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9498 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9499 LLVM_DEBUG( 9500 dbgs() << " argument copy elision failed due to bad fixed stack " 9501 "object size\n"); 9502 return; 9503 } 9504 unsigned RequiredAlignment = AI->getAlignment(); 9505 if (!RequiredAlignment) { 9506 RequiredAlignment = FuncInfo.MF->getDataLayout().getABITypeAlignment( 9507 AI->getAllocatedType()); 9508 } 9509 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9510 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9511 "greater than stack argument alignment (" 9512 << RequiredAlignment << " vs " 9513 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9514 return; 9515 } 9516 9517 // Perform the elision. Delete the old stack object and replace its only use 9518 // in the variable info map. Mark the stack object as mutable. 9519 LLVM_DEBUG({ 9520 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9521 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9522 << '\n'; 9523 }); 9524 MFI.RemoveStackObject(OldIndex); 9525 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9526 AllocaIndex = FixedIndex; 9527 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9528 Chains.push_back(ArgVal.getValue(1)); 9529 9530 // Avoid emitting code for the store implementing the copy. 9531 const StoreInst *SI = ArgCopyIter->second.second; 9532 ElidedArgCopyInstrs.insert(SI); 9533 9534 // Check for uses of the argument again so that we can avoid exporting ArgVal 9535 // if it is't used by anything other than the store. 9536 for (const Value *U : Arg.users()) { 9537 if (U != SI) { 9538 ArgHasUses = true; 9539 break; 9540 } 9541 } 9542 } 9543 9544 void SelectionDAGISel::LowerArguments(const Function &F) { 9545 SelectionDAG &DAG = SDB->DAG; 9546 SDLoc dl = SDB->getCurSDLoc(); 9547 const DataLayout &DL = DAG.getDataLayout(); 9548 SmallVector<ISD::InputArg, 16> Ins; 9549 9550 if (!FuncInfo->CanLowerReturn) { 9551 // Put in an sret pointer parameter before all the other parameters. 9552 SmallVector<EVT, 1> ValueVTs; 9553 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9554 F.getReturnType()->getPointerTo( 9555 DAG.getDataLayout().getAllocaAddrSpace()), 9556 ValueVTs); 9557 9558 // NOTE: Assuming that a pointer will never break down to more than one VT 9559 // or one register. 9560 ISD::ArgFlagsTy Flags; 9561 Flags.setSRet(); 9562 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9563 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9564 ISD::InputArg::NoArgIndex, 0); 9565 Ins.push_back(RetArg); 9566 } 9567 9568 // Look for stores of arguments to static allocas. Mark such arguments with a 9569 // flag to ask the target to give us the memory location of that argument if 9570 // available. 9571 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9572 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9573 ArgCopyElisionCandidates); 9574 9575 // Set up the incoming argument description vector. 9576 for (const Argument &Arg : F.args()) { 9577 unsigned ArgNo = Arg.getArgNo(); 9578 SmallVector<EVT, 4> ValueVTs; 9579 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9580 bool isArgValueUsed = !Arg.use_empty(); 9581 unsigned PartBase = 0; 9582 Type *FinalType = Arg.getType(); 9583 if (Arg.hasAttribute(Attribute::ByVal)) 9584 FinalType = Arg.getParamByValType(); 9585 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9586 FinalType, F.getCallingConv(), F.isVarArg()); 9587 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9588 Value != NumValues; ++Value) { 9589 EVT VT = ValueVTs[Value]; 9590 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9591 ISD::ArgFlagsTy Flags; 9592 9593 // Certain targets (such as MIPS), may have a different ABI alignment 9594 // for a type depending on the context. Give the target a chance to 9595 // specify the alignment it wants. 9596 const Align OriginalAlignment( 9597 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9598 9599 if (Arg.getType()->isPointerTy()) { 9600 Flags.setPointer(); 9601 Flags.setPointerAddrSpace( 9602 cast<PointerType>(Arg.getType())->getAddressSpace()); 9603 } 9604 if (Arg.hasAttribute(Attribute::ZExt)) 9605 Flags.setZExt(); 9606 if (Arg.hasAttribute(Attribute::SExt)) 9607 Flags.setSExt(); 9608 if (Arg.hasAttribute(Attribute::InReg)) { 9609 // If we are using vectorcall calling convention, a structure that is 9610 // passed InReg - is surely an HVA 9611 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9612 isa<StructType>(Arg.getType())) { 9613 // The first value of a structure is marked 9614 if (0 == Value) 9615 Flags.setHvaStart(); 9616 Flags.setHva(); 9617 } 9618 // Set InReg Flag 9619 Flags.setInReg(); 9620 } 9621 if (Arg.hasAttribute(Attribute::StructRet)) 9622 Flags.setSRet(); 9623 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9624 Flags.setSwiftSelf(); 9625 if (Arg.hasAttribute(Attribute::SwiftError)) 9626 Flags.setSwiftError(); 9627 if (Arg.hasAttribute(Attribute::ByVal)) 9628 Flags.setByVal(); 9629 if (Arg.hasAttribute(Attribute::InAlloca)) { 9630 Flags.setInAlloca(); 9631 // Set the byval flag for CCAssignFn callbacks that don't know about 9632 // inalloca. This way we can know how many bytes we should've allocated 9633 // and how many bytes a callee cleanup function will pop. If we port 9634 // inalloca to more targets, we'll have to add custom inalloca handling 9635 // in the various CC lowering callbacks. 9636 Flags.setByVal(); 9637 } 9638 if (F.getCallingConv() == CallingConv::X86_INTR) { 9639 // IA Interrupt passes frame (1st parameter) by value in the stack. 9640 if (ArgNo == 0) 9641 Flags.setByVal(); 9642 } 9643 if (Flags.isByVal() || Flags.isInAlloca()) { 9644 Type *ElementTy = Arg.getParamByValType(); 9645 9646 // For ByVal, size and alignment should be passed from FE. BE will 9647 // guess if this info is not there but there are cases it cannot get 9648 // right. 9649 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9650 Flags.setByValSize(FrameSize); 9651 9652 unsigned FrameAlign; 9653 if (Arg.getParamAlignment()) 9654 FrameAlign = Arg.getParamAlignment(); 9655 else 9656 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9657 Flags.setByValAlign(Align(FrameAlign)); 9658 } 9659 if (Arg.hasAttribute(Attribute::Nest)) 9660 Flags.setNest(); 9661 if (NeedsRegBlock) 9662 Flags.setInConsecutiveRegs(); 9663 Flags.setOrigAlign(OriginalAlignment); 9664 if (ArgCopyElisionCandidates.count(&Arg)) 9665 Flags.setCopyElisionCandidate(); 9666 if (Arg.hasAttribute(Attribute::Returned)) 9667 Flags.setReturned(); 9668 9669 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9670 *CurDAG->getContext(), F.getCallingConv(), VT); 9671 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9672 *CurDAG->getContext(), F.getCallingConv(), VT); 9673 for (unsigned i = 0; i != NumRegs; ++i) { 9674 // For scalable vectors, use the minimum size; individual targets 9675 // are responsible for handling scalable vector arguments and 9676 // return values. 9677 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9678 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9679 if (NumRegs > 1 && i == 0) 9680 MyFlags.Flags.setSplit(); 9681 // if it isn't first piece, alignment must be 1 9682 else if (i > 0) { 9683 MyFlags.Flags.setOrigAlign(Align(1)); 9684 if (i == NumRegs - 1) 9685 MyFlags.Flags.setSplitEnd(); 9686 } 9687 Ins.push_back(MyFlags); 9688 } 9689 if (NeedsRegBlock && Value == NumValues - 1) 9690 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9691 PartBase += VT.getStoreSize().getKnownMinSize(); 9692 } 9693 } 9694 9695 // Call the target to set up the argument values. 9696 SmallVector<SDValue, 8> InVals; 9697 SDValue NewRoot = TLI->LowerFormalArguments( 9698 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9699 9700 // Verify that the target's LowerFormalArguments behaved as expected. 9701 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9702 "LowerFormalArguments didn't return a valid chain!"); 9703 assert(InVals.size() == Ins.size() && 9704 "LowerFormalArguments didn't emit the correct number of values!"); 9705 LLVM_DEBUG({ 9706 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9707 assert(InVals[i].getNode() && 9708 "LowerFormalArguments emitted a null value!"); 9709 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9710 "LowerFormalArguments emitted a value with the wrong type!"); 9711 } 9712 }); 9713 9714 // Update the DAG with the new chain value resulting from argument lowering. 9715 DAG.setRoot(NewRoot); 9716 9717 // Set up the argument values. 9718 unsigned i = 0; 9719 if (!FuncInfo->CanLowerReturn) { 9720 // Create a virtual register for the sret pointer, and put in a copy 9721 // from the sret argument into it. 9722 SmallVector<EVT, 1> ValueVTs; 9723 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9724 F.getReturnType()->getPointerTo( 9725 DAG.getDataLayout().getAllocaAddrSpace()), 9726 ValueVTs); 9727 MVT VT = ValueVTs[0].getSimpleVT(); 9728 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9729 Optional<ISD::NodeType> AssertOp = None; 9730 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9731 nullptr, F.getCallingConv(), AssertOp); 9732 9733 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9734 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9735 Register SRetReg = 9736 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9737 FuncInfo->DemoteRegister = SRetReg; 9738 NewRoot = 9739 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9740 DAG.setRoot(NewRoot); 9741 9742 // i indexes lowered arguments. Bump it past the hidden sret argument. 9743 ++i; 9744 } 9745 9746 SmallVector<SDValue, 4> Chains; 9747 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9748 for (const Argument &Arg : F.args()) { 9749 SmallVector<SDValue, 4> ArgValues; 9750 SmallVector<EVT, 4> ValueVTs; 9751 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9752 unsigned NumValues = ValueVTs.size(); 9753 if (NumValues == 0) 9754 continue; 9755 9756 bool ArgHasUses = !Arg.use_empty(); 9757 9758 // Elide the copying store if the target loaded this argument from a 9759 // suitable fixed stack object. 9760 if (Ins[i].Flags.isCopyElisionCandidate()) { 9761 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9762 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9763 InVals[i], ArgHasUses); 9764 } 9765 9766 // If this argument is unused then remember its value. It is used to generate 9767 // debugging information. 9768 bool isSwiftErrorArg = 9769 TLI->supportSwiftError() && 9770 Arg.hasAttribute(Attribute::SwiftError); 9771 if (!ArgHasUses && !isSwiftErrorArg) { 9772 SDB->setUnusedArgValue(&Arg, InVals[i]); 9773 9774 // Also remember any frame index for use in FastISel. 9775 if (FrameIndexSDNode *FI = 9776 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9777 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9778 } 9779 9780 for (unsigned Val = 0; Val != NumValues; ++Val) { 9781 EVT VT = ValueVTs[Val]; 9782 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9783 F.getCallingConv(), VT); 9784 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9785 *CurDAG->getContext(), F.getCallingConv(), VT); 9786 9787 // Even an apparent 'unused' swifterror argument needs to be returned. So 9788 // we do generate a copy for it that can be used on return from the 9789 // function. 9790 if (ArgHasUses || isSwiftErrorArg) { 9791 Optional<ISD::NodeType> AssertOp; 9792 if (Arg.hasAttribute(Attribute::SExt)) 9793 AssertOp = ISD::AssertSext; 9794 else if (Arg.hasAttribute(Attribute::ZExt)) 9795 AssertOp = ISD::AssertZext; 9796 9797 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9798 PartVT, VT, nullptr, 9799 F.getCallingConv(), AssertOp)); 9800 } 9801 9802 i += NumParts; 9803 } 9804 9805 // We don't need to do anything else for unused arguments. 9806 if (ArgValues.empty()) 9807 continue; 9808 9809 // Note down frame index. 9810 if (FrameIndexSDNode *FI = 9811 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9812 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9813 9814 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9815 SDB->getCurSDLoc()); 9816 9817 SDB->setValue(&Arg, Res); 9818 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9819 // We want to associate the argument with the frame index, among 9820 // involved operands, that correspond to the lowest address. The 9821 // getCopyFromParts function, called earlier, is swapping the order of 9822 // the operands to BUILD_PAIR depending on endianness. The result of 9823 // that swapping is that the least significant bits of the argument will 9824 // be in the first operand of the BUILD_PAIR node, and the most 9825 // significant bits will be in the second operand. 9826 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9827 if (LoadSDNode *LNode = 9828 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9829 if (FrameIndexSDNode *FI = 9830 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9831 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9832 } 9833 9834 // Analyses past this point are naive and don't expect an assertion. 9835 if (Res.getOpcode() == ISD::AssertZext) 9836 Res = Res.getOperand(0); 9837 9838 // Update the SwiftErrorVRegDefMap. 9839 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9840 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9841 if (Register::isVirtualRegister(Reg)) 9842 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9843 Reg); 9844 } 9845 9846 // If this argument is live outside of the entry block, insert a copy from 9847 // wherever we got it to the vreg that other BB's will reference it as. 9848 if (Res.getOpcode() == ISD::CopyFromReg) { 9849 // If we can, though, try to skip creating an unnecessary vreg. 9850 // FIXME: This isn't very clean... it would be nice to make this more 9851 // general. 9852 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9853 if (Register::isVirtualRegister(Reg)) { 9854 FuncInfo->ValueMap[&Arg] = Reg; 9855 continue; 9856 } 9857 } 9858 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9859 FuncInfo->InitializeRegForValue(&Arg); 9860 SDB->CopyToExportRegsIfNeeded(&Arg); 9861 } 9862 } 9863 9864 if (!Chains.empty()) { 9865 Chains.push_back(NewRoot); 9866 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9867 } 9868 9869 DAG.setRoot(NewRoot); 9870 9871 assert(i == InVals.size() && "Argument register count mismatch!"); 9872 9873 // If any argument copy elisions occurred and we have debug info, update the 9874 // stale frame indices used in the dbg.declare variable info table. 9875 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9876 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9877 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9878 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9879 if (I != ArgCopyElisionFrameIndexMap.end()) 9880 VI.Slot = I->second; 9881 } 9882 } 9883 9884 // Finally, if the target has anything special to do, allow it to do so. 9885 emitFunctionEntryCode(); 9886 } 9887 9888 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9889 /// ensure constants are generated when needed. Remember the virtual registers 9890 /// that need to be added to the Machine PHI nodes as input. We cannot just 9891 /// directly add them, because expansion might result in multiple MBB's for one 9892 /// BB. As such, the start of the BB might correspond to a different MBB than 9893 /// the end. 9894 void 9895 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9896 const Instruction *TI = LLVMBB->getTerminator(); 9897 9898 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9899 9900 // Check PHI nodes in successors that expect a value to be available from this 9901 // block. 9902 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9903 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9904 if (!isa<PHINode>(SuccBB->begin())) continue; 9905 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9906 9907 // If this terminator has multiple identical successors (common for 9908 // switches), only handle each succ once. 9909 if (!SuccsHandled.insert(SuccMBB).second) 9910 continue; 9911 9912 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9913 9914 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9915 // nodes and Machine PHI nodes, but the incoming operands have not been 9916 // emitted yet. 9917 for (const PHINode &PN : SuccBB->phis()) { 9918 // Ignore dead phi's. 9919 if (PN.use_empty()) 9920 continue; 9921 9922 // Skip empty types 9923 if (PN.getType()->isEmptyTy()) 9924 continue; 9925 9926 unsigned Reg; 9927 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9928 9929 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9930 unsigned &RegOut = ConstantsOut[C]; 9931 if (RegOut == 0) { 9932 RegOut = FuncInfo.CreateRegs(C); 9933 CopyValueToVirtualRegister(C, RegOut); 9934 } 9935 Reg = RegOut; 9936 } else { 9937 DenseMap<const Value *, unsigned>::iterator I = 9938 FuncInfo.ValueMap.find(PHIOp); 9939 if (I != FuncInfo.ValueMap.end()) 9940 Reg = I->second; 9941 else { 9942 assert(isa<AllocaInst>(PHIOp) && 9943 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9944 "Didn't codegen value into a register!??"); 9945 Reg = FuncInfo.CreateRegs(PHIOp); 9946 CopyValueToVirtualRegister(PHIOp, Reg); 9947 } 9948 } 9949 9950 // Remember that this register needs to added to the machine PHI node as 9951 // the input for this MBB. 9952 SmallVector<EVT, 4> ValueVTs; 9953 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9954 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9955 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9956 EVT VT = ValueVTs[vti]; 9957 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9958 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9959 FuncInfo.PHINodesToUpdate.push_back( 9960 std::make_pair(&*MBBI++, Reg + i)); 9961 Reg += NumRegisters; 9962 } 9963 } 9964 } 9965 9966 ConstantsOut.clear(); 9967 } 9968 9969 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9970 /// is 0. 9971 MachineBasicBlock * 9972 SelectionDAGBuilder::StackProtectorDescriptor:: 9973 AddSuccessorMBB(const BasicBlock *BB, 9974 MachineBasicBlock *ParentMBB, 9975 bool IsLikely, 9976 MachineBasicBlock *SuccMBB) { 9977 // If SuccBB has not been created yet, create it. 9978 if (!SuccMBB) { 9979 MachineFunction *MF = ParentMBB->getParent(); 9980 MachineFunction::iterator BBI(ParentMBB); 9981 SuccMBB = MF->CreateMachineBasicBlock(BB); 9982 MF->insert(++BBI, SuccMBB); 9983 } 9984 // Add it as a successor of ParentMBB. 9985 ParentMBB->addSuccessor( 9986 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9987 return SuccMBB; 9988 } 9989 9990 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9991 MachineFunction::iterator I(MBB); 9992 if (++I == FuncInfo.MF->end()) 9993 return nullptr; 9994 return &*I; 9995 } 9996 9997 /// During lowering new call nodes can be created (such as memset, etc.). 9998 /// Those will become new roots of the current DAG, but complications arise 9999 /// when they are tail calls. In such cases, the call lowering will update 10000 /// the root, but the builder still needs to know that a tail call has been 10001 /// lowered in order to avoid generating an additional return. 10002 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10003 // If the node is null, we do have a tail call. 10004 if (MaybeTC.getNode() != nullptr) 10005 DAG.setRoot(MaybeTC); 10006 else 10007 HasTailCall = true; 10008 } 10009 10010 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10011 MachineBasicBlock *SwitchMBB, 10012 MachineBasicBlock *DefaultMBB) { 10013 MachineFunction *CurMF = FuncInfo.MF; 10014 MachineBasicBlock *NextMBB = nullptr; 10015 MachineFunction::iterator BBI(W.MBB); 10016 if (++BBI != FuncInfo.MF->end()) 10017 NextMBB = &*BBI; 10018 10019 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10020 10021 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10022 10023 if (Size == 2 && W.MBB == SwitchMBB) { 10024 // If any two of the cases has the same destination, and if one value 10025 // is the same as the other, but has one bit unset that the other has set, 10026 // use bit manipulation to do two compares at once. For example: 10027 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10028 // TODO: This could be extended to merge any 2 cases in switches with 3 10029 // cases. 10030 // TODO: Handle cases where W.CaseBB != SwitchBB. 10031 CaseCluster &Small = *W.FirstCluster; 10032 CaseCluster &Big = *W.LastCluster; 10033 10034 if (Small.Low == Small.High && Big.Low == Big.High && 10035 Small.MBB == Big.MBB) { 10036 const APInt &SmallValue = Small.Low->getValue(); 10037 const APInt &BigValue = Big.Low->getValue(); 10038 10039 // Check that there is only one bit different. 10040 APInt CommonBit = BigValue ^ SmallValue; 10041 if (CommonBit.isPowerOf2()) { 10042 SDValue CondLHS = getValue(Cond); 10043 EVT VT = CondLHS.getValueType(); 10044 SDLoc DL = getCurSDLoc(); 10045 10046 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10047 DAG.getConstant(CommonBit, DL, VT)); 10048 SDValue Cond = DAG.getSetCC( 10049 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10050 ISD::SETEQ); 10051 10052 // Update successor info. 10053 // Both Small and Big will jump to Small.BB, so we sum up the 10054 // probabilities. 10055 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10056 if (BPI) 10057 addSuccessorWithProb( 10058 SwitchMBB, DefaultMBB, 10059 // The default destination is the first successor in IR. 10060 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10061 else 10062 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10063 10064 // Insert the true branch. 10065 SDValue BrCond = 10066 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10067 DAG.getBasicBlock(Small.MBB)); 10068 // Insert the false branch. 10069 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10070 DAG.getBasicBlock(DefaultMBB)); 10071 10072 DAG.setRoot(BrCond); 10073 return; 10074 } 10075 } 10076 } 10077 10078 if (TM.getOptLevel() != CodeGenOpt::None) { 10079 // Here, we order cases by probability so the most likely case will be 10080 // checked first. However, two clusters can have the same probability in 10081 // which case their relative ordering is non-deterministic. So we use Low 10082 // as a tie-breaker as clusters are guaranteed to never overlap. 10083 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10084 [](const CaseCluster &a, const CaseCluster &b) { 10085 return a.Prob != b.Prob ? 10086 a.Prob > b.Prob : 10087 a.Low->getValue().slt(b.Low->getValue()); 10088 }); 10089 10090 // Rearrange the case blocks so that the last one falls through if possible 10091 // without changing the order of probabilities. 10092 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10093 --I; 10094 if (I->Prob > W.LastCluster->Prob) 10095 break; 10096 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10097 std::swap(*I, *W.LastCluster); 10098 break; 10099 } 10100 } 10101 } 10102 10103 // Compute total probability. 10104 BranchProbability DefaultProb = W.DefaultProb; 10105 BranchProbability UnhandledProbs = DefaultProb; 10106 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10107 UnhandledProbs += I->Prob; 10108 10109 MachineBasicBlock *CurMBB = W.MBB; 10110 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10111 bool FallthroughUnreachable = false; 10112 MachineBasicBlock *Fallthrough; 10113 if (I == W.LastCluster) { 10114 // For the last cluster, fall through to the default destination. 10115 Fallthrough = DefaultMBB; 10116 FallthroughUnreachable = isa<UnreachableInst>( 10117 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10118 } else { 10119 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10120 CurMF->insert(BBI, Fallthrough); 10121 // Put Cond in a virtual register to make it available from the new blocks. 10122 ExportFromCurrentBlock(Cond); 10123 } 10124 UnhandledProbs -= I->Prob; 10125 10126 switch (I->Kind) { 10127 case CC_JumpTable: { 10128 // FIXME: Optimize away range check based on pivot comparisons. 10129 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10130 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10131 10132 // The jump block hasn't been inserted yet; insert it here. 10133 MachineBasicBlock *JumpMBB = JT->MBB; 10134 CurMF->insert(BBI, JumpMBB); 10135 10136 auto JumpProb = I->Prob; 10137 auto FallthroughProb = UnhandledProbs; 10138 10139 // If the default statement is a target of the jump table, we evenly 10140 // distribute the default probability to successors of CurMBB. Also 10141 // update the probability on the edge from JumpMBB to Fallthrough. 10142 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10143 SE = JumpMBB->succ_end(); 10144 SI != SE; ++SI) { 10145 if (*SI == DefaultMBB) { 10146 JumpProb += DefaultProb / 2; 10147 FallthroughProb -= DefaultProb / 2; 10148 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10149 JumpMBB->normalizeSuccProbs(); 10150 break; 10151 } 10152 } 10153 10154 if (FallthroughUnreachable) { 10155 // Skip the range check if the fallthrough block is unreachable. 10156 JTH->OmitRangeCheck = true; 10157 } 10158 10159 if (!JTH->OmitRangeCheck) 10160 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10161 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10162 CurMBB->normalizeSuccProbs(); 10163 10164 // The jump table header will be inserted in our current block, do the 10165 // range check, and fall through to our fallthrough block. 10166 JTH->HeaderBB = CurMBB; 10167 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10168 10169 // If we're in the right place, emit the jump table header right now. 10170 if (CurMBB == SwitchMBB) { 10171 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10172 JTH->Emitted = true; 10173 } 10174 break; 10175 } 10176 case CC_BitTests: { 10177 // FIXME: Optimize away range check based on pivot comparisons. 10178 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10179 10180 // The bit test blocks haven't been inserted yet; insert them here. 10181 for (BitTestCase &BTC : BTB->Cases) 10182 CurMF->insert(BBI, BTC.ThisBB); 10183 10184 // Fill in fields of the BitTestBlock. 10185 BTB->Parent = CurMBB; 10186 BTB->Default = Fallthrough; 10187 10188 BTB->DefaultProb = UnhandledProbs; 10189 // If the cases in bit test don't form a contiguous range, we evenly 10190 // distribute the probability on the edge to Fallthrough to two 10191 // successors of CurMBB. 10192 if (!BTB->ContiguousRange) { 10193 BTB->Prob += DefaultProb / 2; 10194 BTB->DefaultProb -= DefaultProb / 2; 10195 } 10196 10197 if (FallthroughUnreachable) { 10198 // Skip the range check if the fallthrough block is unreachable. 10199 BTB->OmitRangeCheck = true; 10200 } 10201 10202 // If we're in the right place, emit the bit test header right now. 10203 if (CurMBB == SwitchMBB) { 10204 visitBitTestHeader(*BTB, SwitchMBB); 10205 BTB->Emitted = true; 10206 } 10207 break; 10208 } 10209 case CC_Range: { 10210 const Value *RHS, *LHS, *MHS; 10211 ISD::CondCode CC; 10212 if (I->Low == I->High) { 10213 // Check Cond == I->Low. 10214 CC = ISD::SETEQ; 10215 LHS = Cond; 10216 RHS=I->Low; 10217 MHS = nullptr; 10218 } else { 10219 // Check I->Low <= Cond <= I->High. 10220 CC = ISD::SETLE; 10221 LHS = I->Low; 10222 MHS = Cond; 10223 RHS = I->High; 10224 } 10225 10226 // If Fallthrough is unreachable, fold away the comparison. 10227 if (FallthroughUnreachable) 10228 CC = ISD::SETTRUE; 10229 10230 // The false probability is the sum of all unhandled cases. 10231 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10232 getCurSDLoc(), I->Prob, UnhandledProbs); 10233 10234 if (CurMBB == SwitchMBB) 10235 visitSwitchCase(CB, SwitchMBB); 10236 else 10237 SL->SwitchCases.push_back(CB); 10238 10239 break; 10240 } 10241 } 10242 CurMBB = Fallthrough; 10243 } 10244 } 10245 10246 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10247 CaseClusterIt First, 10248 CaseClusterIt Last) { 10249 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10250 if (X.Prob != CC.Prob) 10251 return X.Prob > CC.Prob; 10252 10253 // Ties are broken by comparing the case value. 10254 return X.Low->getValue().slt(CC.Low->getValue()); 10255 }); 10256 } 10257 10258 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10259 const SwitchWorkListItem &W, 10260 Value *Cond, 10261 MachineBasicBlock *SwitchMBB) { 10262 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10263 "Clusters not sorted?"); 10264 10265 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10266 10267 // Balance the tree based on branch probabilities to create a near-optimal (in 10268 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10269 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10270 CaseClusterIt LastLeft = W.FirstCluster; 10271 CaseClusterIt FirstRight = W.LastCluster; 10272 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10273 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10274 10275 // Move LastLeft and FirstRight towards each other from opposite directions to 10276 // find a partitioning of the clusters which balances the probability on both 10277 // sides. If LeftProb and RightProb are equal, alternate which side is 10278 // taken to ensure 0-probability nodes are distributed evenly. 10279 unsigned I = 0; 10280 while (LastLeft + 1 < FirstRight) { 10281 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10282 LeftProb += (++LastLeft)->Prob; 10283 else 10284 RightProb += (--FirstRight)->Prob; 10285 I++; 10286 } 10287 10288 while (true) { 10289 // Our binary search tree differs from a typical BST in that ours can have up 10290 // to three values in each leaf. The pivot selection above doesn't take that 10291 // into account, which means the tree might require more nodes and be less 10292 // efficient. We compensate for this here. 10293 10294 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10295 unsigned NumRight = W.LastCluster - FirstRight + 1; 10296 10297 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10298 // If one side has less than 3 clusters, and the other has more than 3, 10299 // consider taking a cluster from the other side. 10300 10301 if (NumLeft < NumRight) { 10302 // Consider moving the first cluster on the right to the left side. 10303 CaseCluster &CC = *FirstRight; 10304 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10305 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10306 if (LeftSideRank <= RightSideRank) { 10307 // Moving the cluster to the left does not demote it. 10308 ++LastLeft; 10309 ++FirstRight; 10310 continue; 10311 } 10312 } else { 10313 assert(NumRight < NumLeft); 10314 // Consider moving the last element on the left to the right side. 10315 CaseCluster &CC = *LastLeft; 10316 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10317 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10318 if (RightSideRank <= LeftSideRank) { 10319 // Moving the cluster to the right does not demot it. 10320 --LastLeft; 10321 --FirstRight; 10322 continue; 10323 } 10324 } 10325 } 10326 break; 10327 } 10328 10329 assert(LastLeft + 1 == FirstRight); 10330 assert(LastLeft >= W.FirstCluster); 10331 assert(FirstRight <= W.LastCluster); 10332 10333 // Use the first element on the right as pivot since we will make less-than 10334 // comparisons against it. 10335 CaseClusterIt PivotCluster = FirstRight; 10336 assert(PivotCluster > W.FirstCluster); 10337 assert(PivotCluster <= W.LastCluster); 10338 10339 CaseClusterIt FirstLeft = W.FirstCluster; 10340 CaseClusterIt LastRight = W.LastCluster; 10341 10342 const ConstantInt *Pivot = PivotCluster->Low; 10343 10344 // New blocks will be inserted immediately after the current one. 10345 MachineFunction::iterator BBI(W.MBB); 10346 ++BBI; 10347 10348 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10349 // we can branch to its destination directly if it's squeezed exactly in 10350 // between the known lower bound and Pivot - 1. 10351 MachineBasicBlock *LeftMBB; 10352 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10353 FirstLeft->Low == W.GE && 10354 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10355 LeftMBB = FirstLeft->MBB; 10356 } else { 10357 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10358 FuncInfo.MF->insert(BBI, LeftMBB); 10359 WorkList.push_back( 10360 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10361 // Put Cond in a virtual register to make it available from the new blocks. 10362 ExportFromCurrentBlock(Cond); 10363 } 10364 10365 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10366 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10367 // directly if RHS.High equals the current upper bound. 10368 MachineBasicBlock *RightMBB; 10369 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10370 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10371 RightMBB = FirstRight->MBB; 10372 } else { 10373 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10374 FuncInfo.MF->insert(BBI, RightMBB); 10375 WorkList.push_back( 10376 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10377 // Put Cond in a virtual register to make it available from the new blocks. 10378 ExportFromCurrentBlock(Cond); 10379 } 10380 10381 // Create the CaseBlock record that will be used to lower the branch. 10382 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10383 getCurSDLoc(), LeftProb, RightProb); 10384 10385 if (W.MBB == SwitchMBB) 10386 visitSwitchCase(CB, SwitchMBB); 10387 else 10388 SL->SwitchCases.push_back(CB); 10389 } 10390 10391 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10392 // from the swith statement. 10393 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10394 BranchProbability PeeledCaseProb) { 10395 if (PeeledCaseProb == BranchProbability::getOne()) 10396 return BranchProbability::getZero(); 10397 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10398 10399 uint32_t Numerator = CaseProb.getNumerator(); 10400 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10401 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10402 } 10403 10404 // Try to peel the top probability case if it exceeds the threshold. 10405 // Return current MachineBasicBlock for the switch statement if the peeling 10406 // does not occur. 10407 // If the peeling is performed, return the newly created MachineBasicBlock 10408 // for the peeled switch statement. Also update Clusters to remove the peeled 10409 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10410 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10411 const SwitchInst &SI, CaseClusterVector &Clusters, 10412 BranchProbability &PeeledCaseProb) { 10413 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10414 // Don't perform if there is only one cluster or optimizing for size. 10415 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10416 TM.getOptLevel() == CodeGenOpt::None || 10417 SwitchMBB->getParent()->getFunction().hasMinSize()) 10418 return SwitchMBB; 10419 10420 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10421 unsigned PeeledCaseIndex = 0; 10422 bool SwitchPeeled = false; 10423 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10424 CaseCluster &CC = Clusters[Index]; 10425 if (CC.Prob < TopCaseProb) 10426 continue; 10427 TopCaseProb = CC.Prob; 10428 PeeledCaseIndex = Index; 10429 SwitchPeeled = true; 10430 } 10431 if (!SwitchPeeled) 10432 return SwitchMBB; 10433 10434 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10435 << TopCaseProb << "\n"); 10436 10437 // Record the MBB for the peeled switch statement. 10438 MachineFunction::iterator BBI(SwitchMBB); 10439 ++BBI; 10440 MachineBasicBlock *PeeledSwitchMBB = 10441 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10442 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10443 10444 ExportFromCurrentBlock(SI.getCondition()); 10445 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10446 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10447 nullptr, nullptr, TopCaseProb.getCompl()}; 10448 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10449 10450 Clusters.erase(PeeledCaseIt); 10451 for (CaseCluster &CC : Clusters) { 10452 LLVM_DEBUG( 10453 dbgs() << "Scale the probablity for one cluster, before scaling: " 10454 << CC.Prob << "\n"); 10455 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10456 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10457 } 10458 PeeledCaseProb = TopCaseProb; 10459 return PeeledSwitchMBB; 10460 } 10461 10462 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10463 // Extract cases from the switch. 10464 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10465 CaseClusterVector Clusters; 10466 Clusters.reserve(SI.getNumCases()); 10467 for (auto I : SI.cases()) { 10468 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10469 const ConstantInt *CaseVal = I.getCaseValue(); 10470 BranchProbability Prob = 10471 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10472 : BranchProbability(1, SI.getNumCases() + 1); 10473 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10474 } 10475 10476 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10477 10478 // Cluster adjacent cases with the same destination. We do this at all 10479 // optimization levels because it's cheap to do and will make codegen faster 10480 // if there are many clusters. 10481 sortAndRangeify(Clusters); 10482 10483 // The branch probablity of the peeled case. 10484 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10485 MachineBasicBlock *PeeledSwitchMBB = 10486 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10487 10488 // If there is only the default destination, jump there directly. 10489 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10490 if (Clusters.empty()) { 10491 assert(PeeledSwitchMBB == SwitchMBB); 10492 SwitchMBB->addSuccessor(DefaultMBB); 10493 if (DefaultMBB != NextBlock(SwitchMBB)) { 10494 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10495 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10496 } 10497 return; 10498 } 10499 10500 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10501 SL->findBitTestClusters(Clusters, &SI); 10502 10503 LLVM_DEBUG({ 10504 dbgs() << "Case clusters: "; 10505 for (const CaseCluster &C : Clusters) { 10506 if (C.Kind == CC_JumpTable) 10507 dbgs() << "JT:"; 10508 if (C.Kind == CC_BitTests) 10509 dbgs() << "BT:"; 10510 10511 C.Low->getValue().print(dbgs(), true); 10512 if (C.Low != C.High) { 10513 dbgs() << '-'; 10514 C.High->getValue().print(dbgs(), true); 10515 } 10516 dbgs() << ' '; 10517 } 10518 dbgs() << '\n'; 10519 }); 10520 10521 assert(!Clusters.empty()); 10522 SwitchWorkList WorkList; 10523 CaseClusterIt First = Clusters.begin(); 10524 CaseClusterIt Last = Clusters.end() - 1; 10525 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10526 // Scale the branchprobability for DefaultMBB if the peel occurs and 10527 // DefaultMBB is not replaced. 10528 if (PeeledCaseProb != BranchProbability::getZero() && 10529 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10530 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10531 WorkList.push_back( 10532 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10533 10534 while (!WorkList.empty()) { 10535 SwitchWorkListItem W = WorkList.back(); 10536 WorkList.pop_back(); 10537 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10538 10539 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10540 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10541 // For optimized builds, lower large range as a balanced binary tree. 10542 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10543 continue; 10544 } 10545 10546 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10547 } 10548 } 10549 10550 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10551 SDNodeFlags Flags; 10552 10553 SDValue Op = getValue(I.getOperand(0)); 10554 if (I.getOperand(0)->getType()->isAggregateType()) { 10555 EVT VT = Op.getValueType(); 10556 SmallVector<SDValue, 1> Values; 10557 for (unsigned i = 0; i < Op.getNumOperands(); ++i) { 10558 SDValue Arg(Op.getNode(), i); 10559 SDValue UnNodeValue = DAG.getNode(ISD::FREEZE, getCurSDLoc(), VT, Arg, Flags); 10560 Values.push_back(UnNodeValue); 10561 } 10562 SDValue MergedValue = DAG.getMergeValues(Values, getCurSDLoc()); 10563 setValue(&I, MergedValue); 10564 } else { 10565 SDValue UnNodeValue = DAG.getNode(ISD::FREEZE, getCurSDLoc(), Op.getValueType(), 10566 Op, Flags); 10567 setValue(&I, UnNodeValue); 10568 } 10569 } 10570